diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 94701801da..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 @@ -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 @@ -3692,7 +3816,7 @@ /types/re-base/ @jordandrako /types/reach__router/ @kingdaro /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 +/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 @@ -3838,6 +3965,7 @@ /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 @@ -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 eba170c493..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 { diff --git a/notNeededPackages.json b/notNeededPackages.json index 53ff6a7124..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", 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/ace/index.d.ts b/types/ace/index.d.ts index 7faa5da4f8..cd20b57f05 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -1223,7 +1223,7 @@ declare namespace AceAjax { /** * Returns `true` if the current `textInput` is in focus. **/ - isFocused(): void; + isFocused(): boolean; /** * Blurs the current `textInput`. diff --git a/types/active-win/active-win-tests.ts b/types/active-win/active-win-tests.ts new file mode 100644 index 0000000000..034b03d85a --- /dev/null +++ b/types/active-win/active-win-tests.ts @@ -0,0 +1,17 @@ +import activeWin = require('active-win'); + +// $ExpectType Promise +activeWin(); +// $ExpectType Result +activeWin.sync(); + +let win = { + title: 'Unicorns - Google Search', + id: 5762, + owner: { + name: 'Google Chrome', + processId: 310, + }, +}; + +win = activeWin.sync(); diff --git a/types/active-win/index.d.ts b/types/active-win/index.d.ts new file mode 100644 index 0000000000..7ab1f1e123 --- /dev/null +++ b/types/active-win/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for active-win 4.0 +// Project: https://github.com/sindresorhus/active-win#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = activeWin; + +declare function activeWin(): Promise; + +declare namespace activeWin { + function sync(): Result; + + interface Result { + title: string; + id: number; + bounds?: { + x: number; + y: number; + width: number; + height: number; + }; + owner: { + name: string; + processId: number; + bundleId?: number; + path?: string; + }; + memoryUsage?: number; + } +} diff --git a/types/active-win/tsconfig.json b/types/active-win/tsconfig.json new file mode 100644 index 0000000000..fc292756af --- /dev/null +++ b/types/active-win/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", + "active-win-tests.ts" + ] +} diff --git a/types/active-win/tslint.json b/types/active-win/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/active-win/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/all-property-names/all-property-names-tests.ts b/types/all-property-names/all-property-names-tests.ts new file mode 100644 index 0000000000..b32daa59a3 --- /dev/null +++ b/types/all-property-names/all-property-names-tests.ts @@ -0,0 +1,4 @@ +import allPropertyNames = require('all-property-names'); + +// $ExpectType Set +allPropertyNames(Symbol.prototype); diff --git a/types/all-property-names/index.d.ts b/types/all-property-names/index.d.ts new file mode 100644 index 0000000000..0b396ec94d --- /dev/null +++ b/types/all-property-names/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for all-property-names 1.0 +// Project: https://github.com/sindresorhus/all-property-names#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = allPropertyNames; + +declare function allPropertyNames(input: object): Set; diff --git a/types/all-property-names/tsconfig.json b/types/all-property-names/tsconfig.json new file mode 100644 index 0000000000..394cd3bb53 --- /dev/null +++ b/types/all-property-names/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", + "all-property-names-tests.ts" + ] +} diff --git a/types/all-property-names/tslint.json b/types/all-property-names/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/all-property-names/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/alt/index.d.ts b/types/alt/index.d.ts index 9094642e70..c95e1653b0 100644 --- a/types/alt/index.d.ts +++ b/types/alt/index.d.ts @@ -54,7 +54,7 @@ declare namespace AltJS { export type Source = {[name:string]: () => SourceModel}; export interface SourceModel { - local(state:any, ...args: any[]):any; + local?(state:any, ...args: any[]):any; remote(state:any, ...args: any[]):Promise; shouldFetch?(fetchFn:(...args:Array) => boolean):void; loading?:(args:any) => void; 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/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/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/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/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/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 1a1bf712d7..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!"); } } @@ -109,3 +113,40 @@ const BindingKindTest: Visitor = { 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 e35b12780f..89e242129b 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -143,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/index.d.ts b/types/backbone/index.d.ts index ca36541735..a881284c8f 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -92,7 +92,7 @@ declare namespace Backbone { } interface EventsHash { - [selector: string]: string | {(eventObject: JQueryEventObject): void}; + [selector: string]: string | {(eventObject: JQuery.TriggeredEvent): void}; } export const Events: Events; 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 跟一个

> { + constructor( + editor: editor.Editor, + availablePlugins?: Array P> + ); + + [Symbol.iterator](): Iterator<[new(editor: editor.Editor) => P, P]>; + + destroy(): Promise}>>; + + get( + key: string | (new(editor: editor.Editor) => P) + ): P | undefined; + + load( + plugins: Array P)>, + removePlugins?: Array P)> + ): Promise; +} diff --git a/types/ckeditor__ckeditor5-core/tsconfig.json b/types/ckeditor__ckeditor5-core/tsconfig.json new file mode 100644 index 0000000000..5f53bb9035 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom", + "es2015.promise" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ckeditor__ckeditor5-core-tests.ts" + ] +} diff --git a/types/ckeditor__ckeditor5-core/tslint.json b/types/ckeditor__ckeditor5-core/tslint.json new file mode 100644 index 0000000000..b4dd998211 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/tslint.json @@ -0,0 +1,22 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": { + "options": [ + ["Object", "Avoid using the `Object` type. Did you mean `object`?"], + ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], + ["Number", "Avoid using the `Number` type. Did you mean `number`?"], + ["String", "Avoid using the `String` type. Did you mean `string`?"], + ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] + ] + }, + "no-empty-interface": false, + "prefer-switch": false, + "quotemark": [ + true, + "double", + "avoid-escape", + "avoid-template" + ] + } +} diff --git a/types/ckeditor__ckeditor5-engine/ckeditor__ckeditor5-engine-tests.ts b/types/ckeditor__ckeditor5-engine/ckeditor__ckeditor5-engine-tests.ts new file mode 100644 index 0000000000..676f30ac3b --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/ckeditor__ckeditor5-engine-tests.ts @@ -0,0 +1,81 @@ +import * as engine from "ckeditor__ckeditor5-engine"; + +declare let pattern: engine.view.MatcherPattern; + +pattern = {name: /^p/}; + +pattern = { + attributes: { + title: "foobar", + foo: /^\w+/, + bar: true, + } +}; + +pattern = { + classes: "foobar" +}; + +pattern = { + classes: /foo.../ +}; + +pattern = { + classes: ["baz", "bar", /foo.../] +}; + +pattern = { + styles: { + position: "absolute", + color: /^\w*blue$/ + } +}; + +pattern = { + name: "span", + styles: { + "font-weight": "bold" + }, + classes: "highlighted" +}; + +pattern = (element: engine.view.Element) => { + if (element.name === "div" && element.childCount > 0) { + return {name: true}; + } + + return null; +}; + +pattern = (element: engine.view.Element) => { + if (element.name === "p") { + const fontSize = element.getStyle("font-size")!; + const size = fontSize.match(/(\d+)/px); + + if (size && Number(size[1]) > 26) { + return {name: true, attribute: ["font-size"]}; + } + } + + return null; +}; + +declare let viewDefinition: engine.view.ElementDefinition; + +viewDefinition = "p"; + +viewDefinition = { + name: "h1", + classes: ["foo", "bar"], +}; + +viewDefinition = { + name: "span", + styles: { + "font-size": "12px", + "font-weight": "bold", + }, + attributes: { + "data-id": "123", + } +}; diff --git a/types/ckeditor__ckeditor5-engine/index.d.ts b/types/ckeditor__ckeditor5-engine/index.d.ts new file mode 100644 index 0000000000..280b6ea213 --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/index.d.ts @@ -0,0 +1,1368 @@ +// Type definitions for @ckeditor/ckeditor5-engine 11.0 +// Project: https://github.com/ckeditor/ckeditor5-engine +// Definitions by: denisname +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as ckutils from "ckeditor__ckeditor5-utils"; + +export namespace controller { + // engine/controller/datacontroller + + class DataController implements ckutils.Emitter, ckutils.Observable { + readonly downcastDispatcher: conversion.DowncastDispatcher; + readonly mapper: conversion.Mapper; + readonly model: model.Model; + readonly processor: dataprocessor.DataProcessor; + readonly upcastDispatcher: conversion.UpcastDispatcher; + + constructor(model: model.Model, dataProcessor?: dataprocessor.DataProcessor); + destroy(): void; + get(rootName?: string): string; + init(data: string, rootName?: string): Promise; + parse(data: string, context?: model.SchemaContextDefinition): model.DocumentFragment; + stringify(modelElementOrFragment: Element | model.DocumentFragment): string; + toModel(viewElementOrFragment: Element | model.DocumentFragment, context?: model.SchemaContextDefinition): model.DocumentFragment; + toView(modelElementOrFragment: Element | model.DocumentFragment): model.DocumentFragment; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + // engine/controller/editingcontroller + + class EditingController implements ckutils.Emitter, ckutils.Observable { + readonly downcastDispatcher: conversion.DowncastDispatcher; + readonly mapper: conversion.Mapper; + readonly model: model.Model; + readonly view: view.View; + + constructor(model: model.Model); + destroy(): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } +} + +export namespace conversion { + // engine/conversion/conversion + + class Conversion { + constructor(); + attributeToAttribute(definition?: {model: string | Object, view?: string | Object, upcastAlso?: view.MatcherPattern | view.MatcherPattern[]}): void; + attributeToElement(definition: ConverterDefinition): void; + elementToElement(definition: ConverterDefinition): void; + for(groupName: string): {add: () => void}; + register(groupName: string, dispatchers: Array): void; + } + + interface ConverterDefinition { + converterPriority: ckutils.PriorityString; + model: any; + upcastAlso: view.MatcherPattern | view.MatcherPattern[]; + view: view.ElementDefinition | Object; + } + + // engine/conversion/downcast-converters + + interface HighlightDescriptor { + attributes: Object; + classes: string | string[]; + id: string; + priority: number; + } + + // engine/conversion/downcast-selection-converters + + function clearAttributes(): Function; + + function convertCollapsedSelection(): Function; + + function convertRangeSelection(): Function; + + // engine/conversion/downcastdispatcher + + class DowncastDispatcher { + // TODO + } + + // engine/conversion/mapper + + class Mapper { + constructor(); + bindElementToMarker(element: view.Element, name: string): void; + bindElements(modelElement: model.Element, viewElement: view.Element): void; + clearBindings(): void; + getModelLength(viewNode: view.Element): number; + markerNameToElements(name: string): Set | null; + registerViewToModelLength(viewElementName: string, lengthCallback: Function): void; + toModelElement(viewElement: view.Element): model.Element | undefined; + toModelPosition(viewPosition: view.Position): model.Position; + toModelRange(viewRange: view.Range): model.Range; + toViewElement(modelElement: model.Element): view.Element | undefined; + toViewPosition(modelPosition: model.Position, options?: {isPhantom: boolean}): view.Position; + toViewRange(modelRange: model.Range): view.Range; + unbindElementsFromMarkerName(name: string): void; + unbindModelElement(modelElement: model.Element): void; + unbindViewElement(viewElement: view.Element): void; + } + + // engine/conversion/modelconsumable + + class ModelConsumable { + constructor(); + add(item: model.Item | model.Selection | model.Range, type: string): void; + consume(item: model.Item | model.Selection | model.Range, type: string): boolean; + revert(item: model.Item | model.Selection | model.Range, type: string): null | boolean; + test(item: model.Item | model.Selection | model.Range, type: string): null | boolean; + } + + // engine/conversion/upcast-converters + + function convertText(): Function; + + function convertToModelFragment(): Function; + + function upcastAttributeToAttribute( + config: {view: string | {key: string, name: string, value: string | RegExp | Function}, + model: string | {key: string, value: string | Function}, + converterPriority?: ckutils.PriorityString} + ): Function; + + function upcastElementToAttribute( + config: {view: view.MatcherPattern, model: string | {key: string, value: string | Function}, converterPriority?: ckutils.PriorityString} + ): Function; + + function upcastElementToElement( + config: {view: view.MatcherPattern, model: string | Element | Function, converterPriority?: ckutils.PriorityString} + ): Function; + + function upcastElementToMarker( + config: {view: view.MatcherPattern, model: string | Function, converterPriority?: ckutils.PriorityString} + ): Function; + + // engine/conversion/upcast-selection-converters + + function convertSelectionChange(model: model.Model, mapper: Mapper): Function; + + // engine/conversion/upcastdispatcher + + class UpcastDispatcher { + // TODO + } + + interface ViewConversionApi { + // TODO + } + + // engine/conversion/viewconsumable + + class ViewConsumable { + // TODO + } +} + +export namespace dataprocessor { + // engine/dataprocessor/basichtmlwriter + + class BasicHtmlWriter implements HtmlWriter { + getHtml(fragment: model.DocumentFragment): string; + } + + // engine/dataprocessor/dataprocessor + + interface DataProcessor { + // TODO + } + + // engine/dataprocessor/htmldataprocessor + + class HtmlDataProcessor implements DataProcessor { + // TODO + } + + // engine/dataprocessor/htmlwriter + + interface HtmlWriter { + getHtml(fragment: model.DocumentFragment): string; + } + + // engine/dataprocessor/xmldataprocessor + + class XmlDataProcessor implements DataProcessor { + // TODO + } +} + +export namespace devUtils { + // engine/dev-utils/enableenginedebug + + class DebugPlugin {} + + function disableEngineDebug(): void; + + function enableEngineDebug(_logger: {log: (...arg: any[]) => string, error: (...arg: any[]) => string}): DebugPlugin; + + // engine/dev-utils/model + + namespace devmodel { + function getData( + model: model.Model, + options?: { + withoutSelection?: boolean, + rootName?: string, + convertMarkers?: boolean + } + ): string; + + function parse( + data: string, + schema: model.Schema, + batch: model.Batch, + options?: { + selectionAttributes?: Object[], + lastRangeBackward?: boolean, + context?: model.SchemaContextDefinition + } + ): model.Element | model.Text | model.DocumentFragment | Object; + + function setData(model: string, data: Object, options: {rootName?: string, selectionAttributes?: Object[], lastRangeBackward?: boolean, batchType?: string}): void; + + function stringify( + node: model.RootElement | model.Element | model.Text | model.DocumentFragment, + selectionOrPositionOrRange: model.Selection | model.Position | model.Range, // TODO optional + markers: Iterable | null + ): string; + } + + // engine/dev-utils/operationreplayer + + class OperationReplayer { + // TODO + } + + // engine/dev-utils/view + + function getData( + view: view.View, + options?: { + withoutSelection?: boolean, + rootName?: boolean, + showType?: boolean, + showPriority?: boolean, + showAttributeElementId?: boolean, + renderUIElements?: boolean, + } + ): string; + + function parse( + data: string, + options: { + order?: number[], + lastRangeBackward?: boolean, + rootElement?: view.Element | view.DocumentFragment, + sameSelectionCharacters?: boolean + } + ): view.Text | view.Element | view.DocumentFragment | Object; + + function setData( + view: view.View, + data: string, + options: {rootName?: string} + ): void; + + function stringify( + node: view.Text | view.Element | view.DocumentFragment, + selectionOrPositionOrRange?: view.DocumentSelection | view.Position | view.Range, + options?: { + showType?: boolean, + showPriority?: boolean, + showAttributeElementId?: boolean, + ignoreRoot?: boolean, + sameSelectionCharacters?: boolean, + renderUIElements?: boolean, + } + ): string; +} + +export namespace model { + namespace operation { + // engine/model/operation/attributeoperation + + class AttributeOperation { + // TODO + } + + // engine/model/operation/detachoperation + + class DetachOperation { + // TODO + } + + // engine/model/operation/insertoperation + + class InsertOperation { + // TODO + } + + // engine/model/operation/markeroperation + + class MarkerOperation { + // TODO + } + + // engine/model/operation/mergeoperation + + class MergeOperation { + // TODO + } + + // engine/model/operation/moveoperation + + class MoveOperation { + // TODO + } + + // engine/model/operation/nooperation + + class NoOperation { + // TODO + } + + // engine/model/operation/operation + + class Operation { + // TODO + } + + // engine/model/operation/operationfactory + + class OperationFactory { + // TODO + } + + // engine/model/operation/renameoperation + + class RenameOperation { + // TODO + } + + // engine/model/operation/rootattributeoperation + + class RootAttributeOperation { + // TODO + } + + // engine/model/operation/splitoperation + + class SplitOperation { + // TODO + } + + // engine/model/operation/transform + + class TransformationContext { + // TODO + } + + function transform(a: Operation, b: Operation, context: TransformationContext): Operation[]; + + function transformSets(operationsA: Operation[], operationsB: Operation[], options: {document: Document | null, useRelations: boolean, padWithNoOps: boolean}): object; + } + + namespace utils { + function deleteContent( + model: Model, + selection: Selection | DocumentSelection, + batch: Batch, + options?: {leaveUnmerged: boolean, doNotResetEntireContent: boolean} + ): void; + + function getSelectedContent( + model: Model, + selection: Selection | DocumentSelection + ): DocumentFragment; + + function insertContent( + model: Model, + content: DocumentFragment | Item, + selectable?: Selection | DocumentSelection | Position | Element | Iterable | Range | null + ): void; + + function modifySelection( + model: Model, + selection: Selection | DocumentSelection, + options?: {direction?: "forward" | "backward", unit?: "character" | "codePoint" | "word"} + ): void; + + function injectSelectionPostFixer( + model: Model + ): void; + } + + // engine/model/batch + + class Batch { + // TODO + } + + // engine/model/differ + + class Differ { + // TODO + } + + // engine/model/document + + class Document { + // TODO + } + + // engine/model/documentfragment + + class DocumentFragment { + readonly childCount: number; + readonly isEmpty: boolean; + readonly markers: Map; + readonly maxOffset: number; + readonly parent: null; + readonly root: DocumentFragment; + + protected constructor(children?: Node | Iterable); + [Symbol.iterator](): Iterator; + getChild(index: number): Node | null; + getChildIndex(node: Node): number | null; + getChildStartOffset(node: Node): number | null; + getChildren(): Iterable; + getNodeByPath(relativePath: number[]): Node | DocumentFragment; + getPath(): number[]; /*TS3.0: []*/ + is(type: string): boolean; + offsetToIndex(offset: number): number; + toJSON(): Object; + protected _appendChild(items: Item | Iterable): void; + protected _insertChild(index: number, items: Item | Iterable): void; + protected _removeChildren(index: number, howMany?: number): Node[]; + + static fromJSON(json: object): DocumentFragment; + } + + // engine/model/documentselection + + class DocumentSelection { + // TODO + } + + // engine/model/element + + class Element extends Node { + readonly childCount: number; + readonly isEmpty: boolean; + readonly maxOffset: number; + readonly name: string; + + protected constructor( + name: string, + attrs?: Map | ReadonlyArray<[string, any]>, + children?: Node | Iterable + ); + getChild(index: number): Node; + getChildIndex(node: Node): number; + getChildStartOffset(node: Node): number; + getChildren(): Iterable; + getNodeByPath(relativePath: number[]): Node; + is(type: string, name?: string): boolean; + offsetToIndex(offset: number): number; + toJSON(): object; + protected _appendChild(nodes: Item | Iterable): void; + protected _clone(deep?: boolean): Element; + protected _insertChild(index: number, items: Item | Iterable): void; + protected _removeChildren(index: number, howMany?: number): Node[]; + + static fromJSON(json: object): Element; + } + + // engine/model/history + + class History { + // TODO + } + + // engine/model/item + + type Item = Node | TextProxy; + + // engine/model/liveposition + + class LivePosition { + // TODO + } + + // engine/model/liverange + + class LiveRange { + // TODO + } + + // engine/model/markercollection + + class Marker { + // TODO + } + + class MarkerCollection { + // TODO + } + + // engine/model/model + + class Model implements ckutils.Emitter, ckutils.Observable { + readonly document: Document; + readonly markers: MarkerCollection; + readonly schema: Schema; + + applyOperation(operation: operation.Operation): void; + change(callback: Function): any; + deleteContent(selection: Selection | DocumentSelection, batch: Batch, options: {leaveUnmerged?: boolean, doNotResetEntireContent?: boolean}): void; + destroy(): void; + enqueueChange(batchOrType: Batch | "transparent" | "default", callback: Function): void; + getSelectedContent(selection: Selection | DocumentSelection): DocumentFragment; + hasContent(rangeOrElement: Range | Element): boolean; + insertContent(content: DocumentFragment | Item, selectable?: Selection | DocumentSelection | Position | Element | Iterable | Range | null): void; + modifySelection(selection: Selection | DocumentSelection, options?: {direction?: "forward" | "backward", unit?: "character" | "codePoint" | "word"}): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + // engine/model/node + + class Node { + readonly document: Document | null; + readonly endOffset: number | null; + readonly index: number | null; + readonly nextSibling: Node | null; + readonly offsetSize: number; + readonly parent: Element | DocumentFragment | null; + readonly previousSibling: Node | null; + readonly root: Node | DocumentFragment; + readonly startOffset: number | null; + + constructor(attrs?: Map | ReadonlyArray<[string, any]>); + getAncestors(options: {includeSelf: boolean, parentFirst: boolean}): Node[]; + getAttribute(key: string): any /*| undefined*/; + getAttributeKeys(): Iterable; + getAttributes(): Iterable; + getCommonAncestor(node: Node, options?: {includeSelf: boolean}): Element | DocumentFragment | null; + getPath(): number[]; + hasAttribute(key: string): boolean; + + is(type: "element"): this is Element; + is(type: "rootElement"): this is RootElement; + is(type: "text"): this is Text; + is(type: "textProxy"): this is TextProxy; + is(type: "documentFragment"): this is DocumentFragment; + is(type: string, name: string): boolean; + + isAfter(node: Node): boolean; + isBefore(node: Node): boolean; + toJSON(): object; + } + + type NodeSet = Node | TextProxy | string | NodeList | DocumentFragment | Iterable; + + // engine/model/nodelist + + class NodeList implements Iterable { + readonly length: number; + readonly maxOffset: number; + + [Symbol.iterator](): Iterator; + getNode(index: number): Node | null; + getNodeIndex(node: Node): number | null; + getNodeStartOffset(node: Node): number | null; + indexToOffset(index: number): number; + offsetToIndex(offset: number): number; + toJSON(): Node[]; + } + + // engine/model/position + + class Position { + readonly index: number; + readonly isAtEnd: boolean; + readonly isAtStart: boolean; + readonly nodeAfter: Node | null; + readonly nodeBefore: Node; + offset: number; + readonly parent: Element; + readonly path: number[]; + readonly root: Element | DocumentFragment; + stickiness: PositionStickiness; + readonly textNode: Text | null; + + constructor(root: Element | DocumentFragment, path: number[], stickiness?: PositionStickiness); + compareWith(otherPosition: Position): PositionRelation; + getAncestors(): Item[]; + getCommonAncestor(position: Position): Element | DocumentFragment | null; + getCommonPath(position: Position): number[]; + getLastMatchingPosition(skip: (t: TreeWalkerValue) => boolean, options: object): Position; + getParentPath(): number[]; + getShiftedBy(shift: number): Position; + getTransformedByOperation(operation: operation.Operation): Position; + hasSameParentAs(position: Position): boolean; + isAfter(otherPosition: Position): boolean; + isBefore(otherPosition: Position): boolean; + isEqual(otherPosition: Position): boolean; + isTouching(otherPosition: Position): boolean; + toJSON(): object; + + static createAfter(item: Item): Position; + static createAt(itemOrPosition: Item | Position, offset?: number | "end" | "before" | "after"): void; + static createBefore(item: Item): Position; + static createFromParentAndOffset(parent: Element | DocumentFragment, offset: number): Position; + static createFromPosition(position: Position): Position; + static fromJSON(json: object, doc: Document): Position; + } + + type PositionRelation = "before" | "after" | "same"; + + type PositionStickiness = "toNone" | "toNext" | "toPrevious"; + + // engine/model/range + + class Range implements Iterable { + readonly end: Position; + isCollapsed: boolean; + isFlat: boolean; + root: Element | DocumentFragment; + readonly start: Position; + + constructor(start: Position, end?: Position); + [Symbol.iterator](): Iterator; + containsItem(item: Item): void; + containsPosition(position: Position): boolean; + containsRange(otherRange: Range, loose?: boolean): boolean; + getCommonAncestor(): Element | DocumentFragment | null; + getDifference(otherRange: Range): Range[]; + getIntersection(otherRange: Range): Range | null; + getMinimalFlatRanges(): Range[]; + getPositions(options: object): Iterable; + getTransformedByOperation(operation: operation.Operation): Range[]; + getTransformedByOperations(operations: Iterable): Range[]; + getWalker(options: { + startPosition: Position, + singleCharacters: boolean, + shallow: boolean, + ignoreElementEnd: boolean, + }): void; + isEqual(otherRange: Range): boolean; + isIntersecting(otherRange: Range): boolean; + toJSON(): object; + } + + function getItems(options: object): Iterable; + + // engine/model/rootelement + + class RootElement extends Element { + readonly document: Document | null; + readonly rootName: string; + + constructor(doc: Document, name: string, rootName: string); + // TODO: toJSON(): string; + } + + // engine/model/schema + + class Schema { + // TODO + } + + class SchemaContext { + // TODO + } + + interface SchemaCompiledItemDefinition { + name: string; + allowIn: string | string[]; + allowAttributes: string | string[]; + isBlock: boolean; + isLimit: boolean; + isObject: boolean; + } + + type SchemaContextDefinition = Node | Position | SchemaContext | string | Array; + + interface SchemaContextItem { + name: string; + getAttributeKeys: Iterable; + getAttribute: (key: string) => string; + } + + interface SchemaItemDefinition { + allowIn: string | string[]; + allowAttributes: string | string[]; + allowContentOf: string | string[]; + allowWhere: string | string[]; + allowAttributesOf: string | string[]; + inheritTypesFrom: string | string[]; + inheritAllFrom: string | string[]; + isBlock: boolean; + isLimit: boolean; + isObject: boolean; + } + + // engine/model/selection + + class Selection implements ckutils.Emitter { + // TODO + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + } + + // engine/model/text + + class Text extends Node { + readonly data: string; + protected _data: string; + + protected constructor(data: string, attrs?: Map | ReadonlyArray<[string, any]>); + toJSON(): object; + protected _clone(): Text; + + static fromJSON(json: object): Text; + } + + // engine/model/textproxy + + class TextProxy { + readonly data: string; + readonly document: Document | null; + readonly endOffset: number; + readonly isPartial: boolean; + readonly offsetInText: number; + readonly offsetSize: number; + readonly parent: Element | DocumentFragment | null; + readonly root: Node | DocumentFragment; + readonly startOffset: number; + readonly textNode: Text; + + protected constructor(textNode: Text, offsetInText: number, length: number); + getAncestors(options: {includeSelf?: boolean, parentFirst?: boolean}): Array; + getAttribute(key: string): any; + getAttributeKeys(): Iterable; + getAttributes(): Iterable; + getPath(): number[]; + hasAttribute(key: string): boolean; + is(type: "textProxy"): this is TextProxy; + is(type: string): boolean; + } + + // engine/model/treewalker + + class TreeWalker implements Iterable { + readonly boundaries: Range; + readonly direction: "backward" | "forward"; + readonly ignoreElementEnd: boolean; + readonly position: Position; + readonly shallow: boolean; + readonly singleCharacters: boolean; + + constructor(options?: { + direction?: "forward" | "backward", + boundaries?: Range, + startPosition: Position, + singleCharacters?: boolean, + shallow?: boolean, + ignoreElementEnd?: boolean + }); + [Symbol.iterator](): Iterator; + next(): TreeWalkerValue; + skip(skip: (t: TreeWalkerValue) => boolean): void; + } + + interface TreeWalkerValue { + item: Item; + length: number; + nextPosition: Position; + previousPosition: Position; + type: TreeWalkerValueType; + } + + type TreeWalkerValueType = "elementStart" | "elementEnd" | "character" | "text"; + + // engine/model/writer + + class Writer { + // TODO + } +} + +export namespace utils { + // engine/utils/bindtwostepcarettoattribute + + function bindTwoStepCaretToAttribute(view: view.View, model: model.Model, emitter: ckutils.Emitter, attribute: string): void; +} + +export namespace view { + namespace observer { + // engine/view/observer/clickobserver + + class ClickObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/compositionobserver + + class CompositionObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/domeventdata + + class DomEventData { + // TODO + } + + // engine/view/observer/domeventobserver + + class DomEventObserver extends Observer { + readonly domEventType: string | string[]; + useCapture: boolean; + + fire(eventType: string, domEvent: Event, additionalData?: Object): void; + onDomEvent(): void; + } + + // engine/view/observer/fakeselectionobserver + + class FakeSelectionObserver extends Observer { + constructor(view: View); + destroy(): void; + observe(): void; + } + + // engine/view/observer/focusobserver + + class FocusObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/keyobserver + + class KeyEventData extends DomEventData implements ckutils.KeystrokeInfo { + // KeystrokeInfo + altKey?: boolean; + ctrlKey?: boolean; + keyCode: number; + keystroke: number; + shiftKey?: boolean; + } + + class KeyObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/mouseobserver + + class MouseObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/mutationobserver + + class MutationObserver extends Observer { + domConverter: DomConverter; + renderer: Renderer; + } + + interface MutatedChildren { + newChildren: Node[]; + node: Element; + oldChildren: Node[]; + type: string; + } + + interface MutatedText { + newText: string; + node: Text; + oldText: string; + type: string; + } + + // engine/view/observer/observer + + class Observer { + readonly document: Document; + readonly isEnabled: boolean; + readonly view: View; + + constructor(view: View); + destroy(): void; + disable(): void; + enable(): void; + observe(domElement: HTMLElement, name: string): void; + } + + // engine/view/observer/selectionobserver + + class SelectionObserver extends Observer { + readonly domConverter: DomConverter; + readonly mutationObserver: MutationObserver; + readonly selection: DocumentSelection; + } + } + + // engine/view/attributeelement + + class AttributeElement extends Element { + readonly id: string | number; + readonly priority: number; + protected _clonesGroup: Set | null; + protected _id: string | number; + protected _priority: number; + + static DEFAULT_PRIORITY: number; + + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getElementsWithSameId(): Set; + getFillerOffset(): number | null; + isSimilar(otherElement: Element): boolean; + protected _clone(deep: boolean): AttributeElement; + } + + // engine/view/containerelement + + class ContainerElement extends Element { + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getFillerOffset(): number | null; + } + + // engine/view/document + + class Document implements ckutils.Emitter, ckutils.Observable { + readonly isComposing: boolean; + readonly isFocused: boolean; + isReadOnly: boolean; + readonly roots: ckutils.Collection; + readonly selection: DocumentSelection; + + constructor(); + getRoot(name?: string): RootEditableElement | null; + registerPostFixer(postFixer: (downcastWriter: DowncastWriter) => boolean): void; + protected _callPostFixers(writer: DowncastWriter): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + type ChangeType = "children" | "attributes" | "text"; + + // engine/view/documentfragment + + class DocumentFragment { + readonly childCount: number; + readonly isEmpty: boolean; + readonly parent: null; + readonly root: DocumentFragment; + protected _children: Element[]; + + protected constructor(children?: Node | Iterable); + [Symbol.iterator](): Iterator; + _appendChild(items: Item | Iterable): number; + _insertChild(index: number, items: Item | Iterable): number; + _removeChildren(index: number, howMany?: number): Node[]; + getChild(index: number): Node; + getChildIndex(node: Node): number; + getChildren(): Iterable; + is(type: string): boolean; + } + + // engine/view/documentselection + + class DocumentSelection { + // TODO + } + + // engine/view/domconverter + + class DomConverter { + // TODO + } + + // engine/view/downcastwriter + + class DowncastWriter { + // TODO + } + + // engine/view/editableelement + + class EditableElement extends ContainerElement { + // TODO + } + + // engine/view/element + + class Element extends Node { + readonly childCount: number; + readonly isEmpty: boolean; + readonly name: string; + protected _attrs: Map; + protected _children: Node[]; + protected _classes: Set; + protected _customProperties: Map; + protected _styles: Map; + + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + _removeChildren(index: number, howMany?: number): Node[]; + _removeClass(className: string[] | string): void; + findAncestor(patterns: Object | string | RegExp | Function): Element | null; + getAttribute(key: string): string | undefined; + getAttributeKeys(): Iterable; + getAttributes(): Iterable; + getChild(index: number): Node; + getChildIndex(node: Node): number; + getChildren(): Iterable; + getClassNames(): Iterable; + getCustomProperties(): Iterable; + getCustomProperty(key: string | symbol): any; + getFillerOffset(): void; + getIdentity(): string; + getStyle(property: string): string | undefined; + getStyleNames(): Iterable; + hasAttribute(key: string): boolean; + hasClass(className: string): void; + hasStyle(property: string): void; + is(type: string, name?: string): boolean; + isSimilar(otherElement: Element): boolean; + protected _addClass(className: string[] | string): void; + protected _appendChild(items: Item | Iterable): number; + protected _clone(deep?: boolean): Element; + protected _insertChild(index: number, items: Item | Iterable): number; + protected _removeAttribute(key: string): boolean; + protected _removeCustomProperty(key: string | symbol): boolean; + protected _removeStyle(property: string[] | string): void; + protected _setAttribute(key: string, value: string): void; + protected _setCustomProperty(key: string | symbol, value: any): void; + protected _setStyle(property: string | {[key: string]: string}, value?: string): void; + } + + // engine/view/elementdefinition + + type ElementDefinition = string | { + attributes?: {[key: string]: string}; + classes?: string | string[]; + name: string; + priority?: number; + styles?: {[key: string]: string}; + }; + + // engine/view/emptyelement + + class EmptyElement extends Element { + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getFillerOffset(): null; + } + + // engine/view/filler + + const INLINE_FILLER_LENGTH: number; + + const INLINE_FILLER: string; + + function BR_FILLER(): void; + + function NBSP_FILLER(): void; + + function getDataWithoutFiller(domText: Text): string; + + function injectQuirksHandling(view: View): void; + + function isBlockFiller(domNode: /*TODO globals.*/Node, blockFiller: Function): boolean; + + function isInlineFiller(domText: /*TODO globals.*/Text): boolean; + + function startsWithFiller(domNode: /*TODO globals.*/Text): boolean; + + // engine/view/item + + type Item = Node | TextProxy; + + // engine/view/matcher + + class Matcher { + // TODO + } + + type MatcherPattern = + ((element: Element) => null | {name: boolean; attribute?: string[]; }) | + string | + RegExp | + { + attributes?: {[key: string]: string | RegExp | boolean}; + classes?: string | RegExp | Array; + name?: string | RegExp; + styles?: {[key: string]: string | RegExp}; + }; + + // engine/view/node + + class Node { + readonly document: Document | null; + readonly index: number | null; + readonly nextSibling: Node | null; + readonly parent: Element | DocumentFragment | null; + readonly previousSibling: Node | null; + readonly root: Node | DocumentFragment; + + constructor(); + _fireChange(type: ChangeType, node: Node): void; + getAncestors(options: {includeSelf: boolean, parentFirst?: boolean}): Array; + getCommonAncestor(node: Node, options: {includeSelf?: boolean}): Element | DocumentFragment | null; + getPath(): number[]; + + is(type: "element"): this is Element; + is(type: "containerElement"): this is ContainerElement; + is(type: "attributeElement"): this is AttributeElement; + is(type: "emptyElement"): this is EmptyElement; + is(type: "uiElement"): this is UIElement; + is(type: "documentFragment"): this is DocumentFragment; + is(type: "text"): this is Text; + is(type: "textProxy"): this is TextProxy; + is(type: string, name: string): boolean; + + isAfter(node: Node): boolean; + isBefore(node: Node): boolean; + isSimilar(otherElement: Node): boolean; + toJSON(): object; + protected _clone(): Node; + protected _remove(): void; + } + + // engine/view/placeholder + + function attachPlaceholder(view: View, element: Element, placeholderText: string, checkFunction?: Function): void; + + function detachPlaceholder(view: View, element: Element): void; + + // engine/view/position + + class Position { + // TODO + } + + type PositionRelation = "before" | "after" | "same" | "different"; + + // engine/view/range + + class Range { + // TODO + } + + // engine/view/renderer + + class Renderer { + // TODO + } + + // engine/view/rooteditableelement + + class RootEditableElement extends EditableElement { + // TODO + } + + // engine/view/selection + + class Selection { + // TODO + } + + // engine/view/text + + class Text extends Node { + readonly data: string; + protected _data: string; + protected _textData: string; + + protected constructor(data: string); + isSimilar(otherNode: Text): boolean; + protected _clone(): Text; + } + + // engine/view/textproxy + + class TextProxy { + readonly data: string; + readonly document: Document | null; + readonly isPartial: boolean; + readonly offsetInText: number; + readonly offsetSize: number; + readonly parent: Element | DocumentFragment | null; + readonly root: Node | DocumentFragment; + readonly textNode: Text; + + protected constructor(textNode: Text, offsetInText: number, length: number); + getAncestors(options: {includeSelf?: boolean, parentFirst?: boolean}): Array; + is(type: "textProxy"): this is TextProxy; + is(type: string): boolean; + } + + // engine/view/treewalker + + class TreeWalker { + readonly boundaries: Range; + readonly direction: TreeWalkerDirection; + readonly ignoreElementEnd: boolean; + readonly position: Position; + readonly shallow: boolean; + readonly singleCharacters: boolean; + + constructor(options: { + boundaries?: Range, + startPosition?: Position, + direction?: TreeWalkerDirection, + singleCharacters?: boolean, + shallow?: boolean, + ignoreElementEnd?: boolean; + }); + [Symbol.iterator](): Iterator; + next(): TreeWalkerValue; + skip(skip: (treeWalkerValue: TreeWalkerValue) => boolean): void; + } + + type TreeWalkerDirection = "forward" | "backward"; + + interface TreeWalkerValue { + item: Item; + length: number; + nextPosition: Position; + previousPosition: Position; + type: TreeWalkerValueType; + } + + type TreeWalkerValueType = "elementStart" | "elementEnd" | "text"; + + // engine/view/uielement + + class UIElement extends Element { + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getFillerOffset(): null; + render(domDocument: /*TODO: globals.*/Document): HTMLElement; + toDomElement(domDocument: /*TODO: globals.*/Document): HTMLElement; + } + + // engine/view/upcastwriter + + class UpcastWriter { + // TODO + } + + // engine/view/view + + class View implements ckutils.Emitter, ckutils.Observable { + // TODO + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } +} diff --git a/types/ckeditor__ckeditor5-engine/tsconfig.json b/types/ckeditor__ckeditor5-engine/tsconfig.json new file mode 100644 index 0000000000..36da122d77 --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "ckeditor__ckeditor5-engine-tests.ts" + ] +} diff --git a/types/ckeditor__ckeditor5-engine/tslint.json b/types/ckeditor__ckeditor5-engine/tslint.json new file mode 100644 index 0000000000..6a214f0cfd --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/tslint.json @@ -0,0 +1,20 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": { + "options": [ + ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], + ["Number", "Avoid using the `Number` type. Did you mean `number`?"], + ["String", "Avoid using the `String` type. Did you mean `string`?"], + ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] + ] + }, + "no-empty-interface": false, + "quotemark": [ + true, + "double", + "avoid-escape", + "avoid-template" + ] + } +} diff --git a/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts b/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts index 82c272a6ec..19f21f667a 100644 --- a/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts +++ b/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts @@ -489,24 +489,30 @@ utils.mapsEqual(map, map); // utils/mix ================================================================== -class Editor { - b: () => number; -} - interface SomeMixin { a: () => string; } +class Editor implements SomeMixin { + a: () => string; + b() { return 3; } +} + const SomeMixin = { - a() { - return "a"; - } + a() { return "a"; } +}; + +const SomeMixinNum = { + a() { return 3; } }; utils.mix(Editor, SomeMixin); -const mixEditor = new Editor() as Editor & SomeMixin; -mixEditor.a(); -mixEditor.b(); +// $ExpectError +utils.mix(Editor, SomeMixinNum); + +const editor = new Editor(); +str = editor.a(); +num = editor.b(); // utils/nth ================================================================== diff --git a/types/ckeditor__ckeditor5-utils/index.d.ts b/types/ckeditor__ckeditor5-utils/index.d.ts index 8d9d50e889..50571483f8 100644 --- a/types/ckeditor__ckeditor5-utils/index.d.ts +++ b/types/ckeditor__ckeditor5-utils/index.d.ts @@ -367,7 +367,11 @@ export class KeystrokeHandler { destroy(): void; listenTo(emitter: Emitter): void; press(keyEvtData: KeystrokeInfo): boolean; - set(keystroke: string | Array, callback: Function, options?: {priority?: PriorityString | number}): void; + set( + keystroke: string | Array, + callback: (keyEvtData: KeystrokeInfo, cancel: () => void) => void, + options?: {priority?: PriorityString | number} + ): void; } // utils/locale @@ -392,7 +396,7 @@ export function mapsEqual(mapsA: Map, mapsB: Map): boolean; // utils/mix -export function mix(baseClass: {new(): any}, ...mixins: any[]): void; +export function mix(baseClass: {new(...p: any[]): T}, ...mixins: Array>): void; // utils/nth diff --git a/types/clean-regexp/clean-regexp-tests.ts b/types/clean-regexp/clean-regexp-tests.ts new file mode 100644 index 0000000000..e111e4e78e --- /dev/null +++ b/types/clean-regexp/clean-regexp-tests.ts @@ -0,0 +1,12 @@ +import cleanRegexp = require('clean-regexp'); + +// $ExpectType string +cleanRegexp('[0-9]'); +cleanRegexp('[^0-9]'); +cleanRegexp('[a-zA-Z0-9_]'); +cleanRegexp('[a-z0-9_]', 'i'); +cleanRegexp('[^a-zA-Z0-9_]'); +cleanRegexp('[^a-z0-9_]', 'i'); +cleanRegexp('[a-zA-Z\\d_]'); +cleanRegexp('[^a-zA-Z\\d_]'); +cleanRegexp('[0-9]+\\.[a-zA-Z0-9_]?'); diff --git a/types/clean-regexp/index.d.ts b/types/clean-regexp/index.d.ts new file mode 100644 index 0000000000..7418cfd253 --- /dev/null +++ b/types/clean-regexp/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for clean-regexp 1.0 +// Project: https://github.com/samverschueren/clean-regexp#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = cleanRegexp; + +declare function cleanRegexp(regexp: string, flags?: string): string; diff --git a/types/clean-regexp/tsconfig.json b/types/clean-regexp/tsconfig.json new file mode 100644 index 0000000000..e1bbe6de0b --- /dev/null +++ b/types/clean-regexp/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", + "clean-regexp-tests.ts" + ] +} diff --git a/types/clean-regexp/tslint.json b/types/clean-regexp/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clean-regexp/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cli-box/cli-box-tests.ts b/types/cli-box/cli-box-tests.ts new file mode 100644 index 0000000000..a26b436e21 --- /dev/null +++ b/types/cli-box/cli-box-tests.ts @@ -0,0 +1,47 @@ +import Box = require('cli-box'); + +// Create a simple box +const b1: Box = Box("20x10"); +// console.log(b1.toString()); + +// Set custom marks +const b2: Box = new Box({ + w: 10 + , h: 10 + , stringify: false + , marks: { + nw: "╔" + , n: "══" + , ne: "╗" + , e: "║" + , se: "╝" + , s: "══" + , sw: "╚" + , w: "║" + , b: "░░" + } +}); +// console.log(b2.stringify()); + +// Box with text and use the stringify +const b3: Box = Box("20x10", "I will be \u001b[31mdis\u001b[0mplayed inside! \n A\u001b[34mnd I'm in a\u001b[0m new line!"); +// console.log(b3); + +// Box with aligned text to top-right +const b4: Box = Box("30x20", { + text: "Box content" + , stretch: true + , autoEOL: true + , vAlign: "top" + , hAlign: "right" +}); +// console.log(b4); + +// Full screen box +const b5: Box = Box({fullscreen: true, marks: {}}, "Hello World!"); +// console.log(b5.toString()); + +const b5s: string = Box({stringify: true, fullscreen: true, marks: {}}, "Hello World!"); +const b5ns: Box = Box({stringify: false, fullscreen: true, marks: {}}, "Hello World!"); + +const defaults = Box.defaults; diff --git a/types/cli-box/index.d.ts b/types/cli-box/index.d.ts new file mode 100644 index 0000000000..c2466853a6 --- /dev/null +++ b/types/cli-box/index.d.ts @@ -0,0 +1,70 @@ +// Type definitions for cli-box 6.0 +// Project: https://github.com/IonicaBizau/node-cli-box +// Definitions by: Kent Wong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/*~ Note that ES6 modules cannot directly export callable functions. + *~ This file should be imported using the CommonJS-style: + *~ import x = require('someLibrary'); + *~ + *~ Refer to the documentation to understand common + *~ workarounds for this limitation of ES6 modules. + */ + +/*~ This declaration specifies that the function + *~ is the exported object from the file + */ +export = Box; + +type MarksKeys = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'b'; +type Marks = Record; + +interface Options { + w?: number; + width?: number; + h?: number; + height?: number; + fullscreen?: boolean; + stringify?: boolean; + marks?: Partial; +} + +interface Text { + text?: string; + stretch?: boolean; + autoEOL?: boolean; + hAlign?: 'left' | 'middle' | 'right'; + vAlign?: 'top' | 'center' | 'bottom'; +} + +interface Box { + stringify(): string; + settings: { + width: number; + height: number; + marks: Marks; + lines: Array<{ + text: string; + offset: { + y: number; + } + }> + }; + options: { + width: number; + height: number; + marks: Marks; + fullscreen: boolean; + stringify: boolean; + }; +} + +interface BoxConstructor { + new(options: Options | string, text?: Text | string): Box; + (options: (Exclude & { stringify: true }), text?: Text | string): string; + (options: Options | string, text?: Text | string): Box; + defaults: { marks: Marks }; +} + +declare const Box: BoxConstructor; diff --git a/types/cli-box/tsconfig.json b/types/cli-box/tsconfig.json new file mode 100644 index 0000000000..d9a3d38876 --- /dev/null +++ b/types/cli-box/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cli-box-tests.ts" + ] +} diff --git a/types/cli-box/tslint.json b/types/cli-box/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cli-box/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/coinlist/coinlist-tests.ts b/types/coinlist/coinlist-tests.ts new file mode 100644 index 0000000000..17dbbae3df --- /dev/null +++ b/types/coinlist/coinlist-tests.ts @@ -0,0 +1,36 @@ +import coins = require('coinlist'); +import coinsJson = require('coinlist/src/coins.json'); + +// $ExpectType Coin[] & CoinsAPI +coins; + +// $ExpectType Coin[] +coinsJson; + +let coinsArr = [ + { + id: 'bitcoin', + symbol: 'BTC', + name: 'Bitcoin', + }, + { + id: 'litecoin', + symbol: 'LTC', + name: 'Litecoin', + }, +]; + +coinsArr = coins; +coinsArr = coinsJson; + +// $ExpectType Coin | undefined +coins.get('BTC'); + +// $ExpectType string | undefined +coins.get('BTC', 'name'); +// $ExpectType string | undefined +coins.get('BTC', 'symbol'); +// $ExpectType string | undefined +coins.get('BTC', 'id'); + +coins.map(coin => coin.name); diff --git a/types/coinlist/index.d.ts b/types/coinlist/index.d.ts new file mode 100644 index 0000000000..29aaa1dcaa --- /dev/null +++ b/types/coinlist/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for coinlist 3.1 +// Project: https://github.com/lukechilds/coinlist +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import coinsJson = require('./src/coins.json'); + +export = coins; + +declare const coins: coins.Coin[] & coins.CoinsAPI; + +declare namespace coins { + type Coin = coinsJson.Coin; + + interface CoinsAPI { + get(symbol: string): Coin | undefined; + get(symbol: string, property: 'id' | 'symbol' | 'name'): string | undefined; + } +} diff --git a/types/coinlist/src/coins.json.d.ts b/types/coinlist/src/coins.json.d.ts new file mode 100644 index 0000000000..96c947bd8a --- /dev/null +++ b/types/coinlist/src/coins.json.d.ts @@ -0,0 +1,11 @@ +export = coins; + +declare const coins: coins.Coin[]; + +declare namespace coins { + interface Coin { + id: string; + symbol: string; + name: string; + } +} diff --git a/types/coinlist/tsconfig.json b/types/coinlist/tsconfig.json new file mode 100644 index 0000000000..86b93f8380 --- /dev/null +++ b/types/coinlist/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 + }, + "files": [ + "index.d.ts", + "src/coins.json.d.ts", + "coinlist-tests.ts" + ] +} diff --git a/types/coinlist/tslint.json b/types/coinlist/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/coinlist/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/colornames/colornames-tests.ts b/types/colornames/colornames-tests.ts new file mode 100644 index 0000000000..6fc9bb712a --- /dev/null +++ b/types/colornames/colornames-tests.ts @@ -0,0 +1,29 @@ +import colorNames = require("colornames"); + +// $ExpectType Color +const color = colorNames("red"); + +// $ExpectType string +color.value; +// $ExpectType boolean | undefined +color.css; +// $ExpectType boolean | undefined +color.vga; +// $ExpectType string +color.name; + +// $ExpectType Color +colorNames.get("blue"); +// $ExpectType Color[] +colorNames.get.all(); +// $ExpectType Color[] +colorNames.get.css(); +// $ExpectType Color +colorNames.get.css("orange"); +// $ExpectType Color[] +colorNames.get.vga(); +// $ExpectType Color +colorNames.get.vga("violet"); + +// $ExpectType Color[] +colorNames.all(); diff --git a/types/colornames/index.d.ts b/types/colornames/index.d.ts new file mode 100644 index 0000000000..d9b331167b --- /dev/null +++ b/types/colornames/index.d.ts @@ -0,0 +1,93 @@ +// Type definitions for colornames 1.1 +// Project: https://github.com/timoxley/colornames#readme +// Definitions by: Manuel Thalmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Represents a color. + */ +interface Color { + /** + * Gets the value of the color. + */ + value: string; + + /** + * Gets a value indicating whether the color is a valid `CSS`-color. + */ + css?: boolean; + + /** + * Gets a value indicating whether the color is a valid `VGA`-color. + */ + vga?: boolean; + + /** + * Gets the name of the color. + */ + name: string; +} + +/** + * Povides the functionality to resolve colors of a specific type by its name. + */ +interface ColorResolver { + /** + * Gets the color with the specified name. + * + * @param name + * The name of the color to get. + */ + (name: string): Color; + + /** + * Gets all colors. + */ + (): Color[]; +} + +/** + * Provides the functionality to resolve any kind of color by its name. + */ +interface GlobalResolver { + /** + * Gets the color with the specified name. + */ + (name: string): Color; + + /** + * Provides the functionality to query colors. + */ + get: { + /** + * Gets the color with the specified name. + * + * @param name + * The name of the color to get. + */ + (name: string): Color; + + /** + * Gets all available colors. + */ + all(): Color[]; + + /** + * Provides the functionality to resolve `css`-colors. + */ + css: ColorResolver; + + /** + * Provides the functionality to resolve `vga`-colors. + */ + vga: ColorResolver; + }; + + /** + * Gets all available colors. + */ + all(): Color[]; +} + +declare let colorNames: GlobalResolver; +export = colorNames; diff --git a/types/colornames/tsconfig.json b/types/colornames/tsconfig.json new file mode 100644 index 0000000000..b494da59cd --- /dev/null +++ b/types/colornames/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", + "colornames-tests.ts" + ] +} diff --git a/types/colornames/tslint.json b/types/colornames/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/colornames/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/command-exists/command-exists-tests.ts b/types/command-exists/command-exists-tests.ts new file mode 100644 index 0000000000..60efc1e0e5 --- /dev/null +++ b/types/command-exists/command-exists-tests.ts @@ -0,0 +1,14 @@ +import commandExists = require('command-exists'); + +commandExists('ls', (err, commandExists) => { + // $ExpectType boolean + commandExists; +}); + +commandExists('ls').then(command => { + // $ExpectType string + command; +}); + +// $ExpectType boolean +commandExists.sync('ls'); diff --git a/types/command-exists/index.d.ts b/types/command-exists/index.d.ts new file mode 100644 index 0000000000..634d2a035e --- /dev/null +++ b/types/command-exists/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for command-exists 1.2 +// Project: https://github.com/mathisonian/command-exists +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = commandExists; + +declare function commandExists(commandName: string): Promise; +declare function commandExists( + commandName: string, + cb: (error: null, exists: boolean) => void +): void; + +declare namespace commandExists { + function sync(commandName: string): boolean; +} diff --git a/types/command-exists/tsconfig.json b/types/command-exists/tsconfig.json new file mode 100644 index 0000000000..9782cd2715 --- /dev/null +++ b/types/command-exists/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", + "command-exists-tests.ts" + ] +} diff --git a/types/command-exists/tslint.json b/types/command-exists/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/command-exists/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/common-tags/common-tags-tests.ts b/types/common-tags/common-tags-tests.ts index e504624943..37a1fba789 100644 --- a/types/common-tags/common-tags-tests.ts +++ b/types/common-tags/common-tags-tests.ts @@ -1,167 +1,242 @@ -import * as commonTags from 'common-tags'; +import { + html, + safeHtml, + oneLine, + oneLineTrim, + stripIndent, + stripIndents, + inlineLists, + oneLineInlineLists, + commaLists, + commaListsOr, + commaListsAnd, + oneLineCommaLists, + oneLineCommaListsOr, + oneLineCommaListsAnd, + id, + TemplateTag, + trimResultTransformer, + stripIndentTransformer, + replaceResultTransformer, + replaceSubstitutionTransformer, + inlineArrayTransformer, + splitStringTransformer, + createTag, + TemplateTransformer, + replaceStringTransformer, +} from 'common-tags'; -/* Test Built-in Tags */ - -commonTags.commaLists ` - I like ${['apples', 'bananas', 'watermelons']} - They're good! +const userMessages = ['hi', 'what are you up to?', '']; +html` +

+
    + ${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/compression-webpack-plugin/compression-webpack-plugin-tests.ts b/types/compression-webpack-plugin/compression-webpack-plugin-tests.ts index 423ca4cea7..a679b7f599 100644 --- a/types/compression-webpack-plugin/compression-webpack-plugin-tests.ts +++ b/types/compression-webpack-plugin/compression-webpack-plugin-tests.ts @@ -1,15 +1,76 @@ import { Configuration } from 'webpack'; import CompressionPlugin = require('compression-webpack-plugin'); -const c: Configuration = { +new CompressionPlugin(); + +new CompressionPlugin({ + include: ["a"] as ReadonlyArray, + exclude: [/a/g] as ReadonlyArray, + test: "a", +}); + +const config: Configuration = { plugins: [ new CompressionPlugin({ - asset: "[path].gz[query]", algorithm: "gzip", cache: true, + filename: "[path].gz[query]", + minRatio: 0.8, test: /\.js$|\.html$/, threshold: 10240, - minRatio: 0.8 + deleteOriginalAssets: true + }) + ] +}; + +const configDefaultAlgo = new CompressionPlugin({ + compressionOptions: { level: 7 } +}); + +// $ExpectError +new CompressionPlugin({ asset: "[path].gz[query]" }); + +const zlib: Configuration = { + plugins: [ + new CompressionPlugin({ + algorithm: "deflate", + compressionOptions: { + flush: 5, + windowBits: 20, + level: 7 + } + }) + ] +}; + +const badZlib: Configuration = { + plugins: [ + // $ExpectError + new CompressionPlugin({ + algorithm: "deflate", + compressionOptions: 5 + }) + ] +}; + +function customAlgorithm(input: string, options: number, callback: (err: Error, result: Buffer) => void) { +} + +const custom: Configuration = { + plugins: [ + new CompressionPlugin({ + algorithm: customAlgorithm, + compressionOptions: 5 + }) + ] +}; + +const badCustom: Configuration = { + plugins: [ + // $ExpectError + new CompressionPlugin({ + algorithm: customAlgorithm, + compressionOptions: { flush: 5 } }) ] }; diff --git a/types/compression-webpack-plugin/index.d.ts b/types/compression-webpack-plugin/index.d.ts index a7b38383ef..5d72f1fca8 100644 --- a/types/compression-webpack-plugin/index.d.ts +++ b/types/compression-webpack-plugin/index.d.ts @@ -1,42 +1,47 @@ -// Type definitions for compression-webpack-plugin 0.4 +// Type definitions for compression-webpack-plugin 2.0 // Project: https://github.com/webpack-contrib/compression-webpack-plugin // Definitions by: Anton Kandybo +// Rhys van der Waerden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import { Plugin } from 'webpack'; +import { ZlibOptions as ZlibCompressionOptions } from 'zlib'; export = CompressionPlugin; -declare class CompressionPlugin extends Plugin { - constructor(options?: CompressionPlugin.Options); +declare class CompressionPlugin extends Plugin { + constructor(options?: CompressionPlugin.Options); } declare namespace CompressionPlugin { - interface Options { - asset?: string; - algorithm?: string; + type AlgorithmCallback = (error: Error | null, result: Buffer) => void; + type Algorithm = (source: string, options: O, callback: AlgorithmCallback) => void; + + // NOTE: These are the async compression algorithms on the zlib object. + type ZlibAlgorithm = 'deflate' | 'deflateRaw' | 'gzip'; + type Pattern = string | RegExp | ReadonlyArray | ReadonlyArray; + + interface BaseOptions { cache?: boolean | string; - test?: RegExp | RegExp[]; - regExp?: RegExp | RegExp[]; - threshold?: number; + deleteOriginalAssets?: boolean; + exclude?: Pattern; + filename?: string; + include?: Pattern; minRatio?: number; - - // zopfli options - verbose?: boolean; - verbose_more?: boolean; - numiterations?: number; - blocksplitting?: boolean; - blocksplittinglast?: boolean; - blocksplittingmax?: number; - - // zlib options - level?: number; - flush?: number; - chunkSize?: number; - windowBits?: number; - memLevel?: number; - strategy?: number; - dictionary?: any; + test?: Pattern; + threshold?: number; } + + interface ZlibOptions extends BaseOptions { + algorithm?: ZlibAlgorithm; + compressionOptions?: ZlibCompressionOptions; + } + + interface CustomOptions extends BaseOptions { + algorithm: Algorithm; + compressionOptions?: O; + } + + type Options = ZlibOptions | CustomOptions; } diff --git a/types/conf/conf-tests.ts b/types/conf/conf-tests.ts index 1da0e4de2d..ce67cd4799 100644 --- a/types/conf/conf-tests.ts +++ b/types/conf/conf-tests.ts @@ -4,18 +4,24 @@ const conf = new Conf(); new Conf({ defaults: { foo: 'bar', - unicorn: 'rainbow' + unicorn: 'rainbow', }, - configName: '', - projectName: 'foo', - cwd: '' }); +new Conf({ configName: '' }); +new Conf({ projectName: 'foo' }); +new Conf({ cwd: '' }); +new Conf({ encryptionKey: '' }); +new Conf({ encryptionKey: new Buffer('') }); +new Conf({ encryptionKey: new Uint8Array([1]) }); +new Conf({ encryptionKey: new DataView(new ArrayBuffer(2)) }); +new Conf({ fileExtension: '.foo' }); + // $ExpectError new Conf({ defaults: { foo: 'bar', - unicorn: ['rainbow'] - } + unicorn: ['rainbow'], + }, }); conf.set('foo', 'bar'); conf.set('hello', 1); @@ -28,10 +34,17 @@ conf.get('foo', null); // $ExpectError conf.delete('foo'); conf.has('foo'); // $ExpectType boolean conf.clear(); +conf.onDidChange('foo', (oldVal, newVal) => { + // $ExpectType string | number | boolean | undefined + oldVal; + // $ExpectType string | number | boolean | undefined + newVal; +}); +conf.size; // $ExpectType number conf.store = { foo: 'bar', - unicorn: 'rainbow' + unicorn: 'rainbow', }; conf.path; // $ExpectType string diff --git a/types/conf/index.d.ts b/types/conf/index.d.ts index e58dc3ede7..57d7285a3e 100644 --- a/types/conf/index.d.ts +++ b/types/conf/index.d.ts @@ -1,31 +1,37 @@ -// Type definitions for conf 1.4 +// Type definitions for conf 2.1 // Project: https://github.com/sindresorhus/conf // Definitions by: Sam Verschueren // BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -interface Options { - defaults?: {[key: string]: T}; - configName?: string; - projectName?: string; - cwd?: string; -} +/// declare class Conf implements Iterable<[string, T]> { - store: {[key: string]: T}; + store: { [key: string]: T }; readonly path: string; - readonly size: number; + readonly size: number; - constructor(options?: Options); - get(key: string, defaultValue?: T): T; - set(key: string, val: T): void; - set(object: {[key: string]: T}): void; - has(key: string): boolean; - delete(key: string): void; - clear(): void; - onDidChange(key: string, callback: (oldVal: any, newVal: any) => void): void; - [Symbol.iterator](): Iterator<[string, T]>; + constructor(options?: Conf.Options); + get(key: string, defaultValue?: T): T; + set(key: string, val: T): void; + set(object: { [key: string]: T }): void; + has(key: string): boolean; + delete(key: string): void; + clear(): void; + onDidChange(key: string, callback: (oldVal: T | undefined, newVal: T | undefined) => void): void; + [Symbol.iterator](): Iterator<[string, T]>; +} + +declare namespace Conf { + interface Options { + defaults?: { [key: string]: T }; + configName?: string; + projectName?: string; + cwd?: string; + encryptionKey?: string | Buffer | NodeJS.TypedArray | DataView; + fileExtension?: string; + } } export = Conf; diff --git a/types/conf/tsconfig.json b/types/conf/tsconfig.json index 84d6bf7657..479fa6b41f 100644 --- a/types/conf/tsconfig.json +++ b/types/conf/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "conf-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/conf/v1/conf-tests.ts b/types/conf/v1/conf-tests.ts new file mode 100644 index 0000000000..4ee492da8d --- /dev/null +++ b/types/conf/v1/conf-tests.ts @@ -0,0 +1,41 @@ +import Conf = require('conf'); + +const conf = new Conf(); +new Conf({ + defaults: { + foo: 'bar', + unicorn: 'rainbow', + }, + configName: '', + projectName: 'foo', + cwd: '', +}); +// $ExpectError +new Conf({ + defaults: { + foo: 'bar', + unicorn: ['rainbow'], + }, +}); +conf.set('foo', 'bar'); +conf.set('hello', 1); +conf.set('unicorn', false); +conf.set('null', null); // $ExpectError + +conf.get('foo'); // $ExpectType string | number | boolean +conf.get('foo', 'bar'); // $ExpectType string | number | boolean +conf.get('foo', null); // $ExpectError +conf.delete('foo'); +conf.has('foo'); // $ExpectType boolean +conf.clear(); + +conf.store = { + foo: 'bar', + unicorn: 'rainbow', +}; +conf.path; // $ExpectType string + +for (const [key, value] of conf) { + key; // $ExpectType string + value; // $ExpectType string | number | boolean +} diff --git a/types/conf/v1/index.d.ts b/types/conf/v1/index.d.ts new file mode 100644 index 0000000000..f08cff1584 --- /dev/null +++ b/types/conf/v1/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for conf 1.4 +// Project: https://github.com/sindresorhus/conf +// Definitions by: Sam Verschueren +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +interface Options { + defaults?: { [key: string]: T }; + configName?: string; + projectName?: string; + cwd?: string; +} + +declare class Conf implements Iterable<[string, T]> { + store: { [key: string]: T }; + readonly path: string; + readonly size: number; + + constructor(options?: Options); + get(key: string, defaultValue?: T): T; + set(key: string, val: T): void; + set(object: { [key: string]: T }): void; + has(key: string): boolean; + delete(key: string): void; + clear(): void; + onDidChange(key: string, callback: (oldVal: any, newVal: any) => void): void; + [Symbol.iterator](): Iterator<[string, T]>; +} + +export = Conf; diff --git a/types/conf/v1/tsconfig.json b/types/conf/v1/tsconfig.json new file mode 100644 index 0000000000..86b3a62f41 --- /dev/null +++ b/types/conf/v1/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "conf": [ + "conf/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "conf-tests.ts" + ] +} diff --git a/types/conf/v1/tslint.json b/types/conf/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/conf/v1/tslint.json @@ -0,0 +1 @@ +{ "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/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/create-html-element/create-html-element-tests.ts b/types/create-html-element/create-html-element-tests.ts new file mode 100644 index 0000000000..e94b6cb617 --- /dev/null +++ b/types/create-html-element/create-html-element-tests.ts @@ -0,0 +1,48 @@ +import createHtmlElement = require('create-html-element'); + +createHtmlElement(); // $ExpectType HTMLDivElement +// $ExpectType HTMLDivElement +createHtmlElement({ + attributes: { + class: 'unicorn', + rainbow: true, + horse: false, + number: 1, + multiple: ['a', 'b'], + }, +}); +createHtmlElement({ html: '🦄' }); // $ExpectType HTMLDivElement +createHtmlElement({ text: 'Hello World' }); // $ExpectType HTMLDivElement +createHtmlElement({ html: '🦄', text: 'Hello World' }); // $ExpectError + +createHtmlElement({ name: 'h1' }); // $ExpectType HTMLHeadingElement +// $ExpectType HTMLHeadingElement +createHtmlElement({ + name: 'h1', + attributes: { + class: 'unicorn', + rainbow: true, + horse: false, + number: 1, + multiple: ['a', 'b'], + }, +}); +createHtmlElement({ name: 'h1', html: '🦄' }); // $ExpectType HTMLHeadingElement +createHtmlElement({ name: 'h1', text: 'Hello World' }); // $ExpectType HTMLHeadingElement +createHtmlElement({ name: 'h1', html: '🦄', text: 'Hello World' }); // $ExpectError + +createHtmlElement({ name: 'foo' }); // $ExpectType HTMLElement +// $ExpectType HTMLElement +createHtmlElement({ + name: 'foo', + attributes: { + class: 'unicorn', + rainbow: true, + horse: false, + number: 1, + multiple: ['a', 'b'], + }, +}); +createHtmlElement({ name: 'foo', html: '🦄' }); // $ExpectType HTMLElement +createHtmlElement({ name: 'foo', text: 'Hello World' }); // $ExpectType HTMLElement +createHtmlElement({ name: 'foo', html: '🦄', text: 'Hello World' }); // $ExpectError diff --git a/types/create-html-element/index.d.ts b/types/create-html-element/index.d.ts new file mode 100644 index 0000000000..86fd758b3e --- /dev/null +++ b/types/create-html-element/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for create-html-element 2.0 +// Project: https://github.com/sindresorhus/create-html-element#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export = createHtmlElement; + +declare function createHtmlElement( + options?: createHtmlElement.OptionsWithoutTagName +): HTMLDivElement; +declare function createHtmlElement( + options: createHtmlElement.Options +): HTMLElementTagNameMap[K]; +declare function createHtmlElement(options: createHtmlElement.Options): HTMLElement; + +declare namespace createHtmlElement { + type Without = { [P in Exclude]?: never }; + type XOR = (T | U) extends object ? (Without & U) | (Without & T) : T | U; + + interface AttributesOptions { + attributes?: { [key: string]: string | boolean | number | string[] }; + } + + interface HtmlOptions { + html?: string; + } + + interface TextOptions { + text?: string; + } + + type OptionsWithoutTagName = AttributesOptions & XOR; + + interface OptionsWithTagName extends AttributesOptions { + name: K; + } + + type Options = OptionsWithTagName & XOR; +} diff --git a/types/create-html-element/package.json b/types/create-html-element/package.json new file mode 100644 index 0000000000..bb80441dc0 --- /dev/null +++ b/types/create-html-element/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] } + } +} diff --git a/types/create-html-element/ts3.1/create-html-element-tests.ts b/types/create-html-element/ts3.1/create-html-element-tests.ts new file mode 100644 index 0000000000..6d44f3df60 --- /dev/null +++ b/types/create-html-element/ts3.1/create-html-element-tests.ts @@ -0,0 +1,64 @@ +import createHtmlElement = require('create-html-element'); + +createHtmlElement(); // $ExpectType HTMLDivElement +// $ExpectType HTMLDivElement +createHtmlElement({ + attributes: { + class: 'unicorn', + rainbow: true, + horse: false, + number: 1, + multiple: ['a', 'b'], + }, +}); +createHtmlElement({ html: '🦄' }); // $ExpectType HTMLDivElement +createHtmlElement({ text: 'Hello World' }); // $ExpectType HTMLDivElement +createHtmlElement({ html: '🦄', text: 'Hello World' }); // $ExpectError + +createHtmlElement({ name: 'h1' }); // $ExpectType HTMLHeadingElement +// $ExpectType HTMLHeadingElement +createHtmlElement({ + name: 'h1', + attributes: { + class: 'unicorn', + rainbow: true, + horse: false, + number: 1, + multiple: ['a', 'b'], + }, +}); +createHtmlElement({ name: 'h1', html: '🦄' }); // $ExpectType HTMLHeadingElement +createHtmlElement({ name: 'h1', text: 'Hello World' }); // $ExpectType HTMLHeadingElement +createHtmlElement({ name: 'h1', html: '🦄', text: 'Hello World' }); // $ExpectError + +createHtmlElement({ name: 'listing' }); // $ExpectType HTMLPreElement +// $ExpectType HTMLPreElement +createHtmlElement({ + name: 'listing', + attributes: { + class: 'unicorn', + rainbow: true, + horse: false, + number: 1, + multiple: ['a', 'b'], + }, +}); +createHtmlElement({ name: 'listing', html: '🦄' }); // $ExpectType HTMLPreElement +createHtmlElement({ name: 'listing', text: 'Hello World' }); // $ExpectType HTMLPreElement +createHtmlElement({ name: 'listing', html: '🦄', text: 'Hello World' }); // $ExpectError + +createHtmlElement({ name: 'foo' }); // $ExpectType HTMLElement +// $ExpectType HTMLElement +createHtmlElement({ + name: 'foo', + attributes: { + class: 'unicorn', + rainbow: true, + horse: false, + number: 1, + multiple: ['a', 'b'], + }, +}); +createHtmlElement({ name: 'foo', html: '🦄' }); // $ExpectType HTMLElement +createHtmlElement({ name: 'foo', text: 'Hello World' }); // $ExpectType HTMLElement +createHtmlElement({ name: 'foo', html: '🦄', text: 'Hello World' }); // $ExpectError diff --git a/types/create-html-element/ts3.1/index.d.ts b/types/create-html-element/ts3.1/index.d.ts new file mode 100644 index 0000000000..113f9ba588 --- /dev/null +++ b/types/create-html-element/ts3.1/index.d.ts @@ -0,0 +1,38 @@ +export = createHtmlElement; + +declare function createHtmlElement( + options?: createHtmlElement.OptionsWithoutTagName +): HTMLDivElement; +declare function createHtmlElement( + options: createHtmlElement.Options +): HTMLElementTagNameMap[K]; +/** @deprecated */ +declare function createHtmlElement( + options: createHtmlElement.Options +): HTMLElementDeprecatedTagNameMap[K]; +declare function createHtmlElement(options: createHtmlElement.Options): HTMLElement; + +declare namespace createHtmlElement { + type Without = { [P in Exclude]?: never }; + type XOR = (T | U) extends object ? (Without & U) | (Without & T) : T | U; + + interface AttributesOptions { + attributes?: { [key: string]: string | boolean | number | string[] }; + } + + interface HtmlOptions { + html?: string; + } + + interface TextOptions { + text?: string; + } + + type OptionsWithoutTagName = AttributesOptions & XOR; + + interface OptionsWithTagName extends AttributesOptions { + name: K; + } + + type Options = OptionsWithTagName & XOR; +} diff --git a/types/create-html-element/ts3.1/tsconfig.json b/types/create-html-element/ts3.1/tsconfig.json new file mode 100644 index 0000000000..6c82d9de10 --- /dev/null +++ b/types/create-html-element/ts3.1/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "create-html-element-tests.ts" + ] +} diff --git a/types/create-html-element/ts3.1/tslint.json b/types/create-html-element/ts3.1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-html-element/ts3.1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/create-html-element/tsconfig.json b/types/create-html-element/tsconfig.json new file mode 100644 index 0000000000..44a7146986 --- /dev/null +++ b/types/create-html-element/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "create-html-element-tests.ts" + ] +} diff --git a/types/create-html-element/tslint.json b/types/create-html-element/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-html-element/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/cycled/cycled-tests.ts b/types/cycled/cycled-tests.ts new file mode 100644 index 0000000000..f5945be629 --- /dev/null +++ b/types/cycled/cycled-tests.ts @@ -0,0 +1,53 @@ +import Cycled = require('cycled'); + +const cycled = new Cycled([1, 2, 3]); +// $ExpectType Cycled +cycled; + +// $ExpectType number +cycled.index; +cycled.index = 1; + +// $ExpectType number +cycled.current(); + +// $ExpectType number +cycled.next(); + +// $ExpectType number +cycled.previous(); + +// $ExpectType number +cycled.step(10); + +// $ExpectType Iterator +cycled.indefinitely(); + +// $ExpectType Iterator +cycled.indefinitelyReversed(); + +// $ExpectType number[] +[...cycled]; + +class TabComponent { + views: Cycled; + activeView: string; + + constructor(views: string[]) { + this.activeView = views[0]; + this.views = new Cycled(views); + } + + setActiveView(view: string) { + this.activeView = view; + this.views.index = this.views.indexOf(view); + } + + nextView() { + this.setActiveView(this.views.next()); + } + + previousView() { + this.setActiveView(this.views.previous()); + } +} diff --git a/types/cycled/index.d.ts b/types/cycled/index.d.ts new file mode 100644 index 0000000000..a0940934b8 --- /dev/null +++ b/types/cycled/index.d.ts @@ -0,0 +1,58 @@ +// Type definitions for cycled 1.0 +// Project: https://github.com/sindresorhus/cycled#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Cycled; + +// tslint:disable:jsdoc-format +declare class Cycled extends Array { + /** + * Initiates an array subclass with the methods documented below. + * Since it's an array, you can use all the normal array methods on it. + * + * The instance is an iterable that will cycle through the array. + * It will cycle through the number of elements equaling the length of the array from the current index. + * ``` +const numberCycle = new Cycled([1,2,3,4,5]); + +console.log(...numberCycle); +//=> 1 2 3 4 5 +``` + * + * @param input + */ + constructor(input: T[]); + + /** + * Get or set the current index. + */ + index: number; + + /** + * Returns the current item. + */ + current(): T; + /** + * Returns the next item. + */ + next(): T; + /** + * Returns the previous item. + */ + previous(): T; + /** + * Returns the item by going the given amount of `steps` through the array. + * For example, calling `step(2)` is like calling `next()` twice. You go backward by specifying a negative number. + * @param steps + */ + step(steps: number): T; + /** + * Returns an iterable that will cycle through the array indefinitely. + */ + indefinitely(): Iterator; + /** + * Returns an iterable that will cycle through the array backward indefinitely. + */ + indefinitelyReversed(): Iterator; +} diff --git a/types/cycled/tsconfig.json b/types/cycled/tsconfig.json new file mode 100644 index 0000000000..a8fb15e11e --- /dev/null +++ b/types/cycled/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", + "cycled-tests.ts" + ] +} diff --git a/types/cycled/tslint.json b/types/cycled/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cycled/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/d/auto-bind.d.ts b/types/d/auto-bind.d.ts new file mode 100644 index 0000000000..f52f8a955d --- /dev/null +++ b/types/d/auto-bind.d.ts @@ -0,0 +1,13 @@ +export = autoBind; + +declare function autoBind( + obj: { [key: string]: PropertyDescriptor }, + options?: autoBind.Options +): PropertyDescriptorMap; + +declare namespace autoBind { + interface Options { + overwriteDefinition?: boolean; + resolveContext?: (context: any) => any; + } +} diff --git a/types/d/d-tests.ts b/types/d/d-tests.ts new file mode 100644 index 0000000000..e08582cf0e --- /dev/null +++ b/types/d/d-tests.ts @@ -0,0 +1,85 @@ +import d = require('d'); +import autoBind = require('d/auto-bind'); +import lazy = require('d/lazy'); + +class Account {} +Object.defineProperties(Account.prototype, { + deposit: d(() => {}), + withdraw: d(() => {}), + balance: d.gs(() => {}), +}); + +d('foo'); // $ExpectType PropertyDescriptor +d('foo', { enumerable: true }); // $ExpectType PropertyDescriptor +d('c', 'foo'); // $ExpectType PropertyDescriptor +d('c', 'foo', { enumerable: true }); // $ExpectType PropertyDescriptor + +d('c', 'foo'); // $ExpectType PropertyDescriptor +d('e', 'foo'); // $ExpectType PropertyDescriptor +d('w', 'foo'); // $ExpectType PropertyDescriptor +d('ce', 'foo'); // $ExpectType PropertyDescriptor +d('cw', 'foo'); // $ExpectType PropertyDescriptor +d('ew', 'foo'); // $ExpectType PropertyDescriptor +d('cew', 'foo'); // $ExpectType PropertyDescriptor +d('foo', 'foo'); // $ExpectError + +d.gs('c', { enumerable: true }); // $ExpectType PropertyDescriptor +d.gs('c', () => ({}), { enumerable: true }); // $ExpectType PropertyDescriptor +d.gs(() => ({})); // $ExpectType PropertyDescriptor +d.gs(null, () => ({})); // $ExpectType PropertyDescriptor +d.gs(undefined, () => ({})); // $ExpectType PropertyDescriptor +d.gs('c', () => ({})); // $ExpectType PropertyDescriptor +d.gs('c', null, () => ({})); // $ExpectType PropertyDescriptor +d.gs('c', undefined, () => ({})); // $ExpectType PropertyDescriptor +d.gs('c', null, () => ({}), { enumerable: true }); // $ExpectType PropertyDescriptor +d.gs('c', undefined, () => ({}), { enumerable: true }); // $ExpectType PropertyDescriptor + +d.gs('c', () => ({})); // $ExpectType PropertyDescriptor +d.gs('e', () => ({})); // $ExpectType PropertyDescriptor +d.gs('ce', () => ({})); // $ExpectType PropertyDescriptor +d.gs('cew', () => ({})); // $ExpectError + +class Foo { + _count: number; +} + +Object.defineProperties( + Foo.prototype, + autoBind({ + increment: d(function(this: any) { + ++this._count; + }), + }) +); +autoBind( + { + increment: d(function(this: any) { + ++this._count; + }), + }, + { overwriteDefinition: true } +); +autoBind( + { + increment: d(function(this: any) { + ++this._count; + }), + }, + { + resolveContext(ctx: any) { + return ctx; + }, + } +); + +Object.defineProperties( + Foo.prototype, + lazy({ + items: d(() => { + return []; + }), + }) +); + +const foo = new Foo(); +(foo as any).items.push(1, 2); // foo.items array created and defined directly on foo diff --git a/types/d/index.d.ts b/types/d/index.d.ts new file mode 100644 index 0000000000..9130000999 --- /dev/null +++ b/types/d/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for d 1.0 +// Project: https://github.com/medikoo/d#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export = d; + +declare function d(value: any, options?: PropertyDescriptor): PropertyDescriptor; +declare function d(flags: d.Flags, value: any, options?: PropertyDescriptor): PropertyDescriptor; + +declare namespace d { + function gs(flags: GetSetFlags, options: PropertyDescriptor): PropertyDescriptor; + function gs(flags: GetSetFlags, get: (...args: any[]) => any, options: PropertyDescriptor): PropertyDescriptor; + function gs( + get: (...args: any[]) => any, + set?: ((...args: any[]) => any) | null, + options?: PropertyDescriptor + ): PropertyDescriptor; + function gs( + get: ((...args: any[]) => any) | null | undefined, + set: (...args: any[]) => any, + options?: PropertyDescriptor + ): PropertyDescriptor; + function gs( + flags: GetSetFlags, + get: (...args: any[]) => any, + set?: ((...args: any[]) => any) | null, + options?: PropertyDescriptor + ): PropertyDescriptor; + function gs( + flags: GetSetFlags, + get: ((...args: any[]) => any) | null | undefined, + set: (...args: any[]) => any, + options?: PropertyDescriptor + ): PropertyDescriptor; + + type GetSetFlags = 'c' | 'e' | 'ce'; + type Flags = GetSetFlags | 'w' | 'cw' | 'ew' | 'cew'; +} diff --git a/types/d/lazy.d.ts b/types/d/lazy.d.ts new file mode 100644 index 0000000000..3cba797050 --- /dev/null +++ b/types/d/lazy.d.ts @@ -0,0 +1,3 @@ +export = lazy; + +declare function lazy(obj: { [key: string]: PropertyDescriptor }): PropertyDescriptorMap; diff --git a/types/d/tsconfig.json b/types/d/tsconfig.json new file mode 100644 index 0000000000..26c1a65f3e --- /dev/null +++ b/types/d/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "auto-bind.d.ts", + "lazy.d.ts", + "d-tests.ts" + ] +} diff --git a/types/d/tslint.json b/types/d/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/d/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-hierarchy/d3-hierarchy-tests.ts b/types/d3-hierarchy/d3-hierarchy-tests.ts index 16b372993d..b5982a4d5f 100644 --- a/types/d3-hierarchy/d3-hierarchy-tests.ts +++ b/types/d3-hierarchy/d3-hierarchy-tests.ts @@ -12,6 +12,7 @@ import * as d3Hierarchy from 'd3-hierarchy'; // Preparatory Steps // ----------------------------------------------------------------------- +let str: string; let num: number; let numOrUndefined: number | undefined; let size: [number, number]; @@ -825,22 +826,34 @@ copiedPackNode = packRootNode.copy(); // Pack Siblings and Enclosure // ----------------------------------------------------------------------- -interface CircleData extends d3Hierarchy.PackCircle { - v: string; -} - -let circles: CircleData[] = [ +const radius = [ { r: 10, v: 'a' }, - { r: 1, v: 'b' }, + { r: 30, v: 'b' }, { r: 20, v: 'c' } ]; // packSiblings -circles = d3Hierarchy.packSiblings(circles); +const circles = d3Hierarchy.packSiblings(radius); +str = circles[0].v; +num = circles[0].r; +num = circles[0].x; +num = circles[0].y; // packEnclose -let enclosure: { r: number, x: number, y: number }; +const moreCircles = [ + { r: 10, v: 'a', x: 0, y: 10 }, + { r: 30, v: 'b', x: 5, y: 15 }, + { r: 20, v: 'c', x: 7, y: 30 } +]; -enclosure = d3Hierarchy.packEnclose(circles); +const circle = d3Hierarchy.packEnclose(moreCircles); +num = circle.r; +num = circle.x; +num = circle.y; +// $ExpectError +str = circle.v; // fails, property 'v' does not exist + +// $ExpectError +d3Hierarchy.packEnclose(radius); diff --git a/types/d3-hierarchy/index.d.ts b/types/d3-hierarchy/index.d.ts index 0ec823cc78..fb5ebd5656 100644 --- a/types/d3-hierarchy/index.d.ts +++ b/types/d3-hierarchy/index.d.ts @@ -802,7 +802,7 @@ export function pack(): PackLayout; // Pack Siblings and Enclosure // ----------------------------------------------------------------------- -export interface PackCircle { +export interface PackRadius { /** * The radius of the circle. */ @@ -819,10 +819,25 @@ export interface PackCircle { y?: number; } +export interface PackCircle { + /** + * The radius of the circle. + */ + r: number; + + /** + * The x-coordinate of the circle’s center. + */ + x: number; + + /** + * The y-coordinate of the circle’s center. + */ + y: number; +} + // TODO: Since packSiblings manipulates the circles array in place, technically the x and y properties // are optional on invocation, but will be created after execution for each entry. -// For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment -// on the mandatory nature, then to create separate interfaces and having to deal with recasting. /** * Packs the specified array of circles, each of which must have a `circle.r` property specifying the circle’s radius. @@ -830,7 +845,7 @@ export interface PackCircle { * * @param circles The specified array of circles to pack. */ -export function packSiblings(circles: Datum[]): Datum[]; +export function packSiblings(circles: Datum[]): Array; /** * Computes the smallest circle that encloses the specified array of circles, each of which must have @@ -839,4 +854,4 @@ export function packSiblings(circles: Datum[]): Datum[ * * @param circles The specified array of circles to pack. */ -export function packEnclose(circles: Datum[]): { r: number, x: number, y: number }; +export function packEnclose(circles: Datum[]): PackCircle; 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..42393b9e82 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -9,7 +9,7 @@ import * as d3Zoom from 'd3-zoom'; import { ArrayLike, select, Selection, event } from 'd3-selection'; import { Transition } from 'd3-transition'; -import { scaleLinear, ScaleLinear } from 'd3-scale'; +import { scaleLinear, ScaleLinear, ScaleTime, scaleTime } from 'd3-scale'; import { interpolateZoom, interpolate, interpolateArray, ZoomInterpolator, ZoomView } from 'd3-interpolate'; // -------------------------------------------------------------------------- @@ -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; @@ -248,15 +248,15 @@ let zoomInterpolatorFactory: (a: ZoomView, b: ZoomView) => ZoomInterpolator; // Basic case without casting basicInterpolatorFactory = svgZoom.interpolate(); -// Assuming it is know that a specialized interpolation factory was used. E.g. ZoomInterpolator also has a duration -// argument +// Assuming it is know that a specialized interpolation factory was used. E.g. ZoomInterpolator also has a duration argument zoomInterpolatorFactory = svgZoom.interpolate<(a: ZoomView, b: ZoomView) => ZoomInterpolator>(); // on() -------------------------------------------------------------------- // chainable svgZoom = svgZoom.on('zoom', zoomedSVGOverlay); -// svgZoom = svgZoom.on('zoom', zoomedCanvas); // fails, zoom event handler has wrong this and datum type +// $ExpectError +svgZoom = svgZoom.on('zoom', zoomedCanvas); // fails, zoom event handler has wrong this and datum type let zoomHandler: ((this: SVGRectElement, datum: SVGDatum, index: number, group: SVGRectElement[] | ArrayLike) => void) | undefined; zoomHandler = svgZoom.on('zoom'); @@ -297,7 +297,8 @@ const svgOverlayTransition = svgOverlay.transition(); // use on selection svgZoom.transform(svgOverlay, d3Zoom.zoomIdentity); -// svgZoom.transform(groupsSelection, d3Zoom.zoomIdentity); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.transform(groupsSelection, d3Zoom.zoomIdentity); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.transform(svgOverlay, function(datum, index, groups) { const that: SVGRectElement = this; @@ -308,9 +309,11 @@ svgZoom.transform(svgOverlay, function(datum, index, groups) { console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return d3Zoom.zoomIdentity; }); + // use on transition svgOverlayTransition.call(svgZoom.transform, d3Zoom.zoomIdentity); -// svgZoom.transform(groupsTransition, d3Zoom.zoomIdentity); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.transform(groupsTransition, d3Zoom.zoomIdentity); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.transform(svgOverlayTransition, d3Zoom.zoomIdentity); svgZoom.transform(svgOverlayTransition, function(datum, index, groups) { @@ -327,7 +330,8 @@ svgZoom.transform(svgOverlayTransition, function(datum, index, groups) { // use on selection svgZoom.translateBy(svgOverlay, 20, 50); -// svgZoom.translateBy(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateBy(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.translateBy( svgOverlay, @@ -376,7 +380,8 @@ svgZoom.translateBy( // use on transition svgZoom.translateBy(svgOverlayTransition, 20, 50); -// svgZoom.translateBy(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateBy(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.translateBy( svgOverlayTransition, @@ -427,7 +432,8 @@ svgZoom.translateBy( // use on selection svgZoom.translateTo(svgOverlay, 20, 50); -// svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.translateTo( svgOverlay, @@ -476,7 +482,8 @@ svgZoom.translateTo( // use on transition svgZoom.translateTo(svgOverlayTransition, 20, 50); -// svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.translateTo( svgOverlayTransition, @@ -527,7 +534,8 @@ svgZoom.translateTo( // use on selection svgZoom.scaleBy(svgOverlay, 3); -// svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.scaleBy(svgOverlay, function(datum, index, groups) { const that: SVGRectElement = this; @@ -540,7 +548,8 @@ svgZoom.scaleBy(svgOverlay, function(datum, index, groups) { }); // use on transition svgZoom.scaleBy(svgOverlayTransition, 3); -// svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.scaleBy(svgOverlayTransition, function(datum, index, groups) { const that: SVGRectElement = this; @@ -556,7 +565,8 @@ svgZoom.scaleBy(svgOverlayTransition, function(datum, index, groups) { // use on selection svgZoom.scaleTo(svgOverlay, 3); -// svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.scaleTo(svgOverlay, function(datum, index, groups) { const that: SVGRectElement = this; @@ -569,7 +579,8 @@ svgZoom.scaleTo(svgOverlay, function(datum, index, groups) { }); // use on transition svgZoom.scaleTo(svgOverlayTransition, 3); -// svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.scaleTo(svgOverlayTransition, function(datum, index, groups) { const that: SVGRectElement = this; @@ -616,15 +627,18 @@ const invertedPoint: [number, number] = zTransform.invert([150, 240]); const invertedX: number = zTransform.invertX(150); const invertedY: number = zTransform.invertY(240); -// TODO: reScaleX, reScaleY - let linearScale: ScaleLinear = scaleLinear(); +let timeScale: ScaleTime = scaleTime(); linearScale = zTransform.rescaleX(linearScale); linearScale = zTransform.rescaleY(linearScale); +timeScale = zTransform.rescaleX(timeScale); +timeScale = zTransform.rescaleY(timeScale); + const transformation: string = zTransform.toString(); +zTransform = zTransform.scale(2); zTransform = zTransform.translate(50, 40); // zoomIdentity ------------------------------------------------------------- diff --git a/types/d3-zoom/index.d.ts b/types/d3-zoom/index.d.ts index 827390b871..3f6100d4b8 100644 --- a/types/d3-zoom/index.d.ts +++ b/types/d3-zoom/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for d3JS d3-zoom module 1.7 // Project: https://github.com/d3/d3-zoom/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -26,12 +29,12 @@ export type ZoomedElementBaseType = Element; * that can be passed into zoomTransform methods rescaleX and rescaleY */ export interface ZoomScale { - domain(): number[]; - domain(domain: number[]): this; + domain(): number[] | Date[]; + domain(domain: Array): this; range(): number[]; range(range: number[]): this; copy(): ZoomScale; - invert(value: number): number; + invert(value: number): number | Date; } // -------------------------------------------------------------------------- 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/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/db-migrate-base/db-migrate-base-tests.ts b/types/db-migrate-base/db-migrate-base-tests.ts index e9c46f4873..b094be1280 100644 --- a/types/db-migrate-base/db-migrate-base-tests.ts +++ b/types/db-migrate-base/db-migrate-base-tests.ts @@ -318,4 +318,4 @@ db.runSqlAsync('DROP TABLE `pets`').then(onResolve); /// allAsync(sql, [params]) db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); -db.allAsync('SELECT * FROM `module_user`').then(onResolve); \ No newline at end of file +db.allAsync('SELECT * FROM `module_user`').then(onResolve); diff --git a/types/dd-trace/dd-trace-tests.ts b/types/dd-trace/dd-trace-tests.ts index 9d6936875a..cee1b6e3ee 100644 --- a/types/dd-trace/dd-trace-tests.ts +++ b/types/dd-trace/dd-trace-tests.ts @@ -2,14 +2,15 @@ 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, + env: "dev", logger: { debug: msg => {}, error: err => {}, - }, - tags: { tracerEnv: 'dev'} + } }); function useWebFrameworkPlugin(plugin: "express" | "hapi" | "koa" | "restify") { diff --git a/types/dd-trace/index.d.ts b/types/dd-trace/index.d.ts index 311fa7675e..a55b7f8de7 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 @@ -77,6 +83,11 @@ interface TracerOptions { */ port?: number | string; + /** + * Set an application’s environment e.g. prod, pre-prod, stage. + */ + env?: string; + /** * Percentage of spans to sample as a float between 0 and 1. * @default 1 @@ -185,6 +196,7 @@ declare class Scope { type Plugin = | "amqp10" | "amqplib" + | "bluebird" | "elasticsearch" | "express" | "graphql" @@ -197,8 +209,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/decode-uri-component/decode-uri-component-tests.ts b/types/decode-uri-component/decode-uri-component-tests.ts new file mode 100644 index 0000000000..dfcd379031 --- /dev/null +++ b/types/decode-uri-component/decode-uri-component-tests.ts @@ -0,0 +1,12 @@ +import decodeUriComponent = require('decode-uri-component'); + +// $ExpectType string +decodeUriComponent('%25'); +decodeUriComponent('%'); +decodeUriComponent('st%C3%A5le'); +decodeUriComponent('%st%C3%A5le%'); +decodeUriComponent('%%7Bst%C3%A5le%7D%'); +decodeUriComponent('%7B%ab%%7C%de%%7D'); +decodeUriComponent('%FE%FF'); +decodeUriComponent('%C2'); +decodeUriComponent('%C2%B5'); diff --git a/types/decode-uri-component/index.d.ts b/types/decode-uri-component/index.d.ts new file mode 100644 index 0000000000..a1649d5830 --- /dev/null +++ b/types/decode-uri-component/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for decode-uri-component 0.2 +// Project: https://github.com/samverschueren/decode-uri-component#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = decodeUriComponent; + +declare function decodeUriComponent(encodedURI: string): string; diff --git a/types/decode-uri-component/tsconfig.json b/types/decode-uri-component/tsconfig.json new file mode 100644 index 0000000000..dfd7bc27ca --- /dev/null +++ b/types/decode-uri-component/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", + "decode-uri-component-tests.ts" + ] +} diff --git a/types/decode-uri-component/tslint.json b/types/decode-uri-component/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/decode-uri-component/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/default-gateway/default-gateway-tests.ts b/types/default-gateway/default-gateway-tests.ts new file mode 100644 index 0000000000..7e52d25dc1 --- /dev/null +++ b/types/default-gateway/default-gateway-tests.ts @@ -0,0 +1,11 @@ +import * as defaultGateway from 'default-gateway'; + +defaultGateway.v4().then(result => { + result; // $ExpectType Gateway +}); +defaultGateway.v6().then(result => { + result; // $ExpectType Gateway +}); + +defaultGateway.v4.sync(); // $ExpectType Gateway +defaultGateway.v6.sync(); // $ExpectType Gateway diff --git a/types/default-gateway/index.d.ts b/types/default-gateway/index.d.ts new file mode 100644 index 0000000000..23625451c3 --- /dev/null +++ b/types/default-gateway/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for default-gateway 3.0 +// Project: https://github.com/silverwind/default-gateway#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const v4: DefaultGatewayFn; +export const v6: DefaultGatewayFn; + +export interface DefaultGatewayFn { + (): Promise; + sync(): Gateway; +} + +export interface Gateway { + gateway: string; + interface: string | null; +} diff --git a/types/default-gateway/tsconfig.json b/types/default-gateway/tsconfig.json new file mode 100644 index 0000000000..75e68a34db --- /dev/null +++ b/types/default-gateway/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", + "default-gateway-tests.ts" + ] +} diff --git a/types/default-gateway/tslint.json b/types/default-gateway/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/default-gateway/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/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/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/dir-glob/dir-glob-tests.ts b/types/dir-glob/dir-glob-tests.ts new file mode 100644 index 0000000000..e8aaf721dc --- /dev/null +++ b/types/dir-glob/dir-glob-tests.ts @@ -0,0 +1,23 @@ +import dirGlob = require('dir-glob'); + +dirGlob('index.js').then(files => { + // ExpectType string[] + files; +}); +dirGlob(['index.js', 'test.js', 'fixtures']).then(files => { + // ExpectType string[] + files; +}); + +dirGlob(['index.js', 'inner_folder'], { cwd: 'fixtures' }); +dirGlob(['lib/**', 'fixtures'], { files: ['test', 'unicorn'] }); +dirGlob(['lib/**', 'fixtures'], { extensions: ['js'] }); + +// ExpectType string[] +dirGlob.sync('index.js'); +// ExpectType string[] +dirGlob.sync(['index.js', 'test.js', 'fixtures']); + +dirGlob.sync(['index.js', 'inner_folder'], { cwd: 'fixtures' }); +dirGlob.sync(['lib/**', 'fixtures'], { files: ['test', 'unicorn'] }); +dirGlob.sync(['lib/**', 'fixtures'], { extensions: ['js'] }); diff --git a/types/dir-glob/index.d.ts b/types/dir-glob/index.d.ts new file mode 100644 index 0000000000..c1e78ae111 --- /dev/null +++ b/types/dir-glob/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for dir-glob 2.0 +// Project: https://github.com/kevva/dir-glob#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = dirGlob; + +declare function dirGlob(input: string | string[], options?: dirGlob.Options): Promise; + +declare namespace dirGlob { + function sync(input: string | string[], options?: Options): string[]; + + interface Options { + extensions?: string[]; + files?: string[]; + cwd?: string; + } +} diff --git a/types/dir-glob/tsconfig.json b/types/dir-glob/tsconfig.json new file mode 100644 index 0000000000..2cf8fd31d8 --- /dev/null +++ b/types/dir-glob/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", + "dir-glob-tests.ts" + ] +} diff --git a/types/dir-glob/tslint.json b/types/dir-glob/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dir-glob/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/dom-helpers/activeElement.d.ts b/types/dom-helpers/activeElement.d.ts new file mode 100644 index 0000000000..3a964f0479 --- /dev/null +++ b/types/dom-helpers/activeElement.d.ts @@ -0,0 +1,6 @@ +/** + * Returns focused element safely + */ +declare const activeElement: (doc?: Document) => Element; + +export = activeElement; diff --git a/types/dom-helpers/class/addClass.d.ts b/types/dom-helpers/class/addClass.d.ts new file mode 100644 index 0000000000..5431a9d256 --- /dev/null +++ b/types/dom-helpers/class/addClass.d.ts @@ -0,0 +1,2 @@ +declare const addClass: (element: Element, className: string) => void; +export = addClass; diff --git a/types/dom-helpers/class/hasClass.d.ts b/types/dom-helpers/class/hasClass.d.ts new file mode 100644 index 0000000000..2ec83c8a2f --- /dev/null +++ b/types/dom-helpers/class/hasClass.d.ts @@ -0,0 +1,2 @@ +declare const hasClass: (element: Element, className: string) => boolean; +export = hasClass; diff --git a/types/dom-helpers/class/index.d.ts b/types/dom-helpers/class/index.d.ts new file mode 100644 index 0000000000..24b0dbd1e6 --- /dev/null +++ b/types/dom-helpers/class/index.d.ts @@ -0,0 +1,19 @@ +import * as addClass from "./addClass"; +import * as removeClass from "./removeClass"; +import * as hasClass from "./hasClass"; + +declare const _default: { + addClass: typeof addClass; + removeClass: typeof removeClass; + hasClass: typeof hasClass; +}; + +declare const _export: { + addClass: typeof addClass; + removeClass: typeof removeClass; + hasClass: typeof hasClass; + + default: typeof _export; +}; + +export = _export; diff --git a/types/dom-helpers/class/removeClass.d.ts b/types/dom-helpers/class/removeClass.d.ts new file mode 100644 index 0000000000..a67929344f --- /dev/null +++ b/types/dom-helpers/class/removeClass.d.ts @@ -0,0 +1,2 @@ +declare const removeClass: (element: Element, className: string) => void; +export = removeClass; diff --git a/types/dom-helpers/dom-helpers-tests.ts b/types/dom-helpers/dom-helpers-tests.ts new file mode 100644 index 0000000000..60266ae725 --- /dev/null +++ b/types/dom-helpers/dom-helpers-tests.ts @@ -0,0 +1,105 @@ +import * as helpers from "dom-helpers"; +import * as ownerDocument from "dom-helpers/ownerDocument"; +import * as ownerWindow from "dom-helpers/ownerWindow"; +import * as activeElement from "dom-helpers/activeElement"; + +import * as classes from "dom-helpers/class"; +import * as hasClass from "dom-helpers/class/hasClass"; +import * as removeClass from "dom-helpers/class/removeClass"; +import * as addClass from "dom-helpers/class/addClass"; + +import * as events from "dom-helpers/events"; +import * as on from "dom-helpers/events/on"; +import * as off from "dom-helpers/events/off"; +import * as listen from "dom-helpers/events/listen"; +import * as filter from "dom-helpers/events/filter"; + +import * as query from "dom-helpers/query"; +import * as matches from "dom-helpers/query/matches"; +import * as height from "dom-helpers/query/height"; +import * as width from "dom-helpers/query/width"; +import * as offset from "dom-helpers/query/offset"; +import * as offsetParent from "dom-helpers/query/offsetParent"; +import * as position from "dom-helpers/query/position"; +import * as contains from "dom-helpers/query/contains"; +import * as scrollParent from "dom-helpers/query/scrollParent"; +import * as scrollTop from "dom-helpers/query/scrollTop"; +import * as querySelectorAll from "dom-helpers/query/querySelectorAll"; +import * as closest from "dom-helpers/query/closest"; + +import * as css from "dom-helpers/style"; +import * as getComputedStyle from "dom-helpers/style/getComputedStyle"; +import * as removeStyle from "dom-helpers/style/removeStyle"; + +import * as transition from "dom-helpers/transition"; +import * as end from "dom-helpers/transition/end"; +import * as properties from "dom-helpers/transition/properties"; + +const element = helpers.activeElement() || activeElement(); +const win = + helpers.ownerWindow(element || null || undefined) || + ownerWindow(element || null || undefined); +const doc = helpers.ownerDocument(element) || ownerDocument(element); +const id = helpers.requestAnimationFrame(() => {}); +helpers.requestAnimationFrame.cancel(id); + +const padding: string = css(element, "padding"); +css(element, "padding", 10); +css(element, "padding", "12px"); + +events.on(element, "click", () => {}); +on(element, "click", () => {}); +events.off(element, "click", () => {}, true); +off(element, "click", () => {}, true); +events.listen(element, "click", () => {})(); +listen(element, "click", () => {})(); +events.on(element, "click", filter("div > a", () => {})); +on(element, "click", events.filter("div > a", () => {})); + +classes.addClass(element, "class"); +classes.removeClass(element, "class"); +classes.hasClass(element, "class"); + +addClass(element, "class"); +removeClass(element, "class"); +hasClass(element, "class"); + +const match: boolean = + query.matches(element, ".class") || matches(element, ".class"); +const h: number = query.height(element) || height(element); +const w: number = query.width(element) || width(element); +const _offset: { top: number; left: number; bottom: number; right: number } = + query.offset(element) || offset(element); +const _offsetParent: Element = + query.offsetParent(element) || offsetParent(element); +const _position: { top: number; left: number; bottom: number; right: number } = + query.position(element) || position(element); +const _contains: boolean = + query.contains(element, element) || contains(element, element); +const _scrollParent: Element = + query.scrollParent(element) || scrollParent(element); +const _scrollTop: number = query.scrollTop(element) || scrollTop(element); +query.scrollTop(element, 100); +scrollTop(element, 100); +const _querySelectorAll: HTMLElement[] = + (query.querySelectorAll(element, "*") as HTMLElement[]) || + (querySelectorAll(element, "*") as HTMLElement[]); +const _closest: Element = + query.closest(element, "*", element) || closest(element, "*", element); + +const _getComputedStyle: string = getComputedStyle(element).getPropertyValue( + "padding" +); +removeStyle(element, "padding"); + +transition.end(element, (event) => { + const currentTarget: Element = event.currentTarget; + const target: Element = event.target; +}, 100); + +end(element, (event) => { + const currentTarget: Element = event.currentTarget; + const target: Element = event.target; +}, 100); + +const transform: string = properties.transform; diff --git a/types/dom-helpers/events/filter.d.ts b/types/dom-helpers/events/filter.d.ts new file mode 100644 index 0000000000..fa54287155 --- /dev/null +++ b/types/dom-helpers/events/filter.d.ts @@ -0,0 +1,6 @@ +/** + * Returns a function handler that only fires when the target matches or is contained in the selector + * @example events.on(list, 'click', events.filter('li > a', handler)) + */ +declare const filter: (selector: string, listener: EventListener) => EventListener; +export = filter; diff --git a/types/dom-helpers/events/index.d.ts b/types/dom-helpers/events/index.d.ts new file mode 100644 index 0000000000..fb2e5e89c7 --- /dev/null +++ b/types/dom-helpers/events/index.d.ts @@ -0,0 +1,22 @@ +import * as on from './on'; +import * as off from './off'; +import * as listen from './listen'; +import * as filter from './filter'; + +declare const _default: { + on: typeof on; + off: typeof off; + listen: typeof listen; + filter: typeof filter; +}; + +declare const _export: { + on: typeof on; + off: typeof off; + listen: typeof listen; + filter: typeof filter; + + default: typeof _default; +}; + +export = _export; diff --git a/types/dom-helpers/events/listen.d.ts b/types/dom-helpers/events/listen.d.ts new file mode 100644 index 0000000000..ec12d5c0e3 --- /dev/null +++ b/types/dom-helpers/events/listen.d.ts @@ -0,0 +1,5 @@ +/** + * Wraps on and returns a function that calls off for you + */ +declare const listen: (element: Element, type: string, listener: EventListener, capture?: boolean) => () => void; +export = listen; diff --git a/types/dom-helpers/events/off.d.ts b/types/dom-helpers/events/off.d.ts new file mode 100644 index 0000000000..32699cb8a4 --- /dev/null +++ b/types/dom-helpers/events/off.d.ts @@ -0,0 +1,5 @@ +/** + * Capture is silently ignored in ie8 + */ +declare const off: (element: Element, type: string, listener: EventListener, capture?: boolean) => void; +export = off; diff --git a/types/dom-helpers/events/on.d.ts b/types/dom-helpers/events/on.d.ts new file mode 100644 index 0000000000..2028d70af6 --- /dev/null +++ b/types/dom-helpers/events/on.d.ts @@ -0,0 +1,5 @@ +/** + * Capture is silently ignored in ie8 + */ +declare const on: (element: Element, type: string, listener: EventListener, capture?: boolean) => void; +export = on; diff --git a/types/dom-helpers/index.d.ts b/types/dom-helpers/index.d.ts new file mode 100644 index 0000000000..3215fcc500 --- /dev/null +++ b/types/dom-helpers/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for dom-helpers 3.4 +// Project: https://github.com/react-bootstrap/dom-helpers +// Definitions by: Konstantin Vasiliev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { default as events } from "./events"; +import { default as query } from "./query"; +import * as style from "./style"; +import * as activeElement from "./activeElement"; +import * as ownerDocument from "./ownerDocument"; +import * as ownerWindow from "./ownerWindow"; +import * as requestAnimationFrame from "./util/requestAnimationFrame"; + +declare const _default: typeof events & + typeof query & { + style: typeof style; + activeElement: typeof activeElement; + ownerDocument: typeof ownerDocument; + ownerWindow: typeof ownerWindow; + requestAnimationFrame: typeof requestAnimationFrame; + }; + +declare const _export: { + style: typeof style; + activeElement: typeof activeElement; + ownerDocument: typeof ownerDocument; + ownerWindow: typeof ownerWindow; + requestAnimationFrame: typeof requestAnimationFrame; + + default: typeof _default; +}; + +export = _export; diff --git a/types/dom-helpers/ownerDocument.d.ts b/types/dom-helpers/ownerDocument.d.ts new file mode 100644 index 0000000000..248981141c --- /dev/null +++ b/types/dom-helpers/ownerDocument.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the element's document owner + */ +declare const ownerDocument: (node?: Node | null) => Document; + +export = ownerDocument; diff --git a/types/dom-helpers/ownerWindow.d.ts b/types/dom-helpers/ownerWindow.d.ts new file mode 100644 index 0000000000..f827d3f073 --- /dev/null +++ b/types/dom-helpers/ownerWindow.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the element's document window + */ +declare const ownerWindow: (node?: Node | null) => Window; + +export = ownerWindow; diff --git a/types/dom-helpers/query/closest.d.ts b/types/dom-helpers/query/closest.d.ts new file mode 100644 index 0000000000..5076d3bdf2 --- /dev/null +++ b/types/dom-helpers/query/closest.d.ts @@ -0,0 +1,7 @@ +declare const closest: ( + element: Element, + selector: string, + context: Element +) => Element; + +export = closest; diff --git a/types/dom-helpers/query/contains.d.ts b/types/dom-helpers/query/contains.d.ts new file mode 100644 index 0000000000..d5e03884aa --- /dev/null +++ b/types/dom-helpers/query/contains.d.ts @@ -0,0 +1,2 @@ +declare const contains: (context: Node, node: Node) => boolean; +export = contains; diff --git a/types/dom-helpers/query/height.d.ts b/types/dom-helpers/query/height.d.ts new file mode 100644 index 0000000000..807a3a0782 --- /dev/null +++ b/types/dom-helpers/query/height.d.ts @@ -0,0 +1,2 @@ +declare const height: (element: Element, useClientHeight?: boolean) => number; +export = height; diff --git a/types/dom-helpers/query/index.d.ts b/types/dom-helpers/query/index.d.ts new file mode 100644 index 0000000000..b0dff78ac1 --- /dev/null +++ b/types/dom-helpers/query/index.d.ts @@ -0,0 +1,43 @@ +import * as matches from "./matches"; +import * as height from "./height"; +import * as width from "./width"; +import * as offset from "./offset"; +import * as offsetParent from "./offsetParent"; +import * as position from "./position"; +import * as contains from "./contains"; +import * as scrollParent from "./scrollParent"; +import * as scrollTop from "./scrollTop"; +import * as querySelectorAll from "./querySelectorAll"; +import * as closest from "./closest"; + +declare const _default: { + matches: typeof matches; + height: typeof height; + width: typeof width; + offset: typeof offset; + offsetParent: typeof offsetParent; + position: typeof position; + contains: typeof contains; + scrollParent: typeof scrollParent; + scrollTop: typeof scrollTop; + querySelectorAll: typeof querySelectorAll; + closest: typeof closest; +}; + +declare const _export: { + matches: typeof matches; + height: typeof height; + width: typeof width; + offset: typeof offset; + offsetParent: typeof offsetParent; + position: typeof position; + contains: typeof contains; + scrollParent: typeof scrollParent; + scrollTop: typeof scrollTop; + querySelectorAll: typeof querySelectorAll; + closest: typeof closest; + + default: typeof _default; +}; + +export = _export; diff --git a/types/dom-helpers/query/isWindow.d.ts b/types/dom-helpers/query/isWindow.d.ts new file mode 100644 index 0000000000..e8e0c96534 --- /dev/null +++ b/types/dom-helpers/query/isWindow.d.ts @@ -0,0 +1,2 @@ +declare const isWindow: (node: any) => boolean; +export = isWindow; diff --git a/types/dom-helpers/query/matches.d.ts b/types/dom-helpers/query/matches.d.ts new file mode 100644 index 0000000000..709845bc61 --- /dev/null +++ b/types/dom-helpers/query/matches.d.ts @@ -0,0 +1,5 @@ +/** + * `matches()` polyfill that works in ie8 + */ +declare const matches: (element: Element, selectors: string) => boolean; +export = matches; diff --git a/types/dom-helpers/query/offset.d.ts b/types/dom-helpers/query/offset.d.ts new file mode 100644 index 0000000000..2b41598076 --- /dev/null +++ b/types/dom-helpers/query/offset.d.ts @@ -0,0 +1,11 @@ +declare namespace DomHelpersOffset { + interface DomHelpersRect { + bottom: number; + left: number; + right: number; + top: number; + } +} + +declare const DomHelpersOffset: (element: Element) => DomHelpersOffset.DomHelpersRect; +export = DomHelpersOffset; diff --git a/types/dom-helpers/query/offsetParent.d.ts b/types/dom-helpers/query/offsetParent.d.ts new file mode 100644 index 0000000000..ecdfeb9d71 --- /dev/null +++ b/types/dom-helpers/query/offsetParent.d.ts @@ -0,0 +1,5 @@ +/** + * Returns the parent node that the element is offset from + */ +declare const offsetParent: (element: Element) => Element; +export = offsetParent; diff --git a/types/dom-helpers/query/position.d.ts b/types/dom-helpers/query/position.d.ts new file mode 100644 index 0000000000..5f683f97e1 --- /dev/null +++ b/types/dom-helpers/query/position.d.ts @@ -0,0 +1,7 @@ +import { DomHelpersRect } from "./offset"; +/** + * Return "offset" of the node to its offsetParent, + * optionally you can specify the offset parent if different than the "real" one + */ +declare const position: (element: Element, offsetParent?: Node) => DomHelpersRect; +export = position; diff --git a/types/dom-helpers/query/querySelectorAll.d.ts b/types/dom-helpers/query/querySelectorAll.d.ts new file mode 100644 index 0000000000..21c256adfc --- /dev/null +++ b/types/dom-helpers/query/querySelectorAll.d.ts @@ -0,0 +1,8 @@ +/** + * Optimized qsa, uses `getElementBy{Id|TagName|ClassName}` if it can + */ +declare const querySelectorAll: ( + element: Element, + selector: string +) => Element[]; +export = querySelectorAll; diff --git a/types/dom-helpers/query/scrollLeft.d.ts b/types/dom-helpers/query/scrollLeft.d.ts new file mode 100644 index 0000000000..3a0c0a3fa3 --- /dev/null +++ b/types/dom-helpers/query/scrollLeft.d.ts @@ -0,0 +1,5 @@ +declare function _scrollLeft(element: Element): number; +declare function _scrollLeft(element: Element, value: number): void; + +declare const scrollLeft: typeof _scrollLeft; +export = scrollLeft; diff --git a/types/dom-helpers/query/scrollParent.d.ts b/types/dom-helpers/query/scrollParent.d.ts new file mode 100644 index 0000000000..f104f68bd3 --- /dev/null +++ b/types/dom-helpers/query/scrollParent.d.ts @@ -0,0 +1,2 @@ +declare const scrollParent: (element: Element) => Element; +export = scrollParent; diff --git a/types/dom-helpers/query/scrollTop.d.ts b/types/dom-helpers/query/scrollTop.d.ts new file mode 100644 index 0000000000..d56d9d17e1 --- /dev/null +++ b/types/dom-helpers/query/scrollTop.d.ts @@ -0,0 +1,6 @@ +declare function _scrollTop(element: Element): number; +declare function _scrollTop(element: Element, value: number): void; + +declare const scrollTop: typeof _scrollTop; + +export = scrollTop; diff --git a/types/dom-helpers/query/width.d.ts b/types/dom-helpers/query/width.d.ts new file mode 100644 index 0000000000..4b4fd15bb5 --- /dev/null +++ b/types/dom-helpers/query/width.d.ts @@ -0,0 +1,2 @@ +declare const width: (element: Element, useClientWidth?: boolean) => number; +export = width; diff --git a/types/dom-helpers/style/getComputedStyle.d.ts b/types/dom-helpers/style/getComputedStyle.d.ts new file mode 100644 index 0000000000..c8be2d3976 --- /dev/null +++ b/types/dom-helpers/style/getComputedStyle.d.ts @@ -0,0 +1,4 @@ +declare const getComputedStyle: ( + element: Element +) => { getPropertyValue: (prop: string) => string }; +export = getComputedStyle; diff --git a/types/dom-helpers/style/index.d.ts b/types/dom-helpers/style/index.d.ts new file mode 100644 index 0000000000..2cb8844194 --- /dev/null +++ b/types/dom-helpers/style/index.d.ts @@ -0,0 +1,9 @@ +declare function _style(element: Element, property: string): string; +declare function _style( + element: Element, + property: string | { [key: string]: any }, + value: any +): void; + +declare const style: typeof _style; +export = style; diff --git a/types/dom-helpers/style/removeStyle.d.ts b/types/dom-helpers/style/removeStyle.d.ts new file mode 100644 index 0000000000..4ccdcae438 --- /dev/null +++ b/types/dom-helpers/style/removeStyle.d.ts @@ -0,0 +1,2 @@ +declare const removeStyle: (element: Element, key: string) => void; +export = removeStyle; diff --git a/types/dom-helpers/transition/animate.d.ts b/types/dom-helpers/transition/animate.d.ts new file mode 100644 index 0000000000..9cd71843e5 --- /dev/null +++ b/types/dom-helpers/transition/animate.d.ts @@ -0,0 +1,23 @@ +interface DomHelpersAnimationArgs { + element: Element; + properties: { [key: string]: any }; + duration?: number; + easing?: boolean; + callback?: () => void; +} + +/** + * Programmatically start css transitions + */ +declare function _animate(args: DomHelpersAnimationArgs): { cancel: () => void }; +declare function _animate( + element: Element, + properties: { [key: string]: any }, + duration?: number, + easing?: boolean, + callback?: () => void +): { cancel: () => void }; + +declare const animate: typeof _animate; + +export = animate; diff --git a/types/dom-helpers/transition/end.d.ts b/types/dom-helpers/transition/end.d.ts new file mode 100644 index 0000000000..5b662395e4 --- /dev/null +++ b/types/dom-helpers/transition/end.d.ts @@ -0,0 +1,12 @@ +/** + * Listens for transition end, and ensures that the handler if called + * even if the transition fails to fire its end event. + * Will attempt to read duration from the element, otherwise one can be provided + */ +declare const end: ( + element: T, + handler: (event: { target: T, currentTarget: T }) => void, + duration?: number +) => void; + +export = end; diff --git a/types/dom-helpers/transition/index.d.ts b/types/dom-helpers/transition/index.d.ts new file mode 100644 index 0000000000..28b1ce9eb0 --- /dev/null +++ b/types/dom-helpers/transition/index.d.ts @@ -0,0 +1,16 @@ +import * as end from "./end"; +import * as properties from "./properties"; + +declare const _default: { + end: typeof end; + properties: typeof properties; +}; + +declare const _export: { + end: typeof end; + properties: typeof properties; + + default: typeof _default; +}; + +export = _export; diff --git a/types/dom-helpers/transition/properties.d.ts b/types/dom-helpers/transition/properties.d.ts new file mode 100644 index 0000000000..4049c19982 --- /dev/null +++ b/types/dom-helpers/transition/properties.d.ts @@ -0,0 +1,26 @@ +declare const _default: { + transform: string; + end: string; + property: string; + timing: string; + delay: string; + duration: string; +}; + +declare const _export: { + transform: string; + transitionProperty: string; + transitionTiming: string; + transitionDelay: string; + transitionDuration: string; + transitionEnd: string; + animationName: string; + animationDuration: string; + animationTiming: string; + animationDelay: string; + animationEnd: string; + + default: typeof _default, +}; + +export = _export; diff --git a/types/dom-helpers/tsconfig.json b/types/dom-helpers/tsconfig.json new file mode 100644 index 0000000000..bbaca98dbe --- /dev/null +++ b/types/dom-helpers/tsconfig.json @@ -0,0 +1,60 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "activeElement.d.ts", + "ownerDocument.d.ts", + "ownerWindow.d.ts", + "dom-helpers-tests.ts", + "class/addClass.d.ts", + "class/hasClass.d.ts", + "class/index.d.ts", + "class/removeClass.d.ts", + "events/filter.d.ts", + "events/index.d.ts", + "events/listen.d.ts", + "events/off.d.ts", + "events/on.d.ts", + "query/closest.d.ts", + "query/contains.d.ts", + "query/height.d.ts", + "query/index.d.ts", + "query/isWindow.d.ts", + "query/matches.d.ts", + "query/offset.d.ts", + "query/offsetParent.d.ts", + "query/position.d.ts", + "query/querySelectorAll.d.ts", + "query/scrollLeft.d.ts", + "query/scrollParent.d.ts", + "query/scrollTop.d.ts", + "query/width.d.ts", + "style/getComputedStyle.d.ts", + "style/index.d.ts", + "style/removeStyle.d.ts", + "transition/animate.d.ts", + "transition/end.d.ts", + "transition/index.d.ts", + "transition/properties.d.ts", + "util/requestAnimationFrame.d.ts", + "util/scrollbarSize.d.ts", + "util/scrollTo.d.ts" + ] +} diff --git a/types/dom-helpers/tslint.json b/types/dom-helpers/tslint.json new file mode 100644 index 0000000000..2d469ebdbd --- /dev/null +++ b/types/dom-helpers/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "prefer-declare-function": false + } +} diff --git a/types/dom-helpers/util/requestAnimationFrame.d.ts b/types/dom-helpers/util/requestAnimationFrame.d.ts new file mode 100644 index 0000000000..211fb7486f --- /dev/null +++ b/types/dom-helpers/util/requestAnimationFrame.d.ts @@ -0,0 +1,11 @@ +interface DomHelpersRaf { + /** + * Returns an ID for canceling + */ + (callback: () => void): number; + cancel: (id: number) => void; +} + +declare const requestAnimationFrame: DomHelpersRaf; + +export = requestAnimationFrame; diff --git a/types/dom-helpers/util/scrollTo.d.ts b/types/dom-helpers/util/scrollTo.d.ts new file mode 100644 index 0000000000..b336c1104a --- /dev/null +++ b/types/dom-helpers/util/scrollTo.d.ts @@ -0,0 +1,3 @@ +declare const scrollTo: (element: Element, scrollParent?: Element) => () => void; + +export = scrollTo; diff --git a/types/dom-helpers/util/scrollbarSize.d.ts b/types/dom-helpers/util/scrollbarSize.d.ts new file mode 100644 index 0000000000..67d6c840e2 --- /dev/null +++ b/types/dom-helpers/util/scrollbarSize.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the scrollbar's width size in pixels + */ +declare const scrollbarSize: (recalc?: boolean) => number; + +export = scrollbarSize; 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/ej.web.all/index.d.ts b/types/ej.web.all/index.d.ts index 32b9d1a18b..77db23312f 100644 --- a/types/ej.web.all/index.d.ts +++ b/types/ej.web.all/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ej.web.all 16.3 +// Type definitions for ej.web.all 16.4 // Project: http://help.syncfusion.com/js/typescript // Definitions by: Syncfusion // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,7 @@ /*! * filename: ej.web.all.d.ts -* version : 16.3.0.21 +* version : 16.4.0.40-beta * Copyright Syncfusion Inc. 2001 - 2018. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing @@ -590,6 +590,21 @@ declare namespace ej { */ scope?: string; + /** Used to enable auto scroll while drag and drop the element. + * @Default {'false'} + */ + autoScroll?: boolean; + + /** Represents when to start the scrolling inside the scroll container on dragging + * @Default {'20'} + */ + scrollSensitivity?: number; + + /** Specifies how much distance of scroll should move on dragging once reached scroll sensitivity area. + * @Default {'20'} + */ + scrollSpeed?: number; + /** This event is triggered when dragging element is destroyed. */ destroy?(e: DestroyEventArgs): void; @@ -6293,6 +6308,11 @@ declare namespace ej { */ getValue(): string; + /** sets the date value for the DatePicker. + * @returns {string} + */ + setValue(): string; + /** Close the DatePicker popup, if it is in opened state. * @returns {void} */ @@ -10920,7 +10940,7 @@ declare namespace ej { show(): void; /** To show item in the given index. - * @param {number} Specifies the index value to show the hided item. + * @param {number} Specifies the index value to show the hidden item. * @returns {void} */ showItem(index: number): void; @@ -11069,7 +11089,7 @@ declare namespace ej { itemRequestCount?: number; /** Specifies the maximum number of items to be fetched. Note: This will work only with Virtual scrolling - * @Default {null} + * @Default {5} */ totalItemsCount?: number; @@ -29321,6 +29341,11 @@ declare namespace ej { */ memberEditorPageSize?: number; + /** Enables/Disables sorting option in member editor dialog for the members of the respective field. + * @Default {false} + */ + enableMemberEditorSorting?: boolean; + /** Enables/disables the display of grand total for rows and columns. * @Default {true} */ @@ -31523,6 +31548,11 @@ declare namespace ej { */ memberEditorPageSize?: number; + /** Enables/Disables sorting option in member editor dialog for the members of the respective field. + * @Default {false} + */ + enableMemberEditorSorting?: boolean; + /** Sets the summary layout for the pivot grid. Following are the ways in which the summary can be positioned: normal summary (bottom), top summary, no summary, and Microsoft Excel * summary. * @Default {ej.PivotGrid.Layout.Normal} @@ -37776,6 +37806,11 @@ declare namespace ej { */ reportLoaded?(e: ReportLoadedEventArgs): void; + /** Fires when user clicks on a failed report item in the rendered report, before displaying error details dialog. If you want to show custom error detail or perform any action before + * viewing error detail, you can make use of the showError event. + */ + showError?(e: ShowErrorEventArgs): void; + /** Fires when click the View Report Button. */ viewReportClick?(e: ViewReportClickEventArgs): void; @@ -37914,6 +37949,25 @@ declare namespace ej { type?: string; } + export interface ShowErrorEventArgs { + + /** true if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** returns the error code. + */ + errorCode?: string; + + /** returns the error message. + */ + message?: string; + + /** returns the detailed error information. + */ + detail?: string; + } + export interface ViewReportClickEventArgs { /** true if the event should be canceled; otherwise, false. @@ -42902,17 +42956,22 @@ declare namespace ej { */ redo(): void; - /** This method is used to refresh the content in Spreadsheet. + /** This method is used to refresh the Spreadsheet based on the sheet model values. * @param {number} Pass the index of the sheet. * @returns {void} */ refreshContent(sheetIdx: number): void; - /** This method is used to refresh the Spreadsheet. + /** This method is used to refresh the Spreadsheet element based on the page layout. * @returns {void} */ refreshSpreadsheet(): void; + /** This method destroys and re-creates the entire Spreadsheet control. + * @returns {void} + */ + refresh(): void; + /** This method is used to remove custom formulae in Spreadsheet. * @param {string} Pass the name of the formula. * @param {string} Pass the name of the function. @@ -44335,6 +44394,11 @@ declare namespace ej { */ importSettings?: ImportSettings; + /** Gets a value that indicates whether importing or not while loading the sheets in Spreadsheet. + * @Default {false} + */ + isImport?: boolean; + /** Gets or sets a value that indicates whether to enable or disable readonly support in the Spreadsheet. * @Default {false} */ @@ -46435,6 +46499,11 @@ declare namespace ej { */ abortPrint(): void; + /** Aborts the download operation. + * @returns {void} + */ + abortDownload(): void; + /** Shows/hides the print icon in the toolbar. * @param {boolean} shows/hides print button in the toolbar * @returns {void} @@ -46508,6 +46577,12 @@ declare namespace ej { */ showMagnificationTools(show: boolean): void; + /** Shows/hides the search tool in the toolbar. + * @param {boolean} shows/hides search tool in the toolbar + * @returns {void} + */ + showTextSearchTool(show: boolean): void; + /** Scales the page to fit the page in the container in the control. * @returns {void} */ @@ -46528,6 +46603,11 @@ declare namespace ej { */ zoomOut(): void; + /** Resize the viewer based on the parent element height. + * @returns {void} + */ + updateViewerSize(): void; + /** Scales the page to the specified percentage ranging from 50 to 400. If the given zoomValue is less than 50 or greater than 400; the PDF viewer scales the page to 50 and 400 * respectively. * @param {number} zoom value for scaling the pages in the PDF Viewer @@ -46551,6 +46631,12 @@ declare namespace ej { */ searchPrevious(): void; + /** Set the JSON data that are formed for rendering the document content in PDF viewer. + * @param {any} Set the JSON data that are formed for rendering the document content. + * @returns {void} + */ + setJSONData(jsonData: any): void; + /** Searches the target text with its casing. * @param {boolean} Specifies whether the text search must be performed with match case or not. * @returns {void} @@ -46643,6 +46729,14 @@ declare namespace ej { */ signatureSettings?: SignatureSettings; + /** Enables/ disables the text selection context menu. + */ + textSelectionContextMenu?: TextSelectionContextMenu; + + /** Enables/disables the annotation context menu. + */ + annotationContextMenu?: AnnotationContextMenu; + /** Specifies the type of the annotations. */ annotationType?: ej.PdfViewer.AnnotationType|string; @@ -46667,6 +46761,10 @@ declare namespace ej { */ interactionMode?: ej.PdfViewer.InteractionMode|string; + /** Gets or sets the buffering mode of the PDF viewer control when allowClientBuffering is set to true. + */ + bufferingMode?: ej.PdfViewer.BufferingMode|string; + /** Specifies the open state of the hyperlink in the PDF document. */ hyperlinkOpenState?: ej.PdfViewer.LinkTarget|string; @@ -46711,6 +46809,10 @@ declare namespace ej { */ ajaxRequestFailure?(e: AjaxRequestFailureEventArgs): void; + /** Triggers when the ajax request is Success. + */ + ajaxRequestSuccess?(e: AjaxRequestSuccessEventArgs): void; + /** Triggers when there is change in the magnification value. */ zoomChange?(e: ZoomChangeEventArgs): void; @@ -46767,6 +46869,14 @@ declare namespace ej { */ bufferEnd?(e: BufferEndEventArgs): void; + /** Triggers when the download is started. + */ + downloadStart?(e: DownloadStartEventArgs): void; + + /** Triggers when the download is completed or aborted. + */ + downloadEnd?(e: DownloadEndEventArgs): void; + /** Triggers when PDF viewer control is destroyed successfully. */ destroy?(e: DestroyEventArgs): void; @@ -46844,6 +46954,25 @@ declare namespace ej { message?: string; } + export interface AjaxRequestSuccessEventArgs { + + /** true, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the PDF viewer model + */ + model?: any; + + /** Returns the name of the event + */ + type?: string; + + /** Returns the response data on ajax success. + */ + responseData?: string; + } + export interface ZoomChangeEventArgs { /** Returns the cancel option value. @@ -47194,6 +47323,52 @@ declare namespace ej { isBuffering?: boolean; } + export interface DownloadStartEventArgs { + + /** true, if the event should be canceled; otherwise, false + */ + cancel?: boolean; + + /** Returns the PDF viewer model + */ + model?: any; + + /** Returns the name of the event + */ + type?: string; + + /** Returns the name of the file being displayed in the PDF viewer. + */ + fileName?: string; + + /** Returns the status about the download is started. + */ + status?: string; + } + + export interface DownloadEndEventArgs { + + /** true, if the event should be canceled; otherwise, false + */ + cancel?: boolean; + + /** Returns the PDF viewer model + */ + model?: any; + + /** Returns the name of the event + */ + type?: string; + + /** Returns the name of the file being displayed in the PDF viewer. + */ + fileName?: string; + + /** Returns the status about the download is completed or aborted. + */ + status?: string; + } + export interface DestroyEventArgs { /** Returns the cancel option value. @@ -47331,6 +47506,48 @@ declare namespace ej { opacity?: number; } + export interface TextSelectionContextMenu { + + /** Enables/ disables the text selection context menu. + */ + isEnable?: boolean; + + /** Enables/disables the copy menu in the text selection context menu. + */ + isCopyEnable?: boolean; + + /** Enables/disables the search menu in the text selection context menu. + */ + isSearchEnable?: boolean; + + /** Enables/disables the highlight annotation menu in the text selection context menu. + */ + isHighlightEnable?: boolean; + + /** Enables/disables the strikeout annotation menu in the text selection context menu. + */ + isStrikeoutEnable?: boolean; + } + + export interface AnnotationContextMenu { + + /** Enables/disables the annotation context menu. + */ + isEnable?: boolean; + + /** Enables/disables the popup menu in the annotation context menu. + */ + isPopupEnable?: boolean; + + /** Enables/disables the delete menu in the annotation context menu. + */ + isDeleteEnable?: boolean; + + /** Enables/disables the properties menu in the annotation context menu. + */ + isPropertiesEnable?: boolean; + } + enum ToolbarItems { ///Shows only magnification tools in the toolbar. @@ -47395,6 +47612,16 @@ declare namespace ej { } + enum BufferingMode { + + ///Retrieves details to render first two pages in a request and rest of the pages in other request. + Default, + + ///Retrieves complete details to render all the pages in a single request. + Complete + } + + enum LinkTarget { ///Opens the hyperlink in the same tab of the browser. @@ -47533,6 +47760,11 @@ declare namespace ej { */ enableAsync?: boolean; + /** To set either ‘Post’ or ‘Get’ for ajax request type which invokes when validate, get suggestion and dictionary action.Possible values are ‘POST’ or ‘GET’ + * @Default {GET} + */ + ajaxRequestType?: string; + /** Sets the data type for the ajax call used within the SpellCheck control, denoting the type of data that are expected to be retrieved from the server. The applicable values are * json and jsonp. * @Default {jsonp} @@ -50374,11 +50606,11 @@ declare namespace ej.datavisualization { /** returns the pointer element. */ - markerpointerelement?: any; + markerPointerElement?: any; /** returns the value of the pointer. */ - markerpointervalue?: number; + markerPointerValue?: number; /** returns the pointer style */ 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/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/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/empty-trash/empty-trash-tests.ts b/types/empty-trash/empty-trash-tests.ts new file mode 100644 index 0000000000..296ec63745 --- /dev/null +++ b/types/empty-trash/empty-trash-tests.ts @@ -0,0 +1,5 @@ +import emptyTrash = require('empty-trash'); + +(async () => { + await emptyTrash(); +})(); diff --git a/types/empty-trash/index.d.ts b/types/empty-trash/index.d.ts new file mode 100644 index 0000000000..ef3fca3040 --- /dev/null +++ b/types/empty-trash/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for empty-trash 2.1 +// Project: https://github.com/sindresorhus/empty-trash#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = emptyTrash; + +declare function emptyTrash(): Promise; diff --git a/types/empty-trash/tsconfig.json b/types/empty-trash/tsconfig.json new file mode 100644 index 0000000000..172bf7299a --- /dev/null +++ b/types/empty-trash/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-trash-tests.ts" + ] +} diff --git a/types/empty-trash/tslint.json b/types/empty-trash/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/empty-trash/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ensure-error/ensure-error-tests.ts b/types/ensure-error/ensure-error-tests.ts new file mode 100644 index 0000000000..fbc5e85d23 --- /dev/null +++ b/types/ensure-error/ensure-error-tests.ts @@ -0,0 +1,9 @@ +import ensureError = require('ensure-error'); + +const error = new TypeError('🦄'); + +// $ExpectType TypeError +ensureError(error); + +// $ExpectType NonError +ensureError(10); diff --git a/types/ensure-error/index.d.ts b/types/ensure-error/index.d.ts new file mode 100644 index 0000000000..e6bc2e5a94 --- /dev/null +++ b/types/ensure-error/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for ensure-error 1.0 +// Project: https://github.com/sindresorhus/ensure-error#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export = ensureError; + +declare function ensureError(input: T): T extends Error ? T : ensureError.NonError; + +declare namespace ensureError { + interface NonError extends Error { + name: 'NonError'; + } +} diff --git a/types/ensure-error/tsconfig.json b/types/ensure-error/tsconfig.json new file mode 100644 index 0000000000..687a9dfd1a --- /dev/null +++ b/types/ensure-error/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", + "ensure-error-tests.ts" + ] +} diff --git a/types/ensure-error/tslint.json b/types/ensure-error/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ensure-error/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/env-ci/env-ci-tests.ts b/types/env-ci/env-ci-tests.ts new file mode 100644 index 0000000000..349fb97b48 --- /dev/null +++ b/types/env-ci/env-ci-tests.ts @@ -0,0 +1,359 @@ +import envCi = require('env-ci'); + +const res = envCi(); +envCi({ env: { foo: 'bar' } }); +envCi({ cwd: '.' }); + +if (!res.isCi) { + res.name; // $ExpectError + res.service; // $ExpectError + res.commit; // $ExpectType string | undefined + res.tag; // $ExpectError + res.build; // $ExpectError + res.buildUrl; // $ExpectError + res.branch; // $ExpectType string | undefined + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectError + res.isPr; // $ExpectError + res.prBranch; // $ExpectError + res.slug; // $ExpectError + res.root; // $ExpectError +} else { + if (res.service === 'appveyor') { + res.name; // $ExpectType "Appveyor" + res.service; // $ExpectType "appveyor" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectType string + res.jobUrl; // $ExpectType string + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'bamboo') { + res.name; // $ExpectType "Bamboo" + res.service; // $ExpectType "bamboo" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectType string + res.jobUrl; // $ExpectError + res.pr; // $ExpectError + res.isPr; // $ExpectError + res.prBranch; // $ExpectError + res.slug; // $ExpectError + res.root; // $ExpectType string + } + if (res.service === 'bitbucket') { + res.name; // $ExpectType "Bitbucket Pipelines" + res.service; // $ExpectType "bitbucket" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectError + res.isPr; // $ExpectError + res.prBranch; // $ExpectError + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'bitrise') { + res.name; // $ExpectType "Bitrise" + res.service; // $ExpectType "bitrise" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectType string + res.root; // $ExpectError + } + if (res.service === 'buddy') { + res.name; // $ExpectType "Buddy" + res.service; // $ExpectType "buddy" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string | undefined + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectError + res.slug; // $ExpectType string + res.root; // $ExpectError + } + if (res.service === 'buildkite') { + res.name; // $ExpectType "Buildkite" + res.service; // $ExpectType "buildkite" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'circleci') { + res.name; // $ExpectType "CircleCI" + res.service; // $ExpectType "circleci" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string | undefined + res.job; // $ExpectType string + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectType string + res.root; // $ExpectError + } + if (res.service === 'cirrus') { + res.name; // $ExpectType "Cirrus CI" + res.service; // $ExpectType "cirrus" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectType string + res.jobUrl; // $ExpectType string + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectError + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'codebuild') { + res.name; // $ExpectType "AWS CodeBuild" + res.service; // $ExpectType "codebuild" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectError + res.isPr; // $ExpectError + res.prBranch; // $ExpectError + res.slug; // $ExpectError + res.root; // $ExpectType string + } + if (res.service === 'codefresh') { + res.name; // $ExpectType "Codefresh" + res.service; // $ExpectType "codefresh" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'codeship') { + res.name; // $ExpectType "Codeship" + res.service; // $ExpectType "codeship" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectError + res.isPr; // $ExpectError + res.prBranch; // $ExpectError + res.slug; // $ExpectType string + res.root; // $ExpectError + } + if (res.service === 'drone') { + res.name; // $ExpectType "Drone" + res.service; // $ExpectType "drone" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectError + res.branch; // $ExpectType string + res.job; // $ExpectType string + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectType string + res.root; // $ExpectError + } + if (res.service === 'gitlab') { + res.name; // $ExpectType "GitLab CI/CD" + res.service; // $ExpectType "gitlab" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectType string + res.jobUrl; // $ExpectType string + res.pr; // $ExpectError + res.isPr; // $ExpectError + res.prBranch; // $ExpectError + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'jenkins') { + res.name; // $ExpectType "Jenkins" + res.service; // $ExpectType "jenkins" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectError + res.root; // $ExpectType string + } + if (res.service === 'sail') { + res.name; // $ExpectType "Sail CI" + res.service; // $ExpectType "sail" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectError + res.buildUrl; // $ExpectError + res.branch; // $ExpectType string | undefined + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectError + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'semaphore') { + res.name; // $ExpectType "Semaphore" + res.service; // $ExpectType "semaphore" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectType string + res.buildUrl; // $ExpectError + res.branch; // $ExpectType string | undefined + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'shippable') { + res.name; // $ExpectType "Shippable" + res.service; // $ExpectType "shippable" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectType string + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'teamcity') { + res.name; // $ExpectType "TeamCity" + res.service; // $ExpectType "teamcity" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectType string + res.buildUrl; // $ExpectError + res.branch; // $ExpectType string | undefined + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectError + res.isPr; // $ExpectError + res.prBranch; // $ExpectError + res.slug; // $ExpectType string + res.root; // $ExpectType string | undefined + } + if (res.service === 'travis') { + res.name; // $ExpectType "Travis CI" + res.service; // $ExpectType "travis" + res.commit; // $ExpectType string + res.tag; // $ExpectType string | undefined + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string | undefined + res.job; // $ExpectType string + res.jobUrl; // $ExpectType string + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string + res.slug; // $ExpectType string + res.root; // $ExpectType string + } + if (res.service === 'vsts') { + res.name; // $ExpectType "Visual Studio Team Services" + res.service; // $ExpectType "vsts" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectType string + res.buildUrl; // $ExpectError + res.branch; // $ExpectType string + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectType string | undefined + res.isPr; // $ExpectType boolean + res.prBranch; // $ExpectType string | undefined + res.slug; // $ExpectError + res.root; // $ExpectType string + } + if (res.service === 'wercker') { + res.name; // $ExpectType "Wercker" + res.service; // $ExpectType "wercker" + res.commit; // $ExpectType string + res.tag; // $ExpectError + res.build; // $ExpectType string + res.buildUrl; // $ExpectType string + res.branch; // $ExpectType string + res.job; // $ExpectError + res.jobUrl; // $ExpectError + res.pr; // $ExpectError + res.isPr; // $ExpectError + res.prBranch; // $ExpectError + res.slug; // $ExpectType string + res.root; // $ExpectType string + } +} diff --git a/types/env-ci/index.d.ts b/types/env-ci/index.d.ts new file mode 100644 index 0000000000..d3ac867796 --- /dev/null +++ b/types/env-ci/index.d.ts @@ -0,0 +1,328 @@ +// Type definitions for env-ci 3.1 +// Project: https://github.com/pvdlg/env-ci#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = envCi; + +declare function envCi(options?: envCi.Options): envCi.CiEnv; + +declare namespace envCi { + interface Options { + env?: { [envVar: string]: any }; + cwd?: string; + } + + type CiEnv = NonCiEnv | KnownCiEnv; + type KnownCiEnv = + | AppveyorEnv + | BambooEnv + | BitbucketEnv + | BitriseEnv + | BuddyEnv + | BuildkiteEnv + | CircleCiEnv + | CirrusEnv + | CodeBuildEnv + | CodefreshEnv + | CodeshipEnv + | DroneEnv + | GitLabEnv + | JenkinsEnv + | SailEnv + | SemaphoreEnv + | ShippableEnv + | TeamCityEnv + | TravisEnv + | VstsEnv + | WerckerEnv; + + interface NonCiEnv { + isCi: false; + branch?: string; + commit?: string; + } + + interface CiEnvBase { + isCi: true; + } + + interface AppveyorEnv extends CiEnvBase { + name: 'Appveyor'; + service: 'appveyor'; + commit: string; + tag?: string; + build: string; + buildUrl: string; + branch: string; + job: string; + jobUrl: string; + pr?: string; + isPr: boolean; + prBranch?: string; + slug: string; + root: string; + } + + interface BambooEnv extends CiEnvBase { + name: 'Bamboo'; + service: 'bamboo'; + commit: string; + build: string; + buildUrl: string; + branch: string; + job: string; + root: string; + } + + interface BitbucketEnv extends CiEnvBase { + name: 'Bitbucket Pipelines'; + service: 'bitbucket'; + commit: string; + tag?: string; + build: string; + buildUrl: string; + branch: string; + slug: string; + root: string; + } + + interface BitriseEnv extends CiEnvBase { + name: 'Bitrise'; + service: 'bitrise'; + commit: string; + tag?: string; + build: string; + buildUrl: string; + branch: string; + pr?: string; + isPr: boolean; + prBranch?: string; + slug: string; + } + + interface BuddyEnv extends CiEnvBase { + name: 'Buddy'; + service: 'buddy'; + commit: string; + tag?: string; + build: string; + buildUrl: string; + branch?: string; + pr?: string; + isPr: boolean; + slug: string; + } + + interface BuildkiteEnv extends CiEnvBase { + name: 'Buildkite'; + service: 'buildkite'; + build: string; + buildUrl: string; + commit: string; + tag?: string; + branch: string; + pr?: string; + isPr: boolean; + prBranch?: string; + slug: string; + root: string; + } + + interface CircleCiEnv extends CiEnvBase { + name: 'CircleCI'; + service: 'circleci'; + build: string; + buildUrl: string; + job: string; + commit: string; + tag?: string; + branch?: string; + pr?: string; + isPr: boolean; + prBranch?: string; + slug: string; + } + + interface CirrusEnv extends CiEnvBase { + name: 'Cirrus CI'; + service: 'cirrus'; + commit: string; + tag?: string; + build: string; + buildUrl: string; + job: string; + jobUrl: string; + branch: string; + pr?: string; + isPr: boolean; + slug: string; + root: string; + } + + interface CodeBuildEnv extends CiEnvBase { + name: 'AWS CodeBuild'; + service: 'codebuild'; + commit: string; + build: string; + branch: string; + buildUrl: string; + root: string; + } + + interface CodefreshEnv extends CiEnvBase { + name: 'Codefresh'; + service: 'codefresh'; + commit: string; + build: string; + buildUrl: string; + branch: string; + pr?: string; + isPr: boolean; + prBranch?: string; + slug: string; + root: string; + } + + interface CodeshipEnv extends CiEnvBase { + name: 'Codeship'; + service: 'codeship'; + build: string; + buildUrl: string; + commit: string; + branch: string; + slug: string; + } + + interface DroneEnv extends CiEnvBase { + name: 'Drone'; + service: 'drone'; + commit: string; + tag?: string; + build: string; + branch: string; + job: string; + pr?: string; + isPr: boolean; + prBranch?: string; + slug: string; + } + + interface GitLabEnv extends CiEnvBase { + name: 'GitLab CI/CD'; + service: 'gitlab'; + commit: string; + tag?: string; + build: string; + buildUrl: string; + job: string; + jobUrl: string; + branch: string; + slug: string; + root: string; + } + + interface JenkinsEnv extends CiEnvBase { + name: 'Jenkins'; + service: 'jenkins'; + commit: string; + branch: string; + build: string; + buildUrl: string; + pr?: string; + isPr: boolean; + prBranch?: string; + root: string; + } + + interface SailEnv extends CiEnvBase { + name: 'Sail CI'; + service: 'sail'; + commit: string; + branch?: string; + pr?: string; + isPr: boolean; + slug: string; + root: string; + } + + interface SemaphoreEnv extends CiEnvBase { + name: 'Semaphore'; + service: 'semaphore'; + commit: string; + build: string; + branch?: string; + pr?: string; + isPr: boolean; + prBranch?: string; + slug: string; + root: string; + } + + interface ShippableEnv extends CiEnvBase { + name: 'Shippable'; + service: 'shippable'; + commit: string; + tag?: string; + build: string; + buildUrl: string; + branch: string; + job: string; + pr?: string; + isPr: boolean; + prBranch?: string; + slug: string; + root: string; + } + + interface TeamCityEnv extends CiEnvBase { + name: 'TeamCity'; + service: 'teamcity'; + branch?: string; + commit: string; + build: string; + slug: string; + root?: string; + } + + interface TravisEnv extends CiEnvBase { + name: 'Travis CI'; + service: 'travis'; + commit: string; + tag?: string; + build: string; + buildUrl: string; + branch?: string; + job: string; + jobUrl: string; + pr?: string; + isPr: boolean; + prBranch: string; + slug: string; + root: string; + } + + interface VstsEnv extends CiEnvBase { + name: 'Visual Studio Team Services'; + service: 'vsts'; + commit: string; + build: string; + branch: string; + pr?: string; + isPr: boolean; + prBranch?: string; + root: string; + } + + interface WerckerEnv extends CiEnvBase { + name: 'Wercker'; + service: 'wercker'; + commit: string; + build: string; + buildUrl: string; + branch: string; + slug: string; + root: string; + } +} diff --git a/types/env-ci/tsconfig.json b/types/env-ci/tsconfig.json new file mode 100644 index 0000000000..9544838913 --- /dev/null +++ b/types/env-ci/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", + "env-ci-tests.ts" + ] +} diff --git a/types/env-ci/tslint.json b/types/env-ci/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/env-ci/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/env-editor/env-editor-tests.ts b/types/env-editor/env-editor-tests.ts new file mode 100644 index 0000000000..c03cacc38b --- /dev/null +++ b/types/env-editor/env-editor-tests.ts @@ -0,0 +1,8 @@ +import * as envEditor from 'env-editor'; + +// $ExpectType Editor +envEditor.get('sublime'); +// $ExpectType Editor +envEditor.default(); +// $ExpectType Editor[] +envEditor.all(); diff --git a/types/env-editor/index.d.ts b/types/env-editor/index.d.ts new file mode 100644 index 0000000000..8bf9e6d68f --- /dev/null +++ b/types/env-editor/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for env-editor 0.3 +// Project: https://github.com/sindresorhus/env-editor#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default function(): Editor; +export function get(editor: string): Editor; +export function all(): Editor[]; + +export interface Editor { + id: string; + name: string; + bin: string; + isTerminalEditor: boolean; + paths: string[]; + keywords: string[]; +} diff --git a/types/env-editor/tsconfig.json b/types/env-editor/tsconfig.json new file mode 100644 index 0000000000..6d137bf389 --- /dev/null +++ b/types/env-editor/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", + "env-editor-tests.ts" + ] +} diff --git a/types/env-editor/tslint.json b/types/env-editor/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/env-editor/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/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 75dee784de..aa69df28ad 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Text } from 'react-native'; +import { Text, AccessibilityInfo } from 'react-native'; import { Accelerometer, @@ -8,40 +8,46 @@ import { AdMobInterstitial, AdMobRewarded, Amplitude, - Asset, - AuthSession, - Audio, AppLoading, + Asset, + Audio, + AuthSession, BarCodeScanner, - BlurViewProps, BlurView, Brightness, + Calendar, Camera, CameraObject, + Constants, DocumentPicker, + EdgeInsets, + EdgePadding, + EventUserLocation, Facebook, FacebookAds, - FileSystem, - ImagePicker, - ImageManipulator, FaceDetector, - Linking, - Svg, + FileSystem, + Haptic, + ImageManipulator, + ImagePicker, IntentLauncherAndroid, KeepAwake, + KmlMapEvent, LinearGradient, + Linking, + Location, + MailComposer, + MapEvent, + MapStyleElement, + MapView, + MediaLibrary, Permissions, PublisherBanner, + Region, registerRootComponent, ScreenOrientation, - SQLite, - Calendar, - MailComposer, - Location, - Updates, - MediaLibrary, - Haptic, - Constants + Svg, + Updates } from 'expo'; const reverseGeocode: Promise = Location.reverseGeocodeAsync({ @@ -837,6 +843,100 @@ async () => { result.status === 'saved'; }; +// #region MapView +const initialRegion: Region = { + latitude: 0, + longitude: 0, + latitudeDelta: 0, + longitudeDelta: 0, +}; + +const edgePadding: EdgePadding = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const edgeInsets: EdgeInsets = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const mapStyleElements: MapStyleElement[] = [{ + featureType: 'featureType', + elementType: 'elementType', + stylers: [{}, {}], +}]; + +const mapEventCallback = (event: MapEvent) => console.log(event); +const regionCallback = (region: Region) => console.log(region); +const kmlCallback = (kml: KmlMapEvent) => console.log(kml); +const userLocationCallback = (event: EventUserLocation) => console.log(event); + +() => ( + ({})} + onKmlReady={kmlCallback} + onRegionChange={regionCallback} + onRegionChangeComplete={regionCallback} + onPress={mapEventCallback} + onLongPress={mapEventCallback} + onUserLocationChange={userLocationCallback} + onPanDrag={mapEventCallback} + onPoiClick={(event: MapEvent<{ placeId: string, name: string }>) => console.log(event)} + onMarkerPress={(event: MapEvent<{ action: 'marker-press', id: string }>) => console.log(event)} + onMarkerSelect={(event: MapEvent<{ action: 'marker-select', id: string }>) => console.log(event)} + onMarkerDeselect={(event: MapEvent<{ action: 'marker-deselect', id: string }>) => console.log(event)} + onCalloutPress={(event: MapEvent<{ action: 'callout-press' }>) => console.log(event)} + onMarkerDragStart={mapEventCallback} + onMarkerDrag={mapEventCallback} + onMarkerDragEnd={mapEventCallback} + + minZoomLevel={0} + maxZoomLevel={0} + kmlSrc="src" + style={{ flex: 1 }} + /> +); +// #endegion + async () => { const updateEventListener: Updates.UpdateEventListener = ({ type, manifest, message }) => { switch (type) { @@ -916,6 +1016,7 @@ async () => { return true; } }; + // #region MediaLibrary async () => { const mlAsset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('localUri'); diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 9e48e391d8..55dc4ffd06 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -16,6 +16,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +export * from 'react-native-maps'; +export { default as MapView } from 'react-native-maps'; + import { EventSubscription } from 'fbemitter'; import { Component, ComponentClass, Ref, ComponentType } from 'react'; import { diff --git a/types/expo/package.json b/types/expo/package.json new file mode 100644 index 0000000000..4abdc24638 --- /dev/null +++ b/types/expo/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "react-native-maps": "*" + } +} diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 39b3e45757..60ec11648f 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -4529,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/fast64/fast64-tests.ts b/types/fast64/fast64-tests.ts new file mode 100644 index 0000000000..f038b9d0a8 --- /dev/null +++ b/types/fast64/fast64-tests.ts @@ -0,0 +1,8 @@ +import * as fast64 from "fast64"; + +fast64.encode(""); // $ExpectType string +fast64.decode(""); // $ExpectType string +fast64.decode("", { uint8Array: true }); // $ExpectType Uint8Array +fast64.urlencode(""); // $ExpectType string +fast64.urldecode(""); // $ExpectType string +fast64.urldecode("", { uint8Array: true }); // $ExpectType Uint8Array diff --git a/types/fast64/index.d.ts b/types/fast64/index.d.ts new file mode 100644 index 0000000000..47f067859c --- /dev/null +++ b/types/fast64/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for fast64 0.5 +// Project: https://github.com/superhuman/fast64 +// Definitions by: Rares Matei +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Options { + uint8Array: boolean; +} + +export function encode(value: string): string; +export function decode(base64: string): string; +export function decode(base64: string, options: Options): Uint8Array; +export function urlencode(value: string): string; +export function urldecode(base64: string): string; +export function urldecode(base64: string, options: Options): Uint8Array; diff --git a/types/fast64/tsconfig.json b/types/fast64/tsconfig.json new file mode 100644 index 0000000000..4ad215d37c --- /dev/null +++ b/types/fast64/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", + "fast64-tests.ts" + ] +} \ No newline at end of file diff --git a/types/fast64/tslint.json b/types/fast64/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fast64/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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 5948eadc27..4746b29ff7 100644 --- a/types/feathersjs__feathers/index.d.ts +++ b/types/feathersjs__feathers/index.d.ts @@ -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; diff --git a/types/file-type/file-type-tests.ts b/types/file-type/file-type-tests.ts index 640d2c8fb0..d49a964829 100644 --- a/types/file-type/file-type-tests.ts +++ b/types/file-type/file-type-tests.ts @@ -1,6 +1,8 @@ import fileType = require("file-type"); +// $ExpectType FileTypeResult | null fileType(new Buffer([0xFF, 0xD8, 0xFF])); fileType(new Uint8Array([0xFF, 0xD8, 0xFF])); -const minimumBytes: number = fileType.minimumBytes; +// $ExpectType number +fileType.minimumBytes; diff --git a/types/file-type/index.d.ts b/types/file-type/index.d.ts index 2a0deee26a..c902dc384e 100644 --- a/types/file-type/index.d.ts +++ b/types/file-type/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for file-type 5.2 +// Type definitions for file-type 10.6 // Project: https://github.com/sindresorhus/file-type // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk // BendingBender @@ -8,7 +8,17 @@ export = FileType; -declare function FileType(buf: Buffer | Uint8Array): FileType.FileTypeResult; +/** + * The file type is detected by checking the + * [magic number](http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + * + * @param buf It only needs the first `.minimumBytes` bytes. The exception is detection of + * `docx`, `pptx`, and `xlsx` which potentially requires reading the whole file. + * @returns an Object with: + * - ext - One of the [supported file types](https://github.com/sindresorhus/file-type/blob/master/readme.md#supported-file-types) + * - mime - The [MIME type](http://en.wikipedia.org/wiki/Internet_media_type) + */ +declare function FileType(buf: Buffer | Uint8Array): FileType.FileTypeResult | null; declare namespace FileType { interface FileTypeResult { @@ -16,5 +26,9 @@ declare namespace FileType { mime: string; } + /** + * The minimum amount of bytes needed to detect a file type. Currently, + * it's 4100 bytes, but it can change, so don't hard-code it. + */ const minimumBytes: number; } diff --git a/types/file-type/tsconfig.json b/types/file-type/tsconfig.json index 499b81459c..1894b908af 100644 --- a/types/file-type/tsconfig.json +++ b/types/file-type/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", "file-type-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/find-java-home/find-java-home-tests.ts b/types/find-java-home/find-java-home-tests.ts new file mode 100644 index 0000000000..36b7004055 --- /dev/null +++ b/types/find-java-home/find-java-home-tests.ts @@ -0,0 +1,6 @@ +import findJavaHome = require("find-java-home"); +import { promisify } from "util"; + +findJavaHome(() => { }); // $ExpectType void +findJavaHome({ allowJre: true }, () => { }); // $ExpectType void +promisify(findJavaHome); // $ExpectType (options?: { allowJre?: boolean | undefined; } | undefined) => Promise diff --git a/types/find-java-home/index.d.ts b/types/find-java-home/index.d.ts new file mode 100644 index 0000000000..a512d51b26 --- /dev/null +++ b/types/find-java-home/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for find-java-home 0.2 +// Project: https://github.com/jsdevel/node-find-java-home +// Definitions by: sjx233 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function findJavaHome(callback: (err: Error | undefined, home: string) => void): void; +declare function findJavaHome(options: { allowJre?: boolean }, callback: (err: Error | undefined, home: string) => void): void; + +declare namespace findJavaHome { + function __promisify__(options?: { allowJre?: boolean }): Promise; +} + +export = findJavaHome; diff --git a/types/find-java-home/tsconfig.json b/types/find-java-home/tsconfig.json new file mode 100644 index 0000000000..fcf2def157 --- /dev/null +++ b/types/find-java-home/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", + "find-java-home-tests.ts" + ] +} diff --git a/types/find-java-home/tslint.json b/types/find-java-home/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/find-java-home/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/findup-sync/findup-sync-tests.ts b/types/findup-sync/findup-sync-tests.ts index 789190dcce..87a334eea6 100644 --- a/types/findup-sync/findup-sync-tests.ts +++ b/types/findup-sync/findup-sync-tests.ts @@ -1,14 +1,17 @@ import findup = require('findup-sync'); -var str: string; +let str: string; str = findup('foo'); str = findup(['foo', 'bar']); str = findup('foo', { - debug: true + matchBase: true, }); str = findup('foo', { - cwd: "c:\\" + cwd: 'c:\\', }); + +str = findup('{a,b}*.txt'); +str = findup('{a,b}*.txt', { cwd: '/some/path', nocase: true }); diff --git a/types/findup-sync/index.d.ts b/types/findup-sync/index.d.ts index bd06c12d46..23df60a22f 100644 --- a/types/findup-sync/index.d.ts +++ b/types/findup-sync/index.d.ts @@ -1,14 +1,22 @@ -// Type definitions for findup-sync v0.3.0 +// Type definitions for findup-sync 2.0 // Project: https://github.com/cowboy/node-findup-sync -// Definitions by: Bart van der Schoor , Nathan Brown +// Definitions by: Bart van der Schoor +// Nathan Brown +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -import minimatch = require('minimatch'); +import micromatch = require('micromatch'); -interface IOptions extends minimatch.IOptions { - cwd?: string; +export = findupSync; + +declare function findupSync( + patternOrPatterns: string[] | string, + micromatchOptions?: findupSync.Options +): string; + +declare namespace findupSync { + interface Options extends micromatch.Options { + cwd?: string; + } } - -declare function mod(pattern: string[] | string, opts?: IOptions): string; - -export = mod; diff --git a/types/findup-sync/tslint.json b/types/findup-sync/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/findup-sync/tslint.json +++ b/types/findup-sync/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/findup-sync/v0/findup-sync-tests.ts b/types/findup-sync/v0/findup-sync-tests.ts new file mode 100644 index 0000000000..789190dcce --- /dev/null +++ b/types/findup-sync/v0/findup-sync-tests.ts @@ -0,0 +1,14 @@ +import findup = require('findup-sync'); + +var str: string; + +str = findup('foo'); +str = findup(['foo', 'bar']); + +str = findup('foo', { + debug: true +}); + +str = findup('foo', { + cwd: "c:\\" +}); diff --git a/types/findup-sync/v0/index.d.ts b/types/findup-sync/v0/index.d.ts new file mode 100644 index 0000000000..bd06c12d46 --- /dev/null +++ b/types/findup-sync/v0/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for findup-sync v0.3.0 +// Project: https://github.com/cowboy/node-findup-sync +// Definitions by: Bart van der Schoor , Nathan Brown +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import minimatch = require('minimatch'); + +interface IOptions extends minimatch.IOptions { + cwd?: string; +} + +declare function mod(pattern: string[] | string, opts?: IOptions): string; + +export = mod; diff --git a/types/findup-sync/v0/tsconfig.json b/types/findup-sync/v0/tsconfig.json new file mode 100644 index 0000000000..dd28d081d0 --- /dev/null +++ b/types/findup-sync/v0/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "findup-sync": [ + "findup-sync/v0" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "findup-sync-tests.ts" + ] +} diff --git a/types/findup-sync/v0/tslint.json b/types/findup-sync/v0/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/findup-sync/v0/tslint.json @@ -0,0 +1,79 @@ +{ + "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 + } +} 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/fingerprintjs2/fingerprintjs2-tests.ts b/types/fingerprintjs2/fingerprintjs2-tests.ts index d295ab7aab..f11caae127 100644 --- a/types/fingerprintjs2/fingerprintjs2-tests.ts +++ b/types/fingerprintjs2/fingerprintjs2-tests.ts @@ -1,123 +1,135 @@ -function defaultCallback(result: string, components: [{ key: string, value: string }]) { - console.log(`res: ${result}; components: ${components}`); +import * as fingerprint2 from 'fingerprintjs2'; + +function defaultCallback(components: fingerprint2.Component[]) {} +function v18Callback(murmur: string, components: fingerprint2.V18Component[]) {} + +function test_x64hash128() { + // $ExpectType string + fingerprint2.x64hash128('abc', 99); } -function test_default_settings() { - const fingerprint = new Fingerprint2().get(defaultCallback); +function test_get_default_settings() { + fingerprint2.get(defaultCallback); } -function test_get_exclude_swfContainerId() { - const fingerprint = new Fingerprint2({ swfContainerId: 'swfContainerId' }).get(defaultCallback); +function test_get_with_options() { + fingerprint2.get({ excludes: { userAgent: true } }, defaultCallback); } -function test_get_exclude_swfPath() { - const fingerprint = new Fingerprint2({swfPath: 'pathToSwf'}).get(defaultCallback); +function test_getPromise_default_settings() { + // $ExpectType Promise + fingerprint2.getPromise(); } -function test_get_exclude_userDefinedFonts() { - const fingerprint = new Fingerprint2({ userDefinedFonts: ['font1', 'font2']}).get(defaultCallback); +function test_getPromise_with_options() { + // $ExpectType Promise + fingerprint2.getPromise({ excludes: { userAgent: true } }); } -function test_get_excludeUserAgent() { - const fingerprint = new Fingerprint2({ excludeUserAgent: true }).get(defaultCallback); +function test_getV18_default_settings() { + fingerprint2.getV18(v18Callback); } -function test_get_excludeLanguage() { - const fingerprint = new Fingerprint2({ excludeLanguage: true }).get(defaultCallback); +function test_getV18_with_options() { + fingerprint2.getV18({ excludes: { userAgent: true } }, v18Callback); } -function test_get_excludeColorDepth() { - const fingerprint = new Fingerprint2({ excludeColorDepth: true }).get(defaultCallback); +function test_get_audio_options() { + const options: fingerprint2.Options = { + audio: { + timeout: 10, + excludeIOS11: true, + }, + }; + fingerprint2.get(options, defaultCallback); } -function test_get_excludeScreenResolution() { - const fingerprint = new Fingerprint2({ excludeScreenResolution: true }).get(defaultCallback); +function test_get_fonts_options() { + const options: fingerprint2.Options = { + fonts: { + swfContainerId: 'swfContainerId', + swfPath: 'pathToSwf', + userDefinedFonts: ['font1', 'font2'], + extendedJsFonts: true, + }, + }; + fingerprint2.get(options, defaultCallback); } -function test_get_excludeTimezoneOffset() { - const fingerprint = new Fingerprint2({ excludeTimezoneOffset: true }).get(defaultCallback); +function test_get_screen_options() { + const options: fingerprint2.Options = { + screen: { + detectScreenOrientation: true, + }, + }; + fingerprint2.get(options, defaultCallback); } -function test_get_excludeSessionStorage() { - const fingerprint = new Fingerprint2({ excludeSessionStorage: true }).get(defaultCallback); +function test_get_plugins_options() { + const options: fingerprint2.Options = { + plugins: { + sortPluginsFor: [/foo/i], + excludeIE: true, + }, + }; + fingerprint2.get(options, defaultCallback); } -function test_get_excludeIndexedDB() { - const fingerprint = new Fingerprint2({ excludeIndexedDB: true }).get(defaultCallback); +function test_get_extraComponents_options() { + const options: fingerprint2.Options = { + extraComponents: [ + { + key: 'foo', + getData(done, options) { + // $ExpectType (value: any) => void + done; + // $ExpectType Options + options; + + done('foo'); + }, + pauseBefore: false, + }, + ], + }; + fingerprint2.get(options, defaultCallback); } -function test_get_excludeAddBehavior() { - const fingerprint = new Fingerprint2({ excludeAddBehavior: true }).get(defaultCallback); -} +function test_get_excludes_options() { + let options: fingerprint2.Options; -function test_get_excludeOpenDatabase() { - const fingerprint = new Fingerprint2({ excludeOpenDatabase: true }).get(defaultCallback); -} + options = { excludes: { userAgent: true } }; + options = { excludes: { language: true } }; + options = { excludes: { colorDepth: true } }; + options = { excludes: { deviceMemory: true } }; + options = { excludes: { pixelRatio: true } }; + options = { excludes: { hardwareConcurrency: true } }; + options = { excludes: { screenResolution: true } }; + options = { excludes: { availableScreenResolution: true } }; + options = { excludes: { timezoneOffset: true } }; + options = { excludes: { timezone: true } }; + options = { excludes: { sessionStorage: true } }; + options = { excludes: { localStorage: true } }; + options = { excludes: { indexedDb: true } }; + options = { excludes: { addBehavior: true } }; + options = { excludes: { openDatabase: true } }; + options = { excludes: { cpuClass: true } }; + options = { excludes: { platform: true } }; + options = { excludes: { doNotTrack: true } }; + options = { excludes: { plugins: true } }; + options = { excludes: { canvas: true } }; + options = { excludes: { webgl: true } }; + options = { excludes: { webglVendorAndRenderer: true } }; + options = { excludes: { adBlock: true } }; + options = { excludes: { hasLiedLanguages: true } }; + options = { excludes: { hasLiedResolution: true } }; + options = { excludes: { hasLiedOs: true } }; + options = { excludes: { hasLiedBrowser: true } }; + options = { excludes: { touchSupport: true } }; + options = { excludes: { fonts: true } }; + options = { excludes: { fontsFlash: true } }; + options = { excludes: { audio: true } }; + options = { excludes: { enumerateDevices: true } }; -function test_get_excludeCpuClass() { - const fingerprint = new Fingerprint2({ excludeCpuClass: true }).get(defaultCallback); -} - -function test_get_excludePlatform() { - const fingerprint = new Fingerprint2({ excludePlatform: true }).get(defaultCallback); -} - -function test_get_excludeDoNotTrack() { - const fingerprint = new Fingerprint2({ excludeDoNotTrack: true }).get(defaultCallback); -} - -function test_get_excludeCanvas() { - const fingerprint = new Fingerprint2({ excludeCanvas: true }).get(defaultCallback); -} - -function test_get_excludeWebGL() { - const fingerprint = new Fingerprint2({ excludeWebGL: true }).get(defaultCallback); -} - -function test_get_excludeAdBlock() { - const fingerprint = new Fingerprint2({ excludeAdBlock: true }).get(defaultCallback); -} - -function test_get_excludeHasLiedLanguages() { - const fingerprint = new Fingerprint2({ excludeHasLiedLanguages: true }).get(defaultCallback); -} - -function test_get_excludeHasLiedResolution() { - const fingerprint = new Fingerprint2({ excludeHasLiedResolution: true }).get(defaultCallback); -} - -function test_get_excludeHasLiedOs() { - const fingerprint = new Fingerprint2({ excludeHasLiedOs: true }).get(defaultCallback); -} - -function test_get_excludeHasLiedBrowser() { - const fingerprint = new Fingerprint2({ excludeHasLiedBrowser: true }).get(defaultCallback); -} - -function test_get_excludeJsFonts() { - const fingerprint = new Fingerprint2({ excludeJsFonts: true }).get(defaultCallback); -} - -function test_get_excludeFlashFonts() { - const fingerprint = new Fingerprint2({ excludeFlashFonts: true }).get(defaultCallback); -} - -function test_get_excludePlugins() { - const fingerprint = new Fingerprint2({ excludePlugins: true }).get(defaultCallback); -} - -function test_get_excludeIEPlugins() { - const fingerprint = new Fingerprint2({ excludeIEPlugins: true }).get(defaultCallback); -} - -function test_get_excludeTouchSupport() { - const fingerprint = new Fingerprint2({ excludeTouchSupport: true }).get(defaultCallback); -} - -function test_get_excludePixelRatio() { - const fingerprint = new Fingerprint2({ excludePixelRatio: true }).get(defaultCallback); -} - -function test_get_excludeHardwareConcurrency() { - const fingerprint = new Fingerprint2({ excludeHardwareConcurrency: true }).get(defaultCallback); + fingerprint2.get(options, defaultCallback); } diff --git a/types/fingerprintjs2/index.d.ts b/types/fingerprintjs2/index.d.ts index 5778eebeed..1b8a50fe77 100644 --- a/types/fingerprintjs2/index.d.ts +++ b/types/fingerprintjs2/index.d.ts @@ -1,46 +1,124 @@ -// Type definitions for fingerprintjs2 1.5 +// Type definitions for fingerprintjs2 2.0 // Project: https://github.com/Valve/fingerprintjs2 // Definitions by: Curt Mullin +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class Fingerprint2 { - static VERSION: string; - constructor(options?: Fingerprint2Options); - - get(callback: (result: string, components: [{ key: string, value: string }]) => void): number; -} - -interface Fingerprint2Options { - swfContainerId?: string; - swfPath?: string; - userDefinedFonts?: string[]; - excludeUserAgent?: boolean; - excludeLanguage?: boolean; - excludeColorDepth?: boolean; - excludeScreenResolution?: boolean; - excludeTimezoneOffset?: boolean; - excludeSessionStorage?: boolean; - excludeIndexedDB?: boolean; - excludeAddBehavior?: boolean; - excludeOpenDatabase?: boolean; - excludeCpuClass?: boolean; - excludePlatform?: boolean; - excludeDoNotTrack?: boolean; - excludeCanvas?: boolean; - excludeWebGL?: boolean; - excludeAdBlock?: boolean; - excludeHasLiedLanguages?: boolean; - excludeHasLiedResolution?: boolean; - excludeHasLiedOs?: boolean; - excludeHasLiedBrowser?: boolean; - excludeJsFonts?: boolean; - excludeFlashFonts?: boolean; - excludePlugins?: boolean; - excludeIEPlugins?: boolean; - excludeTouchSupport?: boolean; - excludePixelRatio?: boolean; - excludeHardwareConcurrency?: boolean; -} - -export = Fingerprint2; export as namespace Fingerprint2; +export = Fingerprint2; + +declare var Fingerprint2: Fingerprint2.Static; + +declare namespace Fingerprint2 { + interface Static { + VERSION: string; + + get(options: Options, callback: (components: Component[]) => void): void; + get(callback: (components: Component[]) => void): void; + getPromise(options?: Options): Promise; + getV18( + options: Options, + callback: (murmur: string, components: V18Component[]) => void + ): void; + getV18(callback: (murmur: string, components: V18Component[]) => void): void; + + x64hash128(value: string, num: number): string; + } + + interface Component { + key: string; + value: any; + } + + interface V18Component { + key: string; + value: string; + } + + interface Options { + preprocessor?: (key: string, value: any) => any; + + audio?: { + timeout: number; + /** + * On iOS 11, audio context can only be used in response to user interaction. + * We require users to explicitly enable audio fingerprinting on iOS 11. + * See https://stackoverflow.com/questions/46363048/onaudioprocess-not-called-on-ios11#46534088 + */ + excludeIOS11: boolean; + }; + + fonts?: { + swfContainerId: string; + swfPath: string; + userDefinedFonts: string[]; + extendedJsFonts: boolean; + }; + + screen?: { + /** + * To ensure consistent fingerprints when users rotate their mobile devices + */ + detectScreenOrientation: boolean; + }; + + plugins?: { + sortPluginsFor: RegExp[]; + excludeIE: boolean; + }; + + extraComponents?: Array<{ + key: string; + getData(done: (value: any) => void, options: Options): void; + pauseBefore?: boolean; + }>; + + excludes?: { + userAgent?: boolean; + language?: boolean; + colorDepth?: boolean; + deviceMemory?: boolean; + /** + * devicePixelRatio depends on browser zoom, and it's impossible to detect browser zoom + */ + pixelRatio?: boolean; + hardwareConcurrency?: boolean; + screenResolution?: boolean; + availableScreenResolution?: boolean; + timezoneOffset?: boolean; + timezone?: boolean; + sessionStorage?: boolean; + localStorage?: boolean; + indexedDb?: boolean; + addBehavior?: boolean; + openDatabase?: boolean; + cpuClass?: boolean; + platform?: boolean; + /** + * DNT depends on incognito mode for some browsers (Chrome) and it's impossible to detect incognito mode + */ + doNotTrack?: boolean; + plugins?: boolean; + canvas?: boolean; + webgl?: boolean; + webglVendorAndRenderer?: boolean; + adBlock?: boolean; + hasLiedLanguages?: boolean; + hasLiedResolution?: boolean; + hasLiedOs?: boolean; + hasLiedBrowser?: boolean; + touchSupport?: boolean; + fonts?: boolean; + fontsFlash?: boolean; + audio?: boolean; + /** + * Unreliable on Windows, see https://github.com/Valve/fingerprintjs2/issues/375 + */ + enumerateDevices?: boolean; + }; + + NOT_AVAILABLE?: string; + ERROR?: string; + EXCLUDED?: string; + } +} diff --git a/types/fingerprintjs2/v1/fingerprintjs2-tests.ts b/types/fingerprintjs2/v1/fingerprintjs2-tests.ts new file mode 100644 index 0000000000..d295ab7aab --- /dev/null +++ b/types/fingerprintjs2/v1/fingerprintjs2-tests.ts @@ -0,0 +1,123 @@ +function defaultCallback(result: string, components: [{ key: string, value: string }]) { + console.log(`res: ${result}; components: ${components}`); +} + +function test_default_settings() { + const fingerprint = new Fingerprint2().get(defaultCallback); +} + +function test_get_exclude_swfContainerId() { + const fingerprint = new Fingerprint2({ swfContainerId: 'swfContainerId' }).get(defaultCallback); +} + +function test_get_exclude_swfPath() { + const fingerprint = new Fingerprint2({swfPath: 'pathToSwf'}).get(defaultCallback); +} + +function test_get_exclude_userDefinedFonts() { + const fingerprint = new Fingerprint2({ userDefinedFonts: ['font1', 'font2']}).get(defaultCallback); +} + +function test_get_excludeUserAgent() { + const fingerprint = new Fingerprint2({ excludeUserAgent: true }).get(defaultCallback); +} + +function test_get_excludeLanguage() { + const fingerprint = new Fingerprint2({ excludeLanguage: true }).get(defaultCallback); +} + +function test_get_excludeColorDepth() { + const fingerprint = new Fingerprint2({ excludeColorDepth: true }).get(defaultCallback); +} + +function test_get_excludeScreenResolution() { + const fingerprint = new Fingerprint2({ excludeScreenResolution: true }).get(defaultCallback); +} + +function test_get_excludeTimezoneOffset() { + const fingerprint = new Fingerprint2({ excludeTimezoneOffset: true }).get(defaultCallback); +} + +function test_get_excludeSessionStorage() { + const fingerprint = new Fingerprint2({ excludeSessionStorage: true }).get(defaultCallback); +} + +function test_get_excludeIndexedDB() { + const fingerprint = new Fingerprint2({ excludeIndexedDB: true }).get(defaultCallback); +} + +function test_get_excludeAddBehavior() { + const fingerprint = new Fingerprint2({ excludeAddBehavior: true }).get(defaultCallback); +} + +function test_get_excludeOpenDatabase() { + const fingerprint = new Fingerprint2({ excludeOpenDatabase: true }).get(defaultCallback); +} + +function test_get_excludeCpuClass() { + const fingerprint = new Fingerprint2({ excludeCpuClass: true }).get(defaultCallback); +} + +function test_get_excludePlatform() { + const fingerprint = new Fingerprint2({ excludePlatform: true }).get(defaultCallback); +} + +function test_get_excludeDoNotTrack() { + const fingerprint = new Fingerprint2({ excludeDoNotTrack: true }).get(defaultCallback); +} + +function test_get_excludeCanvas() { + const fingerprint = new Fingerprint2({ excludeCanvas: true }).get(defaultCallback); +} + +function test_get_excludeWebGL() { + const fingerprint = new Fingerprint2({ excludeWebGL: true }).get(defaultCallback); +} + +function test_get_excludeAdBlock() { + const fingerprint = new Fingerprint2({ excludeAdBlock: true }).get(defaultCallback); +} + +function test_get_excludeHasLiedLanguages() { + const fingerprint = new Fingerprint2({ excludeHasLiedLanguages: true }).get(defaultCallback); +} + +function test_get_excludeHasLiedResolution() { + const fingerprint = new Fingerprint2({ excludeHasLiedResolution: true }).get(defaultCallback); +} + +function test_get_excludeHasLiedOs() { + const fingerprint = new Fingerprint2({ excludeHasLiedOs: true }).get(defaultCallback); +} + +function test_get_excludeHasLiedBrowser() { + const fingerprint = new Fingerprint2({ excludeHasLiedBrowser: true }).get(defaultCallback); +} + +function test_get_excludeJsFonts() { + const fingerprint = new Fingerprint2({ excludeJsFonts: true }).get(defaultCallback); +} + +function test_get_excludeFlashFonts() { + const fingerprint = new Fingerprint2({ excludeFlashFonts: true }).get(defaultCallback); +} + +function test_get_excludePlugins() { + const fingerprint = new Fingerprint2({ excludePlugins: true }).get(defaultCallback); +} + +function test_get_excludeIEPlugins() { + const fingerprint = new Fingerprint2({ excludeIEPlugins: true }).get(defaultCallback); +} + +function test_get_excludeTouchSupport() { + const fingerprint = new Fingerprint2({ excludeTouchSupport: true }).get(defaultCallback); +} + +function test_get_excludePixelRatio() { + const fingerprint = new Fingerprint2({ excludePixelRatio: true }).get(defaultCallback); +} + +function test_get_excludeHardwareConcurrency() { + const fingerprint = new Fingerprint2({ excludeHardwareConcurrency: true }).get(defaultCallback); +} diff --git a/types/fingerprintjs2/v1/index.d.ts b/types/fingerprintjs2/v1/index.d.ts new file mode 100644 index 0000000000..5778eebeed --- /dev/null +++ b/types/fingerprintjs2/v1/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for fingerprintjs2 1.5 +// Project: https://github.com/Valve/fingerprintjs2 +// Definitions by: Curt Mullin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Fingerprint2 { + static VERSION: string; + constructor(options?: Fingerprint2Options); + + get(callback: (result: string, components: [{ key: string, value: string }]) => void): number; +} + +interface Fingerprint2Options { + swfContainerId?: string; + swfPath?: string; + userDefinedFonts?: string[]; + excludeUserAgent?: boolean; + excludeLanguage?: boolean; + excludeColorDepth?: boolean; + excludeScreenResolution?: boolean; + excludeTimezoneOffset?: boolean; + excludeSessionStorage?: boolean; + excludeIndexedDB?: boolean; + excludeAddBehavior?: boolean; + excludeOpenDatabase?: boolean; + excludeCpuClass?: boolean; + excludePlatform?: boolean; + excludeDoNotTrack?: boolean; + excludeCanvas?: boolean; + excludeWebGL?: boolean; + excludeAdBlock?: boolean; + excludeHasLiedLanguages?: boolean; + excludeHasLiedResolution?: boolean; + excludeHasLiedOs?: boolean; + excludeHasLiedBrowser?: boolean; + excludeJsFonts?: boolean; + excludeFlashFonts?: boolean; + excludePlugins?: boolean; + excludeIEPlugins?: boolean; + excludeTouchSupport?: boolean; + excludePixelRatio?: boolean; + excludeHardwareConcurrency?: boolean; +} + +export = Fingerprint2; +export as namespace Fingerprint2; diff --git a/types/fingerprintjs2/v1/tsconfig.json b/types/fingerprintjs2/v1/tsconfig.json new file mode 100644 index 0000000000..4f7e97d591 --- /dev/null +++ b/types/fingerprintjs2/v1/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "fingerprintjs2": [ + "fingerprintjs2/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fingerprintjs2-tests.ts" + ] +} diff --git a/types/fingerprintjs2/v1/tslint.json b/types/fingerprintjs2/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fingerprintjs2/v1/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/flushable/flushable-tests.ts b/types/flushable/flushable-tests.ts new file mode 100644 index 0000000000..3d4bf565dc --- /dev/null +++ b/types/flushable/flushable-tests.ts @@ -0,0 +1,20 @@ +/** + * The usage example is taken directly + * from the package's README + */ + +import flushable from 'flushable'; + +// prints a message to the console after 1 second +const operation = flushable(flushed => { + const result = `I completed ${flushed ? 'early' : 'on time'}`; +}, 1000); + +// true if the callback has not been executed +operation.pending(); + +// stops the callback from being executed +operation.cancel(); + +// immediately executes the callback +operation.flush(); diff --git a/types/flushable/index.d.ts b/types/flushable/index.d.ts new file mode 100644 index 0000000000..eb3a08a214 --- /dev/null +++ b/types/flushable/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for flushable 1.0 +// Project: https://github.com/petegleeson/flushable#readme +// Definitions by: Parth Mehta +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type FlushableOnCompleteHandler = (flushed: boolean) => any; + +export interface FlushableOperation { + /** Returns whether or not the callback has been executed */ + pending: () => boolean; + /** Stops the callback from being executed */ + cancel: () => void; + /** Immediately executes the callback */ + flush: () => void; +} + +export default function flushable( + onComplete: FlushableOnCompleteHandler, + delay: number +): FlushableOperation; diff --git a/types/flushable/tsconfig.json b/types/flushable/tsconfig.json new file mode 100644 index 0000000000..27b5900f3e --- /dev/null +++ b/types/flushable/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", "flushable-tests.ts"] +} diff --git a/types/flushable/tslint.json b/types/flushable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/flushable/tslint.json @@ -0,0 +1 @@ +{ "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/get-certain/get-certain-tests.ts b/types/get-certain/get-certain-tests.ts new file mode 100644 index 0000000000..fde423095c --- /dev/null +++ b/types/get-certain/get-certain-tests.ts @@ -0,0 +1,9 @@ +import getCertain = require('get-certain'); + +const map = new Map(); + +map.set('foo', 1); + +// $ExpectType number +getCertain(map, 'foo'); +getCertain(map, 'bar', 'This map is barless.'); diff --git a/types/get-certain/index.d.ts b/types/get-certain/index.d.ts new file mode 100644 index 0000000000..bbde669d19 --- /dev/null +++ b/types/get-certain/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for get-certain 1.0 +// Project: https://github.com/wtgtybhertgeghgtwtg/get-certain#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = getCertain; + +declare function getCertain( + map: Map, + key: TKey, + message?: string +): TValue; diff --git a/types/get-certain/tsconfig.json b/types/get-certain/tsconfig.json new file mode 100644 index 0000000000..777807992c --- /dev/null +++ b/types/get-certain/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", + "get-certain-tests.ts" + ] +} diff --git a/types/get-certain/tslint.json b/types/get-certain/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/get-certain/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/get-emails/get-emails-tests.ts b/types/get-emails/get-emails-tests.ts new file mode 100644 index 0000000000..dbdad0f5a3 --- /dev/null +++ b/types/get-emails/get-emails-tests.ts @@ -0,0 +1,6 @@ +import getEmails = require('get-emails'); + +const text = 'Lorem ipsum dolor, sindresorhus@gmail.com consectetuer unicorn@rainbow.cake elit.'; + +// $ExpectType Set +getEmails(text); diff --git a/types/get-emails/index.d.ts b/types/get-emails/index.d.ts new file mode 100644 index 0000000000..2063abc878 --- /dev/null +++ b/types/get-emails/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for get-emails 2.1 +// Project: https://github.com/sindresorhus/get-emails#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = getEmails; + +declare function getEmails(text: string): Set; diff --git a/types/get-emails/tsconfig.json b/types/get-emails/tsconfig.json new file mode 100644 index 0000000000..3590ec5f4b --- /dev/null +++ b/types/get-emails/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", + "get-emails-tests.ts" + ] +} diff --git a/types/get-emails/tslint.json b/types/get-emails/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/get-emails/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/get-emoji/get-emoji-tests.ts b/types/get-emoji/get-emoji-tests.ts new file mode 100644 index 0000000000..fe196cbb92 --- /dev/null +++ b/types/get-emoji/get-emoji-tests.ts @@ -0,0 +1,7 @@ +import getEmoji, { emojiList } from 'get-emoji'; + +// $ExpectType string +getEmoji('rage'); + +// $ExpectType string[] +emojiList; diff --git a/types/get-emoji/index.d.ts b/types/get-emoji/index.d.ts new file mode 100644 index 0000000000..a596108872 --- /dev/null +++ b/types/get-emoji/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for get-emoji 2.0 +// Project: https://github.com/conorhastings/get-emoji +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default function getEmoji(emojiName: string): string; +export const emojiList: string[]; diff --git a/types/get-emoji/tsconfig.json b/types/get-emoji/tsconfig.json new file mode 100644 index 0000000000..9b947e40e4 --- /dev/null +++ b/types/get-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", + "get-emoji-tests.ts" + ] +} diff --git a/types/get-emoji/tslint.json b/types/get-emoji/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/get-emoji/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/get-port/get-port-tests.ts b/types/get-port/get-port-tests.ts index 53a9e8e69b..5e47c33c1a 100644 --- a/types/get-port/get-port-tests.ts +++ b/types/get-port/get-port-tests.ts @@ -1,13 +1,10 @@ -import * as getPort from "get-port"; +import getPort = require('get-port'); -getPort().then(port => { - console.log(port); -}); - -getPort({ port: 3000 }).then(port => { - console.log(port); -}); - -getPort({ port: [3000, 3001] }).then(port => { - console.log(port); -}); +// $ExpectType Promise +getPort(); +// $ExpectType Promise +getPort({ port: 3000 }); +// $ExpectType Promise +getPort({ port: [3000, 3001] }); +// $ExpectType Promise +getPort({ host: 'foo.local' }); diff --git a/types/get-port/index.d.ts b/types/get-port/index.d.ts index f8adb4851e..9af3b311fc 100644 --- a/types/get-port/index.d.ts +++ b/types/get-port/index.d.ts @@ -1,9 +1,12 @@ // Type definitions for get-port 4.0 // Project: https://github.com/sindresorhus/get-port -// Definitions by: York Yao +// Definitions by: York Yao +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "get-port" { - var getPort: (options?: { port?: number | ReadonlyArray, host?: string }) => PromiseLike - export = getPort; -} +declare function getPort(options?: { + port?: number | ReadonlyArray; + host?: string; +}): Promise; + +export = getPort; diff --git a/types/get-port/tsconfig.json b/types/get-port/tsconfig.json index c221d4e9fd..0d9f3a8975 100644 --- a/types/get-port/tsconfig.json +++ b/types/get-port/tsconfig.json @@ -2,12 +2,11 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +20,4 @@ "index.d.ts", "get-port-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/get-port/tslint.json b/types/get-port/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/get-port/tslint.json +++ b/types/get-port/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/get-urls/get-urls-tests.ts b/types/get-urls/get-urls-tests.ts new file mode 100644 index 0000000000..a901a2aac2 --- /dev/null +++ b/types/get-urls/get-urls-tests.ts @@ -0,0 +1,16 @@ +import getUrls = require('get-urls'); + +const text = + 'Lorem ipsum dolor sit amet, //sindresorhus.com consectetuer adipiscing http://yeoman.io elit.'; + +// $ExpectType Set +getUrls(text); + +// $ExpectType Set +getUrls(text, { extractFromQueryString: true }); + +// $ExpectType Set +getUrls(text, { exclude: ['foo'] }); + +// $ExpectType Set +getUrls(text, { defaultProtocol: 'ftp' }); diff --git a/types/get-urls/index.d.ts b/types/get-urls/index.d.ts new file mode 100644 index 0000000000..b62c32aa24 --- /dev/null +++ b/types/get-urls/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for get-urls 8.0 +// Project: https://github.com/sindresorhus/get-urls#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Options as NormalizeUrlOptions } from 'normalize-url'; + +export = getUrls; + +declare function getUrls(text: string, options?: getUrls.Options): Set; + +declare namespace getUrls { + interface Options extends NormalizeUrlOptions { + extractFromQueryString?: boolean; + exclude?: string[]; + } +} diff --git a/types/get-urls/tsconfig.json b/types/get-urls/tsconfig.json new file mode 100644 index 0000000000..fd5acf72bd --- /dev/null +++ b/types/get-urls/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", + "get-urls-tests.ts" + ] +} diff --git a/types/get-urls/tslint.json b/types/get-urls/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/get-urls/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/github-username/github-username-tests.ts b/types/github-username/github-username-tests.ts new file mode 100644 index 0000000000..0caee06bdc --- /dev/null +++ b/types/github-username/github-username-tests.ts @@ -0,0 +1,4 @@ +import githubUsername = require('github-username'); + +// $ExpectType Promise +githubUsername('sindresorhus@gmail.com', 'deadbeef'); diff --git a/types/github-username/index.d.ts b/types/github-username/index.d.ts new file mode 100644 index 0000000000..a1083c7dc3 --- /dev/null +++ b/types/github-username/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for github-username 4.1 +// Project: https://github.com/sindresorhus/github-username#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = githubUsername; + +declare function githubUsername(email: string, token: string): Promise; diff --git a/types/github-username/tsconfig.json b/types/github-username/tsconfig.json new file mode 100644 index 0000000000..33308515f6 --- /dev/null +++ b/types/github-username/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", + "github-username-tests.ts" + ] +} diff --git a/types/github-username/tslint.json b/types/github-username/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/github-username/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gl-react-dom/GLViewDOM.d.ts b/types/gl-react-dom/GLViewDOM.d.ts index 8450a16a00..5ceef51ec8 100644 --- a/types/gl-react-dom/GLViewDOM.d.ts +++ b/types/gl-react-dom/GLViewDOM.d.ts @@ -4,10 +4,10 @@ export type SupportedImage = 'image/png' | 'image/jpeg' | 'image/bmp' | 'image/w 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; + onContextCreate?: (gl: WebGLRenderingContext) => void; + onContextFailure?: (e: Error) => void; + onContextLost?: () => void; + onContextRestored?: (gl: WebGLRenderingContext) => void; webglContextAttributes?: WebGLContextAttributes; pixelRatio?: number; width: number; 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/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 index 4f0270dd68..5320ccaaa2 100644 --- a/types/gl-react-expo/GLViewNative.d.ts +++ b/types/gl-react-expo/GLViewNative.d.ts @@ -3,7 +3,7 @@ import * as React from 'react'; // import { GLView as EXGLView } from 'expo'; export interface GLViewNativeProps { - onContextCreate: (gl: WebGLRenderingContext) => void; + onContextCreate?: (gl: WebGLRenderingContext) => void; style?: any; children?: any; } 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/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 index a94c1f9769..9b90b25958 100644 --- a/types/gl-react-headless/GLViewHeadless.d.ts +++ b/types/gl-react-headless/GLViewHeadless.d.ts @@ -1,10 +1,10 @@ import * as React from 'react'; export interface GLViewHeadlessProps { - onContextCreate: (gl: WebGLRenderingContext) => void; - onContextFailure: (e: Error) => void; - onContextLost: () => void; - onContextRestored: (gl: WebGLRenderingContext) => void; + onContextCreate?: (gl: WebGLRenderingContext) => void; + onContextFailure?: (e: Error) => void; + onContextLost?: () => void; + onContextRestored?: (gl: WebGLRenderingContext) => void; webglContextAttributes?: WebGLContextAttributes; pixelRatio?: number; width: number; 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/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 index 0a780d3aa7..b4a4c75bc1 100644 --- a/types/gl-react-native/GLViewNative.d.ts +++ b/types/gl-react-native/GLViewNative.d.ts @@ -1,8 +1,8 @@ import * as React from 'react'; export interface GLViewNativeProps { - onContextCreate: (gl: WebGLRenderingContext) => void; - onContextFailure: (e: Error) => void; + onContextCreate?: (gl: WebGLRenderingContext) => void; + onContextFailure?: (e: Error) => void; style?: any; children?: any; } 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/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 e1332fd964..84b82ddd2d 100644 --- a/types/gl-react/index.d.ts +++ b/types/gl-react/index.d.ts @@ -124,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; diff --git a/types/gl/gl-tests.ts b/types/gl/gl-tests.ts new file mode 100644 index 0000000000..9b0a64b491 --- /dev/null +++ b/types/gl/gl-tests.ts @@ -0,0 +1,8 @@ +import createContext = require("gl"); + +createContext(0, 0); // $ExpectType WebGLRenderingContext & StackGLExtension +createContext(0, 0, { preserveDrawingBuffer: true }); // $ExpectType WebGLRenderingContext & StackGLExtension +createContext(0, 0).getExtension("STACKGL_resize_drawingbuffer"); // $ExpectType STACKGL_resize_drawingbuffer | null +createContext(0, 0).getExtension("STACKGL_destroy_context"); // $ExpectType STACKGL_destroy_context | null +createContext(0, 0).getExtension("STACKGL_resize_drawingbuffer")!.resize(0, 0); // $ExpectType void +createContext(0, 0).getExtension("STACKGL_destroy_context")!.destroy(); // $ExpectType void diff --git a/types/gl/index.d.ts b/types/gl/index.d.ts new file mode 100644 index 0000000000..ad8a7b5767 --- /dev/null +++ b/types/gl/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for gl 4.1 +// Project: https://github.com/stackgl/headless-gl#readme +// Definitions by: sjx233 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface StackGLExtension { + getExtension(extensionName: "STACKGL_resize_drawingbuffer"): STACKGL_resize_drawingbuffer | null; + getExtension(extensionName: "STACKGL_destroy_context"): STACKGL_destroy_context | null; +} + +interface STACKGL_resize_drawingbuffer { + resize(width: GLint, height: GLint): void; +} + +interface STACKGL_destroy_context { + destroy(): void; +} + +declare function createContext(width: number, height: number, options?: WebGLContextAttributes): WebGLRenderingContext & StackGLExtension; + +export = createContext; diff --git a/types/gl/tsconfig.json b/types/gl/tsconfig.json new file mode 100644 index 0000000000..36e5d3af07 --- /dev/null +++ b/types/gl/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "gl-tests.ts" + ] +} diff --git a/types/gl/tslint.json b/types/gl/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gl/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/global-dirs/global-dirs-tests.ts b/types/global-dirs/global-dirs-tests.ts new file mode 100644 index 0000000000..9ea2626670 --- /dev/null +++ b/types/global-dirs/global-dirs-tests.ts @@ -0,0 +1,15 @@ +import * as globalDirs from 'global-dirs'; + +// $ExpectType string +globalDirs.npm.prefix; +// $ExpectType string +globalDirs.npm.packages; +// $ExpectType string +globalDirs.npm.binaries; + +// $ExpectType string +globalDirs.yarn.prefix; +// $ExpectType string +globalDirs.yarn.packages; +// $ExpectType string +globalDirs.yarn.binaries; diff --git a/types/global-dirs/index.d.ts b/types/global-dirs/index.d.ts new file mode 100644 index 0000000000..b8f26312a4 --- /dev/null +++ b/types/global-dirs/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for global-dirs 0.1 +// Project: https://github.com/sindresorhus/global-dirs#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const npm: GlobalDirs; +export const yarn: GlobalDirs; + +export interface GlobalDirs { + packages: string; + binaries: string; + prefix: string; +} diff --git a/types/global-dirs/tsconfig.json b/types/global-dirs/tsconfig.json new file mode 100644 index 0000000000..095ad058e0 --- /dev/null +++ b/types/global-dirs/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", + "global-dirs-tests.ts" + ] +} diff --git a/types/global-dirs/tslint.json b/types/global-dirs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/global-dirs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/graphql-errors/graphql-errors-tests.ts b/types/graphql-errors/graphql-errors-tests.ts new file mode 100644 index 0000000000..0820fe2afa --- /dev/null +++ b/types/graphql-errors/graphql-errors-tests.ts @@ -0,0 +1,47 @@ +import { GraphQLSchema, buildSchema } from 'graphql'; +import { + UserError, + maskErrors, + handlerFunction, + setDefaultHandler +} from 'graphql-errors'; + +// $ExpectType GraphQLSchema +const schema: GraphQLSchema = buildSchema(` + # graphql schema definition +`); + +const customHandler: handlerFunction = err => { + return { ...err, message: 'Internal error' }; +}; + +/** + * Mask GraphQL error messages + */ + +// $ExpectType void +maskErrors(schema); + +// $ExpectType void +maskErrors(schema, customHandler); + +// $ExpectError +maskErrors('schema'); + +/** + * Set callback function that modifies the errors + */ + +// $ExpectType void +setDefaultHandler(customHandler); + +// $ExpectError +setDefaultHandler(); + +// $ExpectError +setDefaultHandler(err => {}); + +/** + * Thrown an user error + */ +new UserError("Uh, Houston, we've had a problem"); diff --git a/types/graphql-errors/index.d.ts b/types/graphql-errors/index.d.ts new file mode 100644 index 0000000000..5dc452ab20 --- /dev/null +++ b/types/graphql-errors/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for graphql-errors 2.1 +// Project: https://github.com/kadirahq/graphql-errors +// Definitions by: Matías Olivera +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { GraphQLSchema } from 'graphql'; + +export type handlerFunction = (err: Error) => Error; + +export function setDefaultHandler(fn: handlerFunction): void; + +export function maskErrors(schema: GraphQLSchema, fn?: handlerFunction): void; + +export class UserError extends Error { + constructor(message: string); +} diff --git a/types/graphql-errors/tsconfig.json b/types/graphql-errors/tsconfig.json new file mode 100644 index 0000000000..159013d442 --- /dev/null +++ b/types/graphql-errors/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "esnext.asynciterable"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "graphql-errors-tests.ts"] +} diff --git a/types/graphql-errors/tslint.json b/types/graphql-errors/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphql-errors/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/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/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts b/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts new file mode 100644 index 0000000000..6a31efb820 --- /dev/null +++ b/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts @@ -0,0 +1,3 @@ +import invisibles, { hardBreak, paragraph, space } from 'guardian__prosemirror-invisibles'; + +const plugin = invisibles([hardBreak, paragraph, space]); diff --git a/types/guardian__prosemirror-invisibles/index.d.ts b/types/guardian__prosemirror-invisibles/index.d.ts new file mode 100644 index 0000000000..b2e2434662 --- /dev/null +++ b/types/guardian__prosemirror-invisibles/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for @guardian/prosemirror-invisibles 0.1 +// Project: https://github.com/guardian/prosemirror-invisibles +// Definitions by: Daniil Dotsev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Node } from 'prosemirror-model'; +import { DecorationSet } from "prosemirror-view"; +import { Plugin } from 'prosemirror-state'; + +export type Builder = (from: number, to: number, doc: Node, decos: DecorationSet) => DecorationSet; + +export default function(builders: Builder[]): Plugin; + +export const hardBreak: Builder; +export const paragraph: Builder; +export const space: Builder; diff --git a/types/guardian__prosemirror-invisibles/tsconfig.json b/types/guardian__prosemirror-invisibles/tsconfig.json new file mode 100644 index 0000000000..dd1f2f9a2d --- /dev/null +++ b/types/guardian__prosemirror-invisibles/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "guardian__prosemirror-invisibles-tests.ts" + ] +} diff --git a/types/guardian__prosemirror-invisibles/tslint.json b/types/guardian__prosemirror-invisibles/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/guardian__prosemirror-invisibles/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} 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-bearer-token/hapi-auth-bearer-token-tests.ts b/types/hapi-auth-bearer-token/hapi-auth-bearer-token-tests.ts new file mode 100644 index 0000000000..4d145c3ae5 --- /dev/null +++ b/types/hapi-auth-bearer-token/hapi-auth-bearer-token-tests.ts @@ -0,0 +1,45 @@ +// from https://github.com/johnbrett/hapi-auth-bearer-token + +import { Server } from 'hapi'; +import * as AuthBearer from 'hapi-auth-bearer-token'; + +const server = new Server({ port: 8080 }); + +const start = async () => { + await server.register(AuthBearer); + + server.auth.strategy('simple', 'bearer-access-token', { + allowQueryToken: true, // optional, false by default + validate: (async (request, token, h) => { + // here is where you validate your token + // comparing with token from your database for example + const isValid = token === '1234'; + + const credentials = { token }; + const artifacts = { test: 'info' }; + + return { isValid, credentials, artifacts }; + }) as AuthBearer.Validate + }); + + server.auth.default('simple'); + + server.route({ + method: 'GET', + path: '/', + handler: async (request, h) => { + return { info: 'success!' }; + } + }); + + await server.start(); + + return server; +}; + +start() + .then((server) => console.log(`Server listening on ${server.info.uri}`)) + .catch(err => { + console.error(err); + process.exit(1); + }); diff --git a/types/hapi-auth-bearer-token/index.d.ts b/types/hapi-auth-bearer-token/index.d.ts new file mode 100644 index 0000000000..07ad3b868d --- /dev/null +++ b/types/hapi-auth-bearer-token/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for hapi-auth-bearer-token 6.1 +// Project: https://github.com/johnbrett/hapi-auth-bearer-token +// Definitions by: Rodrigo Saboya +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { + Request, + Plugin, + ResponseToolkit, + AuthenticationData, + } from 'hapi'; + + type ValidateReturn = AuthenticationData & { isValid: boolean }; + + declare module 'hapi' { + interface ServerAuth { + strategy(name: string, scheme: 'bearer-access-token', options: BearerToken.SchemaOptions): void; + } + } + + declare namespace BearerToken { + interface SchemaOptions { + validate: Validate; + accessTokenName?: string; + allowQueryToken?: boolean; + allowCookieToken?: boolean; + allowMultipleHeaders?: boolean; + allowChaining?: boolean; + tokenType?: string; + unauthorized?: (message: string | null, scheme: string) => any; + } + + type Validate = (request: Request, token: string, h: ResponseToolkit) => Promise | ValidateReturn; + } + + declare var BearerToken: Plugin<{}>; + + export = BearerToken; diff --git a/types/hapi-auth-bearer-token/tsconfig.json b/types/hapi-auth-bearer-token/tsconfig.json new file mode 100644 index 0000000000..404bf388a3 --- /dev/null +++ b/types/hapi-auth-bearer-token/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-bearer-token-tests.ts" + ] +} diff --git a/types/hapi-auth-bearer-token/tslint.json b/types/hapi-auth-bearer-token/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hapi-auth-bearer-token/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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-pino/hapi-pino-tests.ts b/types/hapi-pino/hapi-pino-tests.ts new file mode 100644 index 0000000000..eb028d37ad --- /dev/null +++ b/types/hapi-pino/hapi-pino-tests.ts @@ -0,0 +1,44 @@ +import { Server } from 'hapi'; +import * as pino from 'pino'; +import * as HapiPino from 'hapi-pino'; + +const pinoLogger = pino(); + +const server = new Server(); + +server.register({ + plugin: HapiPino, + options: { + logPayload: false, + logRouteTags: false, + stream: process.stdout, + prettyPrint: process.env.NODE_ENV !== 'PRODUCTION', + levelTags: { + trace: 'trace', + debug: 'debug', + info: 'info', + warn: 'warn', + error: 'error' + }, + allTags: 'info', + serializers: { + req: (req: any) => console.log(req) + }, + instance: pinoLogger, + logEvents: false, + mergeHapiLogData: false, + ignorePaths: ['/testRoute'], + level: 'debug', + redact: ['test.property'] + } +}).then(() => { + server.logger().debug('using logger object directly'); + + server.route({ + method: 'GET', + path: '/', + handler: (request, h) => { + request.logger.debug('using logger directly'); + } + }); +}); diff --git a/types/hapi-pino/index.d.ts b/types/hapi-pino/index.d.ts new file mode 100644 index 0000000000..c3f61cbe8d --- /dev/null +++ b/types/hapi-pino/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for hapi-pino 5.2 +// Project: https://github.com/pinojs/hapi-pino#readme +// Definitions by: Rodrigo Saboya +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import { + Plugin, +} from 'hapi'; +import * as pino from 'pino'; + +declare module 'hapi' { +interface Server { + logger: () => pino.Logger; +} + +interface Request { + logger: pino.Logger; +} +} + +declare namespace HapiPino { + type LogLevels = 'trace' | 'debug' | 'info' | 'warn' | 'error'; + + interface Options { + logPayload?: boolean; + logRouteTags?: boolean; + stream?: NodeJS.WriteStream; + prettyPrint?: boolean; + levelTags?: { [key in LogLevels]: string }; + allTags?: LogLevels; + serializers?: { [key: string]: (param: any) => void}; + instance?: pino.Logger; + logEvents?: string[] | false | null; + mergeHapiLogData?: boolean; + ignorePaths?: string[]; + level?: LogLevels; + redact?: string[]; + } +} + +declare var HapiPino: Plugin; + +export = HapiPino; diff --git a/types/hapi-pino/tsconfig.json b/types/hapi-pino/tsconfig.json new file mode 100644 index 0000000000..044a1596b4 --- /dev/null +++ b/types/hapi-pino/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-pino-tests.ts" + ] +} diff --git a/types/hapi-pino/tslint.json b/types/hapi-pino/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hapi-pino/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 3e323f8c44..ec2359ed5a 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1428,7 +1428,7 @@ export interface RouteOptionsPreObject { /** * key name used to assign the response of the method to in request.pre and request.preResponses. */ - assign: string; + assign?: string; /** * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. */ 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/has-yarn/has-yarn-tests.ts b/types/has-yarn/has-yarn-tests.ts new file mode 100644 index 0000000000..925cfe3c43 --- /dev/null +++ b/types/has-yarn/has-yarn-tests.ts @@ -0,0 +1,4 @@ +import hasYarn = require('has-yarn'); + +// $ExpectType boolean +hasYarn('foo'); diff --git a/types/has-yarn/index.d.ts b/types/has-yarn/index.d.ts new file mode 100644 index 0000000000..378f1ee811 --- /dev/null +++ b/types/has-yarn/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for has-yarn 1.0 +// Project: https://github.com/sindresorhus/has-yarn#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = hasYarn; + +declare function hasYarn(cwd?: string): boolean; diff --git a/types/has-yarn/tsconfig.json b/types/has-yarn/tsconfig.json new file mode 100644 index 0000000000..824092017a --- /dev/null +++ b/types/has-yarn/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-yarn-tests.ts" + ] +} diff --git a/types/has-yarn/tslint.json b/types/has-yarn/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/has-yarn/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/index.d.ts b/types/highcharts/index.d.ts index c6aae1e77f..51028bd6af 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -2232,6 +2232,10 @@ declare namespace Highcharts { * The button that appears after a selection zoom, allowing the user to reset zoom. */ resetZoomButton?: ChartResetZoomButton; + /** + * Options for a scrollable plot area + */ + scrollablePlotArea?: ScrollablePropArea; /** * The background color of the marker square when selecting (zooming in on) an area of the chart. * @default 'rgba(69,114,167,0.25)' @@ -3495,6 +3499,11 @@ declare namespace Highcharts { update(options: TitleOptions): void; } + interface ScrollablePropArea { + minWidth?: number; + scrollPositionX?: number; + } + /** * Under which conditions the rule applies. */ diff --git a/types/highcharts/modules/bullet.d.ts b/types/highcharts/modules/bullet.d.ts new file mode 100644 index 0000000000..98819c1963 --- /dev/null +++ b/types/highcharts/modules/bullet.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsBullet(H: Static): Static; +export = HighchartsBullet; +export as namespace HighchartsBullet; diff --git a/types/highcharts/modules/heatmap.d.ts b/types/highcharts/modules/heatmap.d.ts new file mode 100644 index 0000000000..46ae5ff3e1 --- /dev/null +++ b/types/highcharts/modules/heatmap.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsHeatMap(H: Static): Static; +export = HighchartsHeatMap; +export as namespace HighchartsHeatMap; diff --git a/types/highcharts/modules/solid-gauge.d.ts b/types/highcharts/modules/solid-gauge.d.ts new file mode 100644 index 0000000000..4fa17d62cd --- /dev/null +++ b/types/highcharts/modules/solid-gauge.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsSolidGauge(H: Static): Static; +export = HighchartsSolidGauge; +export as namespace HighchartsSolidGauge; diff --git a/types/highcharts/modules/treemap.d.ts b/types/highcharts/modules/treemap.d.ts new file mode 100644 index 0000000000..25a2c58f2e --- /dev/null +++ b/types/highcharts/modules/treemap.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsTreeMap(H: Static): Static; +export = HighchartsTreeMap; +export as namespace HighchartsTreeMap; diff --git a/types/highcharts/modules/wordcloud.d.ts b/types/highcharts/modules/wordcloud.d.ts new file mode 100644 index 0000000000..f6a9141057 --- /dev/null +++ b/types/highcharts/modules/wordcloud.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsWordcloud(H: Static): Static; +export = HighchartsWordcloud; +export as namespace HighchartsWordcloud; diff --git a/types/highcharts/test/bullet.ts b/types/highcharts/test/bullet.ts new file mode 100644 index 0000000000..6a82c891bf --- /dev/null +++ b/types/highcharts/test/bullet.ts @@ -0,0 +1 @@ +HighchartsBullet(Highcharts); diff --git a/types/highcharts/test/heatmap.ts b/types/highcharts/test/heatmap.ts new file mode 100644 index 0000000000..d42454d447 --- /dev/null +++ b/types/highcharts/test/heatmap.ts @@ -0,0 +1 @@ +HighchartsHeatMap(Highcharts); diff --git a/types/highcharts/test/solid-gauge.ts b/types/highcharts/test/solid-gauge.ts new file mode 100644 index 0000000000..3d5c2245dc --- /dev/null +++ b/types/highcharts/test/solid-gauge.ts @@ -0,0 +1 @@ +HighchartsSolidGauge(Highcharts); diff --git a/types/highcharts/test/treemap.ts b/types/highcharts/test/treemap.ts new file mode 100644 index 0000000000..c7772a4dbf --- /dev/null +++ b/types/highcharts/test/treemap.ts @@ -0,0 +1 @@ +HighchartsTreeMap(Highcharts); diff --git a/types/highcharts/test/wordcloud.ts b/types/highcharts/test/wordcloud.ts new file mode 100644 index 0000000000..037d54eb7f --- /dev/null +++ b/types/highcharts/test/wordcloud.ts @@ -0,0 +1 @@ +HighchartsWordcloud(Highcharts); diff --git a/types/highcharts/tsconfig.json b/types/highcharts/tsconfig.json index e69f0eeb57..60bbecc1fa 100644 --- a/types/highcharts/tsconfig.json +++ b/types/highcharts/tsconfig.json @@ -18,23 +18,33 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts", - "modules/map/index.d.ts", - "modules/boost.d.ts", - "modules/drilldown.d.ts", - "modules/exporting.d.ts", - "modules/no-data-to-display.d.ts", - "modules/offline-exporting.d.ts", "highcharts-more.d.ts", "highstock.d.ts", + "index.d.ts", "js/highcharts/index.d.ts", + "modules/boost.d.ts", + "modules/bullet.d.ts", + "modules/drilldown.d.ts", + "modules/exporting.d.ts", + "modules/heatmap.d.ts", + "modules/map/index.d.ts", + "modules/no-data-to-display.d.ts", + "modules/offline-exporting.d.ts", + "modules/solid-gauge.d.ts", + "modules/treemap.d.ts", + "modules/wordcloud.d.ts", "test/boost.ts", + "test/bullet.ts", "test/drilldown.ts", "test/exporting.ts", + "test/heatmap.ts", "test/highstock.ts", "test/index.ts", "test/more.ts", "test/no-data-to-display.ts", - "test/offline-exporting.ts" + "test/offline-exporting.ts", + "test/solid-gauge.ts", + "test/treemap.ts", + "test/wordcloud.ts" ] -} \ No newline at end of file +} diff --git a/types/highcharts/tslint.json b/types/highcharts/tslint.json index d6b6fde9be..113c45ef94 100644 --- a/types/highcharts/tslint.json +++ b/types/highcharts/tslint.json @@ -7,6 +7,7 @@ "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/http-proxy-middleware/index.d.ts b/types/http-proxy-middleware/index.d.ts index b48214b8f6..09b80e21c4 100644 --- a/types/http-proxy-middleware/index.d.ts +++ b/types/http-proxy-middleware/index.d.ts @@ -18,7 +18,7 @@ declare function proxy(config: proxy.Config): proxy.Proxy; declare function proxy(contextOrUri: string | string[] | proxy.Filter, config: proxy.Config): proxy.Proxy; declare namespace proxy { - type Filter = (pathanme: string, req: http.IncomingMessage) => boolean; + type Filter = (pathname: string, req: http.IncomingMessage) => boolean; type Logger = (...args: any[]) => void; interface LogProvider { log: Logger; 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/icon-gen/icon-gen-tests.ts b/types/icon-gen/icon-gen-tests.ts new file mode 100644 index 0000000000..ca02834c04 --- /dev/null +++ b/types/icon-gen/icon-gen-tests.ts @@ -0,0 +1,43 @@ +import icongen = require('icon-gen'); + +icongen('./sample.svg', './icons', { report: true }) + .then(results => { + results[0]; + }) + .catch(err => { + throw err; + }); + +icongen('./sample.svg', './icons') + .then(results => { + results[0]; + }) + .catch(err => { + throw err; + }); + +icongen('./sample.svg', './icons', { + favicon: { + ico: [16, 24, 32, 48, 64], + name: 'favicon-', + sizes: [32, 57, 72, 96, 120, 128, 144, 152, 195, 228], + }, + report: false, +}) + .then(results => { + results[0]; + }) + .catch(err => { + throw err; + }); + +icongen('./sample.svg', './icons', { + favicon: {}, + report: false, +}) + .then(results => { + results[0]; + }) + .catch(err => { + throw err; + }); diff --git a/types/icon-gen/index.d.ts b/types/icon-gen/index.d.ts new file mode 100644 index 0000000000..e7bd6aaa69 --- /dev/null +++ b/types/icon-gen/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for icon-gen 2.0 +// Project: https://github.com/akabekobeko/npm-icon-gen#readme +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace icongen { + interface Options { + favicon?: { + ico: number[]; + name: string; + sizes: number[]; + } | {}; + icns?: { + name: string; + sizes: number[]; + } | {}; + ico?: { + name: string; + sizes: number[]; + } | {}; + report?: boolean; + } +} + +declare function icongen(src: string, dest: string, options?: icongen.Options): Promise; + +export = icongen; diff --git a/types/icon-gen/tsconfig.json b/types/icon-gen/tsconfig.json new file mode 100644 index 0000000000..6b83993922 --- /dev/null +++ b/types/icon-gen/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", + "icon-gen-tests.ts" + ] +} diff --git a/types/icon-gen/tslint.json b/types/icon-gen/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/icon-gen/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/insert-css/index.d.ts b/types/insert-css/index.d.ts new file mode 100644 index 0000000000..9f132c53b4 --- /dev/null +++ b/types/insert-css/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for insert-css 2.0 +// Project: https://github.com/substack/insert-css +// Definitions by: Heye Vöcking +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface InsertCssOptions { + container?: HTMLElement; + prepend?: boolean; +} + +export interface InsertCssStyleElement extends HTMLStyleElement { + styleSheet?: CSSStyleSheet; +} + +export function insertCss( + css: string, + options?: InsertCssOptions, +): InsertCssStyleElement; diff --git a/types/insert-css/insert-css-tests.ts b/types/insert-css/insert-css-tests.ts new file mode 100644 index 0000000000..a26e085626 --- /dev/null +++ b/types/insert-css/insert-css-tests.ts @@ -0,0 +1,27 @@ +import { insertCss } from 'insert-css'; + +insertCss('body{position:absolute}'); + +insertCss('body{position:absolute}', {}); + +insertCss('body{text-decoration:underline !important}', { + prepend: true, +}); + +insertCss('body{text-decoration:underline !important}', { + prepend: false, +}); + +insertCss('body{position:absolute}', { + container: document.createElement(''), +}); + +insertCss('body{text-decoration:underline !important}', { + prepend: true, + container: document.createElement(''), +}); + +insertCss('body{text-decoration:underline !important}', { + prepend: false, + container: document.createElement(''), +}); diff --git a/types/insert-css/tsconfig.json b/types/insert-css/tsconfig.json new file mode 100644 index 0000000000..eed90e2eeb --- /dev/null +++ b/types/insert-css/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "forceConsistentCasingInFileNames": true, + "lib": [ + "dom", + "es6" + ], + "module": "commonjs", + "noEmit": true, + "noImplicitAny": true, + "noImplicitAny": true, + "noImplicitThis": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "strictNullChecks": true, + "typeRoots": ["../"], + "types": [] + }, + "files": [ + "index.d.ts", + "insert-css-tests.ts" + ] +} diff --git a/types/insert-css/tslint.json b/types/insert-css/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/insert-css/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/internal-ip/index.d.ts b/types/internal-ip/index.d.ts index a82dd8c913..1bed7e9059 100644 --- a/types/internal-ip/index.d.ts +++ b/types/internal-ip/index.d.ts @@ -1,7 +1,12 @@ -// Type definitions for internal-ip 2.0 +// Type definitions for internal-ip 3.0 // Project: https://github.com/sindresorhus/internal-ip#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export function v6(): Promise; -export function v4(): Promise; +export const v6: IPGetterFn; +export const v4: IPGetterFn; + +export interface IPGetterFn { // tslint:disable-line:interface-name + (): Promise; + sync(): string | null; +} diff --git a/types/internal-ip/internal-ip-tests.ts b/types/internal-ip/internal-ip-tests.ts index e94ec9f510..1b383de2f3 100644 --- a/types/internal-ip/internal-ip-tests.ts +++ b/types/internal-ip/internal-ip-tests.ts @@ -1,10 +1,15 @@ import * as internalIp from 'internal-ip'; -let str: string; internalIp.v6().then(ip => { - str = ip; + // $ExpectType string | null + ip; }); +// $ExpectType string | null +internalIp.v6.sync(); internalIp.v4().then(ip => { - str = ip; + // $ExpectType string | null + ip; }); +// $ExpectType string | null +internalIp.v4.sync(); diff --git a/types/internal-ip/tsconfig.json b/types/internal-ip/tsconfig.json index 746718e07c..99d54932e0 100644 --- a/types/internal-ip/tsconfig.json +++ b/types/internal-ip/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "internal-ip-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/internal-ip/v2/index.d.ts b/types/internal-ip/v2/index.d.ts new file mode 100644 index 0000000000..a82dd8c913 --- /dev/null +++ b/types/internal-ip/v2/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for internal-ip 2.0 +// Project: https://github.com/sindresorhus/internal-ip#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function v6(): Promise; +export function v4(): Promise; diff --git a/types/internal-ip/v2/internal-ip-tests.ts b/types/internal-ip/v2/internal-ip-tests.ts new file mode 100644 index 0000000000..e94ec9f510 --- /dev/null +++ b/types/internal-ip/v2/internal-ip-tests.ts @@ -0,0 +1,10 @@ +import * as internalIp from 'internal-ip'; + +let str: string; +internalIp.v6().then(ip => { + str = ip; +}); + +internalIp.v4().then(ip => { + str = ip; +}); diff --git a/types/internal-ip/v2/tsconfig.json b/types/internal-ip/v2/tsconfig.json new file mode 100644 index 0000000000..bae5b7feb8 --- /dev/null +++ b/types/internal-ip/v2/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "internal-ip": [ + "internal-ip/v2" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "internal-ip-tests.ts" + ] +} diff --git a/types/internal-ip/v2/tslint.json b/types/internal-ip/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/internal-ip/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/ipify/index.d.ts b/types/ipify/index.d.ts new file mode 100644 index 0000000000..237b15dfcc --- /dev/null +++ b/types/ipify/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for ipify 2.0 +// Project: https://github.com/sindresorhus/ipify#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = ipify; + +declare function ipify(endpoint?: string): Promise; diff --git a/types/ipify/ipify-tests.ts b/types/ipify/ipify-tests.ts new file mode 100644 index 0000000000..f533f49282 --- /dev/null +++ b/types/ipify/ipify-tests.ts @@ -0,0 +1,4 @@ +import ipify = require('ipify'); + +// $ExpectType Promise +ipify(); diff --git a/types/ipify/tsconfig.json b/types/ipify/tsconfig.json new file mode 100644 index 0000000000..96f6f0600d --- /dev/null +++ b/types/ipify/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", + "ipify-tests.ts" + ] +} diff --git a/types/ipify/tslint.json b/types/ipify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ipify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/is-array-sorted/index.d.ts b/types/is-array-sorted/index.d.ts new file mode 100644 index 0000000000..7c45437489 --- /dev/null +++ b/types/is-array-sorted/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for is-array-sorted 1.0 +// Project: https://github.com/sindresorhus/is-array-sorted#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isArraySorted; + +declare function isArraySorted( + array: ReadonlyArray, + comparator?: (a: T, b: T) => number +): boolean; diff --git a/types/is-array-sorted/is-array-sorted-tests.ts b/types/is-array-sorted/is-array-sorted-tests.ts new file mode 100644 index 0000000000..85291fb10c --- /dev/null +++ b/types/is-array-sorted/is-array-sorted-tests.ts @@ -0,0 +1,6 @@ +import isArraySorted = require('is-array-sorted'); + +// $ExpectType boolean +isArraySorted([1, 2, 3]); +// $ExpectType boolean +isArraySorted(['a', 'b', 'c'], (a, b) => a.localeCompare(b)); diff --git a/types/is-array-sorted/tsconfig.json b/types/is-array-sorted/tsconfig.json new file mode 100644 index 0000000000..5fb8aa9921 --- /dev/null +++ b/types/is-array-sorted/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", + "is-array-sorted-tests.ts" + ] +} diff --git a/types/is-array-sorted/tslint.json b/types/is-array-sorted/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-array-sorted/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-charging/index.d.ts b/types/is-charging/index.d.ts new file mode 100644 index 0000000000..7eb5dcfab0 --- /dev/null +++ b/types/is-charging/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-charging 2.0 +// Project: https://github.com/gillstrom/is-charging#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isCharging; + +declare function isCharging(): Promise; diff --git a/types/is-charging/is-charging-tests.ts b/types/is-charging/is-charging-tests.ts new file mode 100644 index 0000000000..f3c4a67fc0 --- /dev/null +++ b/types/is-charging/is-charging-tests.ts @@ -0,0 +1,4 @@ +import isCharging = require('is-charging'); + +// $ExpectType Promise +isCharging(); diff --git a/types/is-charging/tsconfig.json b/types/is-charging/tsconfig.json new file mode 100644 index 0000000000..6516f5c83e --- /dev/null +++ b/types/is-charging/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", + "is-charging-tests.ts" + ] +} diff --git a/types/is-charging/tslint.json b/types/is-charging/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-charging/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-installed-globally/index.d.ts b/types/is-installed-globally/index.d.ts new file mode 100644 index 0000000000..130e44256e --- /dev/null +++ b/types/is-installed-globally/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-installed-globally 0.1 +// Project: https://github.com/sindresorhus/is-installed-globally#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isInstalledGlobally; + +declare const isInstalledGlobally: boolean; diff --git a/types/is-installed-globally/is-installed-globally-tests.ts b/types/is-installed-globally/is-installed-globally-tests.ts new file mode 100644 index 0000000000..8e64ec0c4b --- /dev/null +++ b/types/is-installed-globally/is-installed-globally-tests.ts @@ -0,0 +1,4 @@ +import isInstalledGlobally = require('is-installed-globally'); + +// $ExpectType boolean +isInstalledGlobally; diff --git a/types/is-installed-globally/tsconfig.json b/types/is-installed-globally/tsconfig.json new file mode 100644 index 0000000000..51a5701929 --- /dev/null +++ b/types/is-installed-globally/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", + "is-installed-globally-tests.ts" + ] +} diff --git a/types/is-installed-globally/tslint.json b/types/is-installed-globally/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-installed-globally/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-trademarked/index.d.ts b/types/is-trademarked/index.d.ts new file mode 100644 index 0000000000..700e9b25f2 --- /dev/null +++ b/types/is-trademarked/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for is-trademarked 1.2 +// Project: https://github.com/egoist/is-trademarked#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isTrademarked; + +declare function isTrademarked( + searchTerm: string, + opts?: isTrademarked.Options +): Promise; + +declare namespace isTrademarked { + interface Options { + token?: string; + } + + interface TrademarkedData { + wordmark: string; + reg: Date; + description: string; + sn: string; + serviceCode: string; + } +} diff --git a/types/is-trademarked/is-trademarked-tests.ts b/types/is-trademarked/is-trademarked-tests.ts new file mode 100644 index 0000000000..52f7502435 --- /dev/null +++ b/types/is-trademarked/is-trademarked-tests.ts @@ -0,0 +1,6 @@ +import isTrademarked = require('is-trademarked'); + +// $ExpectType Promise +isTrademarked('unicorns'); +// $ExpectType Promise +isTrademarked('unicorns', { token: 'foo' }); diff --git a/types/is-trademarked/tsconfig.json b/types/is-trademarked/tsconfig.json new file mode 100644 index 0000000000..8121816b1a --- /dev/null +++ b/types/is-trademarked/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", + "is-trademarked-tests.ts" + ] +} diff --git a/types/is-trademarked/tslint.json b/types/is-trademarked/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-trademarked/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-typedarray/index.d.ts b/types/is-typedarray/index.d.ts new file mode 100644 index 0000000000..39f5f91368 --- /dev/null +++ b/types/is-typedarray/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for is-typedarray 1.0 +// Project: https://github.com/hughsk/is-typedarray +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +export = isTypedArray; + +declare function isTypedArray(candidate: any): candidate is isTypedArray.TypedArray; + +declare namespace isTypedArray { + function strict(candidate: any): candidate is TypedArray; + function loose(candidate: any): candidate is TypedArray; + + type TypedArray = + | Int8Array + | Int16Array + | Int32Array + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Float32Array + | Float64Array + | Buffer; +} diff --git a/types/is-typedarray/is-typedarray-tests.ts b/types/is-typedarray/is-typedarray-tests.ts new file mode 100644 index 0000000000..9597f23017 --- /dev/null +++ b/types/is-typedarray/is-typedarray-tests.ts @@ -0,0 +1,19 @@ +import isTypedArray = require('is-typedarray'); + +const buf: any = new Buffer(1); + +// $ExpectType any +buf; + +if (isTypedArray(buf)) { + // $ExpectType TypedArray + buf; +} +if (isTypedArray.strict(buf)) { + // $ExpectType TypedArray + buf; +} +if (isTypedArray.loose(buf)) { + // $ExpectType TypedArray + buf; +} diff --git a/types/is-typedarray/tsconfig.json b/types/is-typedarray/tsconfig.json new file mode 100644 index 0000000000..e8886f1236 --- /dev/null +++ b/types/is-typedarray/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", + "is-typedarray-tests.ts" + ] +} diff --git a/types/is-typedarray/tslint.json b/types/is-typedarray/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-typedarray/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/issue-regex/index.d.ts b/types/issue-regex/index.d.ts new file mode 100644 index 0000000000..110e6b06af --- /dev/null +++ b/types/issue-regex/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for issue-regex 2.0 +// Project: https://github.com/sindresorhus/issue-regex#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = issueRegex; + +declare function issueRegex(): RegExp; diff --git a/types/issue-regex/issue-regex-tests.ts b/types/issue-regex/issue-regex-tests.ts new file mode 100644 index 0000000000..7eb4b352ff --- /dev/null +++ b/types/issue-regex/issue-regex-tests.ts @@ -0,0 +1,5 @@ +import issueRegex = require('issue-regex'); + +// $ExpectType RegExp +issueRegex(); +'Fixes #143 and avajs/ava#1023'.match(issueRegex()); diff --git a/types/issue-regex/tsconfig.json b/types/issue-regex/tsconfig.json new file mode 100644 index 0000000000..46dd7f033b --- /dev/null +++ b/types/issue-regex/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", + "issue-regex-tests.ts" + ] +} diff --git a/types/issue-regex/tslint.json b/types/issue-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/issue-regex/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..fdfe29607c 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -80,18 +80,21 @@ declare function afterAll(action: (done: DoneFn) => void, timeout?: number): voi /** * Create an expectation for a spec. + * @checkReturnValue see https://tsetse.info/check-return-value * @param spy */ declare function expect(spy: Function): jasmine.Matchers; /** * Create an expectation for a spec. + * @checkReturnValue see https://tsetse.info/check-return-value * @param actual */ declare function expect(actual: ArrayLike): jasmine.ArrayLikeMatchers; /** * Create an expectation for a spec. + * @checkReturnValue see https://tsetse.info/check-return-value * @param actual Actual computed value to test expectations against. */ declare function expect(actual: T): jasmine.Matchers; @@ -639,6 +642,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/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/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..cbcc12d956 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,12 @@ $( "body" ).on( "click", "p", foo ); $( "body" ).off( "click", "p", foo ); ``` */ - off(events: string, selector: JQuery.Selector, handler: JQuery.EventHandlerBase> | false): this; + off( + events: TType, + 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 +7339,12 @@ $( "form" ).on( "keypress.validator", "input[type='text']", validate ); $( "form" ).off( ".validator" ); ``` */ - off(events: string, selector_handler?: JQuery.Selector | JQuery.EventHandlerBase> | false): this; + off( + events: TType, + 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 +7353,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 +7365,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 +7538,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 +7574,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 +7637,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 +7726,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 +7735,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 +7828,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 +7925,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 +7936,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 +7965,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 +7976,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 +8028,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 +8039,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 +8073,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 +8087,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 +8181,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 +8196,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 +8225,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 +8235,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 +8246,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 +10004,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 +10022,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 +10037,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 +10087,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 +10262,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 +10311,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 +11283,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 +11352,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 +11861,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 +11904,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 +11972,11 @@ $( "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: TType, + 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 +11997,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 +12067,19 @@ $( "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: TType, + 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 +12089,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/JQueryStatic.d.ts b/types/jquery/JQueryStatic.d.ts index 20d3a9e8c5..4ba7653e69 100644 --- a/types/jquery/JQueryStatic.d.ts +++ b/types/jquery/JQueryStatic.d.ts @@ -148,21 +148,26 @@ $( "div", xml.responseXML ); $( document.body ).css( "background", "black" ); ``` */ - // Using a unified signature is not possible due to a TypeScript 2.4 bug (DefinitelyTyped#27810) - (element: T): JQuery; + // NOTE: `HTMLSelectElement` is both an Element and an Array-Like Object but jQuery treats it as an Element. + (element: HTMLSelectElement): JQuery; /** * Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. - * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. + * @param element_elementArray _@param_ `element_elementArray` + *
+ * * `element` — A DOM element to wrap in a jQuery object.
+ * * `elementArray` — An array containing a set of DOM elements to wrap in a jQuery object. * @see \`{@link https://api.jquery.com/jQuery/ }\` * @since 1.0 + * @example ​ ````Set the background color of the page to black. +```javascript +$( document.body ).css( "background", "black" ); +``` * @example ​ ````Hide all the input elements within a form. ```javascript $( myForm.elements ).hide(); ``` */ - // Using a unified signature is not possible due to a TypeScript 2.4 bug (DefinitelyTyped#27810) - // tslint:disable-next-line:unified-signatures - (elementArray: T[]): JQuery; + (element_elementArray: T | ArrayLike): JQuery; /** * Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. * @param selection An existing jQuery object to clone. diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 515715bf14..9e4dea80ee 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -160,6 +160,9 @@ function JQueryStatic() { // $ExpectType JQuery $([new HTMLSelectElement()]); + // $ExpectType JQuery + $(document.querySelectorAll('p')); + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/19597#issuecomment-378218432 function issue_19597_378218432() { const myDiv = $(document.createElement('div')); @@ -2430,7 +2433,7 @@ function JQuery() { $(document).ajaxComplete(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2446,7 +2449,7 @@ function JQuery() { $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2464,7 +2467,7 @@ function JQuery() { $(document).ajaxSend(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2500,7 +2503,7 @@ function JQuery() { $(document).ajaxSuccess(function(event, jqXHR, ajaxOptions, data) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -3883,21 +3886,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 +3898,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 +3951,37 @@ 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 customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function specificEventType(this: HTMLElement, event: JQuery.MouseDownEvent) { } // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_defaultData); + $('table').off('myEvent', 'td', defaultData); // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_customData); + $('table').off('myEvent', 'td', customData); // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_customData); + $('table').off('mousedown', 'td', specificEventType); // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -4030,16 +3990,13 @@ function JQuery() { $('table').off('myEvent', 'td'); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_defaultData); + $('table').off('myEvent', defaultData); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_customData); + $('table').off('myEvent', customData); // $ExpectType JQuery - $('table').off('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_customData); + $('table').off('mousedown', specificEventType); // $ExpectType JQuery $('table').off('myEvent', false); @@ -4050,52 +4007,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 +4038,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 +4068,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 +4091,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 +4112,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 +4154,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 +4177,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 +4194,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 +4228,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 +4245,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 +4283,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 +4310,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 +4318,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 +4329,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 +4348,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 +4365,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 +4399,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 +4416,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 +4493,20 @@ 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 customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function specificEventType(this: HTMLElement, event: JQuery.MouseDownEvent) { } // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_defaultData); + $('p').unbind('myEvent', defaultData); // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_customData); + $('p').unbind('myEvent', customData); // $ExpectType JQuery - $('p').unbind('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('p').unbind('myEvent', customContext_customData); + $('p').unbind('mousedown', specificEventType); // $ExpectType JQuery $('p').unbind('myEvent', false); @@ -4579,35 +4514,29 @@ 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 customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function specificEventType(this: HTMLElement, event: JQuery.MouseDownEvent) { } // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_defaultData); + $('table').undelegate('td', 'click', defaultData); // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_customData); + $('table').undelegate('td', 'click', customData); // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_defaultData); - - // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_customData); + $('table').undelegate('td', 'mousedown', specificEventType); // $ExpectType JQuery $('table').undelegate('td', 'click', false); @@ -4618,10 +4547,8 @@ function JQuery() { // $ExpectType JQuery $('table').undelegate('td', { myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); // $ExpectType JQuery @@ -4632,21 +4559,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 +4571,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 +4583,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 +4595,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 +4607,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 +4619,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 +4631,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 +4643,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 +4655,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 +4667,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 +4679,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 +4691,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 +4703,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 +4715,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 +4727,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 +4739,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 +4751,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 +4763,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 +4775,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 +4787,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 +4799,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 +4811,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 +4823,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 +4835,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 +4847,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 +4859,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 +4871,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 +4883,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 +4895,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 +4907,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 +4919,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 +4931,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 +4943,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 +4955,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 +4967,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 +4979,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 +4991,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 +5003,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 +5015,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 +5027,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 +5039,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 +5051,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 +5063,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 +5075,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 +5087,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 +5104,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 +5112,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 +5123,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 +7878,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 +8070,7 @@ function JQuery_EventExtensions() { data; // $ExpectType string namespaces; - // $ExpectType EventHandler + // $ExpectType EventHandlerBase> eventHandle; return false; @@ -8481,7 +8096,7 @@ function JQuery_EventExtensions() { trigger(event, data) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; // $ExpectType any data; @@ -8489,7 +8104,7 @@ function JQuery_EventExtensions() { return false; }, _default(event, data) { - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType any data; @@ -8497,7 +8112,7 @@ function JQuery_EventExtensions() { return false; }, handle(event, data) { - // $ExpectType Event & { handleObj: HandleObject; } + // $ExpectType TriggeredEvent & { handleObj: HandleObject; } event; // $ExpectType any data; @@ -8505,7 +8120,7 @@ function JQuery_EventExtensions() { preDispatch(event) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; return false; @@ -8513,7 +8128,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/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/jsonfile/index.d.ts b/types/jsonfile/index.d.ts index 62227c9e84..cc0009ece3 100644 --- a/types/jsonfile/index.d.ts +++ b/types/jsonfile/index.d.ts @@ -1,60 +1,71 @@ -// Type definitions for jsonfile 4.0 +// Type definitions for jsonfile 5.0 // Project: https://github.com/jprichardson/node-jsonfile#readme // Definitions by: Daniel Bowring +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// import { Url } from 'url'; +import { + PathLike, + readFile as fsReadFile, + readFileSync as fsReadFileSync, + writeFile as fsWriteFile, + writeFileSync as fsWriteFileSync, +} from 'fs'; -export type FSReadOptions = { - encoding?: null; - flag?: string; - } | null | undefined; -export type FSWriteOptions = string | { - encoding?: string | null; - mode?: string | number; - flag?: string; - } | null | undefined; - -export type ReadCallback = (err: NodeJS.ErrnoException | null, data: Buffer) => void; -export type WriteCallback = (err: NodeJS.ErrnoException) => void; -export type Path = string | number | Buffer | Url; +export type Path = PathLike | Url; export interface FS { - readFile(path: Path, options: FSReadOptions, callback: ReadCallback): void; - readFileSync(path: Path, options?: FSReadOptions): Buffer; - writeFile(path: Path, data: any, options: FSWriteOptions, callback: WriteCallback): void; - writeFileSync(path: Path, data: any, options?: FSWriteOptions): void; + readFile: typeof fsReadFile; + readFileSync: typeof fsReadFileSync; + writeFile: typeof fsWriteFile; + writeFileSync: typeof fsWriteFileSync; } -export type JFReadOptions = { - encoding?: null; - flag?: string; - throws?: boolean; - fs?: FS; - reviver?: (key: any, value: any) => any; - } | null | undefined; +export type JFReadOptions = + | { + encoding?: string | null; + flag?: string; + throws?: boolean; + fs?: FS; + reviver?: (key: any, value: any) => any; + } + | string + | null + | undefined; -export type JFWriteOptions = string | { - encoding?: string | null; - mode?: string | number; - flag?: string; - throws?: boolean; - fs?: FS; - EOL?: string; - spaces?: string | number; - replacer?: (key: string, value: any) => any; - } | null; +export type JFWriteOptions = + | { + encoding?: string | null; + mode?: string | number; + flag?: string; + fs?: FS; + EOL?: string; + spaces?: string | number; + replacer?: (key: string, value: any) => any; + } + | string + | null; -export type JFReadCallback = (err: NodeJS.ErrnoException | null, data: any) => void; +export type ReadCallback = (err: NodeJS.ErrnoException | null, data: any) => void; +export type WriteCallback = (err: NodeJS.ErrnoException) => void; -export function readFile(file: Path, options?: JFReadOptions, callback?: JFReadCallback): void; -export function readFile(file: Path, callback: JFReadCallback): void; +export function readFile(file: Path, options: JFReadOptions, callback: ReadCallback): void; +export function readFile(file: Path, callback: ReadCallback): void; +export function readFile(file: Path, options?: JFReadOptions): Promise; export function readFileSync(file: Path, options?: JFReadOptions): any; -export function writeFile(file: Path, obj: any, options?: JFWriteOptions, callback?: WriteCallback): void; +export function writeFile( + file: Path, + obj: any, + options: JFWriteOptions, + callback: WriteCallback +): void; export function writeFile(file: Path, obj: any, callback: WriteCallback): void; +export function writeFile(file: Path, obj: any, options?: JFWriteOptions): Promise; export function writeFileSync(file: Path, obj: any, options?: JFWriteOptions): void; diff --git a/types/jsonfile/jsonfile-tests.ts b/types/jsonfile/jsonfile-tests.ts index 675a32d8b9..4725e3c8a3 100644 --- a/types/jsonfile/jsonfile-tests.ts +++ b/types/jsonfile/jsonfile-tests.ts @@ -1,34 +1,67 @@ -// Following are lifted from the samples on the NPM page, modified to pass -// the linter - import * as jsonfile from 'jsonfile'; const file = '/tmp/data.json'; -const obj = {name: 'JP'}; +const obj = { name: 'JP' }; -jsonfile.readFile(file, (err: NodeJS.ErrnoException | null, obj: any) => { - console.dir(obj); +// $ExpectType void +jsonfile.readFile(file, { encoding: 'utf8', throws: true }, (err, obj) => { + // $ExpectType ErrnoException | null + err; + // $ExpectType any + obj; }); -console.dir(jsonfile.readFileSync(file)); - -jsonfile.writeFile(file, obj, (err: NodeJS.ErrnoException) => { - console.error(err); +// $ExpectType void +jsonfile.readFile(file, (err, obj) => { + // $ExpectType ErrnoException | null + err; + // $ExpectType any + obj; }); -jsonfile.writeFile(file, obj, {spaces: 2}, (err: NodeJS.ErrnoException) => { - console.error(err); +jsonfile.readFile(file).then(obj => { + // $ExpectType any + obj; +}); +jsonfile.readFile(file, { encoding: 'utf8', throws: true }).then(obj => { + // $ExpectType any + obj; }); -jsonfile.writeFile(file, obj, {spaces: 2, EOL: '\r\n'}, (err: NodeJS.ErrnoException) => { - console.error(err); +// $ExpectType any +jsonfile.readFileSync(file); +jsonfile.readFileSync(file, { encoding: 'utf8', throws: true }); + +// $ExpectType void +jsonfile.writeFile(file, obj, err => { + // $ExpectType ErrnoException + err; }); -jsonfile.writeFile(file, obj, {flag: 'a'}, (err: NodeJS.ErrnoException) => { - console.error(err); +// $ExpectType void +jsonfile.writeFile(file, obj, { spaces: 2 }, err => { + // $ExpectType ErrnoException + err; }); +// $ExpectType void +jsonfile.writeFile(file, obj, { spaces: 2, EOL: '\r\n' }, err => { + // $ExpectType ErrnoException + err; +}); + +// $ExpectType void +jsonfile.writeFile(file, obj, { flag: 'a' }, err => { + // $ExpectType ErrnoException + err; +}); + +// $ExpectType Promise +jsonfile.writeFile(file, obj); +// $ExpectType Promise +jsonfile.writeFile(file, obj, { flag: 'a' }); + jsonfile.writeFileSync(file, obj); -jsonfile.writeFileSync(file, obj, {spaces: 2}); -jsonfile.writeFileSync(file, obj, {spaces: 2, EOL: '\r\n'}); -jsonfile.writeFileSync(file, obj, {flag: 'a'}); +jsonfile.writeFileSync(file, obj, { spaces: 2 }); +jsonfile.writeFileSync(file, obj, { spaces: 2, EOL: '\r\n' }); +jsonfile.writeFileSync(file, obj, { flag: 'a' }); diff --git a/types/jsonfile/v4/index.d.ts b/types/jsonfile/v4/index.d.ts new file mode 100644 index 0000000000..62227c9e84 --- /dev/null +++ b/types/jsonfile/v4/index.d.ts @@ -0,0 +1,60 @@ +// Type definitions for jsonfile 4.0 +// Project: https://github.com/jprichardson/node-jsonfile#readme +// Definitions by: Daniel Bowring +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Url } from 'url'; + +export type FSReadOptions = { + encoding?: null; + flag?: string; + } | null | undefined; +export type FSWriteOptions = string | { + encoding?: string | null; + mode?: string | number; + flag?: string; + } | null | undefined; + +export type ReadCallback = (err: NodeJS.ErrnoException | null, data: Buffer) => void; +export type WriteCallback = (err: NodeJS.ErrnoException) => void; +export type Path = string | number | Buffer | Url; + +export interface FS { + readFile(path: Path, options: FSReadOptions, callback: ReadCallback): void; + readFileSync(path: Path, options?: FSReadOptions): Buffer; + writeFile(path: Path, data: any, options: FSWriteOptions, callback: WriteCallback): void; + writeFileSync(path: Path, data: any, options?: FSWriteOptions): void; +} + +export type JFReadOptions = { + encoding?: null; + flag?: string; + throws?: boolean; + fs?: FS; + reviver?: (key: any, value: any) => any; + } | null | undefined; + +export type JFWriteOptions = string | { + encoding?: string | null; + mode?: string | number; + flag?: string; + throws?: boolean; + fs?: FS; + EOL?: string; + spaces?: string | number; + replacer?: (key: string, value: any) => any; + } | null; + +export type JFReadCallback = (err: NodeJS.ErrnoException | null, data: any) => void; + +export function readFile(file: Path, options?: JFReadOptions, callback?: JFReadCallback): void; +export function readFile(file: Path, callback: JFReadCallback): void; + +export function readFileSync(file: Path, options?: JFReadOptions): any; + +export function writeFile(file: Path, obj: any, options?: JFWriteOptions, callback?: WriteCallback): void; +export function writeFile(file: Path, obj: any, callback: WriteCallback): void; + +export function writeFileSync(file: Path, obj: any, options?: JFWriteOptions): void; diff --git a/types/jsonfile/v4/jsonfile-tests.ts b/types/jsonfile/v4/jsonfile-tests.ts new file mode 100644 index 0000000000..675a32d8b9 --- /dev/null +++ b/types/jsonfile/v4/jsonfile-tests.ts @@ -0,0 +1,34 @@ +// Following are lifted from the samples on the NPM page, modified to pass +// the linter + +import * as jsonfile from 'jsonfile'; + +const file = '/tmp/data.json'; +const obj = {name: 'JP'}; + +jsonfile.readFile(file, (err: NodeJS.ErrnoException | null, obj: any) => { + console.dir(obj); +}); + +console.dir(jsonfile.readFileSync(file)); + +jsonfile.writeFile(file, obj, (err: NodeJS.ErrnoException) => { + console.error(err); +}); + +jsonfile.writeFile(file, obj, {spaces: 2}, (err: NodeJS.ErrnoException) => { + console.error(err); +}); + +jsonfile.writeFile(file, obj, {spaces: 2, EOL: '\r\n'}, (err: NodeJS.ErrnoException) => { + console.error(err); +}); + +jsonfile.writeFile(file, obj, {flag: 'a'}, (err: NodeJS.ErrnoException) => { + console.error(err); +}); + +jsonfile.writeFileSync(file, obj); +jsonfile.writeFileSync(file, obj, {spaces: 2}); +jsonfile.writeFileSync(file, obj, {spaces: 2, EOL: '\r\n'}); +jsonfile.writeFileSync(file, obj, {flag: 'a'}); diff --git a/types/jsonfile/v4/tsconfig.json b/types/jsonfile/v4/tsconfig.json new file mode 100644 index 0000000000..e6505d789e --- /dev/null +++ b/types/jsonfile/v4/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "jsonfile": [ + "jsonfile/v4" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "jsonfile-tests.ts" + ] +} diff --git a/types/jsonfile/v4/tslint.json b/types/jsonfile/v4/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsonfile/v4/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/lock-system/index.d.ts b/types/lock-system/index.d.ts new file mode 100644 index 0000000000..5498c500c0 --- /dev/null +++ b/types/lock-system/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for lock-system 1.3 +// Project: https://github.com/sindresorhus/lock-system#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = lockSystem; + +declare function lockSystem(): void; diff --git a/types/lock-system/lock-system-tests.ts b/types/lock-system/lock-system-tests.ts new file mode 100644 index 0000000000..6677bae0a9 --- /dev/null +++ b/types/lock-system/lock-system-tests.ts @@ -0,0 +1,3 @@ +import lockSystem = require('lock-system'); + +lockSystem(); diff --git a/types/lock-system/tsconfig.json b/types/lock-system/tsconfig.json new file mode 100644 index 0000000000..0b7c667951 --- /dev/null +++ b/types/lock-system/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", + "lock-system-tests.ts" + ] +} diff --git a/types/lock-system/tslint.json b/types/lock-system/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lock-system/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 0c6ef0eef3..7c6284059e 100644 --- a/types/mailgun-js/index.d.ts +++ b/types/mailgun-js/index.d.ts @@ -50,6 +50,8 @@ declare namespace Mailgun { getType(): string; } + type AttachmentData = string | Buffer | NodeJS.ReadWriteStream | Attachment; + interface MailgunExport { new (options: ConstructorParams): Mailgun; (options: ConstructorParams): Mailgun; @@ -64,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 { diff --git a/types/mailgun-js/mailgun-js-tests.ts b/types/mailgun-js/mailgun-js-tests.ts index e06e683248..0d830308d1 100644 --- a/types/mailgun-js/mailgun-js-tests.ts +++ b/types/mailgun-js/mailgun-js-tests.ts @@ -25,7 +25,15 @@ 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) => {}); diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 91fb68cd96..149d433a89 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -232,7 +232,7 @@ declare namespace mapboxgl { /** * The max number of pixels a user can shift the mouse pointer during a click for it to be * considered a valid click (as opposed to a mouse drag). - * + * * @default 3 */ clickTolerance?: number; @@ -242,7 +242,7 @@ declare namespace mapboxgl { * and Vector Tile web workers (this information is normally inaccessible from the main * Javascript thread). Information will be returned in a `resourceTiming` property of * relevant `data` events. - * + * * @default false */ collectResourceTiming?: boolean; @@ -250,7 +250,7 @@ declare namespace mapboxgl { /** * If `true`, symbols from multiple sources can collide with each other during collision * detection. If `false`, collision detection is run separately for the symbols in each source. - * + * * @default true */ crossSourceCollisions?: boolean; @@ -278,7 +278,7 @@ declare namespace mapboxgl { * Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. * This setting affects all symbol layers. This setting does not affect the duration of runtime * styling transitions or raster tile cross-fading. - * + * * @default 300 */ fadeDuration?: number; @@ -297,14 +297,14 @@ declare namespace mapboxgl { * 'CJK Unified Ideographs' and 'Hangul Syllables' ranges. In these ranges, font settings from * the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). * The purpose of this option is to avoid bandwidth-intensive glyph server requests. - * + * * @default null */ localIdeographFontFamily?: string; /** * A string representing the position of the Mapbox wordmark on the map. - * + * * @default "bottom-left" */ logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; @@ -324,14 +324,14 @@ declare namespace mapboxgl { /** * The initial pitch (tilt) of the map, measured in degrees away from the plane of the * screen (0-60). - * + * * @default 0 */ pitch?: number; /** * If `false`, the map's pitch (tilt) control with "drag to rotate" interaction will be disabled. - * + * * @default true */ pitchWithRotate?: boolean; @@ -339,14 +339,14 @@ declare namespace mapboxgl { /** * If `false`, the map won't attempt to re-request tiles once they expire per their HTTP * `cacheControl`/`expires` headers. - * + * * @default true */ refreshExpiredTiles?: boolean; /** * If `true`, multiple copies of the world will be rendered, when zoomed out. - * + * * @default true */ renderWorldCopies?: boolean; @@ -363,7 +363,7 @@ declare namespace mapboxgl { /** * A callback run before the Map makes a request for an external URL. The callback can be * used to modify the url, set headers, or set the credentials property for cross-origin requests. - * + * * @default null */ transformRequest?: TransformRequestFunction; @@ -377,13 +377,13 @@ declare namespace mapboxgl { /** * The maximum number of tiles stored in the tile cache for a given source. If omitted, the * cache will be dynamically sized based on the current viewport. - * + * * @default null */ maxTileCacheSize?: number; } - export type ResourceType = + export type ResourceType = | 'Unknown' | 'Style' | 'Source' @@ -692,7 +692,7 @@ declare namespace mapboxgl { clusterMaxZoom?: number; lineMetrics?: boolean; - + generateId?: boolean; } @@ -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 { @@ -1476,13 +1477,13 @@ declare namespace mapboxgl { } export interface HeatmapPaint { - 'heatmap-radius'?: number | Expression; + 'heatmap-radius'?: number | StyleFunction | Expression; 'heatmap-radius-transition'?: Transition; 'heatmap-weight'?: number | StyleFunction | Expression; - 'heatmap-intensity'?: number | Expression; + 'heatmap-intensity'?: number | StyleFunction | Expression; 'heatmap-intensity-transition'?: Transition; - 'heatmap-color'?: string | Expression; - 'heatmap-opacity'?: number | Expression; + 'heatmap-color'?: string | StyleFunction | Expression; + 'heatmap-opacity'?: number | StyleFunction | Expression; 'heatmap-opacity-transition'?: Transition; } 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/marked-terminal/index.d.ts b/types/marked-terminal/index.d.ts new file mode 100644 index 0000000000..30e4b8fe38 --- /dev/null +++ b/types/marked-terminal/index.d.ts @@ -0,0 +1,58 @@ +// Type definitions for marked-terminal 3.1 +// Project: https://github.com/mikaelbr/marked-terminal +// Definitions by: Bryan Kendall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Chalk } from 'chalk'; +import { Renderer } from 'marked'; + +export as namespace TerminalRenderer; + +export = TerminalRenderer; + +declare class TerminalRenderer extends Renderer { + constructor(options?: TerminalRenderer.TerminalRendererOptions) +} + +declare namespace TerminalRenderer { + interface TerminalRendererOptions { + code?: Chalk | ((s: string) => string); + blockquote?: Chalk | ((s: string) => string); + html?: Chalk | ((s: string) => string); + heading?: Chalk | ((s: string) => string); + firstHeading?: Chalk | ((s: string) => string); + hr?: Chalk | ((s: string) => string); + listitem?: Chalk | ((s: string) => string); + table?: Chalk | ((s: string) => string); + paragraph?: Chalk | ((s: string) => string); + strong?: Chalk | ((s: string) => string); + em?: Chalk | ((s: string) => string); + codespan?: Chalk | ((s: string) => string); + del?: Chalk | ((s: string) => string); + link?: Chalk | ((s: string) => string); + href?: Chalk | ((s: string) => string); + + // Formats the bulletpoints and numbers for lists + list?: (body: string, ordered?: boolean) => string; + + // Reflow and print-out width + width?: number; // only applicable when reflow is true + reflowText?: boolean; + + // Should it prefix headers? + showSectionPrefix?: boolean; + + // Whether or not to undo marked escaping + // of enitities (" -> " etc) + unescape?: boolean; + + // Whether or not to show emojis + emoji?: boolean; + + // Options passed to cli-table + tableOptions?: any; + + // The size of tabs in number of spaces or as tab characters + tab?: number; + } +} diff --git a/types/marked-terminal/marked-terminal-tests.ts b/types/marked-terminal/marked-terminal-tests.ts new file mode 100644 index 0000000000..230dfa1adc --- /dev/null +++ b/types/marked-terminal/marked-terminal-tests.ts @@ -0,0 +1,29 @@ +import * as marked from 'marked'; +import * as TerminalRenderer from 'marked-terminal'; +import chalk from 'chalk'; + +marked.setOptions({ + // Define custom renderer + renderer: new TerminalRenderer() +}); + +marked.setOptions({ + // Define custom renderer + renderer: new TerminalRenderer({ + // Change style for code + codespan: chalk.underline.magenta, + // Can also override color/styling by own functions. + firstHeading: (text: string) => `*** ${text}` + }) +}); + +marked.setOptions({ + // Define custom renderer + renderer: new TerminalRenderer({ + reflowText: true, + width: 60 + }) +}); + +// Show the parsed data +console.log(marked('# a basic string\nwith stuff')); diff --git a/types/marked-terminal/package.json b/types/marked-terminal/package.json new file mode 100644 index 0000000000..e119a357f0 --- /dev/null +++ b/types/marked-terminal/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "chalk": "^2.4.1" + } +} diff --git a/types/marked-terminal/tsconfig.json b/types/marked-terminal/tsconfig.json new file mode 100644 index 0000000000..77a046fc31 --- /dev/null +++ b/types/marked-terminal/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "marked-terminal-tests.ts" + ] +} diff --git a/types/marked-terminal/tslint.json b/types/marked-terminal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/marked-terminal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/match-media-mock/match-media-mock-tests.ts b/types/match-media-mock/match-media-mock-tests.ts index dc35cff40b..25fe411dd1 100644 --- a/types/match-media-mock/match-media-mock-tests.ts +++ b/types/match-media-mock/match-media-mock-tests.ts @@ -7,7 +7,7 @@ matchMediaMock('(max-width: 991px)').matches // false matchMediaMock('(max-width: 1240px)').matches // true const mediaQueryList = matchMediaMock('(max-width: 991px)'); -const listener = (mql: MediaQueryList) => { }; +const listener = function (this: MediaQueryList) { }; mediaQueryList.addListener(listener) mediaQueryList.removeListener(listener) 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/materialize-css/autoinit.d.ts b/types/materialize-css/autoinit.d.ts new file mode 100644 index 0000000000..c3e9009b1d --- /dev/null +++ b/types/materialize-css/autoinit.d.ts @@ -0,0 +1,6 @@ +declare namespace M { + /** + * Automatically initialize components. + */ + function AutoInit(context?: Element): void; +} diff --git a/types/materialize-css/index.d.ts b/types/materialize-css/index.d.ts index f8502cafb4..3be768a216 100644 --- a/types/materialize-css/index.d.ts +++ b/types/materialize-css/index.d.ts @@ -9,6 +9,7 @@ /// /// +/// /// /// /// 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/mem-fs/index.d.ts b/types/mem-fs/index.d.ts index 4b1d8c4d14..6ab2c43c88 100644 --- a/types/mem-fs/index.d.ts +++ b/types/mem-fs/index.d.ts @@ -10,13 +10,13 @@ import { Transform } from 'stream'; import * as File from 'vinyl'; export interface Store extends EventEmitter { - add: (file: File, content: string) => void; - each: (callback: (file: File, index: number) => void) => void; get: (filepath: string) => File; + add: (file: File) => this; + each: (callback: (file: File, index: number) => void) => this; stream: () => Transform; } -export function create(...args: any[]): Store; +export function create(): Store; export namespace memFs { } diff --git a/types/mem-fs/mem-fs-tests.ts b/types/mem-fs/mem-fs-tests.ts index 9605c65ef7..3b20f30891 100644 --- a/types/mem-fs/mem-fs-tests.ts +++ b/types/mem-fs/mem-fs-tests.ts @@ -3,6 +3,6 @@ import * as fs from 'mem-fs'; const store: fs.Store = fs.create(); const file = store.get('hello'); -store.add(file, 'hahahahah'); - -store.each(file => console.dir(store.get(file.path))); +const file2 = store.add(file) + .each(file => console.dir(store.get(file.path))) + .get('test'); diff --git a/types/memoize-one/index.d.ts b/types/memoize-one/index.d.ts index 71f785e73c..e8ec195875 100644 --- a/types/memoize-one/index.d.ts +++ b/types/memoize-one/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for memoize-one 3.1 +// Type definitions for memoize-one 4.1 // Project: https://github.com/alexreardon/memoize-one#readme // Definitions by: Karol Majewski , Frank Li // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function memoizeOne any>(resultFn: T, isEqual?: EqualityFn): T; -export type EqualityFn = (a: any, b: any) => boolean; +export type EqualityFn = (a: any, b: any, index: number) => boolean; export default memoizeOne; diff --git a/types/memoize-one/memoize-one-tests.ts b/types/memoize-one/memoize-one-tests.ts index 4feddf6e57..a9c565b500 100644 --- a/types/memoize-one/memoize-one-tests.ts +++ b/types/memoize-one/memoize-one-tests.ts @@ -3,6 +3,7 @@ import memoizeOne, { EqualityFn } from 'memoize-one'; declare function add(a: number, b: number): number ; declare function lousyEqualityFn(a: any, b: any): boolean; declare function strictEqualityFn(a: T, b: T): boolean; +declare function equalityFnWithIndex(a: T, b: T, index: number): boolean; /** * Accepts a second argument. @@ -10,17 +11,18 @@ declare function strictEqualityFn(a: T, b: T): boolean; memoizeOne(add); // $ExpectType (a: number, b: number) => number memoizeOne(add, lousyEqualityFn); // $ExpectType (a: number, b: number) => number memoizeOne(add, strictEqualityFn); // $ExpectType (a: number, b: number) => number +memoizeOne(add, equalityFnWithIndex); // $ExpectType (a: number, b: number) => number /** - * The second argument can be, but doesn't have to be stritly typed. + * The second argument can be, but doesn't have to be strictly typed. */ memoizeOne(add, (a, b) => a === b); // $ExpectType (a: number, b: number) => number memoizeOne(add, (a: string, b: string) => a === b); // $ExpectType (a: number, b: number) => number /** - * Function passed as the second argument accepts exactly two arguments. + * Function passed as the second argument accepts no more than three arguments. */ -memoizeOne(add, (a: number, b: number, c: number) => a === b || c); // $ExpectError +memoizeOne(add, (a: number, b: number, c: number, d: number) => Boolean(a && b && c && d)); // $ExpectError /** * Function passed as the second argument returns a boolean. diff --git a/types/memoize-one/v3/index.d.ts b/types/memoize-one/v3/index.d.ts new file mode 100644 index 0000000000..71f785e73c --- /dev/null +++ b/types/memoize-one/v3/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for memoize-one 3.1 +// Project: https://github.com/alexreardon/memoize-one#readme +// Definitions by: Karol Majewski , Frank Li +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function memoizeOne any>(resultFn: T, isEqual?: EqualityFn): T; +export type EqualityFn = (a: any, b: any) => boolean; + +export default memoizeOne; diff --git a/types/memoize-one/v3/memoize-one-tests.ts b/types/memoize-one/v3/memoize-one-tests.ts new file mode 100644 index 0000000000..f163add16e --- /dev/null +++ b/types/memoize-one/v3/memoize-one-tests.ts @@ -0,0 +1,33 @@ +import memoizeOne, { EqualityFn } from 'memoize-one'; + +declare function add(a: number, b: number): number ; +declare function lousyEqualityFn(a: any, b: any): boolean; +declare function strictEqualityFn(a: T, b: T): boolean; + +/** + * Accepts a second argument. + */ +memoizeOne(add); // $ExpectType (a: number, b: number) => number +memoizeOne(add, lousyEqualityFn); // $ExpectType (a: number, b: number) => number +memoizeOne(add, strictEqualityFn); // $ExpectType (a: number, b: number) => number + +/** + * The second argument can be, but doesn't have to be strictly typed. + */ +memoizeOne(add, (a, b) => a === b); // $ExpectType (a: number, b: number) => number +memoizeOne(add, (a: string, b: string) => a === b); // $ExpectType (a: number, b: number) => number + +/** + * Function passed as the second argument accepts exactly two arguments. + */ +memoizeOne(add, (a: number, b: number, c: number) => a === b || c); // $ExpectError + +/** + * Function passed as the second argument returns a boolean. + */ +memoizeOne(add, (a: string, b: string) => 0); // $ExpectError + +/** + * The `EqualityFn` type is publicly accessible. + */ +const simpleIsEqual: EqualityFn = (x: number, y: number): boolean => (x === y); diff --git a/types/memoize-one/v3/tsconfig.json b/types/memoize-one/v3/tsconfig.json new file mode 100644 index 0000000000..728bd3ee58 --- /dev/null +++ b/types/memoize-one/v3/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "memoize-one": [ "memoize-one/v3" ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "memoize-one-tests.ts" + ] +} diff --git a/types/memoize-one/v3/tslint.json b/types/memoize-one/v3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/memoize-one/v3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/merge-images/index.d.ts b/types/merge-images/index.d.ts new file mode 100644 index 0000000000..7dcc6e93f4 --- /dev/null +++ b/types/merge-images/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for merge-images 1.1 +// Project: https://github.com/lukechilds/merge-images +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace mergeImages; + +export = mergeImages; + +declare function mergeImages( + sources: mergeImages.ImageSource[], + options?: mergeImages.Options +): Promise; + +declare namespace mergeImages { + type ImageSource = string | { src: string; x?: number; y?: number; opacity?: number }; + + interface Options { + format?: string; + quality?: number; + width?: number; + height?: number; + Canvas?: any; + } +} diff --git a/types/merge-images/merge-images-tests.ts b/types/merge-images/merge-images-tests.ts new file mode 100644 index 0000000000..260d9edae8 --- /dev/null +++ b/types/merge-images/merge-images-tests.ts @@ -0,0 +1,27 @@ +import mergeImages = require('merge-images'); + +// $ExpectType Promise +mergeImages(['/body.png', '/eyes.png', '/mouth.png']); +mergeImages([ + { src: 'body.png', x: 0, y: 0 }, + { src: 'eyes.png', x: 32, y: 0 }, + { src: 'mouth.png', x: 16, y: 0 }, +]); +mergeImages([ + { src: 'body.png' }, + { src: 'eyes.png', opacity: 0.7 }, + { src: 'mouth.png', opacity: 0.3 }, +]); +mergeImages(['/body.png', '/eyes.png', '/mouth.png'], { + width: 128, + height: 128, +}); +mergeImages(['/body.png', '/eyes.png', '/mouth.png'], { + format: 'image/jpeg', +}); +mergeImages(['/body.png', '/eyes.png', '/mouth.png'], { + quality: 1, +}); +mergeImages(['/body.png', '/eyes.png', '/mouth.png'], { + Canvas: null as any, +}); diff --git a/types/merge-images/tsconfig.json b/types/merge-images/tsconfig.json new file mode 100644 index 0000000000..23f7f12593 --- /dev/null +++ b/types/merge-images/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "merge-images-tests.ts" + ] +} diff --git a/types/merge-images/tslint.json b/types/merge-images/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/merge-images/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/microservice-utilities/index.d.ts b/types/microservice-utilities/index.d.ts new file mode 100644 index 0000000000..7b2c4be923 --- /dev/null +++ b/types/microservice-utilities/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for microservice-utilities 0.1 +// Project: https://github.com/Cimpress-MCP/microservice-utilities.js +// Definitions by: Daan Boerlage +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Authorizer + */ + +export interface AuthorizerConfiguration { + jwkKeyListUrl: string; + authorizerContextResolver?: string; +} + +export interface AuthorizerPolicy { + principalId: string; + policyDocument: object; +} + +export class Authorizer { + constructor(logFunction: (msg: any) => void, configuration: AuthorizerConfiguration); + getPolicy(request: object): Promise; +} + +/** + * PlatformClient + */ + +export interface PlatformClientConfiguration { + client: object; +} + +export interface PlatformClientResponse { + data?: any; + status: number; + statusText: string; + headers: any; + config: object; + request?: any; +} + +export class PlatformClient { + constructor(logFunction: (msg: any) => void, tokenResolverFunction?: Promise<() => string>, configuration?: PlatformClientConfiguration) + get(url: string, headers?: { [s: string]: string; }, type?: string): Promise; + post(url: string, data: object, headers?: { [s: string]: string; }): Promise; + put(url: string, data: object, headers?: { [s: string]: string; }): Promise; + patch(url: string, data: object, headers?: { [s: string]: string; }): Promise; + delete(url: string, headers?: { [s: string]: string; }): Promise; + head(url: string, headers?: { [s: string]: string; }): Promise; + options(url: string, headers?: { [s: string]: string; }): Promise; +} + +/** + * RequestLogger + */ + +export interface RequestLoggerConfiguration { + logFunction?: (msg: any) => void; + extendErrorObjects?: boolean; + jsonSpace?: number; +} + +export class RequestLogger { + constructor(configuration?: RequestLoggerConfiguration); + log(msg: any): void; +} + +/** + * ServiceTokenProvider + */ + +export interface ServiceTokenProviderConfiguration { + clientId: string; + encryptedClientSecret: string; + audience: string; + tokenEndpoint: string; +} + +export class ServiceTokenProvider { + constructor(httpClient: object, kmsClient: object, configuration?: ServiceTokenProviderConfiguration); + getToken(): Promise; + getTokenWithoutCache(): Promise; +} diff --git a/types/microservice-utilities/microservice-utilities-tests.ts b/types/microservice-utilities/microservice-utilities-tests.ts new file mode 100644 index 0000000000..969e5e44d4 --- /dev/null +++ b/types/microservice-utilities/microservice-utilities-tests.ts @@ -0,0 +1,17 @@ +import { Authorizer, PlatformClient, RequestLogger, ServiceTokenProvider } from 'microservice-utilities'; + +(async (): Promise => { + const authorizer = new Authorizer((msg: any) => msg, { jwkKeyListUrl: 'aaa' }); + const authorizerPolicy = authorizer.getPolicy({ test: true }); + + const platformClient = new PlatformClient((msg: any) => msg); + const result = await platformClient.get('https://www.typescriptlang.org/'); + const data = result.data as string; + + platformClient.post('https://www.typescriptlang.org/', { testData: 'abc' }); + + const serviceTokenProvider = new ServiceTokenProvider(platformClient, {}); + + const requestLogger = new RequestLogger({ jsonSpace: 4 }); + requestLogger.log('hello world'); +})(); diff --git a/types/microservice-utilities/tsconfig.json b/types/microservice-utilities/tsconfig.json new file mode 100644 index 0000000000..db45fd6d19 --- /dev/null +++ b/types/microservice-utilities/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", + "microservice-utilities-tests.ts" + ] +} diff --git a/types/microservice-utilities/tslint.json b/types/microservice-utilities/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/microservice-utilities/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/min-indent/index.d.ts b/types/min-indent/index.d.ts new file mode 100644 index 0000000000..8064b85875 --- /dev/null +++ b/types/min-indent/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for min-indent 1.0 +// Project: https://github.com/thejameskyle/min-indent#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = minIndent; + +declare function minIndent(str: string): number; diff --git a/types/min-indent/min-indent-tests.ts b/types/min-indent/min-indent-tests.ts new file mode 100644 index 0000000000..c6deec82a1 --- /dev/null +++ b/types/min-indent/min-indent-tests.ts @@ -0,0 +1,5 @@ +import minIndent = require('min-indent'); + +const str = '\tunicorn\n\t\tcake'; +// $ExpectType number +minIndent(str); diff --git a/types/min-indent/tsconfig.json b/types/min-indent/tsconfig.json new file mode 100644 index 0000000000..f9e5fd94f3 --- /dev/null +++ b/types/min-indent/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", + "min-indent-tests.ts" + ] +} diff --git a/types/min-indent/tslint.json b/types/min-indent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/min-indent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/mongodb/index.d.ts b/types/mongodb/index.d.ts index b31a8dd7b9..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 */ @@ -589,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; @@ -679,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 */ @@ -737,7 +735,7 @@ export interface IndexOptions extends CommonOptions { * Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ partialFilterExpression?: any; - collation?: Object; + collation?: CollationDocument; default_language?: string } @@ -839,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; @@ -888,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; @@ -1294,11 +1292,12 @@ export interface CollectionAggregationOptions { * 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; @@ -1560,7 +1559,7 @@ export interface FindOneOptions { readPreference?: ReadPreference | string; partial?: boolean; maxTimeMs?: number; - collation?: Object; + collation?: CollationDocument; session?: ClientSession; } @@ -1681,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 */ @@ -1827,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 */ @@ -1986,7 +1991,7 @@ export interface ChangeStreamOptions { maxAwaitTimeMS?: number; resumeAfter?: Object; batchSize?: number; - collation?: Object; + collation?: CollationDocument; readPreference?: ReadPreference; } @@ -2067,3 +2072,39 @@ export class Logger { */ 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/mongoose/index.d.ts b/types/mongoose/index.d.ts index 3672b75b8f..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. */ @@ -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 f713ba8538..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; @@ -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/month-days/index.d.ts b/types/month-days/index.d.ts new file mode 100644 index 0000000000..1a4249abac --- /dev/null +++ b/types/month-days/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for month-days 2.1 +// Project: https://github.com/sindresorhus/month-days#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = monthDays; + +declare function monthDays(month?: number, year?: number): number; diff --git a/types/month-days/month-days-tests.ts b/types/month-days/month-days-tests.ts new file mode 100644 index 0000000000..1b33a183fa --- /dev/null +++ b/types/month-days/month-days-tests.ts @@ -0,0 +1,8 @@ +import monthDays = require('month-days'); + +// $ExpectType number +monthDays(); +// $ExpectType number +monthDays(1); +// $ExpectType number +monthDays(1, 2016); diff --git a/types/month-days/tsconfig.json b/types/month-days/tsconfig.json new file mode 100644 index 0000000000..a125d8cae5 --- /dev/null +++ b/types/month-days/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", + "month-days-tests.ts" + ] +} diff --git a/types/month-days/tslint.json b/types/month-days/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/month-days/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/move-file/index.d.ts b/types/move-file/index.d.ts new file mode 100644 index 0000000000..7c86feca71 --- /dev/null +++ b/types/move-file/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for move-file 1.0 +// Project: https://github.com/sindresorhus/move-file#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = moveFile; + +declare function moveFile( + source: string, + destination: string, + options?: moveFile.Options +): Promise; + +declare namespace moveFile { + function sync(source: string, destination: string, options?: Options): void; + + interface Options { + overwrite?: boolean; + } +} diff --git a/types/move-file/move-file-tests.ts b/types/move-file/move-file-tests.ts new file mode 100644 index 0000000000..36badd38c1 --- /dev/null +++ b/types/move-file/move-file-tests.ts @@ -0,0 +1,10 @@ +import moveFile = require('move-file'); + +// $ExpectType Promise +moveFile('source/unicorn.png', 'destination/unicorn.png'); +// $ExpectType Promise +moveFile('source/unicorn.png', 'destination/unicorn.png', { overwrite: false }); +// $ExpectType void +moveFile.sync('source/unicorn.png', 'destination/unicorn.png'); +// $ExpectType void +moveFile.sync('source/unicorn.png', 'destination/unicorn.png', { overwrite: false }); diff --git a/types/move-file/tsconfig.json b/types/move-file/tsconfig.json new file mode 100644 index 0000000000..bcd3f7550e --- /dev/null +++ b/types/move-file/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", + "move-file-tests.ts" + ] +} diff --git a/types/move-file/tslint.json b/types/move-file/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/move-file/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/multi-progress/index.d.ts b/types/multi-progress/index.d.ts new file mode 100644 index 0000000000..91313a75f2 --- /dev/null +++ b/types/multi-progress/index.d.ts @@ -0,0 +1,48 @@ +// 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 = require('progress'); +import { Stream } from 'stream'; + +export as namespace MultiProgress; + +export = MultiProgress; + +declare 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: ProgressBar.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; +} + +declare namespace MultiProgress {} diff --git a/types/multi-progress/multi-progress-tests.ts b/types/multi-progress/multi-progress-tests.ts new file mode 100644 index 0000000000..b14806b7c5 --- /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 * as 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/neat-csv/index.d.ts b/types/neat-csv/index.d.ts new file mode 100644 index 0000000000..7fadcc316a --- /dev/null +++ b/types/neat-csv/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for neat-csv 4.0 +// Project: https://github.com/sindresorhus/neat-csv +// Definitions by: Alex Ruble +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { Readable } from 'stream'; + +declare function neatCsv(input: neatCsv.Input, options?: neatCsv.Options): Promise; + +declare namespace neatCsv { + /** The CSV data to parse. */ + type Input = string | Buffer | Readable; + + /** A configuration object to be passed to csv-parser. */ + interface Options { + escape?: string; + headers?: ReadonlyArray | boolean; + mapHeaders?: (args: { header: string; index: number }) => string | null; + mapValues?: (args: { header: string; index: number; value: any }) => any; + newline?: string; + quote?: string; + raw?: boolean; + separator?: string; + skipLines?: number; + maxRowBytes?: number; + strict?: boolean; + } + + /** A representation of one row of the input CSV. */ + interface Row { + [header: string]: string; + } +} + +export = neatCsv; diff --git a/types/neat-csv/neat-csv-tests.ts b/types/neat-csv/neat-csv-tests.ts new file mode 100644 index 0000000000..18bd94632a --- /dev/null +++ b/types/neat-csv/neat-csv-tests.ts @@ -0,0 +1,10 @@ +import * as neatCsv from 'neat-csv'; + +const data: neatCsv.Input = 'type,part\nunicorn,horn\nrainbow,pink'; +const options: neatCsv.Options = { separator: ',' }; + +neatCsv(data); // $ExpectType Promise +const rowsPromise = neatCsv(data, options); // $ExpectType Promise + +rowsPromise.then(rows => + rows.map(({ type, part }: neatCsv.Row) => `type: ${type}, part: ${part}`)); diff --git a/types/neat-csv/tsconfig.json b/types/neat-csv/tsconfig.json new file mode 100644 index 0000000000..ea4ccaf99e --- /dev/null +++ b/types/neat-csv/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "neat-csv-tests.ts" + ] +} diff --git a/types/neat-csv/tslint.json b/types/neat-csv/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/neat-csv/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/negative-array/index.d.ts b/types/negative-array/index.d.ts new file mode 100644 index 0000000000..1308de4d9c --- /dev/null +++ b/types/negative-array/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for negative-array 2.0 +// Project: https://github.com/sindresorhus/negative-array#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = negativeArray; + +declare function negativeArray(array: T[]): T[]; diff --git a/types/negative-array/negative-array-tests.ts b/types/negative-array/negative-array-tests.ts new file mode 100644 index 0000000000..9ca07b4a69 --- /dev/null +++ b/types/negative-array/negative-array-tests.ts @@ -0,0 +1,5 @@ +import negativeArray = require('negative-array'); + +const unicorn = negativeArray(['pony', 'cake', 'rainbow']); + +unicorn[-1]; diff --git a/types/negative-array/tsconfig.json b/types/negative-array/tsconfig.json new file mode 100644 index 0000000000..be024c1c31 --- /dev/null +++ b/types/negative-array/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", + "negative-array-tests.ts" + ] +} diff --git a/types/negative-array/tslint.json b/types/negative-array/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/negative-array/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/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/node-forge/index.d.ts b/types/node-forge/index.d.ts index 1a2b028a90..d2fcddc2d9 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -67,6 +67,8 @@ declare module "node-forge" { 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; @@ -202,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. @@ -244,6 +246,15 @@ 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): PrivateKey; diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index a8d352ad1a..62f0718c21 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -203,3 +203,22 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin 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/index.d.ts b/types/node/index.d.ts index f71cd9f6ec..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"; @@ -8998,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/inspector.d.ts b/types/node/inspector.d.ts index 3a2bb35afe..a9d0f1140a 100644 --- a/types/node/inspector.d.ts +++ b/types/node/inspector.d.ts @@ -1912,6 +1912,90 @@ declare module "inspector" { } } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + + interface StartParameterType { + traceConfig: TraceConfig; + } + + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + + namespace NodeWorker { + type WorkerID = string; + + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + /** * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. */ @@ -1958,6 +2042,7 @@ declare module "inspector" { * `messageAdded` notification. */ post(method: "Console.enable", callback?: (err: Error | null) => void): void; + /** * Continues execution until specific location is reached. */ @@ -2155,6 +2240,7 @@ declare module "inspector" { * Steps over the statement. */ post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + /** * Enables console to refer to the node with given id via $x (see Command Line API for more details * $x functions). @@ -2193,6 +2279,7 @@ declare module "inspector" { post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; @@ -2250,6 +2337,7 @@ declare module "inspector" { * @experimental */ post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + /** * Add handler to promise with given promise object id. */ @@ -2360,11 +2448,47 @@ declare module "inspector" { * @experimental */ post(method: "Runtime.terminateExecution", callback?: (err: Error | null) => void): void; + /** * Returns supported domains. */ post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + // Events addListener(event: string, listener: (...args: any[]) => void): this; @@ -2464,6 +2588,33 @@ declare module "inspector" { */ addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; emit(event: "Console.messageAdded", message: InspectorNotification): boolean; @@ -2486,6 +2637,11 @@ declare module "inspector" { emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; emit(event: "Runtime.executionContextsCleared"): boolean; emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; on(event: string, listener: (...args: any[]) => void): this; @@ -2584,6 +2740,33 @@ declare module "inspector" { */ on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; /** @@ -2681,6 +2864,33 @@ declare module "inspector" { */ once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; /** @@ -2778,6 +2988,33 @@ declare module "inspector" { */ prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; /** @@ -2874,6 +3111,33 @@ declare module "inspector" { * call). */ prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; } // Top Level API diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index c0f80728fc..e2e24dad68 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. @@ -2932,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 //////////////////////////////////////////////////// @@ -4673,9 +4725,26 @@ import * as constants from 'constants'; const pauseReason: string = message.params.reason; }); session.on('Debugger.resumed', () => {}); + // Node Inspector events + session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { + const value: Array<{}> = message.params.value; + }); } } +/////////////////////////////////////////////////////////// +/// 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/scripts/generate-inspector/event-emitter.ts b/types/node/scripts/generate-inspector/event-emitter.ts index 658109d6b2..3d3410633f 100644 --- a/types/node/scripts/generate-inspector/event-emitter.ts +++ b/types/node/scripts/generate-inspector/event-emitter.ts @@ -66,10 +66,11 @@ export const createListeners = (events: Event[]): string[] => { "", ...createListenerBlockFn("prependOnceListener")(events), ].reduce((acc, next, index, arr) => { - // removes trailing and consecutive empty lines + // removes leading, trailing and consecutive empty lines + const isFirst = index === 0; const isLast = index === arr.length - 1; const followsEmptyLine = acc.length > 0 && acc[acc.length - 1] === ""; - if ((isLast || followsEmptyLine) && next === "") { + if ((isFirst || isLast || followsEmptyLine) && next === "") { return acc; } else { acc.push(next); diff --git a/types/node/scripts/generate-inspector/generate-substitute-args.ts b/types/node/scripts/generate-inspector/generate-substitute-args.ts index 0054e9a85c..cd12eff1a8 100644 --- a/types/node/scripts/generate-inspector/generate-substitute-args.ts +++ b/types/node/scripts/generate-inspector/generate-substitute-args.ts @@ -4,17 +4,21 @@ import { capitalize, createDocs, flattenArgs, hasElements, isObjectReference } f const INDENT = " "; +// Turns a type into a type representing an array of that type +const arrify = (typeString: string) => { + return typeString === '{}' ? `Array<${typeString}>` : `${typeString}[]`; +} + // Converts DevTools type to TS type const createTypeString = (type: schema.Field, domain?: string): string => { return isObjectReference(type) ? type.$ref : - type.type === "any" ? "any" : + type.type === "any" ? "any" : type.type === "integer" ? "number" : type.type === "number" ? "number" : type.type === "boolean" ? "boolean" : type.type === "string" ? "string" : - type.type === "array" ? `${createTypeString(type.items, domain)}[]` : - type.type === "object" ? "{}" // this code path is likely never exercised - : "never"; + type.type === "array" ? arrify(createTypeString(type.items, domain)) : + type.type === "object" ? "{}" : "never"; // "never" has yet to be observed }; // Helper for createInterface -- constructs a list of interface fields @@ -138,7 +142,7 @@ export const generateSubstituteArgs = (protocol: schema.Schema): { [propName: st .map(item => item.commands .map(command => createPostFunctions(command, item.domain)) .reduce(flattenArgs(""), [])) - .reduce(flattenArgs(), []); + .reduce(flattenArgs(""), []); const eventOverloads: string[] = createListeners(protocol.domains .map(item => { diff --git a/types/node/scripts/generate-inspector/index.ts b/types/node/scripts/generate-inspector/index.ts index eb5da5ef2e..f555105e37 100644 --- a/types/node/scripts/generate-inspector/index.ts +++ b/types/node/scripts/generate-inspector/index.ts @@ -2,25 +2,55 @@ // [tag] corresponds to a tag name in the node-core repository. import { execSync } from "child_process"; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; +import { existsSync, readFileSync, writeFileSync } from "fs"; import * as https from "https"; import * as schema from "./devtools-protocol-schema"; import { generateSubstituteArgs } from "./generate-substitute-args"; -import { flattenArgs, substitute, trimRight } from "./utils"; +import { substitute, trimRight } from "./utils"; +import { string } from "parsimmon"; + +const httpsGet = (url: string) => new Promise((resolve, reject) => { + https.get(url, res => { + const frames: Buffer[] = []; + res.on("data", (data: Buffer) => { + frames.push(data); + }); + res.on("end", () => { + resolve(Buffer.concat(frames).toString("utf8")); + }); + res.on("error", (err: Error) => { + reject(err); + }); + }); +}); // Input arguments const tag = process.argv[2] || process.version; -const PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/deps/v8/src/inspector/js_protocol.json`; - -const devToolsPath = `${__dirname}/../../node_modules/devtools-protocol`; - -function writeProtocolToFile(json: string) { - const protocol: schema.Schema = JSON.parse(json); +const V8_PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/deps/v8/src/inspector/js_protocol.json`; +const NODE_PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/src/inspector/node_protocol.pdl`; +const INSPECTOR_PROTOCOL_REMOTE = `https://chromium.googlesource.com/deps/inspector_protocol`; +const INSPECTOR_PROTOCOL_LOCAL_DIR = "/tmp/inspector_protocol"; +/** + * Given a list of Inspector protocol definitions, write an inspector.d.ts + * containing all of those definitions merged together. + * @param jsonProtocols A list of Inspector protocol definitions. + */ +function writeProtocolsToFile(jsonProtocols: string[]) { + const combinedProtocol: schema.Schema = { + version: { major: '', minor: '' }, // doesn't matter + domains: [] + }; + for (const json of jsonProtocols) { + if (json) { + const protocol: schema.Schema = JSON.parse(json); + combinedProtocol.domains.push(...protocol.domains); + } + } + const substituteArgs = generateSubstituteArgs(combinedProtocol); const template = readFileSync(`${__dirname}/inspector.d.ts.template`, "utf8"); - - const substituteArgs = generateSubstituteArgs(protocol); + const inspectorDts = substitute(template, substituteArgs).split("\n") .map(line => trimRight(line)) .join("\n"); @@ -28,12 +58,24 @@ function writeProtocolToFile(json: string) { writeFileSync("./inspector.d.ts", inspectorDts, "utf8"); } -https.get(PROTOCOL_URL, res => { - const frames: Buffer[] = []; - res.on("data", (data: Buffer) => { - frames.push(data); - }); - res.on("end", () => { - writeProtocolToFile(Buffer.concat(frames).toString("utf8")); - }); -}); +/** + * Given a PDL-formatted string, return a JSON-formatted string. + * Note that this function run blocking shell commands, as it depends on an + * external script to do the conversion. + * @param pdl A PDL-formatted string. + */ +function convertPdlToJson(pdl: string): string { + if (!existsSync(INSPECTOR_PROTOCOL_LOCAL_DIR)) { + execSync(`git clone ${INSPECTOR_PROTOCOL_REMOTE} ${INSPECTOR_PROTOCOL_LOCAL_DIR}`); + } + writeFileSync("/tmp/inspector_protocol.pdl", pdl); + execSync(`${INSPECTOR_PROTOCOL_LOCAL_DIR}/convert_protocol_to_json.py /tmp/inspector_protocol.pdl /tmp/inspector_protocol.json`); + return readFileSync("/tmp/inspector_protocol.json", 'utf8'); +} + +// "Main" -- get the V8 built-in inspector protocol definition, as well as the +// Node extensions, and then write this to inspector.d.ts. +Promise.all([ + httpsGet(V8_PROTOCOL_URL), + httpsGet(NODE_PROTOCOL_URL).then(convertPdlToJson).catch(() => '') +]).then(writeProtocolsToFile).catch(console.error); diff --git a/types/npm-name/index.d.ts b/types/npm-name/index.d.ts new file mode 100644 index 0000000000..e4830f377e --- /dev/null +++ b/types/npm-name/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for npm-name 5.0 +// Project: https://github.com/sindresorhus/npm-name#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = npmName; + +declare function npmName(name: string): Promise; + +declare namespace npmName { + function many(names: T[]): Promise>; +} diff --git a/types/npm-name/npm-name-tests.ts b/types/npm-name/npm-name-tests.ts new file mode 100644 index 0000000000..cb8283699c --- /dev/null +++ b/types/npm-name/npm-name-tests.ts @@ -0,0 +1,12 @@ +import npmName = require('npm-name'); + +// $ExpectType Promise +npmName('chalk'); + +npmName.many(['chalk', '@sindresorhus/is', 'abc123']).then(result => { + // $ExpectType Map<"chalk" | "@sindresorhus/is" | "abc123", boolean> + result; + + // $ExpectType boolean | undefined + result.get('chalk'); +}); diff --git a/types/npm-name/tsconfig.json b/types/npm-name/tsconfig.json new file mode 100644 index 0000000000..c60a7df652 --- /dev/null +++ b/types/npm-name/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", + "npm-name-tests.ts" + ] +} diff --git a/types/npm-name/tslint.json b/types/npm-name/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/npm-name/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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 3e7f64375f..b8b06bd1f2 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -9421,7 +9421,7 @@ declare namespace Office { } /** - * The InternetHeaders object represents properties that are preserved after the item leaves Exchange and converted to a MIME message. + * The InternetHeaders object represents properties that are preserved after the message item leaves Exchange and is converted to a MIME message. * These properties are stored as x-headers in the MIME message. * * InternetHeaders are stored as key/value pairs on a per-item basis. @@ -15225,7 +15225,7 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read * * Item IDs retrieved via EWS or via the itemId property use a different format than the format used by REST APIs (such as the - * {@link https://docs.microsoft.com/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations | Outlook Mail API} or the {@link http://graph.microsoft.io/ | Microsoft Graph}. + * {@link https://docs.microsoft.com/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations | Outlook Mail API} or the {@link https://graph.microsoft.io/ | Microsoft Graph}. * The convertToRestId method converts an EWS-formatted ID into the proper format for REST. * * @param itemId An item ID formatted for Exchange Web Services (EWS) diff --git a/types/on-change/index.d.ts b/types/on-change/index.d.ts new file mode 100644 index 0000000000..44fff26e60 --- /dev/null +++ b/types/on-change/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for on-change 0.1 +// Project: https://github.com/sindresorhus/on-change#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = onChange; + +declare function onChange(object: T, onChange: () => void): T; diff --git a/types/on-change/on-change-tests.ts b/types/on-change/on-change-tests.ts new file mode 100644 index 0000000000..003d89aab7 --- /dev/null +++ b/types/on-change/on-change-tests.ts @@ -0,0 +1,17 @@ +import onChange = require('on-change'); + +const object = { + foo: false, + a: { + b: [ + { + c: false, + }, + ], + }, +}; + +const watchedObject = onChange(object, () => {}); + +watchedObject.foo = true; +watchedObject.a.b[0].c = true; diff --git a/types/on-change/tsconfig.json b/types/on-change/tsconfig.json new file mode 100644 index 0000000000..433629ab82 --- /dev/null +++ b/types/on-change/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", + "on-change-tests.ts" + ] +} diff --git a/types/on-change/tslint.json b/types/on-change/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/on-change/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/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-cancelable/index.d.ts b/types/p-cancelable/index.d.ts index 775400bca8..8375149e32 100644 --- a/types/p-cancelable/index.d.ts +++ b/types/p-cancelable/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for p-cancelable 0.5 +// Type definitions for p-cancelable 1.0 // Project: https://github.com/sindresorhus/p-cancelable#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,8 +10,42 @@ declare const PCancelable: PCancelableConstructor; interface PCancelableConstructor extends PromiseConstructor { readonly prototype: PCancelable.PCancelable; readonly CancelError: PCancelable.CancelErrorConstructor; - fn(wrapper: (onCancel: (fn?: () => void) => void, input: T) => PromiseLike): (input: T) => PCancelable.PCancelable; - new(executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void, onCancel: (fn?: () => void) => void) => void): PCancelable.PCancelable; + + new ( + executor: ( + resolve: (value?: T | PromiseLike) => void, + reject: (reason?: any) => void, + onCancel: PCancelable.OnCancelFn + ) => void + ): PCancelable.PCancelable; + + fn( + userFn: (onCancel: PCancelable.OnCancelFn) => PromiseLike + ): () => PCancelable.PCancelable; + fn( + userFn: (param1: T1, onCancel: PCancelable.OnCancelFn) => PromiseLike + ): (param1: T1) => PCancelable.PCancelable; + fn( + userFn: (param1: T1, param2: T2, onCancel: PCancelable.OnCancelFn) => PromiseLike + ): (param1: T1, param2: T2) => PCancelable.PCancelable; + fn( + userFn: ( + param1: T1, + param2: T2, + param3: T3, + onCancel: PCancelable.OnCancelFn + ) => PromiseLike + ): (param1: T1, param2: T2, param3: T3) => PCancelable.PCancelable; + fn( + userFn: ( + param1: T1, + param2: T2, + param3: T3, + param4: T4, + onCancel: PCancelable.OnCancelFn + ) => PromiseLike + ): (param1: T1, param2: T2, param3: T3, param4: T4) => PCancelable.PCancelable; + fn(userFn: (...args: any[]) => PromiseLike): (args: any[]) => PCancelable.PCancelable; } declare namespace PCancelable { @@ -20,6 +54,11 @@ declare namespace PCancelable { cancel(reason?: string): void; } + interface OnCancelFn { + (cancelHandler: () => void): void; + shouldReject: boolean; + } + interface CancelErrorConstructor extends ErrorConstructor { new (reason?: string): CancelError; } diff --git a/types/p-cancelable/p-cancelable-tests.ts b/types/p-cancelable/p-cancelable-tests.ts index 8bd3790e08..3e15c7d1f8 100644 --- a/types/p-cancelable/p-cancelable-tests.ts +++ b/types/p-cancelable/p-cancelable-tests.ts @@ -1,23 +1,25 @@ /// -import PCancelableCtor = require('p-cancelable'); -import { EventEmitter } from "events"; +import PCancelable = require('p-cancelable'); +import { EventEmitter } from 'events'; -const cancelablePromise: PCancelableCtor.PCancelable<{}> = new PCancelableCtor((resolve, reject, onCancel) => { - class Worker extends EventEmitter { - close() { +const cancelablePromise: PCancelable.PCancelable<{}> = new PCancelable( + (resolve, reject, onCancel) => { + class Worker extends EventEmitter { + close() {} } + + const worker = new Worker(); + + onCancel.shouldReject = false; + onCancel(() => { + worker.close(); + }); + + worker.on('finish', resolve); + worker.on('error', reject); } - - const worker = new Worker(); - - onCancel(() => { - worker.close(); - }); - - worker.on('finish', resolve); - worker.on('error', reject); -}); +); cancelablePromise .then(value => { @@ -35,30 +37,52 @@ cancelablePromise setTimeout(() => { cancelablePromise.cancel(); + cancelablePromise.cancel('foo'); }, 10000); -const fn = PCancelableCtor.fn((onCancel: (fn?: () => void) => void, input: string) => { - const job = { - start() { - return Promise.resolve(10); - }, - cleanup() { - } - }; +const fn0 = PCancelable.fn(onCancel => { + // $ExpectType OnCancelFn + onCancel; - onCancel(() => { - job.cleanup(); - }); - - return job.start(); + return Promise.resolve(10); }); +// $ExpectType () => PCancelable +fn0; -const promise = fn('input'); +const fn1 = PCancelable.fn((p1: string, onCancel: PCancelable.OnCancelFn) => { + return Promise.resolve(10); +}); +// $ExpectType (param1: string) => PCancelable +fn1; + +const fn2 = PCancelable.fn((p1: string, p2: boolean, onCancel: PCancelable.OnCancelFn) => { + return Promise.resolve(10); +}); +// $ExpectType (param1: string, param2: boolean) => PCancelable +fn2; + +const fn3 = PCancelable.fn( + (p1: string, p2: boolean, p3: number, onCancel: PCancelable.OnCancelFn) => { + return Promise.resolve(10); + } +); +// $ExpectType (param1: string, param2: boolean, param3: number) => PCancelable +fn3; + +const fn4 = PCancelable.fn( + (p1: string, p2: boolean, p3: number, p4: null, onCancel: PCancelable.OnCancelFn) => { + return Promise.resolve(10); + } +); +// $ExpectType (param1: string, param2: boolean, param3: number, param4: null) => PCancelable +fn4; + +const promise = fn0(); let num: number; -promise.then(innum => num = innum); +promise.then(innum => (num = innum)); if (!promise.isCanceled) { promise.cancel(); } -const err: PCancelableCtor.CancelError = new PCancelableCtor.CancelError(); +const err: PCancelable.CancelError = new PCancelable.CancelError(); throw err; 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/p-forever/index.d.ts b/types/p-forever/index.d.ts new file mode 100644 index 0000000000..df95c88217 --- /dev/null +++ b/types/p-forever/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for p-forever 1.0 +// Project: https://github.com/sindresorhus/p-forever#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +export = pForever; + +declare function pForever( + fn: (previousValue?: T) => T | PromiseLike | typeof pForever.end +): Promise; +declare function pForever( + fn: (previousValue: T) => T | PromiseLike | typeof pForever.end, + initialValue: T +): Promise; + +declare namespace pForever { + const end: unique symbol; +} diff --git a/types/p-forever/p-forever-tests.ts b/types/p-forever/p-forever-tests.ts new file mode 100644 index 0000000000..d6d931799b --- /dev/null +++ b/types/p-forever/p-forever-tests.ts @@ -0,0 +1,33 @@ +import pForever = require('p-forever'); + +// $ExpectType Promise +pForever(i => { + // $ExpectType number + i; + i++; + return i <= 100 ? i : pForever.end; +}, 0); +// $ExpectType Promise +pForever(i => { + // $ExpectType number + i; + i++; + return i <= 100 ? Promise.resolve(i) : pForever.end; +}, 0); + +let i = 0; + +// $ExpectType Promise +pForever(prevI => { + // $ExpectType number | undefined + prevI; + i++; + return i <= 100 ? i : pForever.end; +}); +// $ExpectType Promise +pForever(prevI => { + // $ExpectType number | undefined + prevI; + i++; + return i <= 100 ? Promise.resolve(i) : pForever.end; +}); diff --git a/types/p-forever/tsconfig.json b/types/p-forever/tsconfig.json new file mode 100644 index 0000000000..0bf6e83d7f --- /dev/null +++ b/types/p-forever/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", + "p-forever-tests.ts" + ] +} diff --git a/types/p-forever/tslint.json b/types/p-forever/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-forever/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-is-promise/index.d.ts b/types/p-is-promise/index.d.ts new file mode 100644 index 0000000000..5fd5791038 --- /dev/null +++ b/types/p-is-promise/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for p-is-promise 2.0 +// Project: https://github.com/sindresorhus/p-is-promise#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = pIsPromise; + +declare function pIsPromise(promise: any): promise is Promise; diff --git a/types/p-is-promise/p-is-promise-tests.ts b/types/p-is-promise/p-is-promise-tests.ts new file mode 100644 index 0000000000..3abe1f1115 --- /dev/null +++ b/types/p-is-promise/p-is-promise-tests.ts @@ -0,0 +1,6 @@ +import pIsPromise = require('p-is-promise'); + +// $ExpectType boolean +pIsPromise(Promise.resolve('🦄')); +// $ExpectType boolean +pIsPromise('🦄'); diff --git a/types/p-is-promise/tsconfig.json b/types/p-is-promise/tsconfig.json new file mode 100644 index 0000000000..37d295b57d --- /dev/null +++ b/types/p-is-promise/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", + "p-is-promise-tests.ts" + ] +} diff --git a/types/p-is-promise/tslint.json b/types/p-is-promise/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-is-promise/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-min-delay/index.d.ts b/types/p-min-delay/index.d.ts new file mode 100644 index 0000000000..ad3e8b52cc --- /dev/null +++ b/types/p-min-delay/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for p-min-delay 2.0 +// Project: https://github.com/sindresorhus/p-min-delay#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = pMinDelay; + +declare function pMinDelay( + input: PromiseLike, + minimumDelay: number, + options?: pMinDelay.Options +): Promise; + +declare namespace pMinDelay { + interface Options { + delayRejection?: boolean; + } +} diff --git a/types/p-min-delay/p-min-delay-tests.ts b/types/p-min-delay/p-min-delay-tests.ts new file mode 100644 index 0000000000..039ff5d28a --- /dev/null +++ b/types/p-min-delay/p-min-delay-tests.ts @@ -0,0 +1,6 @@ +import pMinDelay = require('p-min-delay'); + +// $ExpectType Promise +pMinDelay(Promise.resolve(1), 1000); +// $ExpectType Promise +pMinDelay(Promise.resolve("1"), 1000, { delayRejection: false }); diff --git a/types/p-min-delay/tsconfig.json b/types/p-min-delay/tsconfig.json new file mode 100644 index 0000000000..60cae5f27a --- /dev/null +++ b/types/p-min-delay/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", + "p-min-delay-tests.ts" + ] +} diff --git a/types/p-min-delay/tslint.json b/types/p-min-delay/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-min-delay/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-time/index.d.ts b/types/p-time/index.d.ts new file mode 100644 index 0000000000..dd9cb80709 --- /dev/null +++ b/types/p-time/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for p-time 1.0 +// Project: https://github.com/sindresorhus/p-time#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +export = pTime; + +declare function pTime( + fn: (...args: TArgs) => PromiseLike +): (...args: TArgs) => pTime.PromiseWithTime; + +declare namespace pTime { + const log: typeof pTime; + + interface PromiseWithTime extends Promise { + time?: number; + } +} diff --git a/types/p-time/p-time-tests.ts b/types/p-time/p-time-tests.ts new file mode 100644 index 0000000000..5f5102787c --- /dev/null +++ b/types/p-time/p-time-tests.ts @@ -0,0 +1,24 @@ +import pTime = require('p-time'); + +const wrappedFn = pTime(async (input: number) => { + return input; +}); + +// $ExpectType (input: number) => PromiseWithTime +wrappedFn; + +// $ExpectType number | undefined +wrappedFn(1).time; + +// $ExpectError +pTime((input: number) => { + return input; +}); + +// $ExpectError +wrappedFn('foo'); + +// $ExpectType (input: number) => PromiseWithTime +pTime.log(async (input: number) => { + return input; +}); diff --git a/types/p-time/tsconfig.json b/types/p-time/tsconfig.json new file mode 100644 index 0000000000..13daf0f62a --- /dev/null +++ b/types/p-time/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", + "p-time-tests.ts" + ] +} diff --git a/types/p-time/tslint.json b/types/p-time/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-time/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-times/index.d.ts b/types/p-times/index.d.ts new file mode 100644 index 0000000000..aded44388a --- /dev/null +++ b/types/p-times/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for p-times 1.0 +// Project: https://github.com/sindresorhus/p-times#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = pTimes; + +declare function pTimes( + count: number, + mapper: (index: number) => T | PromiseLike, + options?: pTimes.Options +): Promise; + +declare namespace pTimes { + interface Options { + concurrency?: number; + } +} diff --git a/types/p-times/p-times-tests.ts b/types/p-times/p-times-tests.ts new file mode 100644 index 0000000000..a506d03423 --- /dev/null +++ b/types/p-times/p-times-tests.ts @@ -0,0 +1,6 @@ +import pTimes = require('p-times'); + +// $ExpectType Promise +pTimes(5, i => `🦄-${i + 1}`); +// $ExpectType Promise +pTimes(5, i => `🦄-${i + 1}`, { concurrency: 1 }); diff --git a/types/p-times/tsconfig.json b/types/p-times/tsconfig.json new file mode 100644 index 0000000000..318aa53466 --- /dev/null +++ b/types/p-times/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", + "p-times-tests.ts" + ] +} diff --git a/types/p-times/tslint.json b/types/p-times/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-times/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-waterfall/index.d.ts b/types/p-waterfall/index.d.ts new file mode 100644 index 0000000000..d78f1928dd --- /dev/null +++ b/types/p-waterfall/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for p-waterfall 1.0 +// Project: https://github.com/sindresorhus/p-waterfall#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export = pWaterfall; + +type Task = (previousValue: T) => R | PromiseLike; +type InitialTask = () => R | PromiseLike; + +declare function pWaterfall(tasks: [InitialTask]): Promise; +declare function pWaterfall(tasks: [InitialTask, Task]): Promise; +declare function pWaterfall( + tasks: [InitialTask, Task, Task] +): Promise; +declare function pWaterfall( + tasks: [InitialTask, Task, Task, Task] +): Promise; +declare function pWaterfall( + tasks: [InitialTask, Task, Task, Task, Task] +): Promise; +declare function pWaterfall( + tasks: [InitialTask, Task, Task, Task, Task, Task] +): Promise; +declare function pWaterfall( + tasks: [ + InitialTask, + Task, + Task, + Task, + Task, + Task, + Task + ] +): Promise; +declare function pWaterfall( + tasks: [ + InitialTask, + Task, + Task, + Task, + Task, + Task, + Task, + Task + ] +): Promise; + +declare function pWaterfall(tasks: [Task], initialValue: T1): Promise; +declare function pWaterfall( + tasks: [Task, Task], + initialValue: T1 +): Promise; +declare function pWaterfall( + tasks: [Task, Task, Task], + initialValue: T1 +): Promise; +declare function pWaterfall( + tasks: [Task, Task, Task, Task], + initialValue: T1 +): Promise; +declare function pWaterfall( + tasks: [Task, Task, Task, Task, Task], + initialValue: T1 +): Promise; +declare function pWaterfall( + tasks: [Task, Task, Task, Task, Task, Task], + initialValue: T1 +): Promise; +declare function pWaterfall( + tasks: [ + Task, + Task, + Task, + Task, + Task, + Task, + Task + ], + initialValue: T1 +): Promise; +declare function pWaterfall( + tasks: [ + Task, + Task, + Task, + Task, + Task, + Task, + Task, + Task + ], + initialValue: T1 +): Promise; + +declare function pWaterfall(tasks: Iterable>, initialValue?: any): Promise; diff --git a/types/p-waterfall/p-waterfall-tests.ts b/types/p-waterfall/p-waterfall-tests.ts new file mode 100644 index 0000000000..f05587acc1 --- /dev/null +++ b/types/p-waterfall/p-waterfall-tests.ts @@ -0,0 +1,171 @@ +import pWaterfall = require('p-waterfall'); + +pWaterfall([() => `I ❤️ unicorn`]).then(finalValue => { + // $ExpectType string + finalValue; +}); +pWaterfall([() => `I ❤️ unicorn`, (str: string) => true]).then(finalValue => { + // $ExpectType boolean + finalValue; +}); +pWaterfall([() => `I ❤️ unicorn`, (str: string) => true, (bool: boolean) => 1]).then(finalValue => { + // $ExpectType number + finalValue; +}); +pWaterfall([ + () => `I ❤️ unicorn`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, +]).then(finalValue => { + // $ExpectType null + finalValue; +}); +pWaterfall([ + () => `I ❤️ unicorn`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + (n: null) => undefined, +]).then(finalValue => { + // $ExpectType undefined + finalValue; +}); +pWaterfall([ + () => `I ❤️ unicorn`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + (n: null) => undefined, + (u: undefined) => ({}), +]).then(finalValue => { + // $ExpectType {} + finalValue; +}); +pWaterfall([ + () => `I ❤️ unicorn`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + (n: null) => undefined, + (u: undefined) => ({}), + (o: {}) => 'foo', +]).then(finalValue => { + // $ExpectType string + finalValue; +}); +pWaterfall([ + () => `I ❤️ unicorn`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + (n: null) => undefined, + (u: undefined) => ({}), + (o: {}) => 'foo', + (s: string) => 1, +]).then(finalValue => { + // $ExpectType number + finalValue; +}); + +pWaterfall([previousValue => `I ❤️ ${previousValue}`], 'unicorn').then(finalValue => { + // $ExpectType string + finalValue; +}); +pWaterfall([previousValue => `I ❤️ ${previousValue}`, (str: string) => true], 'unicorn').then( + finalValue => { + // $ExpectType boolean + finalValue; + } +); +pWaterfall( + [previousValue => `I ❤️ ${previousValue}`, (str: string) => true, (bool: boolean) => 1], + 'unicorn' +).then(finalValue => { + // $ExpectType number + finalValue; +}); +pWaterfall( + [ + previousValue => `I ❤️ ${previousValue}`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + ], + 'unicorn' +).then(finalValue => { + // $ExpectType null + finalValue; +}); +pWaterfall( + [ + previousValue => `I ❤️ ${previousValue}`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + (n: null) => undefined, + ], + 'unicorn' +).then(finalValue => { + // $ExpectType undefined + finalValue; +}); +pWaterfall( + [ + previousValue => `I ❤️ ${previousValue}`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + (n: null) => undefined, + (u: undefined) => ({}), + ], + 'unicorn' +).then(finalValue => { + // $ExpectType {} + finalValue; +}); +pWaterfall( + [ + previousValue => `I ❤️ ${previousValue}`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + (n: null) => undefined, + (u: undefined) => ({}), + (o: {}) => 'foo', + ], + 'unicorn' +).then(finalValue => { + // $ExpectType string + finalValue; +}); +pWaterfall( + [ + previousValue => `I ❤️ ${previousValue}`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + (n: null) => undefined, + (u: undefined) => ({}), + (o: {}) => 'foo', + (s: string) => 1, + ], + 'unicorn' +).then(finalValue => { + // $ExpectType number + finalValue; +}); + +pWaterfall( + new Set([ + (previousValue: string) => `I ❤️ ${previousValue}`, + (str: string) => true, + (bool: boolean) => 1, + (num: number) => null, + (n: null) => undefined, + ]), + 'unicorn' +).then(finalValue => { + // $ExpectType any + finalValue; +}); diff --git a/types/p-waterfall/tsconfig.json b/types/p-waterfall/tsconfig.json new file mode 100644 index 0000000000..9907fc1223 --- /dev/null +++ b/types/p-waterfall/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", + "p-waterfall-tests.ts" + ] +} diff --git a/types/p-waterfall/tslint.json b/types/p-waterfall/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-waterfall/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index d3c818b112..5709826f6a 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -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/park-miller/index.d.ts b/types/park-miller/index.d.ts new file mode 100644 index 0000000000..5b1a5a893c --- /dev/null +++ b/types/park-miller/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for park-miller 1.0 +// Project: https://github.com/sindresorhus/park-miller#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = ParkMiller; + +declare class ParkMiller { + constructor(seed: number); + + integer(): number; + integerInRange(min: number, max: number): number; + float(): number; + floatInRange(min: number, max: number): number; + boolean(): boolean; +} diff --git a/types/park-miller/park-miller-tests.ts b/types/park-miller/park-miller-tests.ts new file mode 100644 index 0000000000..2add2c1400 --- /dev/null +++ b/types/park-miller/park-miller-tests.ts @@ -0,0 +1,14 @@ +import ParkMiller = require('park-miller'); + +const random = new ParkMiller(10); + +// $ExpectType number +random.integer(); +// $ExpectType number +random.integerInRange(0, 1); +// $ExpectType number +random.float(); +// $ExpectType number +random.floatInRange(0, 1); +// $ExpectType boolean +random.boolean(); diff --git a/types/park-miller/tsconfig.json b/types/park-miller/tsconfig.json new file mode 100644 index 0000000000..4a589ae205 --- /dev/null +++ b/types/park-miller/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", + "park-miller-tests.ts" + ] +} diff --git a/types/park-miller/tslint.json b/types/park-miller/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/park-miller/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/parse-columns/index.d.ts b/types/parse-columns/index.d.ts new file mode 100644 index 0000000000..cbe7c9d8c7 --- /dev/null +++ b/types/parse-columns/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for parse-columns 1.3 +// Project: https://github.com/sindresorhus/parse-columns +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = parseColumns; + +declare function parseColumns( + input: string, + options?: parseColumns.BaseOptions +): Array<{ [key: string]: string }>; +declare function parseColumns( + input: string, + options: parseColumns.Options +): Array<{ [key: string]: T }>; + +declare namespace parseColumns { + interface BaseOptions { + separator?: string; + headers?: ReadonlyArray; + } + + interface Options extends BaseOptions { + transform: (element: string, header: string, columnIndex: number, rowIndex: number) => T; + } +} diff --git a/types/parse-columns/parse-columns-tests.ts b/types/parse-columns/parse-columns-tests.ts new file mode 100644 index 0000000000..51f7ff7661 --- /dev/null +++ b/types/parse-columns/parse-columns-tests.ts @@ -0,0 +1,27 @@ +import parseColumns = require('parse-columns'); + +// $ExpectType { [key: string]: string; }[] +parseColumns('foo'); +// $ExpectType { [key: string]: string; }[] +parseColumns('foo', { separator: ' ' }); +// $ExpectType { [key: string]: string; }[] +parseColumns('foo', { headers: ['foo', 'bar'] }); +// $ExpectType { [key: string]: string | number; }[] +parseColumns('foo', { + transform(el, header, columnIndex, rowIndex) { + // $ExpectType string + el; + // $ExpectType string + header; + // $ExpectType number + columnIndex; + // $ExpectType number + rowIndex; + + if (columnIndex >= 1 && columnIndex <= 3) { + return Number(el); + } + + return el; + }, +}); diff --git a/types/parse-columns/tsconfig.json b/types/parse-columns/tsconfig.json new file mode 100644 index 0000000000..aceda8a52a --- /dev/null +++ b/types/parse-columns/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", + "parse-columns-tests.ts" + ] +} diff --git a/types/parse-columns/tslint.json b/types/parse-columns/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/parse-columns/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/path-type/index.d.ts b/types/path-type/index.d.ts new file mode 100644 index 0000000000..d67856f85e --- /dev/null +++ b/types/path-type/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for path-type 3.0 +// Project: https://github.com/sindresorhus/path-type#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const file: PathTypeFn; +export const dir: PathTypeFn; +export const symlink: PathTypeFn; + +export const fileSync: PathTypeSyncFn; +export const dirSync: PathTypeSyncFn; +export const symlinkSync: PathTypeSyncFn; + +export type PathTypeFn = (path: string) => Promise; +export type PathTypeSyncFn = (path: string) => boolean; diff --git a/types/path-type/path-type-tests.ts b/types/path-type/path-type-tests.ts new file mode 100644 index 0000000000..d070731523 --- /dev/null +++ b/types/path-type/path-type-tests.ts @@ -0,0 +1,15 @@ +import pathType = require('path-type'); + +// $ExpectType Promise +pathType.file('package.json'); +// $ExpectType Promise +pathType.dir('package.json'); +// $ExpectType Promise +pathType.symlink('package.json'); + +// $ExpectType boolean +pathType.fileSync('package.json'); +// $ExpectType boolean +pathType.dirSync('package.json'); +// $ExpectType boolean +pathType.symlinkSync('package.json'); diff --git a/types/path-type/tsconfig.json b/types/path-type/tsconfig.json new file mode 100644 index 0000000000..f2c7533a5d --- /dev/null +++ b/types/path-type/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", + "path-type-tests.ts" + ] +} diff --git a/types/path-type/tslint.json b/types/path-type/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/path-type/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/peerjs/index.d.ts b/types/peerjs/index.d.ts index 4ca88fd50b..f3ec14c796 100644 --- a/types/peerjs/index.d.ts +++ b/types/peerjs/index.d.ts @@ -2,7 +2,7 @@ // Project: http://peerjs.com/ // Definitions by: Toshiya Nakakura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// diff --git a/types/peerjs/package.json b/types/peerjs/package.json new file mode 100644 index 0000000000..d27d838dc6 --- /dev/null +++ b/types/peerjs/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.2.0-0": { "*": ["ts3.2/*"] } + } +} diff --git a/types/peerjs/peerjs-tests.ts b/types/peerjs/peerjs-tests.ts index 2246e6a8fd..eef24bf001 100644 --- a/types/peerjs/peerjs-tests.ts +++ b/types/peerjs/peerjs-tests.ts @@ -40,7 +40,7 @@ var connection = peerById.connect("id", { metadata: {message: 'hi i want to chat with you!'} }); -var call = peerById.call('callto-id', (window).localStream); +var call = peerById.call('callto-id', (window as any).localStream); var openHandler=()=> console.log("open"); peerById.on("open", openHandler); diff --git a/types/peerjs/ts3.2/index.d.ts b/types/peerjs/ts3.2/index.d.ts new file mode 100644 index 0000000000..71a6cc3c26 --- /dev/null +++ b/types/peerjs/ts3.2/index.d.ts @@ -0,0 +1,194 @@ +// Type definitions for PeerJS +// Project: http://peerjs.com/ +// Definitions by: Toshiya Nakakura +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace PeerJs{ + interface PeerJSOption{ + key?: string; + host?: string; + port?: number; + path?: string; + secure?: boolean; + config?: RTCConfiguration; + debug?: number; + } + + interface PeerConnectOption{ + label?: string; + metadata?: any; + serialization?: string; + reliable?: boolean; + + } + + interface DataConnection{ + send(data: any): void; + close(): void; + on(event: string, cb: ()=>void): void; + on(event: 'data', cb: (data: any)=>void): void; + on(event: 'open', cb: ()=>void): void; + on(event: 'close', cb: ()=>void): void; + on(event: 'error', cb: (err: any)=>void): void; + off(event: string, fn: Function, once?: boolean): void; + dataChannel: RTCDataChannel; + label: string; + metadata: any; + open: boolean; + peerConnection: any; + peer: string; + reliable: boolean; + serialization: string; + type: string; + buffSize: number; + } + + interface MediaConnection{ + answer(stream?: any): void; + close(): void; + on(event: string, cb: ()=>void): void; + on(event: 'stream', cb: (stream: any)=>void): void; + on(event: 'close', cb: ()=>void): void; + on(event: 'error', cb: (err: any)=>void): void; + off(event: string, fn: Function, once?: boolean): void; + open: boolean; + metadata: any; + peer: string; + type: string; + } + + interface utilSupportsObj { + audioVideo: boolean; + data: boolean; + binary: boolean; + reliable: boolean; + } + + interface util{ + browser: string; + supports: utilSupportsObj; + } + + export interface Peer{ + /** + * + * @param id The brokering ID of the remote peer (their peer.id). + * @param options for specifying details about Peer Connection + */ + connect(id: string, options?: PeerJs.PeerConnectOption): PeerJs.DataConnection; + /** + * Connects to the remote peer specified by id and returns a data connection. + * @param id The brokering ID of the remote peer (their peer.id). + * @param stream The caller's media stream + * @param options Metadata associated with the connection, passed in by whoever initiated the connection. + */ + call(id: string, stream: any, options?: any): PeerJs.MediaConnection; + /** + * Calls the remote peer specified by id and returns a media connection. + * @param event Event name + * @param cb Callback Function + */ + on(event: string, cb: ()=>void): void; + /** + * Emitted when a connection to the PeerServer is established. + * @param event Event name + * @param cb id is the brokering ID of the peer + */ + on(event: 'open', cb: (id: string)=>void): void; + /** + * Emitted when a new data connection is established from a remote peer. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'connection', cb: (dataConnection: PeerJs.DataConnection)=>void): void; + /** + * Emitted when a remote peer attempts to call you. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'call', cb: (mediaConnection: PeerJs.MediaConnection)=>void): void; + /** + * Emitted when the peer is destroyed and can no longer accept or create any new connections. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'close', cb: ()=>void): void; + /** + * Emitted when the peer is disconnected from the signalling server + * @param event Event name + * @param cb Callback Function + */ + on(event: 'disconnected', cb: ()=>void): void; + /** + * Errors on the peer are almost always fatal and will destroy the peer. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'error', cb: (err: any)=>void): void; + /** + * Remove event listeners.(EventEmitter3) + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Boolean} once Only remove once listeners. + */ + off(event: string, fn: Function, once?: boolean): void; + /** + * Close the connection to the server, leaving all existing data and media connections intact. + */ + disconnect(): void; + /** + * Attempt to reconnect to the server with the peer's old ID + */ + reconnect(): void; + /** + * Close the connection to the server and terminate all existing connections. + */ + destroy(): void; + + /** + * Retrieve a data/media connection for this peer. + * @param peer + * @param id + */ + getConnection(peer: Peer, id: string): any; + + /** + * Get a list of available peer IDs + * @param callback + */ + listAllPeers(callback: (peerIds: Array)=>void): void; + /** + * The brokering ID of this peer + */ + id: string; + /** + * A hash of all connections associated with this peer, keyed by the remote peer's ID. + */ + connections: any; + /** + * false if there is an active connection to the PeerServer. + */ + disconnected: boolean; + /** + * true if this peer and all of its connections can no longer be used. + */ + destroyed: boolean; + } +} + +declare var Peer: { + prototype: RTCIceServer; + /** + * A peer can connect to other peers and listen for connections. + * @param id Other peers can connect to this peer using the provided ID. + * If no ID is given, one will be generated by the brokering server. + * @param options for specifying details about PeerServer + */ + new (id: string, options?: PeerJs.PeerJSOption): PeerJs.Peer; + + /** + * A peer can connect to other peers and listen for connections. + * @param options for specifying details about PeerServer + */ + new (options: PeerJs.PeerJSOption): PeerJs.Peer; +}; diff --git a/types/peerjs/ts3.2/peerjs-tests.ts b/types/peerjs/ts3.2/peerjs-tests.ts new file mode 100644 index 0000000000..eef24bf001 --- /dev/null +++ b/types/peerjs/ts3.2/peerjs-tests.ts @@ -0,0 +1,54 @@ +var peerByOption: PeerJs.Peer = new Peer({ + key: 'peerKey', + debug: 3, +}); + +peerByOption.on("connection", dataConnection => { + var type: string = dataConnection.type; +}); + +peerByOption.listAllPeers(function(items){ + for(var i in items){ + console.log(decodeURI(items[i])); + } +}); + +var peerById: PeerJs.Peer = new Peer("peerid"); + +var peerByIdAndOption: PeerJs.Peer = new Peer( + "peerId", + { + key: 'peerKey', + debug: 3, + }); +peerByIdAndOption.on("call", mediaConnection => { + var isOpen: boolean = mediaConnection.open; +}); + +var id = peerByOption.id; +var connections = peerByOption.connections; +var flag = peerByOption.disconnected; +flag = peerByOption.destroyed; + +peerByOption.disconnect(); +peerByOption.reconnect(); +peerByOption.destroy(); + +var connection = peerById.connect("id", { + label: 'chat', + serialization: 'none', + metadata: {message: 'hi i want to chat with you!'} +}); + +var call = peerById.call('callto-id', (window as any).localStream); + +var openHandler=()=> console.log("open"); +peerById.on("open", openHandler); +peerById.on("connection", (c)=> console.log("connection")); +peerById.on("call", (media)=> console.log("call")); +peerById.on("close", ()=> console.log("close")); +peerById.on("disconnected", ()=> console.log("disconnected")); +peerById.on("error", (err)=> console.log(err)); +peerById.off("open", openHandler); + +var connection2 = peerById.getConnection(peerByOption, "callto-id"); diff --git a/types/peerjs/ts3.2/tsconfig.json b/types/peerjs/ts3.2/tsconfig.json new file mode 100644 index 0000000000..eaa819fc0c --- /dev/null +++ b/types/peerjs/ts3.2/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "peerjs-tests.ts" + ] +} diff --git a/types/peerjs/ts3.2/tslint.json b/types/peerjs/ts3.2/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/peerjs/ts3.2/tslint.json @@ -0,0 +1,79 @@ +{ + "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 + } +} 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/pid-from-port/index.d.ts b/types/pid-from-port/index.d.ts new file mode 100644 index 0000000000..e2cbf97a47 --- /dev/null +++ b/types/pid-from-port/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for pid-from-port 1.1 +// Project: https://github.com/kevva/pid-from-port#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = pidFromPort; + +/** + * Get PID from a port + * @param port Port to lookup. + */ +declare function pidFromPort(port: number): Promise; + +declare namespace pidFromPort { + /** + * Get PIDs for a list of ports. + * @param ports Ports to lookup. + * @returns A `Promise` with the port as key and the PID as value. + */ + function all(ports: number[]): Promise>; + /** + * Get all PIDs from ports. + * @returns A `Promise` with the port as key and the PID as value. + */ + function list(): Promise>; +} diff --git a/types/pid-from-port/pid-from-port-tests.ts b/types/pid-from-port/pid-from-port-tests.ts new file mode 100644 index 0000000000..e3c6e7edca --- /dev/null +++ b/types/pid-from-port/pid-from-port-tests.ts @@ -0,0 +1,10 @@ +import pidFromPort = require('pid-from-port'); + +// $ExpectType Promise +pidFromPort(8080); + +// $ExpectType Promise> +pidFromPort.all([8080, 22]); + +// $ExpectType Promise> +pidFromPort.list(); diff --git a/types/pid-from-port/tsconfig.json b/types/pid-from-port/tsconfig.json new file mode 100644 index 0000000000..a1e39e81b9 --- /dev/null +++ b/types/pid-from-port/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", + "pid-from-port-tests.ts" + ] +} diff --git a/types/pid-from-port/tslint.json b/types/pid-from-port/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pid-from-port/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/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/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/preval.macro/index.d.ts b/types/preval.macro/index.d.ts new file mode 100644 index 0000000000..4ecfa3bf25 --- /dev/null +++ b/types/preval.macro/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for preval.macro 3.0 +// Project: https://github.com/kentcdodds/preval.macro +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function preval(strings: TemplateStringsArray, ...values: any[]): any; +export = preval; diff --git a/types/preval.macro/preval.macro-tests.ts b/types/preval.macro/preval.macro-tests.ts new file mode 100644 index 0000000000..fc2f0aa409 --- /dev/null +++ b/types/preval.macro/preval.macro-tests.ts @@ -0,0 +1,5 @@ +import preval = require('preval.macro'); + +const eg1: string = preval`module.exports = 'hello world`; +const eg2: number = preval`module.exports = 42`; +const eg3: { [key: string]: string } = preval`module.exports = { hello: 'world' }`; diff --git a/types/preval.macro/tsconfig.json b/types/preval.macro/tsconfig.json new file mode 100644 index 0000000000..b895c306f0 --- /dev/null +++ b/types/preval.macro/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", + "preval.macro-tests.ts" + ] +} diff --git a/types/preval.macro/tslint.json b/types/preval.macro/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/preval.macro/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..c1e199ec6c 100644 --- a/types/progress/index.d.ts +++ b/types/progress/index.d.ts @@ -1,67 +1,13 @@ -// Type definitions for node-progress v2.0.0 -// Project: https://github.com/tj/node-progress +// Type definitions for node-progress 2.0 +// Project: https://github.com/visionmedia/node-progress // Definitions by: Sebastian Lenz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +export as namespace ProgressBar; - -/** - * 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 { - /** - * Total number of ticks to complete. - */ - total: number; - - /** - * current completed index - */ - curr?: number; - - /** - * head character defaulting to complete character - */ - head?: string; - - /** - * The displayed width of the progress bar defaulting to total. - */ - width?: number; - - /** - * minimum time between updates in milliseconds defaulting to 16 - */ - renderThrottle?: number; - - /** - * The output stream defaulting to stderr. - */ - stream?: NodeJS.WritableStream; - - /** - * Completion character defaulting to "=". - */ - complete?: string; - - /** - * Incomplete character defaulting to "-". - */ - incomplete?: string; - - /** - * Option to clear the bar on completion defaulting to false. - */ - clear?: boolean; - - /** - * Optional function to call when the progress bar completes. - */ - callback?: Function; -} - +export = ProgressBar; /** * Flexible ascii progress bar. @@ -90,7 +36,7 @@ declare class ProgressBar { * - `:eta` eta in seconds */ constructor(format: string, total: number); - constructor(format: string, options: ProgressBarOptions); + constructor(format: string, options: ProgressBar.ProgressBarOptions); /** @@ -120,7 +66,7 @@ declare class ProgressBar { * overall completion to. */ update(ratio: number, tokens?: any): void; - + /** * "interrupt" the progress bar and write a message above it. */ @@ -128,14 +74,78 @@ declare class ProgressBar { /** * Terminates a progress bar. - */ + */ terminate(): void; /** * Completed status of progress (Boolean) */ complete: boolean; -} -declare namespace ProgressBar { } -export = ProgressBar; + /** + * Current tick number. + */ + curr: number; + + /** + * Total number of ticks to complete. + */ + total: number; +} + +declare namespace ProgressBar { + /** + * 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 { + /** + * Total number of ticks to complete. + */ + total: number; + + /** + * current completed index + */ + curr?: number; + + /** + * head character defaulting to complete character + */ + head?: string; + + /** + * The displayed width of the progress bar defaulting to total. + */ + width?: number; + + /** + * minimum time between updates in milliseconds defaulting to 16 + */ + renderThrottle?: number; + + /** + * The output stream defaulting to stderr. + */ + stream?: NodeJS.WritableStream; + + /** + * Completion character defaulting to "=". + */ + complete?: string; + + /** + * Incomplete character defaulting to "-". + */ + incomplete?: string; + + /** + * Option to clear the bar on completion defaulting to false. + */ + clear?: boolean; + + /** + * Optional function to call when the progress bar completes. + */ + callback?: Function; + } +} diff --git a/types/progress/progress-tests.ts b/types/progress/progress-tests.ts index 561f226b64..d93eb9bc3f 100644 --- a/types/progress/progress-tests.ts +++ b/types/progress/progress-tests.ts @@ -1,42 +1,48 @@ -var ProgressBar = require('progress'); +import * as ProgressBar from 'progress'; /** - * Usage example from https://github.com/tj/node-progress + * Usage example from https://github.com/visionmedia/node-progress + * (in Typescript) */ -var bar = new ProgressBar(':bar', { total: 10 }); -var timer = setInterval(function () { - bar.tick(); - if (bar.complete) { +const usageBar = new ProgressBar(':bar', { total: 10 }); +const timer = setInterval(function () { + usageBar.tick(); + if (usageBar.complete) { console.log('\ncomplete\n'); clearInterval(timer); } }, 100); - /** - * Custom token example from https://github.com/tj/node-progress + * Custom token example from https://github.com/visionmedia/node-progress + * (in Typescript) */ -var bar = new ProgressBar(':current: :token1 :token2', { total: 3 }); - -bar.tick({ - 'token1': "Hello", - 'token2': "World!\n" -}); - -bar.tick(2, { - 'token1': "Goodbye", - 'token2': "World!" -}); + const list = [ + 'image01.jpg', 'image02.jpg', 'image03.jpg', 'image04.jpg', 'image05.jpg', + 'image06.jpg', 'image07.jpg', 'image08.jpg', 'image09.jpg', 'image10.jpg' + ]; + const customTokenBar = new ProgressBar(':percent eta: :eta downloading :current/:total :file', { + total: list.length + }); + const customInterval = setInterval(function (){ + customTokenBar.tick({ + 'file': list[customTokenBar.curr] + }) + if (customTokenBar.complete) { + clearInterval(customInterval) + } + }, 500) /** * Interrupt example from https://github.com/visionmedia/node-progress + * (in Typescript) */ -var bar = new ProgressBar(':bar :current/:total', { total: 10 }); -var timer = setInterval(function () { - bar.tick(); - if (bar.complete) { - clearInterval(timer); - } else if (bar.curr === 5) { - bar.interrupt('this message appears above the progress bar\ncurrent progress is ' + bar.curr + '/' + bar.total); +const interruptBar = new ProgressBar(':bar :current/:total', { total: 10 }); +const interruptTimer = setInterval(function () { + interruptBar.tick(); + if (interruptBar.complete) { + clearInterval(interruptTimer); + } else if (interruptBar.curr === 5 || interruptBar.curr === 8) { + interruptBar.interrupt('interrupt: current progress is ' + interruptBar.curr + '/' + interruptBar.total); } -}, 1000); \ No newline at end of file +}, 1000); 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/prompts/index.d.ts b/types/prompts/index.d.ts index 7aa3f2ea63..7dc3a928a7 100644 --- a/types/prompts/index.d.ts +++ b/types/prompts/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for prompts 1.1 +// Type definitions for prompts 1.2 // Project: https://github.com/terkelg/prompts // Definitions by: Berkay GURSOY // Daniel Perez Alvarez +// Kamontat Chantrachirathumrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -47,18 +48,19 @@ declare namespace prompts { interface Choice { title: string; value: string; + disable?: boolean; } interface Options { - onSubmit: (prompt: PromptObject, answer: any, answers: any[]) => void; - onCancel: (prompt: PromptObject, answers: any) => void; + onSubmit?: (prompt: PromptObject, answer: any, answers: any[]) => void; + onCancel?: (prompt: PromptObject, answers: any) => void; } interface PromptObject { - type: ValueOrFunc; + type: ValueOrFunc | Falsy; name: ValueOrFunc; message?: ValueOrFunc; - initial?: string; + initial?: string | number | boolean; style?: string; format?: PrevCaller; validate?: PrevCaller; @@ -85,5 +87,9 @@ declare namespace prompts { prompt: PromptObject ) => R; + type Falsy = false | null | undefined; + + type PromptType = "text" | "password" | "invisible" | "number" | "confirm" | "list" | "toggle" | "select" | "multiselect" | "autocomplete"; + type ValueOrFunc = T | PrevCaller; } 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/ps-list/index.d.ts b/types/ps-list/index.d.ts new file mode 100644 index 0000000000..2ace498667 --- /dev/null +++ b/types/ps-list/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for ps-list 6.0 +// Project: https://github.com/sindresorhus/ps-list#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = psList; + +declare function psList(options?: psList.Options): Promise; + +declare namespace psList { + interface Options { + all?: boolean; + } + + interface ProcessDescriptor { + pid: number; + name: string; + ppid: number; + cmd?: string; + cpu?: number; + memory?: number; + } +} diff --git a/types/ps-list/ps-list-tests.ts b/types/ps-list/ps-list-tests.ts new file mode 100644 index 0000000000..17ecffe4ff --- /dev/null +++ b/types/ps-list/ps-list-tests.ts @@ -0,0 +1,13 @@ +import psList = require('ps-list'); + +(async () => { + const processes: psList.ProcessDescriptor[] = await psList(); + psList({ all: false }); + + processes[0].pid; // $ExpectType number + processes[0].name; // $ExpectType string + processes[0].ppid; // $ExpectType number + processes[0].cmd; // $ExpectType string | undefined + processes[0].cpu; // $ExpectType number | undefined + processes[0].memory; // $ExpectType number | undefined +})(); diff --git a/types/ps-list/tsconfig.json b/types/ps-list/tsconfig.json new file mode 100644 index 0000000000..4138547b6c --- /dev/null +++ b/types/ps-list/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", + "ps-list-tests.ts" + ] +} diff --git a/types/ps-list/tslint.json b/types/ps-list/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ps-list/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/public-ip/index.d.ts b/types/public-ip/index.d.ts index 463a1a2d18..58fb81aa93 100644 --- a/types/public-ip/index.d.ts +++ b/types/public-ip/index.d.ts @@ -1,12 +1,16 @@ -// Type definitions for public-ip 2.3 +// Type definitions for public-ip 2.4 // Project: https://github.com/sindresorhus/public-ip#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export function v4(options?: Options): Promise; -export function v6(options?: Options): Promise; +export function v4(options?: Options): CancelablePromise; +export function v6(options?: Options): CancelablePromise; export interface Options { https?: boolean; timeout?: number; } + +export type CancelablePromise = Promise & { + cancel(): void; +}; diff --git a/types/public-ip/public-ip-tests.ts b/types/public-ip/public-ip-tests.ts index e7e0540bbe..6e5983bc99 100644 --- a/types/public-ip/public-ip-tests.ts +++ b/types/public-ip/public-ip-tests.ts @@ -1,16 +1,17 @@ import * as publicIp from 'public-ip'; -let str: string; publicIp.v4().then(ip => { - str = ip; + ip; // $ExpectType string }); -publicIp.v4({https: false, timeout: 10}).then(ip => { - str = ip; +publicIp.v4({ https: false, timeout: 10 }).then(ip => { + ip; // $ExpectType string }); +publicIp.v4().cancel(); publicIp.v6().then(ip => { - str = ip; + ip; // $ExpectType string }); -publicIp.v6({https: false, timeout: 10}).then(ip => { - str = ip; +publicIp.v6({ https: false, timeout: 10 }).then(ip => { + ip; // $ExpectType string }); +publicIp.v6().cancel(); 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 cbb31f2fd0..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. @@ -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/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..026da15ec9 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. @@ -1122,6 +1123,7 @@ declare namespace R { * of the condition predicate. */ ifElse(fn: Pred, onTrue: Arity1Fn, onFalse: Arity1Fn): Arity1Fn; + ifElse(fn: Pred, onTrue: Arity2Fn, onFalse: Arity2Fn): Arity2Fn; /** * Increments its argument. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 2f68808d17..2e292ffd59 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, ""); }; () => { @@ -2650,6 +2657,17 @@ class Rectangle { flattenArrays([[[10], 123], [8, [10]], "hello"]); // => [[10, 123], [8, 10], "hello"] }; +() => { + const incCount = R.ifElse( + R.has('count'), + R.over(R.lensProp('count'), R.inc), + R.assoc('count', 1) + ); + incCount({}); // => { count: 1 } + incCount({ count: 1 }); // => { count: 2 } + R.ifElse(R.identical, R.add as (a: number, b: number) => number, R.always(""))(2, 2); // https://goo.gl/CVUSs9 +}; + () => { R.isEmpty([1, 2, 3]); // => false R.isEmpty([]); // => true 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/randoma/index.d.ts b/types/randoma/index.d.ts new file mode 100644 index 0000000000..f0b79a0656 --- /dev/null +++ b/types/randoma/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for randoma 1.2 +// Project: https://github.com/sindresorhus/randoma#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import Color = require('color'); + +export = Randoma; + +declare class Randoma { + static seed(): number; + + constructor(options: Randoma.Options); + + integer(): number; + integerInRange(min: number, max: number): number; + float(): number; + floatInRange(min: number, max: number): number; + boolean(): boolean; + arrayItem(array: T[]): T; + date(): Date; + dateInRange(startDate: Date, endDate: Date): Date; + color(saturation?: number): Color; +} + +declare namespace Randoma { + interface Options { + seed: string | number; + } +} diff --git a/types/randoma/randoma-tests.ts b/types/randoma/randoma-tests.ts new file mode 100644 index 0000000000..d03544c959 --- /dev/null +++ b/types/randoma/randoma-tests.ts @@ -0,0 +1,27 @@ +import Randoma = require('randoma'); + +const random = new Randoma({ seed: 10 }); +new Randoma({ seed: '🦄' }); +new Randoma({ seed: Randoma.seed() }); + +// $ExpectType number +random.integer(); +// $ExpectType number +random.integerInRange(0, 1); +// $ExpectType number +random.float(); +// $ExpectType number +random.floatInRange(0, 1); +// $ExpectType boolean +random.boolean(); +// $ExpectType string +random.arrayItem(['🦄']); +// $ExpectType Date +random.date(); +// $ExpectType Date +random.dateInRange(new Date(), new Date()); + +random + .color(0.5) + .hex() + .toString(); diff --git a/types/randoma/tsconfig.json b/types/randoma/tsconfig.json new file mode 100644 index 0000000000..21813b327f --- /dev/null +++ b/types/randoma/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", + "randoma-tests.ts" + ] +} diff --git a/types/randoma/tslint.json b/types/randoma/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/randoma/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/index.d.ts b/types/rc/index.d.ts index 9a2c6783f6..3ab9cc3a26 100644 --- a/types/rc/index.d.ts +++ b/types/rc/index.d.ts @@ -6,8 +6,17 @@ declare function rc( name: string, defaults?: any, + /** + * Parsed argv object. For example, if args is `--foo bar`, then this value should be `{foo: 'bar'}` + * If `argv` is `null` or `undefined`, then `rc`'s default parser will parse `process.argv`. + */ argv?: {} | null, + /** + * Custom config file parser. + * This function will be passed the string contents of each + * discovered configuration file should return a parsed object dictionary. + */ parse?: ((content: string) => any) | null ): any; -export = rc; \ No newline at end of file +export = rc; 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 790a5887cb..89e6f0eead 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -216,19 +216,19 @@ 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?: Views; @@ -243,7 +243,7 @@ export interface BigCalendarProps extends React.Props; + eventPropGetter?: EventPropGetter; slotPropGetter?: SlotPropGetter; dayPropGetter?: DayPropGetter; showMultiDayTimes?: boolean; @@ -254,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; @@ -278,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 321327e8e7..fd1e70f929 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -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,66 +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 - }, - toolbar: Toolbar, - eventWrapper: EventWrapper, - }} - 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} /> ); } } @@ -132,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; 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 4af6cae9b2..5f07b253f3 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.8 +// Type definitions for react-datepicker 2.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , // Andrey Balokha , @@ -8,72 +8,96 @@ // 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 function registerLocale(localeName: string, localeData: {}): void; +export function setDefaultLocale(localeName: string): void; +export function getDefaultLocale(): string; + export interface ReactDatePickerProps { adjustDateOnChange?: boolean; allowSameDay?: boolean; autoComplete?: string; autoFocus?: boolean; calendarClassName?: string; + calendarContainer?(props: { children: React.ReactNode[] }): React.ReactNode; children?: React.ReactNode; className?: string; + clearButtonTitle?: 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[]; + formatWeekDay?(date: Date): string; + 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; + nextMonthButtonLabel?: 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; + onInputClick?(): void; + onInputError?(err: {code: number; msg: string}): 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; + onYearChange?(date: Date): 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; + previousMonthButtonLabel?: string; readOnly?: boolean; + 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; required?: boolean; scrollableMonthYearDropdown?: boolean; scrollableYearDropdown?: boolean; - selected?: moment.Moment | null; + selected?: Date | null; selectsEnd?: boolean; selectsStart?: boolean; shouldCloseOnSelect?: boolean; @@ -84,17 +108,16 @@ 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; 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..b47c08ed73 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -1,18 +1,121 @@ import * as React from 'react'; -import * as moment from 'moment'; -import DatePicker from 'react-datepicker'; +import DatePicker, { + registerLocale, + setDefaultLocale, + getDefaultLocale, +} from 'react-datepicker'; + +registerLocale('en-GB', { options: { weekStartsOn: 1 } }); +setDefaultLocale('en-GB'); +const defaultLocale = getDefaultLocale(); {}} - onYearChange={(date: moment.Moment) => {}} + adjustDateOnChange + allowSameDay + autoComplete="" + autoFocus + calendarClassName="" + calendarContainer={props =>
} + className="" + clearButtonTitle="" + customInput={} + customInputRef="" + dateFormat="" + dateFormatCalendar="" + dayClassName={date => ''} + disabled + disabledKeyboardNavigation + dropdownMode="scroll" + endDate={new Date()} + excludeDates={[new Date()]} + excludeTimes={[new Date()]} + filterDate={date => true} + fixedHeight + forceShowMonthNavigation + formatWeekDay={date => ''} + formatWeekNumber={date => 0} + highlightDates={[new Date()]} + id="" + includeDates={[new Date()]} + includeTimes={[new Date()]} + injectTimes={[new Date()]} + inline + isClearable + locale="" + maxDate={new Date()} + maxTime={new Date()} + minDate={new Date()} + minTime={new Date()} + monthsShown={1} + name="" + nextMonthButtonLabel="" + onBlur={event => null} + onChange={(date: Date | null) => {}} + onChangeRaw={event => null} + onClickOutside={event => null} + onFocus={event => null} + onInputClick={() => null} + onInputError={err => err.code + err.msg} + onKeyDown={event => null} + onMonthChange={date => null} + onSelect={(date, event) => null} + onWeekSelect={(firstDayOfWeek, weekNumber, event) => null} + onYearChange={(date: Date) => {}} + open + openToDate={new Date()} + peekNextMonth + placeholderText="" + popperClassName="" + popperContainer={props =>
} popperModifiers={{ flip: { - enabled: false - } + enabled: false, + }, }} - includeTimes={[moment()]} + popperPlacement="" + popperProps={{}} + preventOpenOnFocus + previousMonthButtonLabel="" + readOnly + renderCustomHeader={({ + date, + changeYear, + changeMonth, + decreaseMonth, + increaseMonth, + prevMonthButtonDisabled, + nextMonthButtonDisabled, + }) =>
} + renderDayContents={dayOfMonth =>
} + required + scrollableMonthYearDropdown + scrollableYearDropdown + selected={new Date()} + selectsEnd + selectsStart + shouldCloseOnSelect + showDisabledMonthNavigation + showMonthDropdown + showMonthYearDropdown + showTimeSelect + showTimeSelectOnly + showWeekNumbers + showYearDropdown + startDate={new Date()} + startOpen + tabIndex={1} + timeCaption="" + timeFormat="" + timeIntervals={1} + title="" + todayButton={
} + useShortMonthInDropdown + useWeekdaysShort + value="" + weekLabel="" + withPortal + yearDropdownItemNumber={1} > -
- +
+ ; diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index 05058b2ca9..17ea9788f6 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -1,12 +1,11 @@ // Type definitions for react-dates v17.1.0 // Project: https://github.com/airbnb/react-dates -// Definitions by: Artur Ampilogov +// Definitions by: Artur Ampilogov // Nathan Holland // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 - // Required fields are made according to 'minimum REQUIRED setup' in https://github.com/airbnb/react-dates/blob/master/README.md - + import * as React from 'react'; import * as moment from 'moment'; @@ -18,9 +17,8 @@ declare namespace momentPropTypes { type momentDurationObj = any; } - declare namespace ReactDates { - // SHAPES + // SHAPES // // shapes/AnchorDirectionShape.js type AnchorDirectionShape = 'left' | 'right'; @@ -28,95 +26,100 @@ declare namespace ReactDates { // shapes/CalendarInfoPositionShape.js type CalendarInfoPositionShape = 'top' | 'bottom' | 'before' | 'after'; - // shapes/DateRangePickerShape.js interface DateRangePickerShape { // required props for a functional interactive DateRangePicker - startDate: momentPropTypes.momentObj | null, - startDateId: string, - endDate: momentPropTypes.momentObj | null, - endDateId: string, - focusedInput: FocusedInputShape | null, + startDate: momentPropTypes.momentObj | null; + startDateId: string; + endDate: momentPropTypes.momentObj | null; + endDateId: string; + focusedInput: FocusedInputShape | null; - onDatesChange: (arg: { - startDate: momentPropTypes.momentObj | null, - endDate: momentPropTypes.momentObj | null - }) => void, - onFocusChange: (arg: FocusedInputShape | null) => void, - - onClose?: (final: { startDate: momentPropTypes.momentObj, endDate: momentPropTypes.momentObj }) => void, + onDatesChange: ( + arg: { + startDate: momentPropTypes.momentObj | null; + endDate: momentPropTypes.momentObj | null; + } + ) => void; + onFocusChange: (arg: FocusedInputShape | null) => void; + + onClose?: ( + final: { + startDate: momentPropTypes.momentObj; + endDate: momentPropTypes.momentObj; + } + ) => void; // input related props - startDatePlaceholderText?: string, - endDatePlaceholderText?: string, - disabled?: DisabledShape, - required?: boolean, - readOnly?: boolean, - screenReaderInputMessage?: string, - showClearDates?: boolean, - showDefaultInputIcon?: boolean, - customInputIcon?: string | JSX.Element, - customArrowIcon?: string | JSX.Element, - customCloseIcon?: string | JSX.Element, - noBorder?: boolean, - block?: boolean, - small?: boolean, - regular?: boolean, - keepFocusOnInput?: boolean, - + startDatePlaceholderText?: string; + endDatePlaceholderText?: string; + disabled?: DisabledShape; + required?: boolean; + readOnly?: boolean; + screenReaderInputMessage?: string; + showClearDates?: boolean; + showDefaultInputIcon?: boolean; + inputIconPosition?: IconPositionShape; + customInputIcon?: string | JSX.Element; + customArrowIcon?: string | JSX.Element; + customCloseIcon?: string | JSX.Element; + noBorder?: boolean; + block?: boolean; + small?: boolean; + regular?: boolean; + keepFocusOnInput?: boolean; // calendar presentation and interaction related props - renderMonthText?: (day: momentPropTypes.momentObj) => (string | JSX.Element), + renderMonthText?: (day: momentPropTypes.momentObj) => string | JSX.Element; renderMonthElement?: ( props: { - month: momentPropTypes.momentObj; - onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; - onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; + month: momentPropTypes.momentObj; + onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; + onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; } - ) => string | JSX.Element, - orientation?: OrientationShape, - anchorDirection?: AnchorDirectionShape, - openDirection?: OpenDirectionShape, - horizontalMargin?: number, - withPortal?: boolean, - withFullScreenPortal?: boolean, - appendToBody?: boolean, - disableScroll?: boolean, - daySize?: number, - isRTL?: boolean, - firstDayOfWeek?: DayOfWeekShape, - initialVisibleMonth?: () => momentPropTypes.momentObj, - numberOfMonths?: number, - keepOpenOnDateSelect?: boolean, - reopenPickerOnClearDates?: boolean, - renderCalendarInfo?: () => (string | JSX.Element), - calendarInfoPosition?: CalendarInfoPositionShape, - hideKeyboardShortcutsPanel?: boolean, - verticalHeight?: number, - transitionDuration?: number, - verticalSpacing?: number, + ) => string | JSX.Element; + orientation?: OrientationShape; + anchorDirection?: AnchorDirectionShape; + openDirection?: OpenDirectionShape; + horizontalMargin?: number; + withPortal?: boolean; + withFullScreenPortal?: boolean; + appendToBody?: boolean; + disableScroll?: boolean; + daySize?: number; + isRTL?: boolean; + firstDayOfWeek?: DayOfWeekShape; + initialVisibleMonth?: () => momentPropTypes.momentObj; + numberOfMonths?: number; + keepOpenOnDateSelect?: boolean; + reopenPickerOnClearDates?: boolean; + renderCalendarInfo?: () => string | JSX.Element; + calendarInfoPosition?: CalendarInfoPositionShape; + hideKeyboardShortcutsPanel?: boolean; + verticalHeight?: number; + transitionDuration?: number; + verticalSpacing?: number; // navigation related props - navPrev?: string | JSX.Element, - navNext?: string | JSX.Element, - onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, + navPrev?: string | JSX.Element; + navNext?: string | JSX.Element; + onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; // day presentation and interaction related props - renderCalendarDay?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - renderDayContents?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - minimumNights?: number, - enableOutsideDays?: boolean, - isDayBlocked?: (day: any) => boolean, - isOutsideRange?: (day: any) => boolean, - isDayHighlighted?: (day: any) => boolean, - + renderCalendarDay?: (day: momentPropTypes.momentObj) => string | JSX.Element; + renderDayContents?: (day: momentPropTypes.momentObj) => string | JSX.Element; + minimumNights?: number; + enableOutsideDays?: boolean; + isDayBlocked?: (day: any) => boolean; + isOutsideRange?: (day: any) => boolean; + isDayHighlighted?: (day: any) => boolean; // internationalization props - displayFormat?: (string | (() => string)), - monthFormat?: string, - weekDayFormat?: string, - phrases?: DateRangePickerPhrases, - dayAriaLabelFormat?: string + displayFormat?: string | (() => string); + monthFormat?: string; + weekDayFormat?: string; + phrases?: DateRangePickerPhrases; + dayAriaLabelFormat?: string; } // shapes/DayOfWeekShape.js @@ -140,260 +143,270 @@ declare namespace ReactDates { // shape/ScrollableOrientationShape.js type ScrollableOrientationShape = 'horizontal' | 'vertical' | 'verticalScrollable'; - // shapes/SingleDatePickerShape.js interface SingleDatePickerShape { - id: string, + id: string; // required props for a functional interactive SingleDatePicker - date: momentPropTypes.momentObj | null, - focused: boolean, - - onDateChange: (date: momentPropTypes.momentObj | null) => void, - onFocusChange: (arg: { focused: boolean | null }) => void, - + date: momentPropTypes.momentObj | null; + focused: boolean; + + onDateChange: (date: momentPropTypes.momentObj | null) => void; + onFocusChange: (arg: { focused: boolean | null }) => void; + // input related props - placeholder?: string, - disabled?: boolean, - required?: boolean, - readOnly?: boolean, - screenReaderInputMessage?: string, - showClearDate?: boolean, - customCloseIcon?: string | JSX.Element, - showDefaultInputIcon?: boolean, - inputIconPosition?: IconPositionShape, - customInputIcon?: string | JSX.Element, - noBorder?: boolean, - block?: boolean, - small?: boolean, - regular?: boolean, - verticalSpacing?: number, - keepFocusOnInput?: boolean, + placeholder?: string; + disabled?: boolean; + required?: boolean; + readOnly?: boolean; + screenReaderInputMessage?: string; + showClearDate?: boolean; + customCloseIcon?: string | JSX.Element; + showDefaultInputIcon?: boolean; + inputIconPosition?: IconPositionShape; + customInputIcon?: string | JSX.Element; + noBorder?: boolean; + block?: boolean; + small?: boolean; + regular?: boolean; + verticalSpacing?: number; + keepFocusOnInput?: boolean; // calendar presentation and interaction related props - renderMonthText?: (day: momentPropTypes.momentObj) => (string | JSX.Element), + renderMonthText?: (day: momentPropTypes.momentObj) => string | JSX.Element; renderMonthElement?: ( props: { - month: momentPropTypes.momentObj; - onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; - onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; + month: momentPropTypes.momentObj; + onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; + onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; } - ) => string | JSX.Element, - orientation?: OrientationShape, - anchorDirection?: AnchorDirectionShape, - openDirection?: OpenDirectionShape, - horizontalMargin?: number, - withPortal?: boolean, - withFullScreenPortal?: boolean, - appendToBody?: boolean, - disableScroll?: boolean, - initialVisibleMonth?: () => momentPropTypes.momentObj, - firstDayOfWeek?: DayOfWeekShape, - numberOfMonths?: number, - keepOpenOnDateSelect?: boolean, - reopenPickerOnClearDates?: boolean, - renderCalendarInfo?: () => (string | JSX.Element), - calendarInfoPosition?: CalendarInfoPositionShape, - hideKeyboardShortcutsPanel?: boolean, - daySize?: number, - isRTL?: boolean, - verticalHeight?: number | null, - transitionDuration?: number, + ) => string | JSX.Element; + orientation?: OrientationShape; + anchorDirection?: AnchorDirectionShape; + openDirection?: OpenDirectionShape; + horizontalMargin?: number; + withPortal?: boolean; + withFullScreenPortal?: boolean; + appendToBody?: boolean; + disableScroll?: boolean; + initialVisibleMonth?: () => momentPropTypes.momentObj; + firstDayOfWeek?: DayOfWeekShape; + numberOfMonths?: number; + keepOpenOnDateSelect?: boolean; + reopenPickerOnClearDates?: boolean; + renderCalendarInfo?: () => string | JSX.Element; + calendarInfoPosition?: CalendarInfoPositionShape; + hideKeyboardShortcutsPanel?: boolean; + daySize?: number; + isRTL?: boolean; + verticalHeight?: number | null; + transitionDuration?: number; // navigation related props - navPrev?: string | JSX.Element, - navNext?: string | JSX.Element, - onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onClose?: (final: { startDate: momentPropTypes.momentObj, endDate: momentPropTypes.momentObj }) => void, + navPrev?: string | JSX.Element; + navNext?: string | JSX.Element; + onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onClose?: ( + final: { + startDate: momentPropTypes.momentObj; + endDate: momentPropTypes.momentObj; + } + ) => void; // day presentation and interaction related props - renderCalendarDay?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - renderDayContents?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - enableOutsideDays?: boolean, - isDayBlocked?: (day: any) => boolean, - isOutsideRange?: (day: any) => boolean, - isDayHighlighted?: (day: any) => boolean, + renderCalendarDay?: (day: momentPropTypes.momentObj) => string | JSX.Element; + renderDayContents?: (day: momentPropTypes.momentObj) => string | JSX.Element; + enableOutsideDays?: boolean; + isDayBlocked?: (day: any) => boolean; + isOutsideRange?: (day: any) => boolean; + isDayHighlighted?: (day: any) => boolean; // internationalization props - displayFormat?: (string | (() => string)), - monthFormat?: string, - weekDayFormat?: string, - phrases?: SingleDatePickerPhrases, - dayAriaLabelFormat?: string, + displayFormat?: string | (() => string); + monthFormat?: string; + weekDayFormat?: string; + phrases?: SingleDatePickerPhrases; + dayAriaLabelFormat?: string; } // PHRASES // // defaultPhrases.js type DateRangePickerPhrases = { - calendarLabel?: string, - closeDatePicker?: string, - clearDates?: string, - focusStartDate?: string, - jumpToPrevMonth?: string, - jumpToNextMonth?: string, - keyboardShortcuts?: string, - showKeyboardShortcutsPanel?: string, - hideKeyboardShortcutsPanel?: string, - openThisPanel?: string, - enterKey?: string, - leftArrowRightArrow?: string, - upArrowDownArrow?: string, - pageUpPageDown?: string, - homeEnd?: string, - escape?: string, - questionMark?: string, - selectFocusedDate?: string, - moveFocusByOneDay?: string, - moveFocusByOneWeek?: string, - moveFocusByOneMonth?: string, - moveFocustoStartAndEndOfWeek?: string, - returnFocusToInput?: string, - keyboardNavigationInstructions?: string, - chooseAvailableStartDate?: (date: string) => string, - chooseAvailableEndDate?: (date: string) => string, - dateIsUnavailable?: (date: string) => string, - dateIsSelected?: (date: string) => string + calendarLabel?: string; + closeDatePicker?: string; + clearDates?: string; + focusStartDate?: string; + jumpToPrevMonth?: string; + jumpToNextMonth?: string; + keyboardShortcuts?: string; + showKeyboardShortcutsPanel?: string; + hideKeyboardShortcutsPanel?: string; + openThisPanel?: string; + enterKey?: string; + leftArrowRightArrow?: string; + upArrowDownArrow?: string; + pageUpPageDown?: string; + homeEnd?: string; + escape?: string; + questionMark?: string; + selectFocusedDate?: string; + moveFocusByOneDay?: string; + moveFocusByOneWeek?: string; + moveFocusByOneMonth?: string; + moveFocustoStartAndEndOfWeek?: string; + returnFocusToInput?: string; + keyboardNavigationInstructions?: string; + chooseAvailableStartDate?: (date: string) => string; + chooseAvailableEndDate?: (date: string) => string; + dateIsUnavailable?: (date: string) => string; + dateIsSelected?: (date: string) => string; }; // defaultPhrases.js type DateRangePickerInputPhrases = { - focusStartDate?: string, - clearDates?: string, - keyboardNavigationInstructions?: string, - } + focusStartDate?: string; + clearDates?: string; + keyboardNavigationInstructions?: string; + }; // defaultPhrases.js - type SingleDatePickerPhrases = { - calendarLabel?: string, - closeDatePicker?: string, - clearDate?: string, - jumpToPrevMonth?: string, - jumpToNextMonth?: string, - keyboardShortcuts?: string, - showKeyboardShortcutsPanel?: string, - hideKeyboardShortcutsPanel?: string, - openThisPanel?: string, - enterKey?: string, - leftArrowRightArrow?: string, - upArrowDownArrow?: string, - pageUpPageDown?: string, - homeEnd?: string, - escape?: string, - questionMark?: string, - selectFocusedDate?: string, - moveFocusByOneDay?: string, - moveFocusByOneWeek?: string, - moveFocusByOneMonth?: string, - moveFocustoStartAndEndOfWeek?: string, - returnFocusToInput?: string, - keyboardNavigationInstructions?: string, - chooseAvailableDate?: (date: string) => string, - dateIsUnavailable?: (date: string) => string, - dateIsSelected?: (date: string) => string, + type SingleDatePickerPhrases = { + calendarLabel?: string; + closeDatePicker?: string; + clearDate?: string; + jumpToPrevMonth?: string; + jumpToNextMonth?: string; + keyboardShortcuts?: string; + showKeyboardShortcutsPanel?: string; + hideKeyboardShortcutsPanel?: string; + openThisPanel?: string; + enterKey?: string; + leftArrowRightArrow?: string; + upArrowDownArrow?: string; + pageUpPageDown?: string; + homeEnd?: string; + escape?: string; + questionMark?: string; + selectFocusedDate?: string; + moveFocusByOneDay?: string; + moveFocusByOneWeek?: string; + moveFocusByOneMonth?: string; + moveFocustoStartAndEndOfWeek?: string; + returnFocusToInput?: string; + keyboardNavigationInstructions?: string; + chooseAvailableDate?: (date: string) => string; + dateIsUnavailable?: (date: string) => string; + dateIsSelected?: (date: string) => string; }; // defaultPhrases.js type SingleDatePickerInputPhrases = { - clearDate?: string, - keyboardNavigationInstructions?: string, - } + clearDate?: string; + keyboardNavigationInstructions?: string; + }; // defaultPhrases.js type DayPickerPhrases = { - calendarLabel?: string, - jumpToPrevMonth?: string, - jumpToNextMonth?: string, - keyboardShortcuts?: string, - showKeyboardShortcutsPanel?: string, - hideKeyboardShortcutsPanel?: string, - openThisPanel?: string, - enterKey?: string, - leftArrowRightArrow?: string, - upArrowDownArrow?: string, - pageUpPageDown?: string, - homeEnd?: string, - escape?: string, - questionMark?: string, - selectFocusedDate?: string, - moveFocusByOneDay?: string, - moveFocusByOneWeek?: string, - moveFocusByOneMonth?: string, - moveFocustoStartAndEndOfWeek?: string, - returnFocusToInput?: string, - chooseAvailableStartDate?: (date: string) => string, - chooseAvailableEndDate?: (date: string) => string, - chooseAvailableDate?: (date: string) => string, - dateIsUnavailable?: (date: string) => string, - dateIsSelected?: (date: string) => string, + calendarLabel?: string; + jumpToPrevMonth?: string; + jumpToNextMonth?: string; + keyboardShortcuts?: string; + showKeyboardShortcutsPanel?: string; + hideKeyboardShortcutsPanel?: string; + openThisPanel?: string; + enterKey?: string; + leftArrowRightArrow?: string; + upArrowDownArrow?: string; + pageUpPageDown?: string; + homeEnd?: string; + escape?: string; + questionMark?: string; + selectFocusedDate?: string; + moveFocusByOneDay?: string; + moveFocusByOneWeek?: string; + moveFocusByOneMonth?: string; + moveFocustoStartAndEndOfWeek?: string; + returnFocusToInput?: string; + chooseAvailableStartDate?: (date: string) => string; + chooseAvailableEndDate?: (date: string) => string; + chooseAvailableDate?: (date: string) => string; + dateIsUnavailable?: (date: string) => string; + dateIsSelected?: (date: string) => string; }; // defaultPhrases.js type DayPickerKeyboardShortcutsPhrases = { - keyboardShortcuts?: string, - showKeyboardShortcutsPanel?: string, - hideKeyboardShortcutsPanel?: string, - openThisPanel?: string, - enterKey?: string, - leftArrowRightArrow?: string, - upArrowDownArrow?: string, - pageUpPageDown?: string, - homeEnd?: string, - escape?: string, - questionMark?: string, - selectFocusedDate?: string, - moveFocusByOneDay?: string, - moveFocusByOneWeek?: string, - moveFocusByOneMonth?: string, - moveFocustoStartAndEndOfWeek?: string, - returnFocusToInput?: string, + keyboardShortcuts?: string; + showKeyboardShortcutsPanel?: string; + hideKeyboardShortcutsPanel?: string; + openThisPanel?: string; + enterKey?: string; + leftArrowRightArrow?: string; + upArrowDownArrow?: string; + pageUpPageDown?: string; + homeEnd?: string; + escape?: string; + questionMark?: string; + selectFocusedDate?: string; + moveFocusByOneDay?: string; + moveFocusByOneWeek?: string; + moveFocusByOneMonth?: string; + moveFocustoStartAndEndOfWeek?: string; + returnFocusToInput?: string; }; // defaultPhrases.js type DayPickerNavigationPhrases = { - jumpToPrevMonth?: string, - jumpToNextMonth?: string, + jumpToPrevMonth?: string; + jumpToNextMonth?: string; }; - + // defaultPhrases.js type CalendarDayPhrases = { - chooseAvailableDate: (date: string) => string, - dateIsUnavailable: (date: string) => string, - dateIsSelected: (date: string) => string, + chooseAvailableDate: (date: string) => string; + dateIsUnavailable: (date: string) => string; + dateIsSelected: (date: string) => string; }; // COMPONENTS - // + // // components/DateRangePicker.js type DateRangePicker = React.ClassicComponentClass; var DateRangePicker: React.ClassicComponentClass; // components/DayPickerRangeController.jsx - interface DayPickerRangeControllerShape extends DayPickerShape{ + interface DayPickerRangeControllerShape extends DayPickerShape { // REQUIRED props - startDate: momentPropTypes.momentObj | null, - endDate: momentPropTypes.momentObj | null, - onDatesChange: (arg: { - startDate: momentPropTypes.momentObj | null, - endDate: momentPropTypes.momentObj | null - } - ) => void, - focusedInput: FocusedInputShape, - onFocusChange: (arg: FocusedInputShape | null) => void, + startDate: momentPropTypes.momentObj | null; + endDate: momentPropTypes.momentObj | null; + onDatesChange: ( + arg: { + startDate: momentPropTypes.momentObj | null; + endDate: momentPropTypes.momentObj | null; + } + ) => void; + focusedInput: FocusedInputShape; + onFocusChange: (arg: FocusedInputShape | null) => void; - startDateOffset?: (day: any) => any, - endDateOffset?: (day: any) => any, + startDateOffset?: (day: any) => any; + endDateOffset?: (day: any) => any; - onClose?: (final: { startDate: momentPropTypes.momentObj, endDate: momentPropTypes.momentObj }) => void, + onClose?: ( + final: { + startDate: momentPropTypes.momentObj; + endDate: momentPropTypes.momentObj; + } + ) => void; - keepOpenOnDateSelect?: boolean, - minimumNights?: number, - disabled?: DisabledShape, - isOutsideRange?: (day: any) => boolean, - isDayBlocked?: (day: any) => boolean, - isDayHighlighted?: (day: any) => boolean, + keepOpenOnDateSelect?: boolean; + minimumNights?: number; + disabled?: DisabledShape; + isOutsideRange?: (day: any) => boolean; + isDayBlocked?: (day: any) => boolean; + isDayHighlighted?: (day: any) => boolean; } type DayPickerRangeController = React.ClassicComponentClass; @@ -401,64 +414,64 @@ declare namespace ReactDates { // components/DayPickerShape.jsx interface DayPickerShape { - renderMonthText?: (day: momentPropTypes.momentObj) => (string | JSX.Element), + renderMonthText?: (day: momentPropTypes.momentObj) => string | JSX.Element; renderMonthElement?: ( props: { - month: momentPropTypes.momentObj; - onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; - onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; + month: momentPropTypes.momentObj; + onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; + onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; } - ) => string | JSX.Element, - enableOutsideDays?: boolean, - numberOfMonths?: number, - orientation?: ScrollableOrientationShape, - withPortal?: boolean, - initialVisibleMonth?: () => momentPropTypes.momentObj, - firstDayOfWeek?: 0 | 1 | 2 | 3 | 4 | 5 | 6, - hideKeyboardShortcutsPanel?: boolean, - daySize?: number, - verticalHeight?: number, - noBorder?: boolean, - transitionDuration?: number, + ) => string | JSX.Element; + enableOutsideDays?: boolean; + numberOfMonths?: number; + orientation?: ScrollableOrientationShape; + withPortal?: boolean; + initialVisibleMonth?: () => momentPropTypes.momentObj; + firstDayOfWeek?: 0 | 1 | 2 | 3 | 4 | 5 | 6; + hideKeyboardShortcutsPanel?: boolean; + daySize?: number; + verticalHeight?: number; + noBorder?: boolean; + transitionDuration?: number; - navPrev?: string | JSX.Element, - navNext?: string | JSX.Element, + navPrev?: string | JSX.Element; + navNext?: string | JSX.Element; - onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onOutsideClick?: (e: any) => void, - renderCalendarDay?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - renderDayContents?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - renderCalendarInfo?: () => (string | JSX.Element), - calendarInfoPosition?: CalendarInfoPositionShape, + onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onOutsideClick?: (e: any) => void; + renderCalendarDay?: (day: momentPropTypes.momentObj) => string | JSX.Element; + renderDayContents?: (day: momentPropTypes.momentObj) => string | JSX.Element; + renderCalendarInfo?: () => string | JSX.Element; + calendarInfoPosition?: CalendarInfoPositionShape; // accessibility - onBlur?: () => void, - isFocused?: boolean, - showKeyboardShortcuts?: boolean, + onBlur?: () => void; + isFocused?: boolean; + showKeyboardShortcuts?: boolean; // i18n - monthFormat?: string, - weekDayFormat?: string, - phrases?: SingleDatePickerPhrases, - dayAriaLabelFormat?: string, + monthFormat?: string; + weekDayFormat?: string; + phrases?: SingleDatePickerPhrases; + dayAriaLabelFormat?: string; - isRTL?: boolean + isRTL?: boolean; } // components/DayPickerSingleDateController.jsx interface DayPickerSingleDateControllerShape extends DayPickerShape { - date: momentPropTypes.momentObj | null, - onDateChange: (date: momentPropTypes.momentObj | null) => void, - focused: boolean, - onFocusChange: (arg: { focused: boolean | null }) => void, + date: momentPropTypes.momentObj | null; + onDateChange: (date: momentPropTypes.momentObj | null) => void; + focused: boolean; + onFocusChange: (arg: { focused: boolean | null }) => void; - onClose?: (final: { date: momentPropTypes.momentObj }) => void, + onClose?: (final: { date: momentPropTypes.momentObj }) => void; - keepOpenOnDateSelect?: boolean, - isOutsideRange?: (day: any) => boolean, - isDayBlocked?: (day: any) => boolean, - isDayHighlighted?: (day: any) => boolean, + keepOpenOnDateSelect?: boolean; + isOutsideRange?: (day: any) => boolean; + isDayBlocked?: (day: any) => boolean; + isDayHighlighted?: (day: any) => boolean; } type DayPickerSingleDateController = React.ClassicComponentClass; @@ -481,7 +494,13 @@ declare namespace ReactDates { // utils/toISODateString.js var toISODateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; // utils/toLocalizedDateString.js - var toLocalizedDateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; + var toLocalizedDateString: ( + date: moment.MomentInput, + currentFormat: moment.MomentFormatSpecification + ) => string | null; // utils/toMomentObject.js - var toMomentObject: (dateString: moment.MomentInput, customFormat: moment.MomentFormatSpecification) => moment.Moment | null; + var toMomentObject: ( + dateString: moment.MomentInput, + customFormat: moment.MomentFormatSpecification + ) => moment.Moment | null; } 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-foundation/components/responsive.d.ts b/types/react-foundation/components/responsive.d.ts index 9b3a8361ed..94a915f2c8 100644 --- a/types/react-foundation/components/responsive.d.ts +++ b/types/react-foundation/components/responsive.d.ts @@ -24,6 +24,36 @@ export declare class ResponsiveNavigation extends Component; + alignX: PropTypes.Requireable; + alignY: PropTypes.Requireable; + selfAlignX: PropTypes.Requireable; + selfAlignY: PropTypes.Requireable; + centerAlign: PropTypes.Requireable; + flexContainer: PropTypes.Requireable; + flexDirRow: PropTypes.Requireable; + flexDirRowRev: PropTypes.Requireable; + flexDirCol: PropTypes.Requireable; + flexDirColRev: PropTypes.Requireable; + flexChild: PropTypes.Requireable; + flexOrder: PropTypes.Requireable; + flexOrderSmall: PropTypes.Requireable; + flexOrderMedium: PropTypes.Requireable; + flexOrderLarge: PropTypes.Requireable; + showFor: PropTypes.Requireable; + showOnlyFor: PropTypes.Requireable; + hideFor: PropTypes.Requireable; + hideOnlyFor: PropTypes.Requireable; + isHidden: PropTypes.Requireable; + isInvisible: PropTypes.Requireable; + showForLandscape: PropTypes.Requireable; + showForPortrait: PropTypes.Requireable; + showForSr: PropTypes.Requireable; + showOnFocus: PropTypes.Requireable; + isClearfix: PropTypes.Requireable; + float: PropTypes.Requireable; + }; static defaultProps: { breakpoint: number; }; 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-highcharts/index.d.ts b/types/react-highcharts/index.d.ts new file mode 100644 index 0000000000..26a74e28a9 --- /dev/null +++ b/types/react-highcharts/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for react-highcharts 16.0 +// Project: https://github.com/kirjs/react-highcharts +// Definitions by: Jiri Marsicek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as Highcharts from "highcharts"; +import * as React from "react"; + +/** + * Props for ReactHighcharts component. + */ +interface ReactHighchartsProps { + /** + * Highcharts configuration options. + */ + config: Highcharts.Options; + /** + * + * @param after-render callback. + */ + callback?(chart: Highcharts.ChartObject): void; +} + +/** + * React interface for highcharts. + */ +declare class ReactHighcharts extends React.Component { + static Highcharts: Highcharts.Static; +} + +export default ReactHighcharts; diff --git a/types/react-highcharts/react-highcharts-tests.tsx b/types/react-highcharts/react-highcharts-tests.tsx new file mode 100644 index 0000000000..7c0841e566 --- /dev/null +++ b/types/react-highcharts/react-highcharts-tests.tsx @@ -0,0 +1,14 @@ +import * as React from "react"; +import * as Highcharts from "highcharts"; +import ReactHighcharts from "react-highcharts"; + +const config: Highcharts.Options = {}; + +function callback(chart: Highcharts.ChartObject): void {} + +export const _ = () => ( + <> + + + +); diff --git a/types/react-highcharts/tsconfig.json b/types/react-highcharts/tsconfig.json new file mode 100644 index 0000000000..a2060c82fe --- /dev/null +++ b/types/react-highcharts/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "jsx": "react", + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "react-highcharts-tests.tsx"] +} diff --git a/types/react-highcharts/tslint.json b/types/react-highcharts/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-highcharts/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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-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-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-native-dialog/index.d.ts b/types/react-native-dialog/index.d.ts index 10e977f420..14d7458140 100644 --- a/types/react-native-dialog/index.d.ts +++ b/types/react-native-dialog/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for react-native-dialog 4.0 // Project: https://github.com/mmazzarolo/react-native-dialog // Definitions by: MrLuje +// 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/index.d.ts b/types/react-native/index.d.ts index 6e54b6d7c9..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. @@ -9037,8 +9055,11 @@ export const PixelRatio: PixelRatioStatic; * * const View = requireNativeComponent('RCTView'); * + * 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): React.ReactType; +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 b5d7a5faeb..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< ; export interface DrawerItemsProps { - navigation: NavigationScreenProp; + navigation: NavigationScreenProp; items: NavigationRoute[]; activeItemKey?: string; activeTintColor?: string; diff --git a/types/react-panelgroup/index.d.ts b/types/react-panelgroup/index.d.ts new file mode 100644 index 0000000000..4207d8e61d --- /dev/null +++ b/types/react-panelgroup/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for react-panelgroup 1.0 +// Project: https://github.com/DanFessler/react-panelgroup +// Definitions by: Quentin Golsteyn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import * as React from "react"; + +/** + * Interface used to define a number of options for a panel. + */ +export interface PanelWidth { + size?: number; + minSize?: number; + resize?: "fixed" | "dynamic" | "stretch"; + snap?: number[]; +} + +export interface PropTypes { + spacing?: number; + borderColor?: string; + panelColor?: string; + direction?: "row" | "column"; + panelWidths?: Array; + onUpdate?: (data: PanelWidth) => void; +} + +/** + * React component that allows for the creation of resizable panels. + */ +export default class PanelGroup extends React.Component {} diff --git a/types/react-panelgroup/react-panelgroup-tests.tsx b/types/react-panelgroup/react-panelgroup-tests.tsx new file mode 100644 index 0000000000..fcbbeab0ee --- /dev/null +++ b/types/react-panelgroup/react-panelgroup-tests.tsx @@ -0,0 +1,68 @@ +import PanelGroup, { PanelWidth } from "react-panelgroup"; +import * as React from "react"; + +const test1 = ( + +
    panel 1
    +
    panel 2
    +
    panel 3
    +
    +); + +const test2 = ( + +
    panel 1
    +
    panel 2
    +
    panel 3
    +
    +); + +const test3 = ( + + +
    panel 1
    +
    panel 2
    +
    panel 3
    +
    +
    panel 4
    + +
    panel 5
    +
    panel 6
    +
    +
    +); + +const test4 = ( + +
    panel 1
    +
    panel 2
    +
    panel 3
    +
    +); + +const test5 = ( + {}} + > +
    panel 1
    +
    panel 2
    +
    panel 3
    +
    +); + +const test6: PanelWidth = { + size: 100, + minSize: 100, + resize: "fixed", + snap: [50, 75] +}; diff --git a/types/react-panelgroup/tsconfig.json b/types/react-panelgroup/tsconfig.json new file mode 100644 index 0000000000..ace72f23f2 --- /dev/null +++ b/types/react-panelgroup/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "jsx": "react", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "react-panelgroup-tests.tsx"] +} diff --git a/types/react-panelgroup/tslint.json b/types/react-panelgroup/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-panelgroup/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 2f919581f4..bcbcced0bd 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -13,7 +13,7 @@ // 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 @@ -65,11 +65,11 @@ export type AdvancedComponentDecorator = * DecorationTargetProps[P] definition, its definition will be that of InjectedProps[P] */ export type Matching = { - [P in keyof DecorationTargetProps]: P extends keyof InjectedProps - ? InjectedProps[P] extends DecorationTargetProps[P] - ? DecorationTargetProps[P] - : InjectedProps[P] - : DecorationTargetProps[P]; + [P in keyof DecorationTargetProps]: P extends keyof InjectedProps + ? InjectedProps[P] extends DecorationTargetProps[P] + ? DecorationTargetProps[P] + : InjectedProps[P] + : DecorationTargetProps[P]; }; /** @@ -95,16 +95,16 @@ export type GetProps = C extends ComponentType ? P : never; // Applies LibraryManagedAttributes (proper handling of defaultProps // and propTypes), as well as defines WrappedComponent. export type ConnectedComponentClass = ComponentClass> & { - WrappedComponent: C; + 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 type InferableComponentEnhancerWithProps = - >>>( - component: C - ) => ConnectedComponentClass, keyof Shared>> & TNeedsProps>; + >>>( + 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 @@ -112,14 +112,19 @@ export type InferableComponentEnhancerWithProps = export type InferableComponentEnhancer = 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[]) => (...args: any[]) => any - ? ReturnType + 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 WithThunkActionCreators = +export type ResolveThunks = TDispatchProps extends { [key: string]: any } ? { [C in keyof TDispatchProps]: HandleThunkActionCreator @@ -155,17 +160,27 @@ export interface Connect { ( mapStateToProps: null | undefined, - mapDispatchToProps: MapDispatchToPropsParam + mapDispatchToProps: MapDispatchToPropsNonObject + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: null | undefined, + mapDispatchToProps: TDispatchProps, ): InferableComponentEnhancerWithProps< - WithThunkActionCreators, + ResolveThunks, TOwnProps >; ( mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam + mapDispatchToProps: MapDispatchToPropsNonObject + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: MapStateToPropsParam, + mapDispatchToProps: TDispatchProps, ): InferableComponentEnhancerWithProps< - TStateProps & WithThunkActionCreators, + TStateProps & ResolveThunks, TOwnProps >; @@ -203,21 +218,35 @@ 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< - WithThunkActionCreators, + ResolveThunks, TOwnProps >; ( mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam, + mapDispatchToProps: MapDispatchToPropsNonObject, + mergeProps: null | undefined, + options: Options + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: MapStateToPropsParam, + mapDispatchToProps: TDispatchProps, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps< - TStateProps & WithThunkActionCreators, + TStateProps & ResolveThunks, TOwnProps >; // tslint:enable:no-unnecessary-generics @@ -243,10 +272,12 @@ export type MapDispatchToProps = MapDispatchToPropsFunction | TDispatchProps; export type MapDispatchToPropsFactory = - (dispatch: Dispatch, ownProps: TOwnProps) => MapDispatchToProps; + (dispatch: Dispatch, ownProps: TOwnProps) => MapDispatchToPropsFunction; export type MapDispatchToPropsParam = MapDispatchToPropsFactory | MapDispatchToProps; +export type MapDispatchToPropsNonObject = MapDispatchToPropsFactory | MapDispatchToPropsFunction; + export type MergeProps = (stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps) => TMergedProps; diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index aff8515e87..554ace09ff 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -102,23 +102,79 @@ function MapDispatch() { } function MapDispatchWithThunkActionCreators() { - class TestComponent extends React.Component<{ - foo: string, - onClick(): void, - thunkAction(): Promise - }> {} - - const mapDispatchToProps = () => ({ - onClick: () => {}, - thunkAction: () => async () => {} + 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 Test = connect( - null, - mapDispatchToProps, + 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 =
    + ; + + ; + +
    ; +} - 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() { diff --git a/types/react-router-dom/react-router-dom-tests.tsx b/types/react-router-dom/react-router-dom-tests.tsx index a550a579fa..a7715e9ea1 100644 --- a/types/react-router-dom/react-router-dom-tests.tsx +++ b/types/react-router-dom/react-router-dom-tests.tsx @@ -27,6 +27,10 @@ type OtherProps = RouteComponentProps<{ }>; const Component: React.SFC = props => { + if (!props.match) { + return null; + } + const { id } = props.match.params; return (
    {id}
    diff --git a/types/react-router-redux/index.d.ts b/types/react-router-redux/index.d.ts index 9dfbd58c11..7abdc88505 100644 --- a/types/react-router-redux/index.d.ts +++ b/types/react-router-redux/index.d.ts @@ -4,7 +4,7 @@ // Shoya Tanaka // Mykolas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { Store, diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index f62fc44b18..eee1b15972 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -72,11 +72,20 @@ export interface RouteComponentProps { + history: H.History; + location: H.Location; + match: match | null; +} + export interface RouteProps { location?: H.Location; component?: React.ComponentType> | React.ComponentType; render?: ((props: RouteComponentProps) => React.ReactNode); - children?: ((props: RouteComponentProps) => React.ReactNode) | React.ReactNode; + children?: ((props: RouteChildrenProps) => React.ReactNode) | React.ReactNode; path?: string | string[]; exact?: boolean; sensitive?: boolean; diff --git a/types/react-router/test/Children.tsx b/types/react-router/test/Children.tsx index c3dea4f482..7f33629f3c 100644 --- a/types/react-router/test/Children.tsx +++ b/types/react-router/test/Children.tsx @@ -20,3 +20,9 @@ function RouteWithElementJsxChildren() { {
    Hello!
    } ; } + +function RouteWithFunctionChildrenUsingNullableMatch() { + return + {({ match }) => match !== null ?
    Matched path: {match.path}
    :
    No match!
    } +
    ; +} diff --git a/types/react-rte/index.d.ts b/types/react-rte/index.d.ts new file mode 100644 index 0000000000..c4e4a2bad8 --- /dev/null +++ b/types/react-rte/index.d.ts @@ -0,0 +1,159 @@ +// Type definitions for react-rte 0.16 +// Project: https://github.com/sstur/react-rte +// Definitions by: jclyons52 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Component, ReactNode } from "react"; +import { ContentBlock, EditorState } from "draft-js"; +import draftjs = require("draft-js"); + +type CustomBlockFn = ( + element: Element +) => undefined | null | CustomBlockObject; +type CustomInlineFn = ( + element: Element, + inlineCreators: InlineCreators +) => undefined | null | Style | draftjs.EntityInstance; + +interface CustomBlockObject { + type?: string; + data?: object; +} + +interface InlineCreators { + Style: (style: string) => Style; + Entity: (type: string, data?: object) => draftjs.EntityInstance; +} + +interface Style { + type: "STYLE"; + style: string; +} + +interface ImportOptions { + parser?: (html: string) => HTMLBodyElement; + elementStyles?: { [styleName: string]: string }; + customBlockFn?: CustomBlockFn; + customInlineFn?: CustomInlineFn; +} + +declare function stateFromHTML( + html: string, + options?: ImportOptions +): draftjs.ContentState; + +type BlockStyleFn = (block: draftjs.ContentBlock) => RenderConfig; +type EntityStyleFn = (entity: draftjs.EntityInstance) => RenderConfig; +type BlockRenderer = (block: draftjs.ContentBlock) => string; +interface RenderConfig { + element?: string; + attributes?: any; + style?: any; +} + +interface ExportOptions { + inlineStyles?: { [styleName: string]: RenderConfig }; + blockRenderers?: { [blockType: string]: BlockRenderer }; + blockStyleFn?: BlockStyleFn; + entityStyleFn?: EntityStyleFn; +} + +declare function stateToHTML( + content: draftjs.ContentState, + options?: ExportOptions +): string; + +interface StringMap { + [key: string]: string; +} + +export class EditorValue { + constructor(editorState: EditorState, cache: StringMap); + getEditorState(): EditorState; + setEditorState(editorState: EditorState): EditorValue; + toString(format: string, options?: ExportOptions): string; + setContentFromString( + markup: string, + format: string, + options?: ImportOptions + ): EditorValue; + static createEmpty(decorator?: any): EditorValue; + static createFromState(editorState: EditorState): EditorValue; + static createFromString( + markup: string, + format: string, + decorator?: any, + options?: ImportOptions + ): EditorValue; +} + +interface StyleConfig { + label: string; + style: string; + className?: string; +} + +type StyleConfigList = StyleConfig[]; + +type ChangeHandler = (value: EditorValue) => any; + +type GetControlState = (key: string) => string | undefined; + +type SetControlState = (key: string, value: string) => void; + +type CustControlFunc = ( + set: SetControlState, + get: GetControlState, + state: EditorState +) => ReactNode; + +type CustomControl = ReactNode | CustControlFunc; + +type GroupName = + | "INLINE_STYLE_BUTTONS" + | "BLOCK_TYPE_BUTTONS" + | "LINK_BUTTONS" + | "BLOCK_TYPE_DROPDOWN" + | "HISTORY_BUTTONS" + | "IMAGE_BUTTON"; + +interface ToolbarConfig { + display: GroupName[]; + extraProps?: object; + INLINE_STYLE_BUTTONS: StyleConfigList; + BLOCK_TYPE_DROPDOWN: StyleConfigList; + BLOCK_TYPE_BUTTONS: StyleConfigList; +} + +interface Props { + className?: string; + toolbarClassName?: string; + editorClassName?: string; + value: EditorValue; + onChange?: ChangeHandler; + placeholder?: string; + customStyleMap?: { [style: string]: { [key: string]: any } }; + handleReturn?: (event: object) => boolean; + customControls?: CustomControl[]; + readOnly?: boolean; + disabled?: boolean; // Alias of readOnly + toolbarConfig?: ToolbarConfig; + blockStyleFn?: (block: ContentBlock) => string | undefined; + autoFocus?: boolean; + keyBindingFn?: (event: object) => string | undefined; + rootStyle?: object; + editorStyle?: object; + toolbarStyle?: object; +} + +declare class RichTextEditor extends Component { + static createEmptyValue(): EditorValue; + static createValueFromString( + markup: string, + format: string, + options?: ImportOptions + ): EditorValue; +} + +export default RichTextEditor; diff --git a/types/react-rte/react-rte-tests.tsx b/types/react-rte/react-rte-tests.tsx new file mode 100644 index 0000000000..93e7ffa8f9 --- /dev/null +++ b/types/react-rte/react-rte-tests.tsx @@ -0,0 +1,33 @@ +import * as React from "react"; +import RichTextEditor, { EditorValue } from "react-rte"; + +interface Props { + onChange: (val: string) => void; +} + +class MyStatefulEditor extends React.Component { + state = { + value: RichTextEditor.createEmptyValue() + }; + + onChange = (value: EditorValue) => { + this.setState({value}); + if (this.props.onChange) { + // Send the changes up to the parent component as an HTML string. + // This is here to demonstrate using `.toString()` but in a real app it + // would be better to avoid generating a string on each change. + this.props.onChange( + value.toString('html') + ); + } + } + + render() { + return ( + + ); + } +} diff --git a/types/react-rte/tsconfig.json b/types/react-rte/tsconfig.json new file mode 100644 index 0000000000..1fa35271b4 --- /dev/null +++ b/types/react-rte/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "react-rte-tests.tsx"] +} diff --git a/types/react-rte/tslint.json b/types/react-rte/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-rte/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-select/lib/components/Menu.d.ts b/types/react-select/lib/components/Menu.d.ts index 8c6e5fb6c8..387b538882 100644 --- a/types/react-select/lib/components/Menu.d.ts +++ b/types/react-select/lib/components/Menu.d.ts @@ -67,6 +67,9 @@ export type MenuProps = CommonProps & { export function menuCSS(state: MenuState): React.CSSProperties; export class Menu extends Component, MenuState> { + static contextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; getPlacement: (ref: ElementRef) => void; getState: () => MenuProps & MenuState; } @@ -143,6 +146,9 @@ interface PortalStyleArgs { export function menuPortalCSS(args: PortalStyleArgs): React.CSSProperties; export class MenuPortal extends Component, MenuPortalState> { + static childContextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; getChildContext(): { getPortalPlacement: (state: MenuState) => void; }; diff --git a/types/react-select/test/examples/CustomNoOptionsMessage.tsx b/types/react-select/test/examples/CustomNoOptionsMessage.tsx index 3896272d5b..6bea4cb47a 100644 --- a/types/react-select/test/examples/CustomNoOptionsMessage.tsx +++ b/types/react-select/test/examples/CustomNoOptionsMessage.tsx @@ -18,12 +18,7 @@ const NoOptionsMessage = (props: any) => { export default class CustomNoOptionsMessage extends React.Component { render() { return ( - // Without the type argument, `OptionType` is inferred as `never` from the - // `options` attribute of type `never[]`, and `Select.defaultProps` (of - // type `Props`) fails to be assignable to the instantiated props - // type, `Props`. This issue shouldn't come up in real code where - // the `options` attribute isn't a literal empty array. - + onClick(id, e.shiftKey, row)} + checked={checked} + /> +); + +const SelectAllInput: React.StatelessComponent< + SelectAllInputComponentProps +> = ({ onClick, checked }) => ( + +); + const selectTableAdditionalProps: SelectTableAdditionalProps = { isSelected: () => true, keyField: 'id', selectAll: true, selectType: 'checkbox', toggleAll: () => null, - toggleSelection: () => null + toggleSelection: () => null, + SelectInputComponent: SelectInput, + SelectAllInputComponent: SelectAllInput }; const data = [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }]; @@ -29,6 +52,7 @@ ReactDOM.render( {...selectTableAdditionalProps} data={data} columns={columns} + ref={React.createRef()} />, document.getElementById('root') ); diff --git a/types/react-table/test/tree-table-tests.tsx b/types/react-table/test/tree-table-tests.tsx index a099124c61..6bb9461f78 100644 --- a/types/react-table/test/tree-table-tests.tsx +++ b/types/react-table/test/tree-table-tests.tsx @@ -4,7 +4,7 @@ import * as ReactDOM from 'react-dom'; import ReactTable, { Column } from 'react-table'; import treeTableHOC from 'react-table/lib/hoc/treeTable'; -const SelectTable = treeTableHOC(ReactTable); +const TreeTable = treeTableHOC(ReactTable); const data = [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }]; @@ -14,6 +14,6 @@ const columns: Column[] = [ ]; ReactDOM.render( - , + , document.getElementById('root') ); diff --git a/types/react-virtualized/dist/es/List.d.ts b/types/react-virtualized/dist/es/List.d.ts index 9de78e4066..57e00ae909 100644 --- a/types/react-virtualized/dist/es/List.d.ts +++ b/types/react-virtualized/dist/es/List.d.ts @@ -30,7 +30,7 @@ export type ListProps = GridCoreProps & { /** Height constraint for list (determines how many actual rows are rendered) */ height: number; /** Optional renderer to be used in place of rows when rowCount is 0 */ - noRowsRenderer?: () => JSX.Element | null; + noRowsRenderer?: () => JSX.Element; /** * Callback invoked with information about the slice of rows that were just rendered. * ({ startIndex, stopIndex }): void diff --git a/types/react-virtualized/dist/es/Table.d.ts b/types/react-virtualized/dist/es/Table.d.ts index e9a09dae4c..b66fac389b 100644 --- a/types/react-virtualized/dist/es/Table.d.ts +++ b/types/react-virtualized/dist/es/Table.d.ts @@ -152,6 +152,26 @@ export type ColumnProps = { width: number; }; export class Column extends Component { + static propTypes: { + "aria-label": Requireable; + cellDataGetter: Requireable; + cellRenderer: Requireable; + className: Requireable; + columnData: Requireable; + dataKey: Validator; + disableSort: Requireable; + flexGrow: Requireable; + flexShrink: Requireable; + headerClassName: Requireable; + headerRenderer: Validator; + label: Requireable; + maxWidth: Requireable; + minWidth: Requireable; + style: Requireable; + width: Validator; + id: Requireable; + }; + static defaultProps: { cellDataGetter: TableCellDataGetter; cellRenderer: TableCellRenderer; @@ -358,6 +378,63 @@ export const SortIndicator: React.StatelessComponent<{ * This component expects explicit width, height, and padding parameters. */ export class Table extends PureComponent { + static propTypes: { + "aria-label": Requireable; + autoHeight: Requireable; + children: Validator; + className: Requireable; + disableHeader: Requireable; + estimatedRowSize: Validator; + gridClassName: Requireable; + gridStyle: Requireable; + headerClassName: Requireable; + headerHeight: Validator; + headerRowRenderer: Requireable; + headerStyle: Requireable; + height: Validator; + id: Requireable; + noRowsRenderer: Requireable<() => JSX.Element>; + onHeaderClick: Requireable< + (params: HeaderMouseEventHandlerParams) => void + >; + onRowClick: Requireable<(params: RowMouseEventHandlerParams) => void>; + onRowDoubleClick: Requireable< + (params: RowMouseEventHandlerParams) => void + >; + onRowMouseOut: Requireable< + (params: RowMouseEventHandlerParams) => void + >; + onRowMouseOver: Requireable< + (params: RowMouseEventHandlerParams) => void + >; + onRowsRendered: Requireable< + (params: RowMouseEventHandlerParams) => void + >; + onScroll: Requireable<(params: ScrollEventData) => void>; + overscanRowCount: Validator; + rowClassName: Requireable string)>; + rowGetter: Validator<(params: Index) => any>; + rowHeight: Validator number)>; + rowCount: Validator; + rowRenderer: Requireable<(props: TableRowProps) => React.ReactNode>; + rowStyle: Validator< + React.CSSProperties | ((params: Index) => React.CSSProperties) + >; + scrollToAlignment: Validator; + scrollToIndex: Validator; + scrollTop: Requireable; + sort: Requireable< + ( + params: { sortBy: string; sortDirection: SortDirectionType } + ) => void + >; + sortBy: Requireable; + sortDirection: Validator; + style: Requireable; + tabIndex: Requireable; + width: Validator; + }; + static defaultProps: { disableHeader: false; estimatedRowSize: 30; @@ -368,7 +445,7 @@ export class Table extends PureComponent { onScroll: () => null; overscanRowCount: 10; rowRenderer: TableRowRenderer; - headerRowRenderer: TableHeaderRowRenderer; + headerRowRenderer: TableHeaderRenderer; rowStyle: {}; scrollToAlignment: "auto"; scrollToIndex: -1; diff --git a/types/react/global.d.ts b/types/react/global.d.ts index 0c7a24070a..2ea2b7ca91 100644 --- a/types/react/global.d.ts +++ b/types/react/global.d.ts @@ -34,6 +34,7 @@ interface HTMLBodyElement extends HTMLElement { } interface HTMLBRElement extends HTMLElement { } interface HTMLButtonElement extends HTMLElement { } interface HTMLCanvasElement extends HTMLElement { } +interface HTMLDataListElement extends HTMLElement { } interface HTMLDialogElement extends HTMLElement { } interface HTMLDivElement extends HTMLElement { } interface HTMLDListElement extends HTMLElement { } @@ -43,8 +44,6 @@ interface HTMLFormElement extends HTMLElement { } interface HTMLHeadingElement extends HTMLElement { } interface HTMLHeadElement extends HTMLElement { } interface HTMLHRElement extends HTMLElement { } -interface HTMLTableColElement extends HTMLElement { } -interface HTMLDataListElement extends HTMLElement { } interface HTMLHtmlElement extends HTMLElement { } interface HTMLIFrameElement extends HTMLElement { } interface HTMLImageElement extends HTMLElement { } @@ -71,53 +70,13 @@ interface HTMLSourceElement extends HTMLElement { } interface HTMLSpanElement extends HTMLElement { } interface HTMLStyleElement extends HTMLElement { } interface HTMLTableElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } -interface HTMLTableDataCellElement extends HTMLElement { } -interface HTMLTextAreaElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } -interface HTMLTableHeaderCellElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } -interface HTMLTitleElement extends HTMLElement { } -interface HTMLTableRowElement extends HTMLElement { } -interface HTMLTrackElement extends HTMLElement { } -interface HTMLUListElement extends HTMLElement { } -interface HTMLVideoElement extends HTMLElement { } interface HTMLTableColElement extends HTMLElement { } -interface HTMLDataListElement extends HTMLElement { } -interface HTMLHtmlElement extends HTMLElement { } -interface HTMLIFrameElement extends HTMLElement { } -interface HTMLImageElement extends HTMLElement { } -interface HTMLInputElement extends HTMLElement { } -interface HTMLModElement extends HTMLElement { } -interface HTMLLabelElement extends HTMLElement { } -interface HTMLLegendElement extends HTMLElement { } -interface HTMLLIElement extends HTMLElement { } -interface HTMLLinkElement extends HTMLElement { } -interface HTMLMapElement extends HTMLElement { } -interface HTMLMetaElement extends HTMLElement { } -interface HTMLObjectElement extends HTMLElement { } -interface HTMLOListElement extends HTMLElement { } -interface HTMLOptGroupElement extends HTMLElement { } -interface HTMLOptionElement extends HTMLElement { } -interface HTMLParagraphElement extends HTMLElement { } -interface HTMLParamElement extends HTMLElement { } -interface HTMLPreElement extends HTMLElement { } -interface HTMLProgressElement extends HTMLElement { } -interface HTMLQuoteElement extends HTMLElement { } -interface HTMLScriptElement extends HTMLElement { } -interface HTMLSelectElement extends HTMLElement { } -interface HTMLSourceElement extends HTMLElement { } -interface HTMLSpanElement extends HTMLElement { } -interface HTMLStyleElement extends HTMLElement { } -interface HTMLTableElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } interface HTMLTableDataCellElement extends HTMLElement { } -interface HTMLTextAreaElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } interface HTMLTableHeaderCellElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } -interface HTMLTitleElement extends HTMLElement { } interface HTMLTableRowElement extends HTMLElement { } +interface HTMLTableSectionElement extends HTMLElement { } +interface HTMLTextAreaElement extends HTMLElement { } +interface HTMLTitleElement extends HTMLElement { } interface HTMLTrackElement extends HTMLElement { } interface HTMLUListElement extends HTMLElement { } interface HTMLVideoElement extends HTMLElement { } diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 5cefb7fca2..730268f974 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -298,7 +298,7 @@ declare namespace React { } interface ProviderExoticComponent

    extends ExoticComponent

    { - propTypes?: ValidationMap

    ; + propTypes?: WeakValidationMap

    ; } type ContextType> = C extends Context ? T : never; @@ -322,23 +322,25 @@ declare namespace React { const Children: ReactChildren; const Fragment: ExoticComponent<{ children?: ReactNode }>; const StrictMode: ExoticComponent<{ children?: ReactNode }>; - /** - * This feature is not yet available for server-side rendering. - * Suspense support will be added in a later release. - */ - const Suspense: ExoticComponent<{ - children?: ReactNode + + interface SuspenseProps { + children?: ReactNode; /** A fallback react tree to show when a Suspense child (like React.lazy) suspends */ - fallback: NonNullable|null + fallback: NonNullable|null; // I tried looking at the code but I have no idea what it does. // https://github.com/facebook/react/issues/13206#issuecomment-432489986 /** * Not implemented yet, requires unstable_ConcurrentMode */ - // maxDuration?: number - }>; + // maxDuration?: number; + } + /** + * This feature is not yet available for server-side rendering. + * Suspense support will be added in a later release. + */ + const Suspense: ExoticComponent; const version: string; // @@ -421,34 +423,6 @@ declare namespace React { refs: { [key: string]: ReactInstance }; - - // Static properties copied from ComponentClass interface. - /** - * The validity of the type of `propTypes` cannot be checked - * automatically at the definition of a component class because the - * required type depends on `P`. We recommend checking it using - * `asPropTypes` from the `react-typescript-helpers` package. If you - * don't do that, then the type will still be checked by - * JSX.LibraryManagedAttributes every time the component is used, - * assuming you use TypeScript 3.0 or newer. - */ - // Note: `propTypes` and `defaultProps` need to be `any` so that a - // component class that does not redeclare them is assignable to - // `ComponentClass

    `. - static propTypes?: any; - static contextTypes?: ValidationMap; - static childContextTypes?: ValidationMap; - /** - * The validity of the type of `defaultProps` cannot be checked - * automatically at the definition of a component class because the - * required type depends on `P`. We recommend checking it using - * `asDefaultProps` from the `react-typescript-helpers` package. If you - * don't do that, then the type will still be checked by - * JSX.LibraryManagedAttributes every time the component is used, - * assuming you use TypeScript 3.0 or newer. - */ - static defaultProps?: any; - static displayName?: string; } class PureComponent

    extends Component { } @@ -487,7 +461,7 @@ declare namespace React { interface FunctionComponent

    { (props: P & { children?: ReactNode }, context?: any): ReactElement | null; - propTypes?: ValidationMap

    ; + propTypes?: WeakValidationMap

    ; contextTypes?: ValidationMap; defaultProps?: Partial

    ; displayName?: string; @@ -495,7 +469,7 @@ declare namespace React { interface RefForwardingComponent { (props: P & { children?: ReactNode }, ref: Ref | null): ReactElement | null; - propTypes?: ValidationMap

    ; + propTypes?: WeakValidationMap

    ; contextTypes?: ValidationMap; defaultProps?: Partial

    ; displayName?: string; @@ -503,7 +477,7 @@ declare namespace React { interface ComponentClass

    extends StaticLifecycle { new (props: P, context?: any): Component; - propTypes?: ValidationMap

    ; + propTypes?: WeakValidationMap

    ; contextType?: Context; contextTypes?: ValidationMap; childContextTypes?: ValidationMap; @@ -862,17 +836,6 @@ declare namespace React { */ // TODO (TypeScript 3.0): function useRef(initialValue: T|null): RefObject; - /** - * The signature is identical to `useEffect`, but it fires synchronously during the same phase that - * React performs its DOM mutations, before sibling components have been updated. Use this to perform - * custom DOM mutations. - * - * Prefer the standard `useEffect` when possible to avoid blocking visual updates. - * - * @version experimental - * @see https://reactjs.org/docs/hooks-reference.html#usemutationeffect - */ - function useMutationEffect(effect: EffectCallback, inputs?: InputIdentityList): void; /** * The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations. * Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside @@ -1050,6 +1013,8 @@ declare namespace React { */ getModifierState(key: string): boolean; metaKey: boolean; + movementX: number; + movementY: number; nativeEvent: NativeMouseEvent; pageX: number; pageY: number; @@ -1188,6 +1153,8 @@ declare namespace React { // Form Events onChange?: FormEventHandler; onChangeCapture?: FormEventHandler; + onBeforeInput?: FormEventHandler; + onBeforeInputCapture?: FormEventHandler; onInput?: FormEventHandler; onInputCapture?: FormEventHandler; onReset?: FormEventHandler; @@ -2595,6 +2562,14 @@ declare namespace React { type ValidationMap = PropTypes.ValidationMap; + type WeakValidationMap = { + [K in keyof T]?: null extends T[K] + ? Validator + : undefined extends T[K] + ? Validator + : Validator + }; + interface ReactPropTypes { any: typeof PropTypes.any; array: typeof PropTypes.array; @@ -2664,77 +2639,31 @@ declare namespace React { */ componentStack: string; } - - const Invalid_propTypes: unique symbol; - /** - * Dummy interface that is intersected into the props type of a component on - * use to generate an error if the component's `propTypes` static property - * is invalid. In most cases, you can get more information about the - * problem with the `propTypes` by trying to assign the component to a - * variable of type `React.ComponentType

    ` where `P` is the appropriate - * props type. You can bypass the type checking of `propTypes` by defining - * a static property named `bypassPropTypesTypecheck`. - */ - interface Invalid_propTypes { - [Invalid_propTypes]: never; - } - - const Invalid_defaultProps: unique symbol; - /** - * Dummy interface that is intersected into the props type of a component on - * use to generate an error if the component's `defaultProps` static - * property is invalid. In most cases, you can get more information about - * the problem with the `defaultProps` by trying to assign the component to - * a variable of type `React.ComponentType

    ` where `P` is the appropriate - * props type. You can bypass the type checking of `defaultProps` by - * defining a static property named `bypassDefaultPropsTypecheck`. - */ - interface Invalid_defaultProps { - [Invalid_defaultProps]: never; - } - - // For a component class, the P passed to JSX.LibraryManagedAttributes is - // based on the `props` property and includes `children` regardless of - // whether the original props type (the `P` type argument to - // React.Component) does. However, it's common for component classes not - // to list `children` in the `propTypes` if the original props type did not - // include `children`. We accommodate that here by making the validator for - // `children` optional. - type ValidationMapWithOptionalChildren

    = - ValidationMap>> & - Partial>>>; - - // Explicitly check for excess properties in CheckPropTypes and - // CheckDefaultProps because by the time we get to - // JSX.LibraryManagedAttributes, we have lost the opportunity to do an - // excess properties check on the original object literal. - - type CheckPropTypes = - // This condition attempts to single out `T = any`, which needs to bypass the rest of the check - // because `keyof T` would come out as not extending `keyof P`. - T extends typeof Invalid_propTypes ? {} : - [keyof T, T] extends [keyof P, ValidationMapWithOptionalChildren

    ] ? {} : Invalid_propTypes; - - type CheckDefaultProps = - D extends typeof Invalid_defaultProps ? {} : - [keyof D, D] extends [keyof P, Partial

    ] ? {} : Invalid_defaultProps; - - // Any prop that has a default prop becomes optional, but its type is unchanged - // If declared props have indexed properties, ignore default props entirely as keyof gets widened - // Wrap in an outer-level conditional type to allow distribution over props that are unions - type Defaultize = P extends any - ? string extends keyof P ? P : - & Pick> - & Partial>> - : never; - - type ReactManagedAttributes = - (C extends { propTypes: infer T; } - ? (C extends { bypassPropTypesTypecheck: {}; } ? {} : CheckPropTypes) : {}) & - (C extends { defaultProps: infer D; } - ? (C extends { bypassDefaultPropsTypecheck: {}; } ? {} : CheckDefaultProps) & Defaultize : P); } +// Declared props take priority over inferred props +// If declared props have indexed properties, ignore inferred props entirely as keyof gets widened +type MergePropTypes = P & Pick>; + +// Any prop that has a default prop becomes optional, but its type is unchanged +// Undeclared default props are augmented into the resulting allowable attributes +// If declared props have indexed properties, ignore default props entirely as keyof gets widened +// Wrap in an outer-level conditional type to allow distribution over props that are unions +type Defaultize = P extends any + ? string extends keyof P ? P : + & Pick> + & Partial>> + & Partial>> + : never; + +type ReactManagedAttributes = C extends { propTypes: infer T; defaultProps: infer D; } + ? Defaultize>, D> + : C extends { propTypes: infer T; } + ? MergePropTypes> + : C extends { defaultProps: infer D; } + ? Defaultize + : P; + declare global { namespace JSX { // tslint:disable-next-line:no-empty-interface @@ -2749,9 +2678,9 @@ declare global { // let's assume it's reasonable to do a single React.lazy() around a single React.memo() / vice-versa type LibraryManagedAttributes = C extends React.MemoExoticComponent | React.LazyExoticComponent ? T extends React.MemoExoticComponent | React.LazyExoticComponent - ? React.ReactManagedAttributes - : React.ReactManagedAttributes - : React.ReactManagedAttributes; + ? ReactManagedAttributes + : ReactManagedAttributes + : ReactManagedAttributes; // tslint:disable-next-line:no-empty-interface interface IntrinsicAttributes extends React.Attributes { } diff --git a/types/react/test/hooks.tsx b/types/react/test/hooks.tsx index c3495dd717..5239d3b522 100644 --- a/types/react/test/hooks.tsx +++ b/types/react/test/hooks.tsx @@ -95,11 +95,9 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { // $ExpectError React.useImperativeMethods(ref, () => ({}), [id]); - React.useMutationEffect(() => { + React.useLayoutEffect(() => { setState(1); setState(prevState => prevState - 1); - }, []); - React.useLayoutEffect(() => { didLayout.current = true; }, []); React.useEffect(() => { diff --git a/types/react/test/managedAttributes.tsx b/types/react/test/managedAttributes.tsx index a4213c58b1..1e0e8226d9 100644 --- a/types/react/test/managedAttributes.tsx +++ b/types/react/test/managedAttributes.tsx @@ -1,18 +1,14 @@ interface LeaveMeAloneDtslint { foo: string; } -// Re-enable when we move @types/react to TS 3.0 (except for the tests marked as -// requiring TS >= 3.2) -// -// In the meantime, these tests can be run manually by uncommenting the code -// below and running `dtslint --onlyTestTsNext`. +// // Re-enable when we move @types/react to TS 3.0 // import * as React from 'react'; // import * as PropTypes from 'prop-types'; // interface Props { -// bool?: boolean | null; +// bool?: boolean; // fnc: () => any; // node?: React.ReactNode; -// num?: number | null; +// num?: number; // reqNode: NonNullable; // str: string; // } @@ -22,12 +18,14 @@ interface LeaveMeAloneDtslint { foo: string; } // fnc: PropTypes.func.isRequired, // node: PropTypes.node, // num: PropTypes.number, -// reqNode: PropTypes.node.isRequired, // str: PropTypes.string.isRequired, +// extraStr: PropTypes.string.isRequired, +// extraNum: PropTypes.number // }; // const defaultProps = { // fnc: (() => 'abc') as () => any, +// extraBool: false, // reqNode: 'text_node' as NonNullable // }; @@ -38,12 +36,39 @@ interface LeaveMeAloneDtslint { foo: string; } // const annotatedPropTypesAndDefaultPropsTests = [ // // $ExpectError -// , // str is required -// , +// , // str and extraStr are required +// , // // $ExpectError // , // num type mismatch // } +// num={0} +// reqNode={} +// str='abc' +// /> +// ]; + +// class UnannotatedPropTypesAndDefaultProps extends React.Component { +// static propTypes = propTypes; +// static defaultProps = defaultProps; +// } + +// const unannotatedPropTypesAndDefaultPropsTests = [ +// // $ExpectError +// , // stra and extraStr are required +// , +// // $ExpectError +// , // extraBool type mismatch +// } // num={0} @@ -58,14 +83,16 @@ interface LeaveMeAloneDtslint { foo: string; } // const annotatedPropTypesTests = [ // // $ExpectError -// , // str, reqNode and fnc are required -// } />, +// , // str, extraStr, reqNode and fnc are required +// } />, // // $ExpectError -// } extraBool={false} />, // extraBool doesn't exist +// } extraBool={false} />, // extraBool doesn't exist // // $ExpectError -// } num='abc' />, // num type mismatch +// } num='abc' />, // num type mismatch // } // num={0} @@ -74,6 +101,29 @@ interface LeaveMeAloneDtslint { foo: string; } // /> // ]; +// class UnannotatedPropTypes extends React.Component { +// static propTypes = propTypes; +// } + +// const unannotatedPropTypesTests = [ +// // $ExpectError +// , // str, extraStr and fnc are required +// , +// // $ExpectError +// } />, // reqNode doesn't exist +// // $ExpectError +// } num='abc' />, // num type mismatch +// } +// num={0} +// str='abc' +// /> +// ]; + // class AnnotatedDefaultProps extends React.Component { // static defaultProps = defaultProps; // } @@ -87,6 +137,7 @@ interface LeaveMeAloneDtslint { foo: string; } // { }} />, // str type mismatch // // ]; +// class UnannotatedDefaultProps extends React.Component { +// static defaultProps = defaultProps; +// } + +// const unannotatedDefaultPropsTests = [ +// , +// } +// /> +// ]; + // class ComponentWithNoDefaultProps extends React.Component {} -// function FunctionalComponent(props: Props) { return <>{props.reqNode}; } +// function FunctionalComponent(props: Props) { return <>{props.reqNode} } // FunctionalComponent.defaultProps = defaultProps; // const functionalComponentTests = [ // // $ExpectError // , -// // NOTE: This test requires TypeScript >= 3.2, which honors JSX.LibraryManagedAttributes for function components. +// // This is possibly a bug/limitation of TS +// // Even if JSX.LibraryManagedAttributes returns the correct type, it doesn't seem to work with non-classes +// // This also doesn't work with things typed React.SFC

    because defaultProps will always be Partial

    +// // $ExpectError // // ]; @@ -115,28 +182,27 @@ interface LeaveMeAloneDtslint { foo: string; } // const memoTests = [ // // $ExpectError // , -// // Requires TypeScript >= 3.2; see comment re FunctionalComponent above +// // $ExpectError won't work as long as FunctionalComponent doesn't work either // , // // $ExpectError // , // , -// // Requires TypeScript >= 3.2; see comment re FunctionalComponent above +// // $ExpectError this doesn't work despite JSX.LibraryManagedAttributes returning the correct type // , -// // Requires TypeScript >= 3.2; see comment re FunctionalComponent above +// // $ExpectError won't work as long as FunctionalComponent doesn't work either // , // // $ExpectError // , -// // Requires TypeScript >= 3.2; see comment re FunctionalComponent above +// // $ExpectError this doesn't work despite JSX.LibraryManagedAttributes returning the correct type // // ]; -// // $ExpectType Pick & Partial> // type AnnotatedDefaultPropsLibraryManagedAttributes = JSX.LibraryManagedAttributes; -// // $ExpectType Pick & Partial> +// // $ExpectType AnnotatedDefaultPropsLibraryManagedAttributes // type FunctionalComponentLibraryManagedAttributes = JSX.LibraryManagedAttributes; -// // $ExpectType Pick & Partial> +// // $ExpectType FunctionalComponentLibraryManagedAttributes // type MemoFunctionalComponentLibraryManagedAttributes = JSX.LibraryManagedAttributes; -// // $ExpectType Pick & Partial> +// // $ExpectType FunctionalComponentLibraryManagedAttributes // type LazyMemoFunctionalComponentLibraryManagedAttributes = JSX.LibraryManagedAttributes; // const ForwardRef = React.forwardRef((props: Props, ref: React.Ref) => ( @@ -152,97 +218,7 @@ interface LeaveMeAloneDtslint { foo: string; } // reqNode={} // str='' // />, -// // the type of ForwardRef.defaultProps stays Partial

    anyway even if assigned -// // $ExpectError +// // same bug as MemoFunctionalComponent and React.SFC-typed things +// // $ExpectError the type of ForwardRef.defaultProps stays Partial

    anyway even if assigned // // ]; - -// const wrongDefaultProps = { -// fnc: 42 -// }; -// class WrongDefaultPropsComponent extends React.Component { -// static defaultProps = wrongDefaultProps; -// } -// const wrongDefaultPropsComponentTests = [ -// // $ExpectError -// undefined} reqNode="text" str="str" /> -// ]; -// // $ExpectError -// const investigateWrongDefaultPropsComponent: React.ComponentType = WrongDefaultPropsComponent; - -// const excessDefaultProps = { -// another: 43 -// }; -// class ExcessDefaultPropsComponent extends React.Component { -// static defaultProps = excessDefaultProps; -// } -// const excessDefaultPropsComponentTests = [ -// // $ExpectError -// undefined} reqNode="text" str="str" /> -// ]; -// // $ExpectError -// const investigateExcessDefaultPropsComponent: React.ComponentType = ExcessDefaultPropsComponent; - -// const wrongPropTypes = { -// bool: PropTypes.bool, -// fnc: PropTypes.number.isRequired, -// node: PropTypes.node, -// num: PropTypes.number, -// reqNode: PropTypes.node.isRequired, -// str: PropTypes.string.isRequired, -// }; -// class WrongPropTypesComponent extends React.Component { -// static propTypes = wrongPropTypes; -// } -// const wrongPropTypesComponentTests = [ -// // $ExpectError -// undefined} reqNode="text" str="str" /> -// ]; - -// const incompletePropTypes = { -// bool: PropTypes.bool, -// node: PropTypes.node, -// num: PropTypes.number, -// reqNode: PropTypes.node.isRequired, -// str: PropTypes.string.isRequired, -// }; -// class IncompletePropTypesComponent extends React.Component { -// static propTypes = incompletePropTypes; -// } -// const incompletePropTypesComponentTests = [ -// // $ExpectError -// undefined} reqNode="text" str="str" /> -// ]; - -// const excessPropTypes = { -// another: PropTypes.number.isRequired, -// bool: PropTypes.bool, -// fnc: PropTypes.func.isRequired, -// node: PropTypes.node, -// num: PropTypes.number, -// reqNode: PropTypes.node.isRequired, -// str: PropTypes.string.isRequired, -// }; -// class ExcessPropTypesComponent extends React.Component { -// static propTypes = excessPropTypes; -// } -// const ExcessPropTypesComponentTests = [ -// // $ExpectError -// undefined} reqNode="text" str="str" /> -// ]; - -// class WrongDefaultPropsSuppressedComponent extends React.Component { -// static defaultProps = wrongDefaultProps; -// static bypassDefaultPropsTypecheck = true; -// } -// const wrongDefaultPropsSuppressedComponentTests = [ -// undefined} reqNode="text" str="str" /> -// ]; - -// class WrongPropTypesSuppressedComponent extends React.Component { -// static propTypes = wrongPropTypes; -// static bypassPropTypesTypecheck = true; -// } -// const wrongPropTypesSuppressedComponentTests = [ -// undefined} reqNode="text" str="str" /> -// ]; diff --git a/types/react/test/tsx.tsx b/types/react/test/tsx.tsx index 60fcb6dccc..9309799de7 100644 --- a/types/react/test/tsx.tsx +++ b/types/react/test/tsx.tsx @@ -345,3 +345,28 @@ declare global { } const CustomElement2: React.ReactType = 'my-declared-element'; + +interface TestPropTypesProps { + foo: string; +} +interface TestPropTypesProps1 { + foo?: string; +} +interface TestPropTypesProps2 { + foo: string | null; +} +interface TestPropTypesProps3 { + foo?: string | null; +} +const testPropTypes = { + foo: PropTypes.string +}; +type DeclaredPropTypes

    = Required['propTypes'], undefined>>; +// $ExpectType false +type propTypesTest = typeof testPropTypes extends DeclaredPropTypes ? true : false; +// $ExpectType true +type propTypesTest1 = typeof testPropTypes extends DeclaredPropTypes ? true : false; +// $ExpectType true +type propTypesTest2 = typeof testPropTypes extends DeclaredPropTypes ? true : false; +// $ExpectType true +type propTypesTest3 = typeof testPropTypes extends DeclaredPropTypes ? true : false; diff --git a/types/rebass__grid/index.d.ts b/types/rebass__grid/index.d.ts index 079506e631..3f5012851f 100644 --- a/types/rebass__grid/index.d.ts +++ b/types/rebass__grid/index.d.ts @@ -34,6 +34,10 @@ export interface CommonProps { px?: ResponsiveProp; py?: ResponsiveProp; theme?: any; + // this is actually more powerful than the plugin because of some limitations of the transform + /** + * This works even without babel-plugin-styled-components. + */ css?: Interpolation; } diff --git a/types/rebass__grid/rebass__grid-tests.tsx b/types/rebass__grid/rebass__grid-tests.tsx index 2cef66a972..147f3ff084 100644 --- a/types/rebass__grid/rebass__grid-tests.tsx +++ b/types/rebass__grid/rebass__grid-tests.tsx @@ -1,8 +1,11 @@ import * as React from "react"; import { Flex, Box } from "@rebass/grid"; +import { css } from "styled-components"; const Layout = () => ( ); + +const cssTest = ; diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 34e3cbcb88..78da1ec8f5 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -11,6 +11,7 @@ // Paul Melnikow // Harry Cruse // Andrew Palugniok +// Robert Stigsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -45,6 +46,7 @@ export type StackOffsetType = 'sign' | 'expand' | 'none' | 'wiggle' | 'silhouett export type LineType = 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | CurveFactory; +export type IfOverflowType = 'hidden' | 'visible' | 'discard' | 'extendDomain'; export type AxisInterval = number | 'preserveStart' | 'preserveEnd' | 'preserveStartEnd'; export type PickedCSSStyleDeclarationKeys = @@ -363,6 +365,7 @@ export interface LegendPayload { value: any; id: any; type: LegendType; + color?: string; } export type BBoxUpdateCallback = (box: { width: number; height: number; }) => void; @@ -447,6 +450,7 @@ export interface PieProps extends EventAttributes, Partial | ContentRenderer | boolean; activeShape?: object | ContentRenderer | React.ReactElement; activeIndex?: number | number[]; + blendStroke?: boolean; } export class Pie extends React.Component { } @@ -634,6 +638,7 @@ export interface ReferenceAreaProps extends Partial { yAxis?: object; isFront?: boolean; alwaysShow?: boolean; + ifOverflow?: IfOverflowType; x1?: number | string; x2?: number | string; y1?: number | string; @@ -657,6 +662,7 @@ export interface ReferenceDotProps extends EventAttributes, Partial | React.ReactElement; diff --git a/types/rechoir/index.d.ts b/types/rechoir/index.d.ts new file mode 100644 index 0000000000..2cb3bbb7ab --- /dev/null +++ b/types/rechoir/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for rechoir 0.6 +// Project: https://github.com/tkellen/node-rechoir +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Extensions } from 'interpret'; + +export function prepare( + config: Extensions, + filepath: string, + requireFrom?: string +): true | Attempt[]; + +export interface Attempt { + moduleName: string; + module: any; + error: Error | null; +} diff --git a/types/rechoir/rechoir-tests.ts b/types/rechoir/rechoir-tests.ts new file mode 100644 index 0000000000..de4b18c74f --- /dev/null +++ b/types/rechoir/rechoir-tests.ts @@ -0,0 +1,6 @@ +import { extensions as config } from 'interpret'; +import { prepare } from 'rechoir'; + +// $ExpectType true | Attempt[] +prepare(config, './test/fixtures/test.coffee'); +prepare(config, './test/fixtures/test.coffee', './'); diff --git a/types/rechoir/tsconfig.json b/types/rechoir/tsconfig.json new file mode 100644 index 0000000000..03a006d997 --- /dev/null +++ b/types/rechoir/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", + "rechoir-tests.ts" + ] +} diff --git a/types/rechoir/tslint.json b/types/rechoir/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rechoir/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index e44ca48706..fc9ec4f15f 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -152,7 +152,7 @@ declare module 'recompose' { [updaterName: string]: StateHandler; }; type StateUpdaters = { - [updaterName in keyof TUpdaters]: (state: TState, props: TOutter) => StateHandler; + [updaterName in keyof TUpdaters]: (state: TState, props: TOutter) => TUpdaters[updaterName]; }; export function withStateHandlers, TOutter = {}>( createProps: TState | mapper, @@ -273,10 +273,10 @@ declare module 'recompose' { // fromRenderProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#fromrenderprops export function fromRenderProps( - RenderPropsComponent: StatelessComponent, - propsMapper: (props: TRenderProps) => Partial, + RenderPropsComponent: Component, + propsMapper: (props: TRenderProps) => TInner, renderPropName?: string - ): ComponentEnhancer; + ): ComponentEnhancer; // Static property helpers: https://github.com/acdlite/recompose/blob/master/docs/API.md#static-property-helpers diff --git a/types/recompose/recompose-tests.tsx b/types/recompose/recompose-tests.tsx index a0ba38a87a..53cf796fd6 100644 --- a/types/recompose/recompose-tests.tsx +++ b/types/recompose/recompose-tests.tsx @@ -521,18 +521,30 @@ function testFromRenderProps() { interface InnerProps { renderValue: string; - outterValue: number; } interface OutterProps { outterValue: number; } - const RenderPropComponent: React.StatelessComponent<{ - render: (renderProps: RenderProps) => React.ReactElement; - }> = ({ render }) => render({ value: 'test' }); + interface ComponentProps { + renderValue: string; + outterValue: number; + } - const component: React.StatelessComponent = ({ renderValue }) =>

    {renderValue}
    ; + interface RenderComponentProps { + render: (renderProps: RenderProps) => React.ReactElement; + } + + class RenderPropComponent extends React.Component { + render () { + return this.props.render({ value: 'test' }); + } + } + + const component: React.StatelessComponent = ({ outterValue, renderValue }) => ( +
    {outterValue}{renderValue}
    + ); const Enhanced = fromRenderProps( RenderPropComponent, diff --git a/types/redent/index.d.ts b/types/redent/index.d.ts new file mode 100644 index 0000000000..0f540413e3 --- /dev/null +++ b/types/redent/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for redent 2.0 +// Project: https://github.com/sindresorhus/redent#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = redent; + +declare function redent(input: string, count?: number, indent?: string): string; diff --git a/types/redent/redent-tests.ts b/types/redent/redent-tests.ts new file mode 100644 index 0000000000..b2283882a6 --- /dev/null +++ b/types/redent/redent-tests.ts @@ -0,0 +1,8 @@ +import redent = require('redent'); + +// $ExpectType string +redent('\n foo\n bar\n'); +// $ExpectType string +redent('\n foo\n bar\n', 1); +// $ExpectType string +redent('\n foo\n bar\n', 1, ' '); diff --git a/types/redent/tsconfig.json b/types/redent/tsconfig.json new file mode 100644 index 0000000000..5e977c1134 --- /dev/null +++ b/types/redent/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", + "redent-tests.ts" + ] +} diff --git a/types/redent/tslint.json b/types/redent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/redent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/redux-action/index.d.ts b/types/redux-action/index.d.ts index dc5b9e5229..51c3cc3b61 100644 --- a/types/redux-action/index.d.ts +++ b/types/redux-action/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/coderhaoxin/redux-action // Definitions by: newraina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /** * inspired by @types/redux-actions, thanks. diff --git a/types/redux-action/package.json b/types/redux-action/package.json index 0a14f5edc6..7cc600c266 100644 --- a/types/redux-action/package.json +++ b/types/redux-action/package.json @@ -1,7 +1,6 @@ { "private": true, "dependencies": { - "redux": "^3.6.0", - "redux-thunk": "^2.2.0" + "redux": "^4.0.1" } } diff --git a/types/redux-action/redux-action-tests.ts b/types/redux-action/redux-action-tests.ts index 2290ed9a3f..d1b065c08f 100644 --- a/types/redux-action/redux-action-tests.ts +++ b/types/redux-action/redux-action-tests.ts @@ -1,5 +1,4 @@ import * as ReduxAction from 'redux-action'; -import * as ReduxThunk from 'redux-thunk'; import * as Redux from 'redux'; interface Payload { @@ -11,7 +10,7 @@ const dispatch: Redux.Dispatch = (...args: any[]): any => { }; const actionCreator0 = ReduxAction.createAction('get items'); -dispatch(actionCreator0(1)) +actionCreator0(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: Payload = action.payload; @@ -19,7 +18,7 @@ dispatch(actionCreator0(1)) const actionCreator1 = ReduxAction.createAction(); -dispatch(actionCreator1(1)) +actionCreator1(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: Payload = action.payload; @@ -27,7 +26,7 @@ dispatch(actionCreator1(1)) const actionCreator2 = ReduxAction.createAction('get items', (name: string) => name); -dispatch(actionCreator2(1)) +actionCreator2(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: string = action.payload; @@ -35,7 +34,7 @@ dispatch(actionCreator2(1)) const actionCreator3 = ReduxAction.createAction('get items', (name: string) => Promise.resolve(name)); -dispatch(actionCreator3(1)) +actionCreator3(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: string = action.payload; @@ -43,7 +42,7 @@ dispatch(actionCreator3(1)) const actionCreator4 = ReduxAction.createAction((name: string) => name); -dispatch(actionCreator4(1)) +actionCreator4(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: string = action.payload; @@ -51,7 +50,7 @@ dispatch(actionCreator4(1)) const actionCreator5 = ReduxAction.createAction((name: string) => 1); -dispatch(actionCreator5('items')) +actionCreator5('items')(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: number = action.payload; @@ -59,7 +58,7 @@ dispatch(actionCreator5('items')) const actionCreator6 = ReduxAction.createAction((name: string) => 1); -dispatch(actionCreator6('items', false)) +actionCreator6('items', false)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: number = action.payload; @@ -80,4 +79,4 @@ const reducer = ReduxAction.createReducer({ name: 'name' }, { } }); -const combinedReducer: Redux.Reducer = Redux.combineReducers({ reducer }); +const combinedReducer: Redux.Reducer<{ reducer: State }> = Redux.combineReducers<{ reducer: State }>({ reducer }); diff --git a/types/redux-auth-wrapper/index.d.ts b/types/redux-auth-wrapper/index.d.ts index 728be4a54b..3ec88b50dc 100644 --- a/types/redux-auth-wrapper/index.d.ts +++ b/types/redux-auth-wrapper/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mjrussell/redux-auth-wrapper // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { ComponentClass, StatelessComponent, ComponentType, ReactType } from "react"; diff --git a/types/redux-devtools/index.d.ts b/types/redux-devtools/index.d.ts index 234fb9a4bb..ddead025ff 100644 --- a/types/redux-devtools/index.d.ts +++ b/types/redux-devtools/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gaearon/redux-devtools // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import * as React from 'react'; import { GenericStoreEnhancer } from 'redux'; diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index e80c196c0a..5851728369 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -12,7 +12,7 @@ // Maddi Joyce // Kamil Wojcik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.9 +// TypeScript Version: 3.0 import { ComponentClass, StatelessComponent, diff --git a/types/redux-form/v6/index.d.ts b/types/redux-form/v6/index.d.ts index a8209a7643..5127457884 100644 --- a/types/redux-form/v6/index.d.ts +++ b/types/redux-form/v6/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full , Daniel Lytkin , Karol Janyst , Luka Zakrajsek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { ComponentClass, diff --git a/types/redux-saga-tester/index.d.ts b/types/redux-saga-tester/index.d.ts index fda97e494b..d7772626ef 100644 --- a/types/redux-saga-tester/index.d.ts +++ b/types/redux-saga-tester/index.d.ts @@ -1,27 +1,19 @@ // Type definitions for redux-saga-tester 1.0 // Project: https://github.com/wix/redux-saga-tester#readme -// Definitions by: Ben Lorantfy +// Definitions by: Ben Lorantfy , Law Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 + +import { Task } from 'redux-saga'; +import { AnyAction, Middleware, Reducer, ReducersMapObject } from 'redux'; -export interface AnyAction { - type: string; - [key: string]: any; -} -export type Reducer = (state: object, action: AnyAction) => object; -export interface ReducerMap { - [key: string]: Reducer; -} -export type ReduxMiddleware = (options: { dispatch: (action: AnyAction) => void, getState: () => object }) - => (next: (action: AnyAction) => any) - => any; export type SagaFunction = (...args: any[]) => any; -export interface SagaTesterOptions { +export interface SagaTesterOptions { initialState?: StateType; - reducers?: ReducerMap|Reducer; - middlewares?: ReduxMiddleware[]; - combineReducers?: (map: ReducerMap) => Reducer; + reducers?: ReducersMapObject | Reducer; + middlewares?: Middleware[]; + combineReducers?: (map: ReducersMapObject) => Reducer; ignoreReduxActions?: boolean; options?: object; } @@ -32,7 +24,7 @@ export default class SagaTester { /** * Starts execution of the provided saga. */ - start(saga: SagaFunction): void; + start(saga: SagaFunction, ...args: any[]): Task; /** * Dispatches an action to the redux store. diff --git a/types/redux-saga-tester/package.json b/types/redux-saga-tester/package.json new file mode 100644 index 0000000000..8d41143894 --- /dev/null +++ b/types/redux-saga-tester/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "redux": "^3.7.2", + "redux-saga": "^0.15.3" + } +} diff --git a/types/redux-saga-tester/redux-saga-tester-tests.ts b/types/redux-saga-tester/redux-saga-tester-tests.ts index 0dba716533..48eb490d0a 100644 --- a/types/redux-saga-tester/redux-saga-tester-tests.ts +++ b/types/redux-saga-tester/redux-saga-tester-tests.ts @@ -2,62 +2,79 @@ import SagaTester from 'redux-saga-tester'; // constructor with all options new SagaTester({ - initialState: { - orders: [], - }, - reducers: { - orders: (state, action) => state, - }, - middlewares: [ - ({ dispatch, getState }) => (next) => (action: { type: string }) => { - dispatch({ type: 'BLA' }); - getState(); - - return next(action); + initialState: { + orders: [], + }, + reducers: { + orders: (state, action) => state, + }, + middlewares: [ + ({dispatch, getState}) => (next) => (action) => { + dispatch({type: 'BLA'}); + getState(); + + return next(action); + }, + ], + ignoreReduxActions: false, + options: { + a: 23, }, - ], - ignoreReduxActions: false, - options: { - a: 23, - }, }); // constructor with function as reducers new SagaTester({ - reducers: (state, action) => state, + reducers: (state = {}, action) => state, +}); + +// constructor with reducer map +new SagaTester({ + reducers: { + a: (state, action) => state, + b: (state, action) => state, + c: (state, action) => state, + } }); // constructor with no options interface MockStateType { - orders: Array<{ name: string }>; + orders: Array<{ name: string }>; } -const sagaTester = new SagaTester({ initialState: { orders: [] }}); + +const sagaTester = new SagaTester({initialState: {orders: []}}); // start function* fakeSaga() { - return 23; + return 23; +} + +function* fakeSagaWithParams(param1: string, param2: number) { + return param1.length > param2; } sagaTester.start(fakeSaga); +sagaTester.start(fakeSagaWithParams, 'foo', 3); // dispatch -sagaTester.dispatch({ type: 'LOAD_ORDERS', orders: [] }); +sagaTester.dispatch({type: 'LOAD_ORDERS', orders: []}); // updateState -sagaTester.updateState({ orders: [] }); +sagaTester.updateState({orders: []}); // getState sagaTester.getState().orders; // waitFor -sagaTester.waitFor('LOAD_ORDERS').then(() => {}); -sagaTester.waitFor('LOAD_ORDERS', true).then(() => {}); +sagaTester.waitFor('LOAD_ORDERS').then(() => { +}); +sagaTester.waitFor('LOAD_ORDERS', true).then(() => { +}); // wasCalled -sagaTester.wasCalled("LOAD_ORDERS"); +sagaTester.wasCalled('LOAD_ORDERS'); // numCalled -sagaTester.numCalled("LOAD_ORDERS") === 1; +sagaTester.numCalled('LOAD_ORDERS') === 1; // getLatestCalledAction sagaTester.getLatestCalledAction().type; @@ -68,3 +85,8 @@ sagaTester.getCalledActions()[0].type; // getCalledActions sagaTester.reset(); sagaTester.reset(true); + +// getState +const state = sagaTester.getState(); +state.orders.length; +state.orders[0].name; diff --git a/types/replace-string/index.d.ts b/types/replace-string/index.d.ts new file mode 100644 index 0000000000..7819754746 --- /dev/null +++ b/types/replace-string/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for replace-string 2.0 +// Project: https://github.com/sindresorhus/replace-string#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = replaceString; + +declare function replaceString( + input: string, + needle: string, + replacement: string | replaceString.ReplacementFn, + options?: replaceString.Options +): string; + +declare namespace replaceString { + type ReplacementFn = ( + needle: string, + matchCount: number, + input: string, + matchIndex: number + ) => string; + + interface Options { + fromIndex?: number; + } +} diff --git a/types/replace-string/replace-string-tests.ts b/types/replace-string/replace-string-tests.ts new file mode 100644 index 0000000000..385ae1f023 --- /dev/null +++ b/types/replace-string/replace-string-tests.ts @@ -0,0 +1,21 @@ +import replaceString = require('replace-string'); + +const input = 'My friend has a 🐑. I want a 🐑 too!'; + +// $ExpectType string +replaceString(input, '🐑', '🦄'); +// $ExpectType string +replaceString(input, '🐑', (needle, matchCount, input, matchIndex) => { + // $ExpectType string + needle; + // $ExpectType number + matchCount; + // $ExpectType string + input; + // $ExpectType number + matchIndex; + + return '🦄'; +}); +// $ExpectType string +replaceString(input, '🐑', '🦄', { fromIndex: 1 }); diff --git a/types/replace-string/tsconfig.json b/types/replace-string/tsconfig.json new file mode 100644 index 0000000000..ef0dcb7937 --- /dev/null +++ b/types/replace-string/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", + "replace-string-tests.ts" + ] +} diff --git a/types/replace-string/tslint.json b/types/replace-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/replace-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/resolve-cwd/index.d.ts b/types/resolve-cwd/index.d.ts new file mode 100644 index 0000000000..65ffcb04f4 --- /dev/null +++ b/types/resolve-cwd/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for resolve-cwd 2.0 +// Project: https://github.com/sindresorhus/resolve-cwd#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = resolveCwd; + +declare function resolveCwd(moduleId: string): string; + +declare namespace resolveCwd { + function silent(moduleId: string): string | null; +} diff --git a/types/resolve-cwd/resolve-cwd-tests.ts b/types/resolve-cwd/resolve-cwd-tests.ts new file mode 100644 index 0000000000..bfd5db4ac2 --- /dev/null +++ b/types/resolve-cwd/resolve-cwd-tests.ts @@ -0,0 +1,7 @@ +import resolveCwd = require('resolve-cwd'); + +// $ExpectType string +resolveCwd('./foo'); + +// $ExpectType string | null +resolveCwd.silent('./foo'); diff --git a/types/resolve-cwd/tsconfig.json b/types/resolve-cwd/tsconfig.json new file mode 100644 index 0000000000..027baa2348 --- /dev/null +++ b/types/resolve-cwd/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", + "resolve-cwd-tests.ts" + ] +} diff --git a/types/resolve-cwd/tslint.json b/types/resolve-cwd/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/resolve-cwd/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/resolve-from/index.d.ts b/types/resolve-from/index.d.ts index da968fdaa8..9715d3ed25 100644 --- a/types/resolve-from/index.d.ts +++ b/types/resolve-from/index.d.ts @@ -1,7 +1,13 @@ -// Type definitions for resolve-from +// Type definitions for resolve-from 4.0 // Project: https://github.com/sindresorhus/resolve-from // Definitions by: unional +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function resolveFrom(fromDir: string, moduleId: string): string; -declare namespace resolveFrom {} + export = resolveFrom; + +declare function resolveFrom(fromDir: string, moduleId: string): string; + +declare namespace resolveFrom { + function silent(fromDir: string, moduleId: string): string | null; +} diff --git a/types/resolve-from/resolve-from-tests.ts b/types/resolve-from/resolve-from-tests.ts index ddbc5bdbea..dc645103ec 100644 --- a/types/resolve-from/resolve-from-tests.ts +++ b/types/resolve-from/resolve-from-tests.ts @@ -1,7 +1,6 @@ import resolveFrom = require("resolve-from"); -let from: string; -let moduleId: string; -let result: string; - -result = resolveFrom(from, moduleId); +// $ExpectType string +resolveFrom('foo', './bar'); +// $ExpectType string | null +resolveFrom.silent('foo', './baz'); diff --git a/types/resolve-from/tsconfig.json b/types/resolve-from/tsconfig.json index b1d826c64c..790d2f09ee 100644 --- a/types/resolve-from/tsconfig.json +++ b/types/resolve-from/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", "resolve-from-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/resolve-from/tslint.json b/types/resolve-from/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/resolve-from/tslint.json +++ b/types/resolve-from/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/resolve-from/v2/index.d.ts b/types/resolve-from/v2/index.d.ts new file mode 100644 index 0000000000..d29d0c1676 --- /dev/null +++ b/types/resolve-from/v2/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for resolve-from 2.0 +// Project: https://github.com/sindresorhus/resolve-from +// Definitions by: unional +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare function resolveFrom(fromDir: string, moduleId: string): string; +declare namespace resolveFrom {} +export = resolveFrom; diff --git a/types/resolve-from/v2/resolve-from-tests.ts b/types/resolve-from/v2/resolve-from-tests.ts new file mode 100644 index 0000000000..ddbc5bdbea --- /dev/null +++ b/types/resolve-from/v2/resolve-from-tests.ts @@ -0,0 +1,7 @@ +import resolveFrom = require("resolve-from"); + +let from: string; +let moduleId: string; +let result: string; + +result = resolveFrom(from, moduleId); diff --git a/types/resolve-from/v2/tsconfig.json b/types/resolve-from/v2/tsconfig.json new file mode 100644 index 0000000000..d9f3015659 --- /dev/null +++ b/types/resolve-from/v2/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "resolve-from": [ + "resolve-from/v2" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "resolve-from-tests.ts" + ] +} diff --git a/types/resolve-from/v2/tslint.json b/types/resolve-from/v2/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/resolve-from/v2/tslint.json @@ -0,0 +1,79 @@ +{ + "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 + } +} diff --git a/types/resolve-global/index.d.ts b/types/resolve-global/index.d.ts new file mode 100644 index 0000000000..30f6e563d9 --- /dev/null +++ b/types/resolve-global/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for resolve-global 0.1 +// Project: https://github.com/sindresorhus/resolve-global#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = resolveGlobal; + +declare function resolveGlobal(moduleId: string): string; + +declare namespace resolveGlobal { + function silent(moduleId: string): string | null; +} diff --git a/types/resolve-global/resolve-global-tests.ts b/types/resolve-global/resolve-global-tests.ts new file mode 100644 index 0000000000..6a1270c368 --- /dev/null +++ b/types/resolve-global/resolve-global-tests.ts @@ -0,0 +1,6 @@ +import resolveGlobal = require('resolve-global'); + +// $ExpectType string +resolveGlobal('cat-names'); +// $ExpectType string | null +resolveGlobal.silent('cat-names'); diff --git a/types/resolve-global/tsconfig.json b/types/resolve-global/tsconfig.json new file mode 100644 index 0000000000..141f47e1aa --- /dev/null +++ b/types/resolve-global/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", + "resolve-global-tests.ts" + ] +} diff --git a/types/resolve-global/tslint.json b/types/resolve-global/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/resolve-global/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/resolve-pkg/index.d.ts b/types/resolve-pkg/index.d.ts new file mode 100644 index 0000000000..61d9fd3152 --- /dev/null +++ b/types/resolve-pkg/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for resolve-pkg 1.0 +// Project: https://github.com/sindresorhus/resolve-pkg +// Definitions by: Meno Abels +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = resolvePkg; + +declare function resolvePkg(moduleId: string, options?: resolvePkg.Options): string; + +declare namespace resolvePkg { + interface Options { + cwd?: boolean; + } +} diff --git a/types/resolve-pkg/resolve-pkg-tests.ts b/types/resolve-pkg/resolve-pkg-tests.ts new file mode 100644 index 0000000000..e4540e2ee9 --- /dev/null +++ b/types/resolve-pkg/resolve-pkg-tests.ts @@ -0,0 +1,9 @@ +import rpkg = require('resolve-pkg'); +import resolvePkg = require('resolve-pkg'); + +// $ExpectType string +rpkg('hello'); +rpkg('hello', {}); +rpkg('hello', { cwd: true }); + +const resolvePkgOpts: resolvePkg.Options = {}; diff --git a/types/resolve-pkg/tsconfig.json b/types/resolve-pkg/tsconfig.json new file mode 100644 index 0000000000..04c11fa02f --- /dev/null +++ b/types/resolve-pkg/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", + "resolve-pkg-tests.ts" + ] +} diff --git a/types/resolve-pkg/tslint.json b/types/resolve-pkg/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/resolve-pkg/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rethinkdb/index.d.ts b/types/rethinkdb/index.d.ts index 87293230a9..d54856f08c 100644 --- a/types/rethinkdb/index.d.ts +++ b/types/rethinkdb/index.d.ts @@ -377,7 +377,7 @@ declare module "rethinkdb" { /** * Turn a sequence into an array or object, necessary when merging a sequence. - * + * * See: https://www.rethinkdb.com/api/javascript/coerce_to/ */ coerceTo(key: 'array'): Expression; @@ -539,6 +539,7 @@ declare module "rethinkdb" { le(value: T): Expression; add(n: number): Expression; + add(n: Expression): Expression; /** * Subtract two numbers. diff --git a/types/ripemd160/index.d.ts b/types/ripemd160/index.d.ts new file mode 100644 index 0000000000..27de423a18 --- /dev/null +++ b/types/ripemd160/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for ripemd160 2.0 +// Project: https://github.com/crypto-browserify/ripemd160#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Hash } from 'crypto'; + +export = RIPEMD160; + +declare const RIPEMD160: RIPEMD160Static; + +interface RIPEMD160Static { + new (): Hash; +} diff --git a/types/ripemd160/ripemd160-tests.ts b/types/ripemd160/ripemd160-tests.ts new file mode 100644 index 0000000000..3a78efbac3 --- /dev/null +++ b/types/ripemd160/ripemd160-tests.ts @@ -0,0 +1,7 @@ +import RIPEMD160 = require('ripemd160'); + +new RIPEMD160().update('42').digest('hex'); + +const ripemd160stream = new RIPEMD160(); +ripemd160stream.end('42'); +(ripemd160stream.read() as Buffer).toString('hex'); diff --git a/types/ripemd160/tsconfig.json b/types/ripemd160/tsconfig.json new file mode 100644 index 0000000000..07abc9bd05 --- /dev/null +++ b/types/ripemd160/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", + "ripemd160-tests.ts" + ] +} diff --git a/types/ripemd160/tslint.json b/types/ripemd160/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ripemd160/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/roman-numerals/index.d.ts b/types/roman-numerals/index.d.ts new file mode 100644 index 0000000000..0ab8e88047 --- /dev/null +++ b/types/roman-numerals/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for roman-numerals 0.3 +// Project: https://github.com/joshleaves/roman-numerals +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function toRoman(arabic: number): string; +export function toArabic(roman: string): number; diff --git a/types/roman-numerals/roman-numerals-tests.ts b/types/roman-numerals/roman-numerals-tests.ts new file mode 100644 index 0000000000..a99972afae --- /dev/null +++ b/types/roman-numerals/roman-numerals-tests.ts @@ -0,0 +1,5 @@ +import { toArabic, toRoman } from "roman-numerals"; + +const XLII: string = toRoman(42); +const meaningOfLife: number = toArabic(XLII); +toRoman(meaningOfLife); diff --git a/types/roman-numerals/tsconfig.json b/types/roman-numerals/tsconfig.json new file mode 100644 index 0000000000..7edc311353 --- /dev/null +++ b/types/roman-numerals/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", "roman-numerals-tests.ts"] +} diff --git a/types/roman-numerals/tslint.json b/types/roman-numerals/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/roman-numerals/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rosie/index.d.ts b/types/rosie/index.d.ts index 1078b53573..01dc76c5af 100644 --- a/types/rosie/index.d.ts +++ b/types/rosie/index.d.ts @@ -3,11 +3,13 @@ // Definitions by: Abner Oliveira , // Chris Grigg , // Alex Bukurov +// Adam Misiorny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 declare namespace rosie { interface IFactoryStatic { + new(): IFactory; /** * Defines a factory by name and constructor function. Call #attr and #option * on the result to define the properties of this factory. @@ -163,7 +165,8 @@ declare namespace rosie { * @param {function(number): *=} builder * @return {Factory} */ - sequence(name: keyof T, dependenciesOrBuilder?: () => any | keyof T[], builder?: Function) : IFactory; + sequence(name: K, builder?: (i: number) => any): IFactory; + sequence(name: K, dependencies: D[], builder: (i: number, ...args: any[]) => any): IFactory; /** * Sets a post-processor callback that will receive built objects and the diff --git a/types/rosie/rosie-tests.ts b/types/rosie/rosie-tests.ts index 6c2152a9e7..bb6b9defb8 100644 --- a/types/rosie/rosie-tests.ts +++ b/types/rosie/rosie-tests.ts @@ -19,6 +19,7 @@ resultObj = Factory.build('some'); Factory.define('coach') .option('buildPlayer', false) .sequence('id') + .sequence('name', (i: number) => `Coach${i}`) .attr('players', ['id', 'buildPlayer'], function(id: any, buildPlayer: boolean) { if (buildPlayer) { return [Factory.build('player', {coach_id: id})]; @@ -69,6 +70,21 @@ const person = Factory.build('Person'); let aString = ''; aString = person.firstName; +// Unregistered factories +const unregisteredPersonFactory = new Factory(); + +unregisteredPersonFactory.attr('firstName', 'John').sequence('id'); + +// Sequence with dependencies +unregisteredPersonFactory.sequence('lastName', ['age'], (i: number, age: number) => `Doe ${i} ${age}`) + +// Unregistered extended factories + +const unregisteredExtendedPersonFactory = new Factory().extend(unregisteredPersonFactory) + +unregisteredExtendedPersonFactory.attr('firstName', 'John2') +unregisteredExtendedPersonFactory.sequence('lastName', ['age'], (i: number) => `Doe2 ${i}`) + class CustomClass { type: string; diff --git a/types/sammy/tslint.json b/types/sammy/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/sammy/tslint.json +++ b/types/sammy/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/sasl-anonymous/index.d.ts b/types/sasl-anonymous/index.d.ts new file mode 100644 index 0000000000..b438a411d7 --- /dev/null +++ b/types/sasl-anonymous/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for sasl-anonymous 0.1 +// Project: https://github.com/jaredhanson/js-sasl-anonymous +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = AnonymousMechanism; + +declare class AnonymousMechanism implements Mechanism { + static Mechanism: typeof AnonymousMechanism; + static prototype: { + name: 'ANONYMOUS'; + clientFirst: true; + }; + + name: 'ANONYMOUS'; + clientFirst: true; + + response(cred: AnonymousMechanism.Credentials): string; + + challenge(chal: string): void; +} + +declare namespace AnonymousMechanism { + interface Credentials { + trace?: string; + } +} diff --git a/types/sasl-anonymous/sasl-anonymous-tests.ts b/types/sasl-anonymous/sasl-anonymous-tests.ts new file mode 100644 index 0000000000..dd993fa49d --- /dev/null +++ b/types/sasl-anonymous/sasl-anonymous-tests.ts @@ -0,0 +1,22 @@ +import AnonymousMechanism = require('sasl-anonymous'); +import { Mechanism } from 'sasl-anonymous'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(AnonymousMechanism); +new Factory().use(Mechanism); + +// $ExpectType "ANONYMOUS" +AnonymousMechanism.prototype.name; +// $ExpectType true +AnonymousMechanism.prototype.clientFirst; + +const m = new AnonymousMechanism(); + +// $ExpectType "ANONYMOUS" +m.name; +// $ExpectType true +m.clientFirst; +// $ExpectType string +m.response({ trace: 't' }); +// $ExpectType void +m.challenge('challenge'); diff --git a/types/sasl-anonymous/tsconfig.json b/types/sasl-anonymous/tsconfig.json new file mode 100644 index 0000000000..5a9ebd2f35 --- /dev/null +++ b/types/sasl-anonymous/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", + "sasl-anonymous-tests.ts" + ] +} diff --git a/types/sasl-anonymous/tslint.json b/types/sasl-anonymous/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-anonymous/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sasl-digest-md5/index.d.ts b/types/sasl-digest-md5/index.d.ts new file mode 100644 index 0000000000..001875f330 --- /dev/null +++ b/types/sasl-digest-md5/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for sasl-digest-md5 0.1 +// Project: https://github.com/jaredhanson/js-sasl-digest-md5 +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = DigestMd5Mechanism; + +declare class DigestMd5Mechanism implements Mechanism { + static Mechanism: typeof DigestMd5Mechanism; + static prototype: { + name: 'DIGEST-MD5'; + clientFirst: false; + }; + + name: 'DIGEST-MD5'; + clientFirst: false; + + constructor(options?: DigestMd5Mechanism.Options); + + response(cred: DigestMd5Mechanism.Credentials): string; + + challenge(chal: string): this; +} + +declare namespace DigestMd5Mechanism { + interface Options { + genNonce?: () => number; + } + + interface Credentials { + serviceType: string; + host: string; + username: string; + password: string; + serviceName?: string; + realm?: string; + authzid?: string; + } +} diff --git a/types/sasl-digest-md5/sasl-digest-md5-tests.ts b/types/sasl-digest-md5/sasl-digest-md5-tests.ts new file mode 100644 index 0000000000..f63c4b7359 --- /dev/null +++ b/types/sasl-digest-md5/sasl-digest-md5-tests.ts @@ -0,0 +1,30 @@ +import DigestMd5Mechanism = require('sasl-digest-md5'); +import { Mechanism } from 'sasl-digest-md5'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(DigestMd5Mechanism); +new Factory().use(Mechanism); + +// $ExpectType "DIGEST-MD5" +DigestMd5Mechanism.prototype.name; +// $ExpectType false +DigestMd5Mechanism.prototype.clientFirst; + +const m = new DigestMd5Mechanism(); +new DigestMd5Mechanism({ + genNonce() { + return 1; + }, +}); + +// $ExpectType "DIGEST-MD5" +m.name; +// $ExpectType false +m.clientFirst; +// $ExpectType string +m.response({ serviceType: 's', host: 'h', username: 'u', password: 'p' }); +m.response({ serviceType: 's', host: 'h', username: 'u', password: 'p', serviceName: 'sn' }); +m.response({ serviceType: 's', host: 'h', username: 'u', password: 'p', realm: 'r' }); +m.response({ serviceType: 's', host: 'h', username: 'u', password: 'p', authzid: 'a' }); +// $ExpectType DigestMd5Mechanism +m.challenge('challenge'); diff --git a/types/sasl-digest-md5/tsconfig.json b/types/sasl-digest-md5/tsconfig.json new file mode 100644 index 0000000000..84059391b2 --- /dev/null +++ b/types/sasl-digest-md5/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", + "sasl-digest-md5-tests.ts" + ] +} diff --git a/types/sasl-digest-md5/tslint.json b/types/sasl-digest-md5/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-digest-md5/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sasl-external/index.d.ts b/types/sasl-external/index.d.ts new file mode 100644 index 0000000000..06a90ce3a4 --- /dev/null +++ b/types/sasl-external/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for sasl-external 0.1 +// Project: https://github.com/jaredhanson/js-sasl-external +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = ExternalMechanism; + +declare class ExternalMechanism implements Mechanism { + static Mechanism: typeof ExternalMechanism; + static prototype: { + name: 'EXTERNAL'; + clientFirst: true; + }; + + name: 'EXTERNAL'; + clientFirst: true; + + response(cred: ExternalMechanism.Credentials): string; + + challenge(chal: string): void; +} + +declare namespace ExternalMechanism { + interface Credentials { + authzid?: string; + } +} diff --git a/types/sasl-external/sasl-external-tests.ts b/types/sasl-external/sasl-external-tests.ts new file mode 100644 index 0000000000..919721aec5 --- /dev/null +++ b/types/sasl-external/sasl-external-tests.ts @@ -0,0 +1,22 @@ +import ExternalMechanism = require('sasl-external'); +import { Mechanism } from 'sasl-external'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(ExternalMechanism); +new Factory().use(Mechanism); + +// $ExpectType "EXTERNAL" +ExternalMechanism.prototype.name; +// $ExpectType true +ExternalMechanism.prototype.clientFirst; + +const m = new ExternalMechanism(); + +// $ExpectType "EXTERNAL" +m.name; +// $ExpectType true +m.clientFirst; +// $ExpectType string +m.response({ authzid: 'a' }); +// $ExpectType void +m.challenge('challenge'); diff --git a/types/sasl-external/tsconfig.json b/types/sasl-external/tsconfig.json new file mode 100644 index 0000000000..b319008559 --- /dev/null +++ b/types/sasl-external/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", + "sasl-external-tests.ts" + ] +} diff --git a/types/sasl-external/tslint.json b/types/sasl-external/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-external/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sasl-plain/index.d.ts b/types/sasl-plain/index.d.ts new file mode 100644 index 0000000000..a1c5f61467 --- /dev/null +++ b/types/sasl-plain/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for sasl-plain 0.1 +// Project: https://github.com/jaredhanson/js-sasl-plain +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = PlainMechanism; + +declare class PlainMechanism implements Mechanism { + static Mechanism: typeof PlainMechanism; + static prototype: { + name: 'PLAIN'; + clientFirst: true; + }; + + name: 'PLAIN'; + clientFirst: true; + + response(cred: PlainMechanism.Credentials): string; + + challenge(chal: string): this; +} + +declare namespace PlainMechanism { + interface Credentials { + authzid?: string; + username: string; + password: string; + } +} diff --git a/types/sasl-plain/sasl-plain-tests.ts b/types/sasl-plain/sasl-plain-tests.ts new file mode 100644 index 0000000000..144d21451f --- /dev/null +++ b/types/sasl-plain/sasl-plain-tests.ts @@ -0,0 +1,23 @@ +import PlainMechanism = require('sasl-plain'); +import { Mechanism } from 'sasl-plain'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(PlainMechanism); +new Factory().use(Mechanism); + +// $ExpectType "PLAIN" +PlainMechanism.prototype.name; +// $ExpectType true +PlainMechanism.prototype.clientFirst; + +const m = new PlainMechanism(); + +// $ExpectType "PLAIN" +m.name; +// $ExpectType true +m.clientFirst; +// $ExpectType string +m.response({ username: 'u', password: 'pw' }); +m.response({ username: 'u', password: 'pw', authzid: 'a' }); +// $ExpectType PlainMechanism +m.challenge('challenge'); diff --git a/types/sasl-plain/tsconfig.json b/types/sasl-plain/tsconfig.json new file mode 100644 index 0000000000..3e33152c74 --- /dev/null +++ b/types/sasl-plain/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", + "sasl-plain-tests.ts" + ] +} diff --git a/types/sasl-plain/tslint.json b/types/sasl-plain/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-plain/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sasl-scram-sha-1/index.d.ts b/types/sasl-scram-sha-1/index.d.ts new file mode 100644 index 0000000000..d332b6126a --- /dev/null +++ b/types/sasl-scram-sha-1/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for sasl-scram-sha-1 1.2 +// Project: https://github.com/legastero/js-sasl-scram-sha-1 +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = ScramSha1Mechanism; + +declare class ScramSha1Mechanism implements Mechanism { + static Mechanism: typeof ScramSha1Mechanism; + static prototype: { + name: 'SCRAM-SHA-1'; + clientFirst: true; + }; + + name: 'SCRAM-SHA-1'; + clientFirst: true; + + constructor(options?: ScramSha1Mechanism.Options); + + response(cred: ScramSha1Mechanism.Credentials): string; + + challenge(chal: string): this; +} + +declare namespace ScramSha1Mechanism { + interface Options { + genNonce?: () => number; + } + + interface Credentials { + authzid?: string; + username?: string; + password?: string; + salt?: string; + saltedPassword?: string; + clientKey?: string; + serverKey?: string; + } +} diff --git a/types/sasl-scram-sha-1/sasl-scram-sha-1-tests.ts b/types/sasl-scram-sha-1/sasl-scram-sha-1-tests.ts new file mode 100644 index 0000000000..85eb648193 --- /dev/null +++ b/types/sasl-scram-sha-1/sasl-scram-sha-1-tests.ts @@ -0,0 +1,33 @@ +import ScramSha1Mechanism = require('sasl-scram-sha-1'); +import { Mechanism } from 'sasl-scram-sha-1'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(ScramSha1Mechanism); +new Factory().use(Mechanism); + +// $ExpectType "SCRAM-SHA-1" +ScramSha1Mechanism.prototype.name; +// $ExpectType true +ScramSha1Mechanism.prototype.clientFirst; + +const m = new ScramSha1Mechanism(); +new ScramSha1Mechanism({ + genNonce() { + return 1; + }, +}); + +// $ExpectType "SCRAM-SHA-1" +m.name; +// $ExpectType true +m.clientFirst; +// $ExpectType string +m.response({ authzid: 'a' }); +m.response({ username: 'u' }); +m.response({ password: 'pw' }); +m.response({ salt: 's' }); +m.response({ saltedPassword: 'sp' }); +m.response({ clientKey: 'ck' }); +m.response({ serverKey: 'sk' }); +// $ExpectType ScramSha1Mechanism +m.challenge('challenge'); diff --git a/types/sasl-scram-sha-1/tsconfig.json b/types/sasl-scram-sha-1/tsconfig.json new file mode 100644 index 0000000000..80181379ea --- /dev/null +++ b/types/sasl-scram-sha-1/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", + "sasl-scram-sha-1-tests.ts" + ] +} diff --git a/types/sasl-scram-sha-1/tslint.json b/types/sasl-scram-sha-1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-scram-sha-1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/saslmechanisms/index.d.ts b/types/saslmechanisms/index.d.ts new file mode 100644 index 0000000000..62f71e8a25 --- /dev/null +++ b/types/saslmechanisms/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for saslmechanisms 0.1 +// Project: https://github.com/jaredhanson/js-sasl +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Factory; + +declare class Factory { + static Factory: typeof Factory; + + use(name: string, mechanism: Factory.MechanismStatic): this; + use(mechanism: Factory.MechanismStatic): this; + create(mechanisms: string[]): Factory.Mechanism | null; +} + +declare namespace Factory { + interface MechanismStatic { + new (): Mechanism; + prototype: { + [key: string]: any; + name: string; + }; + } + interface Mechanism { + name: string; + + response(cred: { [key: string]: any }): string; + + challenge(chal: string): void; + } +} diff --git a/types/saslmechanisms/saslmechanisms-tests.ts b/types/saslmechanisms/saslmechanisms-tests.ts new file mode 100644 index 0000000000..d7e6fe7620 --- /dev/null +++ b/types/saslmechanisms/saslmechanisms-tests.ts @@ -0,0 +1,22 @@ +import Fct = require('saslmechanisms'); +import { Factory, MechanismStatic, Mechanism } from 'saslmechanisms'; + +const Mech: MechanismStatic = null as any; + +const factory = new Fct(); +new Factory(); +new Factory.Factory(); + +// $ExpectType Factory +factory.use(Mech); +factory.use('Mech', Mech); + +const mech: Mechanism | null = factory.create(['Mech']); +if (mech) { + // $ExpectType string + mech.name; + // $ExpectType string + mech.response({ foo: 'bar' }); + // $ExpectType void + mech.challenge('challenge'); +} diff --git a/types/saslmechanisms/tsconfig.json b/types/saslmechanisms/tsconfig.json new file mode 100644 index 0000000000..64beedfc0f --- /dev/null +++ b/types/saslmechanisms/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", + "saslmechanisms-tests.ts" + ] +} diff --git a/types/saslmechanisms/tslint.json b/types/saslmechanisms/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/saslmechanisms/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sass/index.d.ts b/types/sass/index.d.ts new file mode 100644 index 0000000000..bd416d9718 --- /dev/null +++ b/types/sass/index.d.ts @@ -0,0 +1,208 @@ +// Type definitions for sass 1.15 +// Project: https://github.com/sass/dart-sass +// Definitions by: Silas Rech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +export type ImporterReturnType = { file: string } | { contents: string } | Error | null; + +export type Importer = (url: string, prev: string, done: (data: ImporterReturnType) => void) => ImporterReturnType | void; + +export interface Options { + /** + * Path to a file to compile. + * + * @default null + */ + file?: string; + + /** + * A string to pass to compile. + * + * It is recommended that you use `includePaths` in conjunction with this so that sass can find files when using the @import directive. + * + * @default null + */ + data?: string; + + /** + * Handles when the @import directive is encountered. + * + * A custom importer allows extension of the sass engine in both a synchronous and asynchronous manner. + * + * @default undefined + */ + importer?: Importer | Importer[]; + + /** + * Holds a collection of custom functions that may be invoked by the sass files being compiled. + * + * @default undefined + */ + functions?: { [key: string]: () => void }; + + /** + * An array of paths that should be looked in to attempt to resolve your @import declarations. + * When using `data`, it is recommended that you use this. + * + * @default [] + */ + includePaths?: string[]; + + /** + * Enable Sass Indented Syntax for parsing the data string or file. + * + * @default false + */ + indentedSyntax?: boolean; + + /** + * Used to determine whether to use space or tab character for indentation. + * + * @default 'space' + */ + indentType?: 'space' | 'tab'; + + /** + * Used to determine the number of spaces or tabs to be used for indentation. + * + * @default 2 + */ + indentWidth?: number; + + /** + * Used to determine which sequence to use for line breaks. + * + * @default 'lf' + */ + linefeed?: 'cr' | 'crlf' | 'lf' | 'lfcr'; + + /** + * Disable the inclusion of source map information in the output file. + * + * @default false + */ + omitSourceMapUrl?: boolean; + + /** + * Specify the intended location of the output file. + * Strongly recommended when outputting source maps so that they can properly refer back to their intended files. + * + * @default null + */ + outFile?: string; + + /** + * Determines the output format of the final CSS style. + * + * @default 'expanded' + */ + outputStyle?: 'compressed' | 'expanded'; + + /** + * Enables the outputting of a source map. + * + * @default undefined + */ + sourceMap?: boolean | string; + + /** + * Includes the contents in the source map information. + * + * @default false + */ + sourceMapContents?: boolean; + + /** + * Embeds the source map as a data URI. + * + * @default false + */ + sourceMapEmbed?: boolean; + + /** + * The value will be emitted as `sourceRoot` in the source map information. + * + * @default undefined + */ + sourceMapRoot?: string; +} + +export interface SassException extends Error { + /** + * The error message. + */ + message: string; + + /** + * The formatted error. + */ + formatted: string; + + /** + * The line number of error. + */ + line: number; + + /** + * The column number of error. + */ + column: number; + + /** + * The status code. + */ + status: number; + + /** + * The filename of error. + * + * In case file option was not set (in favour of `data`), this will reflect the value `stdin`. + */ + file: string; +} + +export interface Result { + /** + * The compiled CSS. + * + * Write this to a file, or serve it out as needed. + */ + css: Buffer; + + /** + * The source map. + */ + map?: Buffer; + stats: { + /** + * The path to the scss file, or `data` if the source was not a file. + */ + entry: string; + + /** + * `Date.now()` before the compilation. + */ + start: number; + + /** + * `Date.now()` after the compilation. + */ + end: number; + + /** + * `end - start` + */ + duration: number; + + /** + * Absolute paths to all related files in no particular order. + */ + includedFiles: string[]; + }; +} + +export function render(options: Options, callback: (exception: SassException, result: Result) => void): void; +export function renderSync(options: Options): Result; diff --git a/types/sass/sass-tests.ts b/types/sass/sass-tests.ts new file mode 100644 index 0000000000..ae656d0a98 --- /dev/null +++ b/types/sass/sass-tests.ts @@ -0,0 +1,7 @@ +import * as sass from 'sass'; + +sass.renderSync({ + file: 'index.scss', + sourceMap: true, + outFile: 'index.css', +}); diff --git a/types/sass/tsconfig.json b/types/sass/tsconfig.json new file mode 100644 index 0000000000..11599da1da --- /dev/null +++ b/types/sass/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", + "sass-tests.ts" + ] +} diff --git a/types/sass/tslint.json b/types/sass/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sass/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sc-auth/index.d.ts b/types/sc-auth/index.d.ts new file mode 100644 index 0000000000..84f92bf674 --- /dev/null +++ b/types/sc-auth/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for sc-auth 5.0 +// Project: https://github.com/SocketCluster/sc-auth +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { VerifyOptions, VerifyCallback, Secret, SignCallback, SignOptions } from "jsonwebtoken"; + +export interface SCAuthEngine { + verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; + signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void; +} + +export class AuthEngine implements SCAuthEngine { + constructor(); + + verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; + signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void; +} diff --git a/types/sc-auth/sc-auth-tests.ts b/types/sc-auth/sc-auth-tests.ts new file mode 100644 index 0000000000..4fa57d3391 --- /dev/null +++ b/types/sc-auth/sc-auth-tests.ts @@ -0,0 +1,102 @@ +/** + * This mostly delegates to jwt, so using its tests as base + */ + +import scAuth = require("sc-auth"); +import fs = require("fs"); + +let signedToken = ""; +let cert: Buffer; + +interface TestObject { + foo: string; +} + +const testObject = { foo: "bar" }; + +const authEngine = new scAuth.AuthEngine(); + +// sign with default (HMAC SHA256) +authEngine.signToken(testObject, "shhhhh"); + +// sign with default (HMAC SHA256) and single audience +authEngine.signToken(testObject, "shhhhh", { audience: "theAudience" }); + +// sign with default (HMAC SHA256) and multiple audiences +authEngine.signToken(testObject, "shhhhh", { + audience: ["audience1", "audience2"] +}); + +// sign with default (HMAC SHA256) and a keyid +authEngine.signToken(testObject, "shhhhh", { keyid: "theKeyId" }); + +// sign with RSA SHA256 +cert = fs.readFileSync("private.key"); // get private key +authEngine.signToken(testObject, cert, { algorithm: "RS256" }); + +// sign with encrypted RSA SHA256 private key (only PEM encoding is supported) +const privKey: Buffer = fs.readFileSync("encrypted_private.key"); // get private key +const secret = { key: privKey.toString(), passphrase: "keypwd" }; +authEngine.signToken(testObject, secret, { algorithm: "RS256" }); // the algorithm option is mandatory in this case + +// sign asynchronously +authEngine.signToken(testObject, cert, { algorithm: "RS256" }, (err, token) => { + signedToken = token; +}); + +// verify a token symmetric +authEngine.verifyToken(signedToken, "shhhhh", {}, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// use external time for verifying +authEngine.verifyToken(signedToken, "shhhhh", { clockTimestamp: 1 }, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// invalid token +authEngine.verifyToken(signedToken, "wrong-secret", {}, (err, decoded) => { + console.log(err); + + // decoded undefined +}); + +// verify a token asymmetric +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, {}, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// verify audience +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { audience: "urn:foo" }, (err, decoded) => { + // if audience mismatch, err == invalid audience + console.log(err); +}); + +// verify issuer +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { audience: "urn:foo", issuer: "urn:issuer" }, (err, decoded) => { + // if issuer mismatch, err == invalid issuer + console.log(err); +}); + +// verify algorithm +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { algorithms: ["RS256"] }, (err, decoded) => { + // if algorithm mismatch, err == invalid algorithm + console.log(err); +}); + +// verify without expiration check +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { ignoreExpiration: true }, (err, decoded) => { + // if ignoreExpration == false and token is expired, err == expired token + console.log(err); +}); diff --git a/types/sc-auth/tsconfig.json b/types/sc-auth/tsconfig.json new file mode 100644 index 0000000000..5c8e3a1e19 --- /dev/null +++ b/types/sc-auth/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", + "sc-auth-tests.ts" + ] +} diff --git a/types/sc-auth/tslint.json b/types/sc-auth/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sc-auth/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sc-broker-cluster/clientcluster.d.ts b/types/sc-broker-cluster/clientcluster.d.ts new file mode 100644 index 0000000000..f2234df6ab --- /dev/null +++ b/types/sc-broker-cluster/clientcluster.d.ts @@ -0,0 +1,10 @@ +import { EventEmitter } from "events"; +import { SCBrokerClient } from "sc-broker"; +import { mapperFunction } from "."; + +export class ClientCluster extends EventEmitter { + constructor(clients: SCBrokerClient[]); + + setMapper(mapper: mapperFunction): void; + getMapper(): mapperFunction; +} diff --git a/types/sc-broker-cluster/index.d.ts b/types/sc-broker-cluster/index.d.ts new file mode 100644 index 0000000000..9314acda82 --- /dev/null +++ b/types/sc-broker-cluster/index.d.ts @@ -0,0 +1,160 @@ +// Type definitions for sc-broker-cluster 6.1 +// Project: https://github.com/SocketCluster/sc-broker-cluster +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCServerSocket, SCServer } from "socketcluster-server"; +import { BrokerStartInfo, BrokerExitInfo } from "socketcluster"; +import { SpliceOptions, QueryOptions } from "sc-broker"; +import { SCChannel } from "sc-channel"; +import { EventEmitter } from "events"; +import { AsyncResultArrayCallback } from "async"; +import { KeyChain, FlexiMap } from "fleximap"; +import { Keys } from "expirymanager"; +import { ClientCluster } from "./clientcluster"; + +export class AbstractDataClient extends EventEmitter { + constructor(dataClient: ClientCluster); + + set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void; + unexpire(keys: Keys, callback?: (err?: Error) => void): void; + + add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void; + + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void; + getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void; + + getAll(callback: (err: Error | null, value: any[] | object) => void): void; + + count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void; + + remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void; + remove(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void; + + removeAll(callback?: (err: Error) => void): void; + + splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void; + splice(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void; + + hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void; + + extractKeys(keyChain: KeyChain): string[]; + + extractValues(keyChain: KeyChain): any[]; + + exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void; + exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; +} + +export type handlerFunction = (data: any) => void; + +export type mapperFunction = (keyChain: KeyChain, method: string, clientIds: number[]) => number | number[]; + +/** + * The exchange object is a top-level SCBrokerClient which lets you publish events and manipulate data within your brokers - It represents a cluster of 1 or more brokers. + */ +export class SCExchange extends AbstractDataClient { + constructor(privateClientCluster: ClientCluster, publicClientCluster: ClientCluster, ioClusterClient: Client); + + send(data: any, mapIndex: number | string | string[] | null, callback?: (err?: Error) => void): void; + + publish(channelName: string, data: any, callback: (err?: Error) => void): void; + + subscribe(channelName: string): SCChannel; + unsubscribe(channelName: string): void; + + channel(channelName: string): SCChannel; + destroyChannel(channelName: string): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channelName: string, includePending?: boolean): boolean; + + watch(channelName: string, handler: handlerFunction): void; + unwatch(channelName: string, handler?: handlerFunction): void; + watchers(channelName: string): handlerFunction[]; + + setMapper(mapper: mapperFunction): void; + getMapper(): mapperFunction; + + map(keyChain: KeyChain, method: string): { type: string; targets: Client[] }; + + destroy(): void; +} + +export interface SCBrokerClusterServerOptions { + brokers: string[]; + debug?: boolean; + inspect?: boolean; + instanceId?: string; + secretKey?: string; + expiryAccuracy?: number; + downgradeToUser: number | string; + appBrokerControllerPath?: string; + processTermTimeout?: number; + ipcAckTimeout?: number; + brokerOptions?: SCServer.SCServerOptions; +} + +export class Server extends EventEmitter { + constructor(options: SCBrokerClusterServerOptions); + + on(event: "brokerStart", listener: (brokerInfo: BrokerStartInfo) => void): this; + on(event: "brokerExit", listener: (brokerInfo: BrokerExitInfo) => void): this; + on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "error", listener: (err?: Error) => void): this; + + sendToBroker(brokerId: string, data: any, callback: (err: Error | null, data: any) => void): void; + killBrokers(): void; + destroy(): void; +} + +export interface SCBrokerClusterClientOptions { + brokers: string[]; + secretKey?: string; + pubSubBatchDuration?: number; + connectRetryErrorThreshold: number; +} + +export interface MessagePacket { + channel: string; + data: any; +} + +export class Client extends EventEmitter { + constructor(options: SCBrokerClusterClientOptions); + + exchange(): SCExchange; + + options: SCBrokerClusterClientOptions; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "warning", listener: (warning?: Error) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "message", listener: (packet: MessagePacket) => void): this; + + destroy(callback: AsyncResultArrayCallback): void; + + subscribe(channel: string, callback: (err?: Error) => void): void; + unsubscribe(channel: string, callback: () => void): void; + unsubscribeAll(callback: () => void): void; + isSubscribed(channel: string, includePending: boolean): boolean; + + subscribeSocket(socket: SCServerSocket, channel: string, callback?: (err?: Error) => void): void; + unsubscribeSocket(socket: SCServerSocket, channel: string, callback?: () => void): void; + + setSCServer(scServer: SCServer): void; +} diff --git a/types/sc-broker-cluster/sc-broker-cluster-tests.ts b/types/sc-broker-cluster/sc-broker-cluster-tests.ts new file mode 100644 index 0000000000..0f5c274248 --- /dev/null +++ b/types/sc-broker-cluster/sc-broker-cluster-tests.ts @@ -0,0 +1,29 @@ +import { Client } from "sc-broker-cluster"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import WebSocket = require("ws"); + +const client = new Client({ + brokers: [], + secretKey: "secretKey", + pubSubBatchDuration: 100, + connectRetryErrorThreshold: 5 +}); + +client.on("error", err => {}); +client.on("warning", err => {}); + +const exchange = client.exchange(); + +const scServer = new SCServer(); +client.setSCServer(scServer); + +client.once("ready", () => {}); + +const wsSocket = new WebSocket("address"); +const socket = new SCServerSocket("id", scServer, wsSocket); +client.subscribeSocket(socket, "channelName", err => {}); + +client.unsubscribeSocket(socket, "channelName"); + +const data: any = {}; +exchange.publish("channelName", data, err => {}); diff --git a/types/sc-broker-cluster/scbroker.d.ts b/types/sc-broker-cluster/scbroker.d.ts new file mode 100644 index 0000000000..a7ddb7db87 --- /dev/null +++ b/types/sc-broker-cluster/scbroker.d.ts @@ -0,0 +1,3 @@ +import SCBroker = require("sc-broker/scbroker"); + +export = SCBroker; diff --git a/types/sc-broker-cluster/tsconfig.json b/types/sc-broker-cluster/tsconfig.json new file mode 100644 index 0000000000..8ace8fc9dc --- /dev/null +++ b/types/sc-broker-cluster/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clientcluster.d.ts", + "scbroker.d.ts", + "sc-broker-cluster-tests.ts" + ] +} diff --git a/types/sc-broker-cluster/tslint.json b/types/sc-broker-cluster/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-broker-cluster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sc-broker/index.d.ts b/types/sc-broker/index.d.ts new file mode 100644 index 0000000000..ccb83e880e --- /dev/null +++ b/types/sc-broker/index.d.ts @@ -0,0 +1,165 @@ +// Type definitions for sc-broker 5.1 +// Project: https://github.com/SocketCluster/sc-broker +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCServer } from "socketcluster-server"; +import { WorkerExitInfo } from "socketcluster"; +import { EventEmitter } from "events"; +import { KeyChain, FlexiMap } from "fleximap"; +import { Keys, Key } from "expirymanager"; + +export interface SCBrokerServerOptions { + id?: string; + instanceId?: string; + debug?: boolean; + inspect?: boolean; + socketPath?: string; + port?: number; + expiryAccuracy?: number; + downgradeToUser: number | string; + brokerControllerPath?: string; + processTermTimeout?: number; + ipcAckTimeout?: number; + secretKey?: string; + brokerOptions?: SCServer.SCServerOptions; +} + +export interface SCBrokerServer extends EventEmitter { + options: SCBrokerServerOptions; + socketPath?: string; + port?: number; + ipcAckTimeout: number; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this; + on(event: "ready", listener: (data: any) => void): this; + on(event: "exit", listener: (data: WorkerExitInfo) => void): this; + + sendToBroker(data: any, callback?: (err: Error | null, data: any, brokerId: string) => void): void; +} + +export function createServer(options?: SCBrokerServerOptions): SCBrokerServer; + +export interface AutoReconnectOptions { + initialDelay?: number; + randomness?: number; + multiplier?: number; + maxDelay?: number; +} + +export interface SCBrokerClientOptions { + secretKey?: string; + timeout?: number; + socketPath?: string; + port?: number; + host?: string; + autoReconnect?: boolean; + autoReconnectOptions?: AutoReconnectOptions; + connectRetryErrorThreshold?: number; + pubSubBatchDuration?: number; +} + +export interface QueryOptions { + baseKey?: KeyChain; + noAck?: boolean; + data?: any; +} + +export interface SpliceOptions { + index?: number; + count?: number; + items?: any[]; + getValue?: boolean; + noAck?: boolean; +} + +export interface SCBrokerClient extends EventEmitter { + readonly CONNECTED: "connected"; + readonly CONNECTING: "connecting"; + readonly DISCONNECTED: "disconnected"; + + socketPath?: string; + port?: number; + host?: string; + autoReconnect: boolean; + autoReconnectOptions?: AutoReconnectOptions; + connectRetryErrorThreshold: number; + state: "connected" | "connecting" | "disconnected"; + connectAttempts: number; + pendingReconnect: boolean; + pendingReconnectTimeout: number | null; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "warning", listener: (warning?: Error) => void): this; + on(event: "ready", listener: (data: any) => void): this; + on(event: "message", listener: (channel: string, data: any) => void): this; + on(event: "subscribeFail", listener: (err: Error | null, channel: string) => void): this; + on(event: "subscribe", listener: (channel: string) => void): this; + on(event: "unsubscribe", listener: () => void): this; + + isConnected(): boolean; + + subscribe(channel: string, ackCallback: (err?: Error) => void, force?: boolean): void; + unsubscribe(channel: string, ackCallback: (err?: Error) => void): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channel: string, includePending?: boolean): boolean; + + publish(channel: string, data: any, callback: (err?: Error) => void): void; + + send(data: any, callback: (err?: Error) => void): void; + + set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void; + unexpire(keys: Keys, callback?: (err?: Error) => void): void; + getExpiry(key: Key, callback?: (err?: Error) => void): number; + + add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + concat(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + concat(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void; + + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void; + getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void; + + getAll(callback: (err: Error | null, value: any[] | object) => void): void; + + count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void; + + exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void; + exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; + + query(query: (datamap: FlexiMap) => void, data?: any, callback?: (err: Error | null, data: any) => void): void; + query(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; + + remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void; + remove(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void; + + removeAll(callback?: (err: Error) => void): void; + + splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void; + splice(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void; + + hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void; + + extractKeys(keyChain: KeyChain): string[]; + + extractValues(keyChain: KeyChain): any[]; + + end(callback: (err?: Error) => void): void; +} + +export function createClient(options?: SCBrokerClientOptions): SCBrokerClient; diff --git a/types/sc-broker/sc-broker-tests.ts b/types/sc-broker/sc-broker-tests.ts new file mode 100644 index 0000000000..201ff10a27 --- /dev/null +++ b/types/sc-broker/sc-broker-tests.ts @@ -0,0 +1,58 @@ +import { SCServer, SCServerSocket } from "socketcluster-server"; +import SCBroker = require("sc-broker/scbroker"); +import { FlexiMap } from "fleximap"; +import { ExpiryManager } from "expirymanager"; + +//////////////////////////////////////////////////// +/// SCBroker tests +//////////////////////////////////////////////////// + +const options: SCServer.SCServerOptions = { port: 80 }; + +let scBroker = new SCBroker(); +scBroker = new SCBroker(options); +scBroker.options = { environment: "prod" }; + +const id: number = scBroker.id; +const instanceId: number = scBroker.instanceId; +const dataMap: FlexiMap = scBroker.dataMap; +const dataExpirer: ExpiryManager = scBroker.dataExpirer; +const subscriptions = scBroker.subscriptions; + +const socket: SCServerSocket = subscriptions[1]["test"]; + +scBroker.on("subscribe", channel => { + const subscribeChannel: string = channel; +}); +scBroker.on("unsubscribe", channel => { + const unsubscribeChannel: string = channel; +}); +scBroker.on("publish", (channel, data) => { + const publishChannel: string = channel; + const publishData: any = data; +}); +scBroker.on("masterMessage", (data, masterMessageResponse) => { + const masterMessageData: any = data; + masterMessageResponse(null, "test"); + masterMessageResponse(new Error(), null); +}); + +scBroker.publish("testChannel", 123); + +scBroker.exec(dataMap => { + dataMap.set(["main", "message"], "Message"); + return dataMap.get(["main"]); +}); + +scBroker.sendToMaster("data"); +scBroker.sendToMaster(123, (err, response) => { + if (!err) { + const answer = response; + } +}); + +class MyBroker extends SCBroker { + run() { + this.on("subscribe", channel => {}); + } +} diff --git a/types/sc-broker/scbroker.d.ts b/types/sc-broker/scbroker.d.ts new file mode 100644 index 0000000000..057b983adf --- /dev/null +++ b/types/sc-broker/scbroker.d.ts @@ -0,0 +1,32 @@ +import { EventEmitter } from "events"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import { FlexiMap, KeyChain } from "fleximap"; +import { ExpiryManager } from "expirymanager"; + +export = SCBroker; + +interface Subscriptions { + [socketId: number]: { + [channel: string]: SCServerSocket; + }; +} + +declare class SCBroker extends EventEmitter { + id: number; + options: SCServer.SCServerOptions; + instanceId: number; + dataMap: FlexiMap; + dataExpirer: ExpiryManager; + subscriptions: Subscriptions; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "subscribe" | "unsubscribe", listener: (channel: string) => void): this; + on(event: "publish", listener: (channel: string, data: any) => void): this; + on(event: "masterMessage", listener: (data: any, respond: (err: Error | null, responseData: any) => void) => void): this; + + publish(channel: string, message: any): void; + run(): void; + exec(query: (dataMap: FlexiMap, dataExpirer: ExpiryManager, subscriptions: Subscriptions) => any, baseKey?: KeyChain): any; + sendToMaster(data: any, callback?: (err: Error | null, responseData: any) => void): void; +} diff --git a/types/sc-broker/tsconfig.json b/types/sc-broker/tsconfig.json new file mode 100644 index 0000000000..6adfe07a5b --- /dev/null +++ b/types/sc-broker/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 + }, + "files": [ + "index.d.ts", + "scbroker.d.ts", + "sc-broker-tests.ts" + ] +} diff --git a/types/sc-broker/tslint.json b/types/sc-broker/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-broker/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sc-channel/index.d.ts b/types/sc-channel/index.d.ts new file mode 100644 index 0000000000..034723c0ba --- /dev/null +++ b/types/sc-channel/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for sc-channel 1.2 +// Project: https://github.com/SocketCluster/sc-channel +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Emitter = require("component-emitter"); +import { SCExchange, handlerFunction } from "sc-broker-cluster"; + +export interface SCChannelOptions { + waitForAuth?: boolean; + batch?: boolean; + data?: any; +} + +export class SCChannel extends Emitter { + readonly PENDING: "pending"; + readonly SUBSCRIBED: "subscribed"; + readonly UNSUBSCRIBED: "unsubscribed"; + + name: string; + state: ChannelState; + waitForAuth: boolean; + batch: boolean; + data: any; + + constructor(name: string, client: SCExchange, options?: SCChannelOptions); + + setOptions(options?: SCChannelOptions): void; + getState(): "pending" | "subscribed" | "unsubscribed"; + + subscribe(options?: any): void; + unsubscribe(): void; + isSubscribed(includePending?: boolean): boolean; + + publish(data: any, callback?: (err?: Error) => void): void; + + watch(handler: handlerFunction): void; + unwatch(handler?: handlerFunction): void; + watchers(): handlerFunction[]; + + destroy(): void; +} + +export type ChannelState = "pending" | "subscribed" | "unsubscribed"; diff --git a/types/sc-channel/sc-channel-tests.ts b/types/sc-channel/sc-channel-tests.ts new file mode 100644 index 0000000000..bfc90cee12 --- /dev/null +++ b/types/sc-channel/sc-channel-tests.ts @@ -0,0 +1,33 @@ +import { SCChannel, SCChannelOptions } from "sc-channel"; +import { handlerFunction, Client, SCBrokerClusterClientOptions } from "sc-broker-cluster"; + +const clientOptions: SCBrokerClusterClientOptions = { brokers: [], connectRetryErrorThreshold: 0 }; +const client = new Client(clientOptions); + +let channel = new SCChannel("channelName", client.exchange()); +const channelOptions: SCChannelOptions = {}; +channel = new SCChannel("channelName", client.exchange(), channelOptions); + +channel.state = channel.PENDING; +channel.state = channel.SUBSCRIBED; +channel.state = channel.UNSUBSCRIBED; + +const channelName: string = channel.name; + +const handler: handlerFunction = () => { }; + +channel.watch(handler); +channel.unwatch(); + +channel.subscribe(); +channel.subscribe(channelOptions); +channel.unsubscribe(); + +const data: any = channel.data; + +channel.emit("subscribe", channelName); +channel.emit("unsubscribe", channelName); + +channel.setOptions(channelOptions); + +channel.publish(data); diff --git a/types/sc-channel/tsconfig.json b/types/sc-channel/tsconfig.json new file mode 100644 index 0000000000..c5c5ce5f14 --- /dev/null +++ b/types/sc-channel/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", + "sc-channel-tests.ts" + ] +} diff --git a/types/sc-channel/tslint.json b/types/sc-channel/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-channel/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sdbm/index.d.ts b/types/sdbm/index.d.ts new file mode 100644 index 0000000000..e2edb994d0 --- /dev/null +++ b/types/sdbm/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for sdbm 1.0 +// Project: https://github.com/sindresorhus/sdbm#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = sdbm; + +declare function sdbm(string: string): number; diff --git a/types/sdbm/sdbm-tests.ts b/types/sdbm/sdbm-tests.ts new file mode 100644 index 0000000000..6b586efff1 --- /dev/null +++ b/types/sdbm/sdbm-tests.ts @@ -0,0 +1,4 @@ +import sdbm = require('sdbm'); + +// $ExpectType number +sdbm('🦄🌈'); diff --git a/types/sdbm/tsconfig.json b/types/sdbm/tsconfig.json new file mode 100644 index 0000000000..cad9717aae --- /dev/null +++ b/types/sdbm/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", + "sdbm-tests.ts" + ] +} diff --git a/types/sdbm/tslint.json b/types/sdbm/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sdbm/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/segment-analytics/tslint.json b/types/segment-analytics/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/segment-analytics/tslint.json +++ b/types/segment-analytics/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/selectize/tslint.json b/types/selectize/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/selectize/tslint.json +++ b/types/selectize/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/selenium-webdriver/index.d.ts b/types/selenium-webdriver/index.d.ts index aa8a696576..4fa0ccf7ac 100644 --- a/types/selenium-webdriver/index.d.ts +++ b/types/selenium-webdriver/index.d.ts @@ -4,7 +4,8 @@ // Yuki Kokubun , // Craig Nishina , // Simon Gellis , -// Ben Dixon +// Ben Dixon , +// Ziyu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -540,7 +541,7 @@ export namespace logging { * @param {string} name the logger's name. * @return {!Logger} the requested logger. */ - getLogger(name: string): Logger; + getLogger(name?: string): Logger; /** * Creates a new logger. @@ -552,6 +553,34 @@ export namespace logging { */ createLogger_(name: string, parent: Logger): Logger; } + + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + function getLogger(name?: string): Logger; + + /** + * Adds the console handler to the given logger. The console handler will log + * all messages using the JavaScript Console API. + * + * @param {Logger=} opt_logger The logger to add the handler to; defaults + * to the root logger. + */ + function addConsoleHandler(opt_logger?: Logger): void; + + /** + * Removes the console log handler from the given logger. + * + * @param {Logger=} opt_logger The logger to remove the handler from; defaults + * to the root logger. + * @see exports.addConsoleHandler + */ + function removeConsoleHandler(opt_logger?: Logger): void; } export namespace promise { diff --git a/types/selenium-webdriver/test/index.ts b/types/selenium-webdriver/test/index.ts index f8decdace1..84ffc6a8c2 100644 --- a/types/selenium-webdriver/test/index.ts +++ b/types/selenium-webdriver/test/index.ts @@ -758,6 +758,12 @@ function TestLogging() { type = webdriver.logging.Type.DRIVER; type = webdriver.logging.Type.PERFORMANCE; type = webdriver.logging.Type.SERVER; + + let logger: webdriver.logging.Logger = webdriver.logging.getLogger(); + webdriver.logging.addConsoleHandler(); + webdriver.logging.addConsoleHandler(logger); + webdriver.logging.removeConsoleHandler(); + webdriver.logging.removeConsoleHandler(logger); } function TestLoggingEntry() { diff --git a/types/semantic-ui-form/global.d.ts b/types/semantic-ui-form/global.d.ts index 8e5b2c20b8..1f3294c8d6 100644 --- a/types/semantic-ui-form/global.d.ts +++ b/types/semantic-ui-form/global.d.ts @@ -212,7 +212,7 @@ declare namespace SemanticUI { /** * Callback if a form is all valid */ - onSuccess(this: JQuery, event: JQuery.Event, fields: any): void; + onSuccess(this: JQuery, event: JQuery.TriggeredEvent, fields: any): void; /** * Callback if any form field is invalid */ diff --git a/types/semantic-ui-form/semantic-ui-form-tests.ts b/types/semantic-ui-form/semantic-ui-form-tests.ts index f17ca33112..d481cb00ad 100644 --- a/types/semantic-ui-form/semantic-ui-form-tests.ts +++ b/types/semantic-ui-form/semantic-ui-form-tests.ts @@ -144,7 +144,7 @@ function test_form() { }, onSuccess(event, fields) { this; // $ExpectType JQuery - event; // $ExpectType Event + event; // $ExpectType TriggeredEvent fields; // $ExpectType any }, onFailure(formErrors, fields) { diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index f25aacc3e4..6898a82ca4 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Sequelize 4.27.10 +// Type definitions for Sequelize 4.27.11 // Project: http://sequelizejs.com // Definitions by: samuelneff // Peter Harris @@ -15,6 +15,7 @@ // Nick Schultz // Thomas Breleur // Antoine Boisadam +// Dima Smirnov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -3290,6 +3291,11 @@ declare namespace sequelize { */ type FindOptionsAttributesArray = Array; + /** + * Shortcut for order type in FindOptions.attributes + */ + type FindOptionsOrderArray = Array | { model: Model, as?: string } | fn>; + /** * Options that are passed to any model creating a SELECT query * @@ -3330,7 +3336,7 @@ declare namespace sequelize { * first element is the column / function to order by, the second is the direction. For example: * `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not. */ - order?: string | col | literal | Array | { model: Model, as?: string }> | Array | { model: Model, as?: string }>>; + order?: string | col | literal | FindOptionsOrderArray | fn | Array; /** * Limit the results @@ -5240,13 +5246,13 @@ declare namespace sequelize { * `this.constructor.prototype.find.apply(this, arguments)` */ classMethods?: Object; - + /** * Change the database schema. PG only feature, but also works with other dialects. */ schema?: string; - - + + /** * Change the database schema delimiter. Defaults to "." on PG but for other dialects can be also changed to "_". */ diff --git a/types/sequelize/sequelize-tests.ts b/types/sequelize/sequelize-tests.ts index 6b7ea6ea0a..943fed79e3 100644 --- a/types/sequelize/sequelize-tests.ts +++ b/types/sequelize/sequelize-tests.ts @@ -946,6 +946,8 @@ User.findAll( { where : { user_id : 1 }, attributes : ['a', 'b'], include : [{ m User.findAll( { order : s.literal( 'email =' ) } ); User.findAll( { order : [s.literal( 'email = ' + s.escape( 'test@sequelizejs.com' ) )] } ); User.findAll( { order : [['id', ';DELETE YOLO INJECTIONS']] } ); +User.findAll( { order : s.random() } ); +User.findAll( { order : [s.random()] } ); User.findAll( { include : [User], order : [[User, 'id', ';DELETE YOLO INJECTIONS']] } ); User.findAll( { include : [User], order : [['id', 'ASC NULLS LAST'], [User, 'id', 'DESC NULLS FIRST']] } ); User.findAll( { include : [{ model : User, where : { title : 'DoDat' }, include : [{ model : User }] }] } ); diff --git a/types/serialport/index.d.ts b/types/serialport/index.d.ts index 14ded3b6e3..c1a81376fa 100644 --- a/types/serialport/index.d.ts +++ b/types/serialport/index.d.ts @@ -103,7 +103,7 @@ declare namespace SerialPort { constructor(options: {delimiter: string | Buffer | number[], encoding?: 'ascii'|'utf8'|'utf16le'|'ucs2'|'base64'|'binary'|'hex'}); } class Ready extends Stream.Transform { - constructor(options: {data: string | Buffer | number[]}); + constructor(options: {delimiter: string | Buffer | number[]}); } class Regex extends Stream.Transform { constructor(options: {regex: RegExp}); diff --git a/types/serialport/serialport-tests.ts b/types/serialport/serialport-tests.ts index 16cf2b6a70..d6541a63c2 100644 --- a/types/serialport/serialport-tests.ts +++ b/types/serialport/serialport-tests.ts @@ -107,7 +107,7 @@ function test_parsers() { const CCTalkParser = new SerialPort.parsers.CCTalk(); const DelimiterParser = new SerialPort.parsers.Delimiter({ delimiter: Buffer.from('EOL') }); const ReadlineParser = new SerialPort.parsers.Readline({ delimiter: '\r\n' }); - const ReadyParser = new SerialPort.parsers.Ready({ data: 'READY' }); + const ReadyParser = new SerialPort.parsers.Ready({ delimiter: 'READY' }); const RegexParser = new SerialPort.parsers.Regex({regex: /.*/}); port.pipe(ByteLengthParser); diff --git a/types/sha.js/index.d.ts b/types/sha.js/index.d.ts new file mode 100644 index 0000000000..d5dc4ba752 --- /dev/null +++ b/types/sha.js/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for sha.js 2.4 +// Project: https://github.com/crypto-browserify/sha.js +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Hash } from 'crypto'; + +export = SHA; + +declare function SHA(algorithm: string): Hash; + +declare namespace SHA { + type Algorithm = 'sha' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512'; + interface HashStatic { + new (): Hash; + } + + const sha: HashStatic; + const sha1: HashStatic; + const sha224: HashStatic; + const sha256: HashStatic; + const sha384: HashStatic; + const sha512: HashStatic; +} diff --git a/types/sha.js/sha.js-tests.ts b/types/sha.js/sha.js-tests.ts new file mode 100644 index 0000000000..fd3cde2e47 --- /dev/null +++ b/types/sha.js/sha.js-tests.ts @@ -0,0 +1,15 @@ +import shajs = require('sha.js'); + +shajs('sha256') + .update('42') + .digest('hex'); +new shajs.sha().update('42').digest('hex'); +new shajs.sha1().update('42').digest('hex'); +new shajs.sha224().update('42').digest('hex'); +new shajs.sha256().update('42').digest('hex'); +new shajs.sha384().update('42').digest('hex'); +new shajs.sha512().update('42').digest('hex'); + +const sha256stream = shajs('sha256'); +sha256stream.end('42'); +(sha256stream.read() as Buffer).toString('hex'); diff --git a/types/sha.js/tsconfig.json b/types/sha.js/tsconfig.json new file mode 100644 index 0000000000..9f10462f5a --- /dev/null +++ b/types/sha.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", + "sha.js-tests.ts" + ] +} diff --git a/types/sha.js/tslint.json b/types/sha.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sha.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sharepoint/sharepoint-tests.ts b/types/sharepoint/sharepoint-tests.ts index e76536cd18..d3bbe1f808 100644 --- a/types/sharepoint/sharepoint-tests.ts +++ b/types/sharepoint/sharepoint-tests.ts @@ -2038,7 +2038,7 @@ namespace _ { // do is retrieve a reference to the term set with the same ID as the div, and // then add the term that belong to that term set under the div that was clicked. - function showTerms(event: JQuery.Event, groupID: SP.Guid, termSetID: SP.Guid) { + function showTerms(event: JQuery.ClickEvent, groupID: SP.Guid, termSetID: SP.Guid) { // First, cancel the bubble so that the group div click handler does not also fire // because that removes all term set divs and we don't want that here. event.originalEvent.cancelBubble = true; diff --git a/types/shasum/index.d.ts b/types/shasum/index.d.ts new file mode 100644 index 0000000000..500c811d07 --- /dev/null +++ b/types/shasum/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for shasum 1.0 +// Project: https://github.com/dominictarr/shasum +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Single function that return the sha1sum. Installing this is just a little bit quicker than reading the crypto documentation. + * var shasum = require('shasum') + * shasum(string || buffer || object) + * It also works in the browser with browserify. + */ +declare function shasum(str: any, alg?: string | null, format?: "hex" | "latin1" | "base64"): string; + +export = shasum; diff --git a/types/shasum/shasum-tests.ts b/types/shasum/shasum-tests.ts new file mode 100644 index 0000000000..01c0ba32fc --- /dev/null +++ b/types/shasum/shasum-tests.ts @@ -0,0 +1,7 @@ +import shasum = require("shasum"); + +function test(): string { + const res1 = shasum("source"); + const res2 = shasum({ prop: "source" }, null, "hex"); + return res1 || res2; +} diff --git a/types/shasum/tsconfig.json b/types/shasum/tsconfig.json new file mode 100644 index 0000000000..a0be2a9c4b --- /dev/null +++ b/types/shasum/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", + "shasum-tests.ts" + ] +} \ No newline at end of file diff --git a/types/shasum/tslint.json b/types/shasum/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/shasum/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/shelljs/make.d.ts b/types/shelljs/make.d.ts new file mode 100644 index 0000000000..ca4c2b6135 --- /dev/null +++ b/types/shelljs/make.d.ts @@ -0,0 +1,41 @@ +import * as shelljs from './'; +declare global { + interface Target { + (...args: any[]): void; + result?: any; + done?: boolean; + } + const target: { + all?: Target; + [s: string]: Target; + }; + const cd: typeof shelljs.cd; + const pwd: typeof shelljs.pwd; + const ls: typeof shelljs.ls; + const find: typeof shelljs.find; + const cp: typeof shelljs.cp; + const rm: typeof shelljs.rm; + const mv: typeof shelljs.mv; + const mkdir: typeof shelljs.mkdir; + const cat: typeof shelljs.cat; + const sed: typeof shelljs.sed; + const grep: typeof shelljs.grep; + const echo: typeof shelljs.echo; + const pushd: typeof shelljs.pushd; + const popd: typeof shelljs.popd; + const dirs: typeof shelljs.dirs; + const ln: typeof shelljs.ln; + const exit: typeof shelljs.exit; + const env: typeof shelljs.env; + const exec: typeof shelljs.exec; + const chmod: typeof shelljs.chmod; + const tempdir: typeof shelljs.tempdir; + const error: typeof shelljs.error; + const touch: typeof shelljs.touch; + const head: typeof shelljs.head; + const sort: typeof shelljs.sort; + const tail: typeof shelljs.tail; + const uniq: typeof shelljs.uniq; + const set: typeof shelljs.set; + const config: typeof shelljs.config; +} diff --git a/types/shelljs/tsconfig.json b/types/shelljs/tsconfig.json index 7343a42a7e..51937bc2c0 100644 --- a/types/shelljs/tsconfig.json +++ b/types/shelljs/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "make.d.ts", "shelljs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/shorten-repo-url/index.d.ts b/types/shorten-repo-url/index.d.ts new file mode 100644 index 0000000000..94fc3a6836 --- /dev/null +++ b/types/shorten-repo-url/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for shorten-repo-url 1.5 +// Project: https://github.com/bfred-it/shorten-repo-url#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = shortenRepoUrl; + +declare function shortenRepoUrl(url: string, currentUrl?: string): string; + +declare namespace shortenRepoUrl { + function applyToLink(link: HTMLAnchorElement, currentUrl?: string): boolean; +} diff --git a/types/shorten-repo-url/shorten-repo-url-tests.ts b/types/shorten-repo-url/shorten-repo-url-tests.ts new file mode 100644 index 0000000000..8ff67ba9d2 --- /dev/null +++ b/types/shorten-repo-url/shorten-repo-url-tests.ts @@ -0,0 +1,14 @@ +import shortenRepoUrl = require('shorten-repo-url'); + +// $ExpectType string +shortenRepoUrl('https://github.com/nodejs/node/tree/v0.12/doc', 'https://github.com/nodejs/node'); +// $ExpectType string +shortenRepoUrl('https://github.com/nodejs/node/tree/v0.12/doc'); + +const link = document.createElement('a'); +link.setAttribute('href', 'https://github.com/nodejs/node/tree/v0.12/doc'); + +// $ExpectType boolean +shortenRepoUrl.applyToLink(link); +// $ExpectType boolean +shortenRepoUrl.applyToLink(link, 'https://github.com/nodejs/node'); diff --git a/types/shorten-repo-url/tsconfig.json b/types/shorten-repo-url/tsconfig.json new file mode 100644 index 0000000000..8b9890cac7 --- /dev/null +++ b/types/shorten-repo-url/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "shorten-repo-url-tests.ts" + ] +} diff --git a/types/shorten-repo-url/tslint.json b/types/shorten-repo-url/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/shorten-repo-url/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/should-sinon/index.d.ts b/types/should-sinon/index.d.ts index 79b04d5092..6544a55253 100644 --- a/types/should-sinon/index.d.ts +++ b/types/should-sinon/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/shouldjs/sinon // Definitions by: AryloYeung // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as s from 'sinon'; import should = require('should'); diff --git a/types/simpl-schema/index.d.ts b/types/simpl-schema/index.d.ts new file mode 100644 index 0000000000..b09a8fde96 --- /dev/null +++ b/types/simpl-schema/index.d.ts @@ -0,0 +1,246 @@ +// Type definitions for simpl-schema 0.1 +// Project: https://github.com/aldeed/simple-schema-js +// Definitions by: Andreas Richter +// Qkramer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ValidationContext extends SimpleSchemaValidationContextStatic { + addValidationErrors(errors: any): void; + clean(...args: any[]): any; + getErrorForKey(key: any, ...args: any[]): any; + reset(): void; + setValidationErrors(errors: any): void; + validationErrors(): any; +} + +interface CustomValidationContext { + /** The name of the schema key (e.g., "addresses.0.street") */ + key: string; + + /** The generic name of the schema key (e.g., "addresses.$.street") */ + genericKey: string; + + /** The schema definition object. */ + definition: SchemaDefinition; + + /** Does the object being validated have this key set? */ + isSet: boolean; + + /** Value to validate */ + value: any; + + /** The Mongo operator for which we're doing validation. Might be null. */ + operator: any; + validationContext: ValidationContext; + + /** + * Use this method to get information about other fields. Pass a field name + * (non-generic schema key) as the only argument. The return object will + * have isSet, value, and operator properties for that field. + */ + field(): any; + /** + * Use this method to get information about other fields that have the same + * parent object. Works the same way as field(). This is helpful when you use + * sub-schemas or when you're dealing with arrays of objects. + */ + siblingField(): any; + + /** + * Call this to add validation errors for any key. In general, you should use + * this to add errors for other keys. To add an error for the current key, + * return the error type string. If you do use this to add an error for the + * current key, return false from your custom validation function. + */ + addValidationErrors(errors: SimpleSchemaValidationError): any; +} + +interface SchemaDefinition { + type: any; + label?: string | (() => string); + optional?: boolean | (() => boolean); + min?: number | boolean | Date | (() => number | boolean | Date); + max?: number | boolean | Date | (() => number | boolean | Date); + minCount?: number | (() => number); + maxCount?: number | (() => number); + allowedValues?: any[] | (() => any[]); + decimal?: boolean; + exclusiveMax?: boolean; + exclusiveMin?: boolean; + regEx?: RegExp | RegExp[]; + /** + * For custom validation function. If you use an arrow function the context + * for "this" will not be available. Use "custom: function() { return + * something(this.value); }" instead. + */ + custom?: (this: CustomValidationContext) => undefined | string | SimpleSchemaValidationError; + blackbox?: boolean; + autoValue?: () => any; + defaultValue?: any; + trim?: boolean; +} + +interface CleanOption { + filter?: boolean; + autoConvert?: boolean; + removeEmptyStrings?: boolean; + trimStrings?: boolean; + getAutoValues?: boolean; + isModifier?: boolean; + extendAutoValueContext?: boolean; + removeNullsFromArrays?: boolean; +} + +interface SimpleSchemaOptions { + check?: boolean; + clean?: CleanOption; + defaultLabel?: string; + humanizeAutoLabels?: boolean; + requiredByDefault?: boolean; + tracker?: any; +} + +interface SimpleSchemaValidationError { + type: string; + [key: string]: number | string; +} + +interface SimpleSchemaStatic { + new( + schema: { + [key: string]: SchemaDefinition + | BooleanConstructor | StringConstructor | NumberConstructor | DateConstructor + | ArrayConstructor + | string | RegExp + | SimpleSchema + } | any[], + options?: SimpleSchemaOptions + ): SimpleSchema; + namedContext(name?: string): SimpleSchemaValidationContextStatic; + addValidator(validator: () => boolean): any; + pick(...fields: string[]): SimpleSchemaStatic; + omit(...fields: string[]): SimpleSchemaStatic; + clean(doc: any, options?: CleanOption): any; + schema(key?: string): SchemaDefinition | SchemaDefinition[]; + getDefinition(key: string, propList?: any, functionContext?: any): any; + keyIsInBlackBox(key: string): boolean; + labels(labels: {[key: string]: string}): void; + label(key: any): any; + Integer: RegExp; + messages(messages: any): any; + messageForError(type: any, key: any, def: any, value: any): string; + allowsKey(key: any): string; + newContext(): ValidationContext; + objectKeys(keyPrefix: any): any[]; + validate(obj: any, options?: ValidationOption): void; + validator(options: ValidationOption): () => boolean; + RegEx: { + Email: RegExp; + EmailWithTLD: RegExp; + Domain: RegExp; + WeakDomain: RegExp; + IP: RegExp; + IPv4: RegExp; + IPv6: RegExp; + Url: RegExp; + Id: RegExp; + ZipCode: RegExp; + Phone: RegExp; + }; + ErrorTypes: { + REQUIRED: string, + MIN_STRING: string, + MAX_STRING: string, + MIN_NUMBER: string, + MAX_NUMBER: string, + MIN_NUMBER_EXCLUSIVE: string, + MAX_NUMBER_EXCLUSIVE: string, + MIN_DATE: string, + MAX_DATE: string, + BAD_DATE: string, + MIN_COUNT: string, + MAX_COUNT: string, + MUST_BE_INTEGER: string, + VALUE_NOT_ALLOWED: string, + EXPECTED_TYPE: string, + FAILED_REGULAR_EXPRESSION: string, + KEY_NOT_IN_SCHEMA: string + }; +} + +interface ValidationOption { + modifier?: boolean; + upsert?: boolean; + clean?: boolean; + filter?: boolean; + upsertextendedCustomContext?: boolean; + keys?: string[]; +} + +interface SimpleSchemaValidationContextStaticKeys { + name: string; + type: string; + value?: any; +} + +interface SimpleSchemaError { + name: string; + type: string; +} + +interface SimpleSchemaValidationContextStatic { + validate(obj: any, options?: ValidationOption): boolean; + validateOne(doc: any, keyName: string, options?: ValidationOption): boolean; + resetValidation(): void; + isValid(): boolean; + invalidKeys(): SimpleSchemaValidationContextStaticKeys[]; + addInvalidKeys(errors: SimpleSchemaError[]): void; + keyIsInvalid(name: any): boolean; + keyErrorMessage(name: any): string; + getErrorObject(): any; +} + +interface MongoObjectStatic { + forEachNode(func: (() => void), options?: {endPointsOnly: boolean}): void; + getValueForPosition(position: string): any; + setValueForPosition(position: string, value: any): void; + removeValueForPosition(position: string): void; + getKeyForPosition(position: string): any; + getGenericKeyForPosition(position: string): any; + getInfoForKey(key: string): any; + getPositionForKey(key: string): string; + getPositionsForGenericKey(key: string): string[]; + getValueForKey(key: string): any; + addKey(key: string, val: any, op: string): any; + removeGenericKeys(keys: string[]): void; + removeGenericKey(key: string): void; + removeKey(key: string): void; + removeKeys(keys: string[]): void; + filterGenericKeys(test: (() => boolean)): void; + setValueForKey(key: string, val: any): void; + setValueForGenericKey(key: string, val: any): void; + getObject(): any; + getFlatObject(options?: {keepArrays?: boolean}): any; + affectsKey(key: string): any; + affectsGenericKey(key: string): any; + affectsGenericKeyImplicit(key: string): any; +} + +export const SimpleSchema: SimpleSchemaStatic; +export const SimpleSchemaValidationContext: SimpleSchemaValidationContextStatic; +export const MongoObject: MongoObjectStatic; + +export interface SimpleSchema extends SimpleSchemaStatic { + debug: boolean; + /** Validate a data object. Options: {keys: []} to limit */ + validate(obj: any, options?: ValidationOption): void; + addValidator(validator: () => boolean): any; + extendOptions(options: {[key: string]: any}): void; + messages(messages: any): void; +} + +export interface MongoObject { + expandKey(val: any, key: string, obj: any): void; +} + +export default SimpleSchema; diff --git a/types/simpl-schema/simpl-schema-tests.ts b/types/simpl-schema/simpl-schema-tests.ts new file mode 100644 index 0000000000..a3555c4428 --- /dev/null +++ b/types/simpl-schema/simpl-schema-tests.ts @@ -0,0 +1,77 @@ +import SimpleSchema from 'simpl-schema'; + +const StringSchema = new SimpleSchema({ + basicString: { + type: String + }, + limitedString: { + type: String, + allowedValues: ['pro', 'con'] + }, + regExpString: { + type: String, + regEx: SimpleSchema.RegEx.Id + }, + createdAt: { + type: Date, + autoValue: () => new Date() + }, + title: { + type: String, + label: "Title", + /* Can't use arrow function here, else the context won't be available */ + custom: function() { + const text = this.value; + + if (text.length > 100) return { type: SimpleSchema.ErrorTypes.MAX_STRING, max: 100 }; + else if (text.length < 10) return SimpleSchema.ErrorTypes.MIN_STRING; + } + } +}); + +StringSchema.validate({ + basicString: "Test", + limitedString: "pro", + regExpString: "id" +}, {keys: ['basicString']}); + +const StringSchemaWithOptions = new SimpleSchema({ + basicString: { + type: String + }, + limitedString: { + type: String, + allowedValues: ['pro', 'con'] + }, + subschema: { + type: StringSchema + }, + userId: { + type: String, + regEx: SimpleSchema.RegEx.Id + }, + createdAt: { + type: Date, + autoValue: () => new Date(), + }, +}, +{ + clean: { + filter: true, + autoConvert: true, + removeEmptyStrings: true, + trimStrings: true, + getAutoValues: true, + removeNullsFromArrays: true, + } +}); + +new SimpleSchema({ + shortBoolean: Boolean, + shortString: String, + shortNumber: Number, + shortInteger: SimpleSchema.Integer, + shortDate: Date, + shortArray: Array, + subSchema: StringSchemaWithOptions +}); diff --git a/types/simpl-schema/tsconfig.json b/types/simpl-schema/tsconfig.json new file mode 100644 index 0000000000..d079496f4e --- /dev/null +++ b/types/simpl-schema/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", + "simpl-schema-tests.ts" + ] +} diff --git a/types/simpl-schema/tslint.json b/types/simpl-schema/tslint.json new file mode 100644 index 0000000000..3043773b06 --- /dev/null +++ b/types/simpl-schema/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "object-literal-shorthand": false + } +} diff --git a/types/sindresorhus__class-names/index.d.ts b/types/sindresorhus__class-names/index.d.ts new file mode 100644 index 0000000000..fbb81c48c6 --- /dev/null +++ b/types/sindresorhus__class-names/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for @sindresorhus/class-names 1.0 +// Project: https://github.com/sindresorhus/class-names +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = classNames; + +declare function classNames(...input: any[]): string; diff --git a/types/sindresorhus__class-names/sindresorhus__class-names-tests.ts b/types/sindresorhus__class-names/sindresorhus__class-names-tests.ts new file mode 100644 index 0000000000..d8627cb705 --- /dev/null +++ b/types/sindresorhus__class-names/sindresorhus__class-names-tests.ts @@ -0,0 +1,25 @@ +import classNames = require('@sindresorhus/class-names'); + +// $ExpectType string +classNames('unicorn', 'rainbow'); +// $ExpectType string +classNames({ awesome: true, foo: false }, 'unicorn', { rainbow: false }); +// $ExpectType string +classNames('unicorn', null, undefined, 0, 1, { foo: null }); + +const buttonType = 'main'; +// $ExpectType string +classNames({ [`button-${buttonType}`]: true }); + +const props = { + type: 'success', + small: true, + block: undefined, +}; + +// $ExpectType string +classNames('button', { + [`button-${props.type}`]: props.type, + 'button-block': props.block, + 'button-small': props.small, +}); diff --git a/types/sindresorhus__class-names/tsconfig.json b/types/sindresorhus__class-names/tsconfig.json new file mode 100644 index 0000000000..a0b866ebdf --- /dev/null +++ b/types/sindresorhus__class-names/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@sindresorhus/class-names": [ + "sindresorhus__class-names" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sindresorhus__class-names-tests.ts" + ] +} diff --git a/types/sindresorhus__class-names/tslint.json b/types/sindresorhus__class-names/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sindresorhus__class-names/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sindresorhus__djb2a/index.d.ts b/types/sindresorhus__djb2a/index.d.ts new file mode 100644 index 0000000000..33e16db621 --- /dev/null +++ b/types/sindresorhus__djb2a/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for @sindresorhus/djb2a 1.0 +// Project: https://github.com/sindresorhus/djb2a +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = djb2a; + +declare function djb2a(string: string): number; diff --git a/types/sindresorhus__djb2a/sindresorhus__djb2a-tests.ts b/types/sindresorhus__djb2a/sindresorhus__djb2a-tests.ts new file mode 100644 index 0000000000..8af200101e --- /dev/null +++ b/types/sindresorhus__djb2a/sindresorhus__djb2a-tests.ts @@ -0,0 +1,4 @@ +import djb2a = require('@sindresorhus/djb2a'); + +// $ExpectType number +djb2a('🦄🌈'); diff --git a/types/sindresorhus__djb2a/tsconfig.json b/types/sindresorhus__djb2a/tsconfig.json new file mode 100644 index 0000000000..e88751963c --- /dev/null +++ b/types/sindresorhus__djb2a/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "paths": { + "@sindresorhus/djb2a": [ + "sindresorhus__djb2a" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sindresorhus__djb2a-tests.ts" + ] +} diff --git a/types/sindresorhus__djb2a/tslint.json b/types/sindresorhus__djb2a/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sindresorhus__djb2a/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sindresorhus__fnv1a/index.d.ts b/types/sindresorhus__fnv1a/index.d.ts new file mode 100644 index 0000000000..732d8cbd52 --- /dev/null +++ b/types/sindresorhus__fnv1a/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for @sindresorhus/fnv1a 1.0 +// Project: https://github.com/sindresorhus/fnv1a +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = fnv1a; + +declare function fnv1a(string: string): number; diff --git a/types/sindresorhus__fnv1a/sindresorhus__fnv1a-tests.ts b/types/sindresorhus__fnv1a/sindresorhus__fnv1a-tests.ts new file mode 100644 index 0000000000..9c5a525d85 --- /dev/null +++ b/types/sindresorhus__fnv1a/sindresorhus__fnv1a-tests.ts @@ -0,0 +1,4 @@ +import fnv1a = require('@sindresorhus/fnv1a'); + +// $ExpectType number +fnv1a('🦄🌈'); diff --git a/types/sindresorhus__fnv1a/tsconfig.json b/types/sindresorhus__fnv1a/tsconfig.json new file mode 100644 index 0000000000..6ac527a578 --- /dev/null +++ b/types/sindresorhus__fnv1a/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "paths": { + "@sindresorhus/fnv1a": [ + "sindresorhus__fnv1a" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sindresorhus__fnv1a-tests.ts" + ] +} diff --git a/types/sindresorhus__fnv1a/tslint.json b/types/sindresorhus__fnv1a/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sindresorhus__fnv1a/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sindresorhus__slugify/index.d.ts b/types/sindresorhus__slugify/index.d.ts new file mode 100644 index 0000000000..2bce172863 --- /dev/null +++ b/types/sindresorhus__slugify/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for @sindresorhus/slugify 0.6 +// Project: https://github.com/sindesorhus/slugify +// Definitions by: Carlos Precioso +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace slugify { + interface Options { + /** + * @default "-" + */ + separator?: string; + + /** + * Make the slug lowercase. + * @default true + */ + lowercase?: boolean; + + /** + * Convert camelcase to separate words. Internally it does `fooBar` → `foo bar`. + * @default true + */ + decamelize?: boolean; + + /** + * Specifying this only replaces the default if you set an item with the same key, like &. + * The replacements are run on the original string before any other transformations. + * + * Add a leading and trailing space to the replacement to have it separated by dashes. + * + * @default [ ['&', ' and '], ['🦄', ' unicorn '], ['♥', ' love '] ] + */ + customReplacements?: ReadonlyArray<[string, string]>; + } +} + +/** + * Slugify a string + */ +declare function slugify(input: string, options?: slugify.Options): string; + +export = slugify; diff --git a/types/sindresorhus__slugify/sindresorhus__slugify-tests.ts b/types/sindresorhus__slugify/sindresorhus__slugify-tests.ts new file mode 100644 index 0000000000..50a45a2ba0 --- /dev/null +++ b/types/sindresorhus__slugify/sindresorhus__slugify-tests.ts @@ -0,0 +1,29 @@ +import slugify = require("@sindresorhus/slugify"); + +slugify("I ♥ Dogs"); + +slugify(" Déjà Vu! "); + +slugify("fooBar 123 $#%"); + +slugify("I ♥ 🦄 & 🐶", { customReplacements: [["🐶", "dog"]] }); + +slugify("BAR and baz"); + +slugify("BAR and baz", { separator: "_" }); + +slugify("Déjà Vu!"); + +slugify("Déjà Vu!", { lowercase: false }); + +slugify("fooBar"); + +slugify("fooBar", { decamelize: false }); + +slugify("Foo@unicorn", { + customReplacements: [["@", "at"]] +}); + +slugify("foo@unicorn", { + customReplacements: [["@", " at "]] +}); diff --git a/types/sindresorhus__slugify/tsconfig.json b/types/sindresorhus__slugify/tsconfig.json new file mode 100644 index 0000000000..24230965e5 --- /dev/null +++ b/types/sindresorhus__slugify/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@sindresorhus/slugify": ["sindresorhus__slugify"] + } + }, + "files": ["index.d.ts", "sindresorhus__slugify-tests.ts"] +} diff --git a/types/sindresorhus__slugify/tslint.json b/types/sindresorhus__slugify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sindresorhus__slugify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sindresorhus__to-milliseconds/index.d.ts b/types/sindresorhus__to-milliseconds/index.d.ts new file mode 100644 index 0000000000..8eb44b2a7b --- /dev/null +++ b/types/sindresorhus__to-milliseconds/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for @sindresorhus/to-milliseconds 1.0 +// Project: https://github.com/sindresorhus/to-milliseconds +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = toMilliseconds; + +declare function toMilliseconds(input: toMilliseconds.TimeSpec): number; + +declare namespace toMilliseconds { + interface TimeSpec { + days?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + microseconds?: number; + nanoseconds?: number; + } +} diff --git a/types/sindresorhus__to-milliseconds/sindresorhus__to-milliseconds-tests.ts b/types/sindresorhus__to-milliseconds/sindresorhus__to-milliseconds-tests.ts new file mode 100644 index 0000000000..aff7ba6fe0 --- /dev/null +++ b/types/sindresorhus__to-milliseconds/sindresorhus__to-milliseconds-tests.ts @@ -0,0 +1,24 @@ +import toMilliseconds = require('@sindresorhus/to-milliseconds'); + +// $ExpectType number +toMilliseconds({ + days: 15, +}); +toMilliseconds({ + hours: 11, +}); +toMilliseconds({ + minutes: 23, +}); +toMilliseconds({ + seconds: 20, +}); +toMilliseconds({ + milliseconds: 1, +}); +toMilliseconds({ + microseconds: 1, +}); +toMilliseconds({ + nanoseconds: 1, +}); diff --git a/types/sindresorhus__to-milliseconds/tsconfig.json b/types/sindresorhus__to-milliseconds/tsconfig.json new file mode 100644 index 0000000000..be9b1a9bec --- /dev/null +++ b/types/sindresorhus__to-milliseconds/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@sindresorhus/to-milliseconds": [ + "sindresorhus__to-milliseconds" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sindresorhus__to-milliseconds-tests.ts" + ] +} diff --git a/types/sindresorhus__to-milliseconds/tslint.json b/types/sindresorhus__to-milliseconds/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sindresorhus__to-milliseconds/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sinon-as-promised/index.d.ts b/types/sinon-as-promised/index.d.ts index 5e2e06ed83..5187168d61 100644 --- a/types/sinon-as-promised/index.d.ts +++ b/types/sinon-as-promised/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/bendrucker/sinon-as-promised // Definitions by: igrayson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as s from "sinon"; diff --git a/types/sinon-chai/index.d.ts b/types/sinon-chai/index.d.ts index 6a0901eb8c..ad7c8cb857 100644 --- a/types/sinon-chai/index.d.ts +++ b/types/sinon-chai/index.d.ts @@ -4,7 +4,7 @@ // Jed Mao // Eyal Lapid // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// /// diff --git a/types/sinon-chai/v2/index.d.ts b/types/sinon-chai/v2/index.d.ts index 8a03ea671c..cff6d0b3a2 100644 --- a/types/sinon-chai/v2/index.d.ts +++ b/types/sinon-chai/v2/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/domenic/sinon-chai // Definitions by: Kazi Manzur Rashid , Jed Mao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// /// diff --git a/types/sinon-chrome/index.d.ts b/types/sinon-chrome/index.d.ts index eec9604dec..c25273d757 100644 --- a/types/sinon-chrome/index.d.ts +++ b/types/sinon-chrome/index.d.ts @@ -4,7 +4,7 @@ // CRIMX // kobanyan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// /// diff --git a/types/sinon-express-mock/index.d.ts b/types/sinon-express-mock/index.d.ts index 84454048cd..f3974fc005 100644 --- a/types/sinon-express-mock/index.d.ts +++ b/types/sinon-express-mock/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jared Chapiewsky // Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import { SinonStub, diff --git a/types/sinon-mongoose/index.d.ts b/types/sinon-mongoose/index.d.ts index f725965349..86109b4917 100644 --- a/types/sinon-mongoose/index.d.ts +++ b/types/sinon-mongoose/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/underscopeio/sinon-mongoose // Definitions by: stevehipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as s from "sinon"; diff --git a/types/sinon-stub-promise/index.d.ts b/types/sinon-stub-promise/index.d.ts index 298eed87c0..d817113cf7 100644 --- a/types/sinon-stub-promise/index.d.ts +++ b/types/sinon-stub-promise/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Thiago Temple // Tim Stackhouse // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// diff --git a/types/sinon-test/index.d.ts b/types/sinon-test/index.d.ts index 63318554ae..902064a7cb 100644 --- a/types/sinon-test/index.d.ts +++ b/types/sinon-test/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/sinonjs/sinon-test // Definitions by: Francis Saul // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as Sinon from 'sinon'; diff --git a/types/sinon/index.d.ts b/types/sinon/index.d.ts index b5c3952e7a..bc265d6718 100644 --- a/types/sinon/index.d.ts +++ b/types/sinon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Sinon 5.0 +// Type definitions for Sinon 7.0 // Project: http://sinonjs.org/ // Definitions by: William Sears // Jonathan Little @@ -9,21 +9,21 @@ // Greg Jednaszewski // John Wood // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 // sinon uses DOM dependencies which are absent in browser-less environment like node.js // to avoid compiler errors this monkey patch is used // see more details in https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11351 -interface Event {} // tslint:disable-line no-empty-interface -interface Document {} // tslint:disable-line no-empty-interface +interface Event { } // tslint:disable-line no-empty-interface +interface Document { } // tslint:disable-line no-empty-interface declare namespace Sinon { - interface SinonSpyCallApi { + interface SinonSpyCallApi { // Properties /** * Array of received arguments. */ - args: TArgs; + args: any[]; // Methods /** @@ -38,11 +38,11 @@ declare namespace Sinon { * so a call that received the provided arguments (in the same spots) and possibly others as well will return true. * @param args */ - calledWith(...args: TArgs): boolean; + calledWith(...args: any[]): boolean; /** * Returns true if spy was called at least once with the provided arguments and no others. */ - calledWithExactly(...args: TArgs): boolean; + calledWithExactly(...args: any[]): boolean; /** * Returns true if spy/stub was called the new operator. * Beware that this is inferred based on the value of the this object and the spy function’s prototype, @@ -53,31 +53,31 @@ declare namespace Sinon { * Returns true if spy was called at exactly once with the provided arguments. * @param args */ - calledOnceWith(...args: TArgs): boolean; - calledOnceWithExactly(...args: TArgs): boolean; + calledOnceWith(...args: any[]): boolean; + calledOnceWithExactly(...args: any[]): boolean; /** * Returns true if spy was called with matching arguments (and possibly others). * This behaves the same as spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...). * @param args */ - calledWithMatch(...args: TArgs): boolean; + calledWithMatch(...args: any[]): boolean; /** * Returns true if call did not receive provided arguments. * @param args */ - notCalledWith(...args: TArgs): boolean; + notCalledWith(...args: any[]): boolean; /** * Returns true if call did not receive matching arguments. * This behaves the same as spyCall.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...). * @param args */ - notCalledWithMatch(...args: TArgs): boolean; + notCalledWithMatch(...args: any[]): boolean; /** * Returns true if spy returned the provided value at least once. * Uses deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) for strict comparison (see matchers). * @param value */ - returned(value: TReturnValue): boolean; + returned(value: any): boolean; /** * Returns true if spy threw an exception at least once. */ @@ -118,8 +118,7 @@ declare namespace Sinon { yieldToOn(property: string, obj: any, ...args: any[]): void; } - interface SinonSpyCall - extends SinonSpyCallApi { + interface SinonSpyCall extends SinonSpyCallApi { /** * The call’s this value. */ @@ -131,7 +130,7 @@ declare namespace Sinon { /** * Return value. */ - returnValue: TReturnValue; + returnValue: any; /** * This property is a convenience for a call’s callback. * When the last argument in a call is a Function, then callback will reference that. Otherwise it will be undefined. @@ -154,11 +153,7 @@ declare namespace Sinon { calledAfter(call: SinonSpyCall): boolean; } - interface SinonSpy - extends Pick< - SinonSpyCallApi, - Exclude, 'args'> - > { + interface SinonSpy extends SinonSpyCallApi { // Properties /** * The number of recorded calls. @@ -187,19 +182,19 @@ declare namespace Sinon { /** * The first call */ - firstCall: SinonSpyCall; + firstCall: SinonSpyCall; /** * The second call */ - secondCall: SinonSpyCall; + secondCall: SinonSpyCall; /** * The third call */ - thirdCall: SinonSpyCall; + thirdCall: SinonSpyCall; /** * The last call */ - lastCall: SinonSpyCall; + lastCall: SinonSpyCall; /** * Array of this objects, spy.thisValues[0] is the this object for the first call. */ @@ -207,7 +202,7 @@ declare namespace Sinon { /** * Array of arguments received, spy.args[0] is an array of arguments received in the first call. */ - args: TArgs[]; + args: any[][]; /** * Array of exception objects thrown, spy.exceptions[0] is the exception thrown by the first call. * If the call did not throw an error, the value at the call’s location in .exceptions will be undefined. @@ -217,7 +212,7 @@ declare namespace Sinon { * Array of return values, spy.returnValues[0] is the return value of the first call. * If the call did not explicitly return a value, the value at the call’s location in .returnValues will be undefined. */ - returnValues: TReturnValue[]; + returnValues: any[]; // Methods (...args: any[]): any; @@ -246,7 +241,7 @@ declare namespace Sinon { * This is useful to be more expressive in your assertions, where you can access the spy with the same call. * @param args Expected args */ - withArgs(...args: TArgs): SinonSpy; + withArgs(...args: any[]): SinonSpy; /** * Returns true if the spy was always called with @param obj as this. * @param obj @@ -255,29 +250,29 @@ declare namespace Sinon { /** * Returns true if spy was always called with the provided arguments (and possibly others). */ - alwaysCalledWith(...args: TArgs): boolean; + alwaysCalledWith(...args: any[]): boolean; /** * Returns true if spy was always called with the exact provided arguments. * @param args */ - alwaysCalledWithExactly(...args: TArgs): boolean; + alwaysCalledWithExactly(...args: any[]): boolean; /** * Returns true if spy was always called with matching arguments (and possibly others). * This behaves the same as spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...). * @param args */ - alwaysCalledWithMatch(...args: TArgs): boolean; + alwaysCalledWithMatch(...args: any[]): boolean; /** * Returns true if the spy/stub was never called with the provided arguments. * @param args */ - neverCalledWith(...args: TArgs): boolean; + neverCalledWith(...args: any[]): boolean; /** * Returns true if the spy/stub was never called with matching arguments. * This behaves the same as spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...). * @param args */ - neverCalledWithMatch(...args: TArgs): boolean; + neverCalledWithMatch(...args: any[]): boolean; /** * Returns true if spy always threw an exception. */ @@ -300,22 +295,22 @@ declare namespace Sinon { * If the stub was never called with a function argument, yield throws an error. * Returns an Array with all callbacks return values in the order they were called, if no error is thrown. */ - invokeCallback(...args: TArgs): void; + invokeCallback(...args: any[]): void; /** * Set the displayName of the spy or stub. * @param name */ - named(name: string): SinonSpy; + named(name: string): SinonSpy; /** * Returns the nth call. * Accessing individual calls helps with more detailed behavior verification when the spy is called more than once. * @param n */ - getCall(n: number): SinonSpyCall; + getCall(n: number): SinonSpyCall; /** * Returns an Array of all calls recorded by the spy. */ - getCalls(): Array>; + getCalls(): SinonSpyCall[]; /** * Resets the state of a spy. */ @@ -355,15 +350,10 @@ declare namespace Sinon { * The original method can be restored by calling object.method.restore(). * The returned spy is the function object which replaced the original method. spy === object.method. */ - (obj: T, method: K): T[K] extends ( - ...args: infer TArgs - ) => infer TReturnValue - ? SinonSpy - : SinonSpy; + (obj: T, method: keyof T): SinonSpy; } - interface SinonStub - extends SinonSpy { + interface SinonStub extends SinonSpy { /** * Resets the stub’s behaviour to the default behaviour * You can reset behaviour of all stubs using sinon.resetBehavior() @@ -381,13 +371,13 @@ declare namespace Sinon { * Causes the stub to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. * Returns the stub to allow chaining. */ - usingPromise(promiseLibrary: any): SinonStub; + usingPromise(promiseLibrary: any): SinonStub; /** * Makes the stub return the provided @param obj value. * @param obj */ - returns(obj: TReturnValue): SinonStub; + returns(obj: any): SinonStub; /** * Causes the stub to return the argument at the provided @param index. * stub.returnsArg(0); causes the stub to return the first argument. @@ -395,12 +385,12 @@ declare namespace Sinon { * starting from sinon@6.1.2, a TypeError will be thrown. * @param index */ - returnsArg(index: number): SinonStub; + returnsArg(index: number): SinonStub; /** * Causes the stub to return its this value. * Useful for stubbing jQuery-style fluent APIs. */ - returnsThis(): SinonStub; + returnsThis(): SinonStub; /** * Causes the stub to return a Promise which resolves to the provided value. * When constructing the Promise, sinon uses the Promise.resolve method. @@ -408,26 +398,26 @@ declare namespace Sinon { * The Promise library can be overwritten using the usingPromise method. * Since sinon@2.0.0 */ - resolves(value?: any): SinonStub; + resolves(value?: any): SinonStub; /** * Causes the stub to return a Promise which resolves to the argument at the provided index. * stub.resolvesArg(0); causes the stub to return a Promise which resolves to the first argument. * If the argument at the provided index is not available, a TypeError will be thrown. */ - resolvesArg(index: number): SinonStub; + resolvesArg(index: number): SinonStub; /** * Causes the stub to return a Promise which resolves to its this value. */ - resolvesThis(): SinonStub; + resolvesThis(): SinonStub; /** * Causes the stub to throw an exception (Error). * @param type */ - throws(type?: string): SinonStub; + throws(type?: string): SinonStub; /** * Causes the stub to throw the provided exception object. */ - throws(obj: any): SinonStub; + throws(obj: any): SinonStub; /** * Causes the stub to throw the argument at the provided index. * stub.throwsArg(0); causes the stub to throw the first argument as the exception. @@ -435,9 +425,9 @@ declare namespace Sinon { * Since sinon@2.3.0 * @param index */ - throwsArg(index: number): SinonStub; - throwsException(type?: string): SinonStub; - throwsException(obj: any): SinonStub; + throwsArg(index: number): SinonStub; + throwsException(type?: string): SinonStub; + throwsException(obj: any): SinonStub; /** * Causes the stub to return a Promise which rejects with an exception (Error). * When constructing the Promise, sinon uses the Promise.reject method. @@ -445,57 +435,53 @@ declare namespace Sinon { * The Promise library can be overwritten using the usingPromise method. * Since sinon@2.0.0 */ - rejects(): SinonStub; + rejects(): SinonStub; /** * Causes the stub to return a Promise which rejects with an exception of the provided type. * Since sinon@2.0.0 */ - rejects(errorType: string): SinonStub; + rejects(errorType: string): SinonStub; /** * Causes the stub to return a Promise which rejects with the provided exception object. * Since sinon@2.0.0 */ - rejects(value: any): SinonStub; + rejects(value: any): SinonStub; /** * Causes the stub to call the argument at the provided index as a callback function. * stub.callsArg(0); causes the stub to call the first argument as a callback. * If the argument at the provided index is not available or is not a function, a TypeError will be thrown. */ - callsArg(index: number): SinonStub; + callsArg(index: number): SinonStub; /** * Causes the original method wrapped into the stub to be called when none of the conditional stubs are matched. */ - callThrough(): SinonStub; + callThrough(): SinonStub; /** * Like stub.callsArg(index); but with an additional parameter to pass the this context. * @param index * @param context */ - callsArgOn(index: number, context: any): SinonStub; + callsArgOn(index: number, context: any): SinonStub; /** * Like callsArg, but with arguments to pass to the callback. * @param index * @param args */ - callsArgWith(index: number, ...args: any[]): SinonStub; + callsArgWith(index: number, ...args: any[]): SinonStub; /** * Like above but with an additional parameter to pass the this context. * @param index * @param context * @param args */ - callsArgOnWith( - index: number, - context: any, - ...args: any[] - ): SinonStub; + callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). * @param index */ - callsArgAsync(index: number): SinonStub; + callsArgAsync(index: number): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. @@ -503,99 +489,91 @@ declare namespace Sinon { * @param index * @param context */ - callsArgOnAsync(index: number, context: any): SinonStub; + callsArgOnAsync(index: number, context: any): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). */ - callsArgWithAsync(index: number, ...args: any[]): SinonStub; + callsArgWithAsync(index: number, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). */ - callsArgOnWithAsync( - index: number, - context: any, - ...args: any[] - ): SinonStub; + callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; /** * Makes the stub call the provided @param func when invoked. * @param func */ - callsFake(func: (...args: TArgs) => TReturnValue): SinonStub; + callsFake(func: (...args: any[]) => any): SinonStub; /** * Replaces a new getter for this stub. */ - get(func: () => any): SinonStub; + get(func: () => any): SinonStub; /** * Defines a new setter for this stub. * @param func */ - set(func: (v: any) => void): SinonStub; + set(func: (v: any) => void): SinonStub; /** * Defines the behavior of the stub on the @param n call. Useful for testing sequential interactions. * There are methods onFirstCall, onSecondCall,onThirdCall to make stub definitions read more naturally. * onCall can be combined with all of the behavior defining methods in this section. In particular, it can be used together with withArgs. * @param n */ - onCall(n: number): SinonStub; + onCall(n: number): SinonStub; /** * Alias for stub.onCall(0); */ - onFirstCall(): SinonStub; + onFirstCall(): SinonStub; /** * Alias for stub.onCall(1); */ - onSecondCall(): SinonStub; + onSecondCall(): SinonStub; /** * Alias for stub.onCall(2); */ - onThirdCall(): SinonStub; + onThirdCall(): SinonStub; /** * Defines a new value for this stub. * @param val */ - value(val: any): SinonStub; + value(val: any): SinonStub; /** * Set the displayName of the spy or stub. * @param name */ - named(name: string): SinonStub; + named(name: string): SinonStub; /** * Similar to callsArg. * Causes the stub to call the first callback it receives with the provided arguments (if any). * If a method accepts more than one callback, you need to use callsArg to have the stub invoke other callbacks than the first one. */ - yields(...args: any[]): SinonStub; + yields(...args: any[]): SinonStub; /** * Like above but with an additional parameter to pass the this context. */ - yieldsOn(context: any, ...args: any[]): SinonStub; - yieldsRight(...args: any[]): SinonStub; + yieldsOn(context: any, ...args: any[]): SinonStub; + yieldsRight(...args: any[]): SinonStub; /** * Causes the spy to invoke a callback passed as a property of an object to the spy. * Like yields, yieldsTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments. * @param property * @param args */ - yieldsTo(property: string, ...args: any[]): SinonStub; + yieldsTo(property: string, ...args: any[]): SinonStub; /** * Like above but with an additional parameter to pass the this context. */ - yieldsToOn( - property: string, - context: any, - ...args: any[] - ): SinonStub; + yieldsToOn(property: string, context: any, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). * @param args */ - yieldsAsync(...args: any[]): SinonStub; + yieldsAsync(...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. @@ -603,7 +581,7 @@ declare namespace Sinon { * @param context * @param args */ - yieldsOnAsync(context: any, ...args: any[]): SinonStub; + yieldsOnAsync(context: any, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. @@ -611,7 +589,7 @@ declare namespace Sinon { * @param property * @param args */ - yieldsToAsync(property: string, ...args: any[]): SinonStub; + yieldsToAsync(property: string, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. @@ -620,18 +598,14 @@ declare namespace Sinon { * @param context * @param args */ - yieldsToOnAsync( - property: string, - context: any, - ...args: any[] - ): SinonStub; + yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub; /** * Stubs the method only for the provided arguments. * This is useful to be more expressive in your assertions, where you can access the spy with the same call. * It is also useful to create a stub that can act differently in response to different arguments. * @param args */ - withArgs(...args: TArgs): SinonStub; + withArgs(...args: any[]): SinonStub; } interface SinonStubStatic { @@ -651,11 +625,7 @@ declare namespace Sinon { * An exception is thrown if the property is not already a function. * The original function can be restored by calling object.method.restore(); (or stub.restore();). */ - (obj: T, method: K): T[K] extends ( - ...args: infer TArgs - ) => infer TReturnValue - ? SinonStub - : SinonStub; + (obj: T, method: keyof T): SinonStub; } interface SinonExpectation extends SinonStub { @@ -757,22 +727,11 @@ declare namespace Sinon { interface SinonFakeTimers { now: number; - setTimeout( - callback: (...args: any[]) => void, - timeout: number, - ...args: any[] - ): SinonTimerId; + setTimeout(callback: (...args: any[]) => void, timeout: number, ...args: any[]): SinonTimerId; clearTimeout(id: SinonTimerId): void; - setInterval( - callback: (...args: any[]) => void, - timeout: number, - ...args: any[] - ): SinonTimerId; + setInterval(callback: (...args: any[]) => void, timeout: number, ...args: any[]): SinonTimerId; clearInterval(id: SinonTimerId): void; - setImmediate( - callback: (...args: any[]) => void, - ...args: any[] - ): SinonTimerId; + setImmediate(callback: (...args: any[]) => void, ...args: any[]): SinonTimerId; clearImmediate(id: SinonTimerId): void; requestAnimationFrame(callback: (...args: any[]) => void): number; cancelAnimationFrame(id: number): void; @@ -806,30 +765,9 @@ declare namespace Sinon { Date(year: number, month: number): Date; Date(year: number, month: number, day: number): Date; Date(year: number, month: number, day: number, hour: number): Date; - Date( - year: number, - month: number, - day: number, - hour: number, - minute: number - ): Date; - Date( - year: number, - month: number, - day: number, - hour: number, - minute: number, - second: number - ): Date; - Date( - year: number, - month: number, - day: number, - hour: number, - minute: number, - second: number, - ms: number - ): Date; + Date(year: number, month: number, day: number, hour: number, minute: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date; /** * Restore the faked methods. @@ -950,7 +888,7 @@ declare namespace Sinon { } interface SinonFakeXMLHttpRequestStatic { - new (): SinonFakeXMLHttpRequest; + new(): SinonFakeXMLHttpRequest; /** * Default false. * When set to true, Sinon will check added filters if certain requests should be “unfaked” @@ -962,15 +900,7 @@ declare namespace Sinon { * 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; + 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. @@ -1036,10 +966,7 @@ declare namespace Sinon { /** * Responds to all requests to given URL, e.g. /posts/1. */ - respondWith( - url: string, - fn: (xhr: SinonFakeXMLHttpRequest) => void - ): void; + respondWith(url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; /** * Responds to all method requests to the given URL with the given response. * method is an HTTP verb. @@ -1054,11 +981,7 @@ declare namespace Sinon { * 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: SinonFakeXMLHttpRequest) => void - ): void; + respondWith(method: string, url: string, fn: (xhr: SinonFakeXMLHttpRequest) => 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: @@ -1073,10 +996,7 @@ declare namespace Sinon { * 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: SinonFakeXMLHttpRequest) => void - ): void; + respondWith(url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; /** * Responds to all method requests to URLs matching the regular expression. */ @@ -1088,11 +1008,7 @@ declare namespace Sinon { /** * Responds to all method requests to URLs matching the regular expression. */ - respondWith( - method: string, - url: RegExp, - fn: (xhr: SinonFakeXMLHttpRequest) => void - ): void; + respondWith(method: string, url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; /** * Causes all queued asynchronous requests to receive a response. * If none of the responses added through respondWith match, the default response is [404, {}, ""]. @@ -1221,10 +1137,7 @@ declare namespace Sinon { * @param spyOrSpyCall * @param args */ - calledWithExactly( - spyOrSpyCall: SinonSpy | SinonSpyCall, - ...args: any[] - ): void; + calledWithExactly(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; /** * Passes if spy was always called with the provided arguments and no others. */ @@ -1234,10 +1147,7 @@ declare namespace Sinon { * This behaves the same way as sinon.assert.calledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithMatch(spy.secondCall, arg1, arg2, ...);. */ - calledWithMatch( - spyOrSpyCall: SinonSpy | SinonSpyCall, - ...args: any[] - ): void; + calledWithMatch(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; /** * Passes if spy was always called with matching arguments. * This behaves the same way as sinon.assert.alwaysCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). @@ -1529,7 +1439,7 @@ declare namespace Sinon { * @template TType Object type being stubbed. */ type SinonStubbedInstance = { - [P in keyof TType]: SinonStubbedMember + [P in keyof TType]: SinonStubbedMember; }; /** @@ -1619,9 +1529,7 @@ declare namespace Sinon { * You would have to call either clock.next(), clock.tick(), clock.runAll() or clock.runToLast() (see example below). Please refer to the lolex documentation for more information. * @param config */ - useFakeTimers( - config?: number | Date | Partial - ): SinonFakeTimers; + useFakeTimers(config?: number | Date | Partial): SinonFakeTimers; /** * Causes Sinon to replace the native XMLHttpRequest object in browsers that support it with a custom implementation which does not send actual requests. * In browsers that support ActiveXObject, this constructor is replaced, and fake objects are returned for XMLHTTP progIds. @@ -1675,8 +1583,7 @@ declare namespace Sinon { replace( obj: T, prop: TKey, - replacement: T[TKey] - ): T[TKey]; + replacement: T[TKey]): T[TKey]; /** * Replaces getter for property on object with replacement argument. Attempts to replace an already replaced getter cause an exception. * replacement must be a Function, and can be instances of spies, stubs and fakes. @@ -1687,8 +1594,7 @@ declare namespace Sinon { replaceGetter( obj: T, prop: TKey, - replacement: () => T[TKey] - ): () => T[TKey]; + replacement: () => T[TKey]): () => T[TKey]; /** * Replaces setter for property on object with replacement argument. Attempts to replace an already replaced setter cause an exception. * replacement must be a Function, and can be instances of spies, stubs and fakes. @@ -1699,8 +1605,7 @@ declare namespace Sinon { replaceSetter( obj: T, prop: TKey, - replacement: (val: T[TKey]) => void - ): (val: T[TKey]) => void; + replacement: (val: T[TKey]) => void): (val: T[TKey]) => void; /** * Creates a new object with the given functions as the prototype and stubs all implemented functions. @@ -1710,9 +1615,7 @@ declare namespace Sinon { * @returns A stubbed version of the constructor. * @remarks The given constructor function is not invoked. See also the stub API. */ - createStubInstance( - constructor: StubbableType - ): SinonStubbedInstance; + createStubInstance(constructor: StubbableType): SinonStubbedInstance; } interface SinonApi { diff --git a/types/sinon/package.json b/types/sinon/package.json new file mode 100644 index 0000000000..bb80441dc0 --- /dev/null +++ b/types/sinon/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] } + } +} diff --git a/types/sinon/sinon-tests.ts b/types/sinon/sinon-tests.ts index d5ae4b0eb2..b892f22980 100644 --- a/types/sinon/sinon-tests.ts +++ b/types/sinon/sinon-tests.ts @@ -288,6 +288,41 @@ function testAssert() { sinon.assert.expose(obj, { includeFail: true }); } +function testTypedSpy() { + const cls = class { + foo(a: number, b: string): number { + return 3; + } + }; + + const instance = new cls(); + const spy = sinon.spy(instance, 'foo'); + + spy.calledWith(5, 'x'); + spy.calledWith(sinon.match(5), 'x'); + spy.calledWithExactly(5, 'x'); + spy.calledWithExactly(5, sinon.match('x')); + spy.calledOnceWith(5, 'x'); + spy.calledOnceWith(sinon.match(5), 'x'); + spy.notCalledWith(5, 'x'); + spy.notCalledWith(sinon.match(5), 'x'); + spy.returned(5); + spy.returned(sinon.match(5)); + + spy.withArgs(sinon.match(5), 'x').calledWith(5, 'x'); + spy.alwaysCalledWith(sinon.match(5), 'x'); + spy.alwaysCalledWith(5, 'x'); + spy.alwaysCalledWithExactly(sinon.match(5), 'x'); + spy.alwaysCalledWithExactly(5, 'x'); + spy.neverCalledWith(sinon.match(5), 'x'); + spy.neverCalledWith(5, 'x'); + + const stub = sinon.stub(instance, 'foo'); + + stub.withArgs(5, 'x').returns(3); + stub.withArgs(sinon.match(5), 'x').returns(5); +} + function testSpy() { const fn = () => { }; const obj = class { diff --git a/types/sinon/ts3.1/index.d.ts b/types/sinon/ts3.1/index.d.ts new file mode 100644 index 0000000000..bc91a3285a --- /dev/null +++ b/types/sinon/ts3.1/index.d.ts @@ -0,0 +1,1747 @@ +// sinon uses DOM dependencies which are absent in browser-less environment like node.js +// to avoid compiler errors this monkey patch is used +// see more details in https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11351 +interface Event {} // tslint:disable-line no-empty-interface +interface Document {} // tslint:disable-line no-empty-interface + +declare namespace Sinon { + type MatchArguments = { + [K in keyof T]: SinonMatcher | T[K]; + }; + + interface SinonSpyCallApi { + // Properties + /** + * Array of received arguments. + */ + args: TArgs; + + // Methods + /** + * Returns true if the spy was called at least once with @param obj as this. + * calledOn also accepts a matcher spyCall.calledOn(sinon.match(fn)) (see matchers). + * @param obj + */ + calledOn(obj: any): boolean; + /** + * Returns true if spy was called at least once with the provided arguments. + * Can be used for partial matching, Sinon only checks the provided arguments against actual arguments, + * so a call that received the provided arguments (in the same spots) and possibly others as well will return true. + * @param args + */ + calledWith(...args: MatchArguments): boolean; + /** + * Returns true if spy was called at least once with the provided arguments and no others. + */ + calledWithExactly(...args: MatchArguments): boolean; + /** + * Returns true if spy/stub was called the new operator. + * Beware that this is inferred based on the value of the this object and the spy function’s prototype, + * so it may give false positives if you actively return the right kind of object. + */ + calledWithNew(): boolean; + /** + * Returns true if spy was called at exactly once with the provided arguments. + * @param args + */ + calledOnceWith(...args: MatchArguments): boolean; + calledOnceWithExactly(...args: MatchArguments): boolean; + /** + * Returns true if spy was called with matching arguments (and possibly others). + * This behaves the same as spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...). + * @param args + */ + calledWithMatch(...args: TArgs): boolean; + /** + * Returns true if call did not receive provided arguments. + * @param args + */ + notCalledWith(...args: MatchArguments): boolean; + /** + * Returns true if call did not receive matching arguments. + * This behaves the same as spyCall.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...). + * @param args + */ + notCalledWithMatch(...args: TArgs): boolean; + /** + * Returns true if spy returned the provided value at least once. + * Uses deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) for strict comparison (see matchers). + * @param value + */ + returned(value: TReturnValue|SinonMatcher): boolean; + /** + * Returns true if spy threw an exception at least once. + */ + threw(): boolean; + /** + * Returns true if spy threw an exception of the provided type at least once. + */ + threw(type: string): boolean; + /** + * Returns true if spy threw the provided exception object at least once. + */ + threw(obj: any): boolean; + /** + * Like yield, but with an explicit argument number specifying which callback to call. + * Useful if a function is called with more than one callback, and simply calling the first callback is not desired. + * @param pos + */ + callArg(pos: number): void; + callArgOn(pos: number, obj: any, ...args: any[]): void; + /** + * Like callArg, but with arguments. + */ + callArgWith(pos: number, ...args: any[]): void; + callArgOnWith(pos: number, obj: any, ...args: any[]): void; + /** + * Invoke callbacks passed to the stub with the given arguments. + * If the stub was never called with a function argument, yield throws an error. + * Returns an Array with all callbacks return values in the order they were called, if no error is thrown. + * Also aliased as invokeCallback. + */ + yield(...args: any[]): void; + yieldOn(obj: any, ...args: any[]): void; + /** + * Invokes callbacks passed as a property of an object to the stub. + * Like yield, yieldTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments. + */ + yieldTo(property: string, ...args: any[]): void; + yieldToOn(property: string, obj: any, ...args: any[]): void; + } + + interface SinonSpyCall + extends SinonSpyCallApi { + /** + * The call’s this value. + */ + thisValue: any; + /** + * Exception thrown, if any. + */ + exception: any; + /** + * Return value. + */ + returnValue: TReturnValue; + /** + * This property is a convenience for a call’s callback. + * When the last argument in a call is a Function, then callback will reference that. Otherwise it will be undefined. + */ + callback: Function | undefined; + /** + * This property is a convenience for the last argument of the call. + */ + lastArg: any; + + /** + * Returns true if the spy call occurred before another spy call. + * @param call + */ + calledBefore(call: SinonSpyCall): boolean; + /** + * Returns true if the spy call occurred after another spy call. + * @param call + */ + calledAfter(call: SinonSpyCall): boolean; + } + + interface SinonSpy + extends Pick< + SinonSpyCallApi, + Exclude, 'args'> + > { + // Properties + /** + * The number of recorded calls. + */ + callCount: number; + /** + * true if the spy was called at least once + */ + called: boolean; + /** + * true if the spy was not called + */ + notCalled: boolean; + /** + * true if spy was called exactly once + */ + calledOnce: boolean; + /** + * true if the spy was called exactly twice + */ + calledTwice: boolean; + /** + * true if the spy was called exactly thrice + */ + calledThrice: boolean; + /** + * The first call + */ + firstCall: SinonSpyCall; + /** + * The second call + */ + secondCall: SinonSpyCall; + /** + * The third call + */ + thirdCall: SinonSpyCall; + /** + * The last call + */ + lastCall: SinonSpyCall; + /** + * Array of this objects, spy.thisValues[0] is the this object for the first call. + */ + thisValues: any[]; + /** + * Array of arguments received, spy.args[0] is an array of arguments received in the first call. + */ + args: TArgs[]; + /** + * Array of exception objects thrown, spy.exceptions[0] is the exception thrown by the first call. + * If the call did not throw an error, the value at the call’s location in .exceptions will be undefined. + */ + exceptions: any[]; + /** + * Array of return values, spy.returnValues[0] is the return value of the first call. + * If the call did not explicitly return a value, the value at the call’s location in .returnValues will be undefined. + */ + returnValues: TReturnValue[]; + + // Methods + (...args: any[]): any; + /** + * Returns true if the spy was called before @param anotherSpy + * @param anotherSpy + */ + calledBefore(anotherSpy: SinonSpy): boolean; + /** + * Returns true if the spy was called after @param anotherSpy + * @param anotherSpy + */ + calledAfter(anotherSpy: SinonSpy): boolean; + /** + * Returns true if spy was called before @param anotherSpy, and no spy calls occurred between spy and @param anotherSpy. + * @param anotherSpy + */ + calledImmediatelyBefore(anotherSpy: SinonSpy): boolean; + /** + * Returns true if spy was called after @param anotherSpy, and no spy calls occurred between @param anotherSpy and spy. + * @param anotherSpy + */ + calledImmediatelyAfter(anotherSpy: SinonSpy): boolean; + /** + * Creates a spy that only records calls when the received arguments match those passed to withArgs. + * This is useful to be more expressive in your assertions, where you can access the spy with the same call. + * @param args Expected args + */ + withArgs(...args: MatchArguments): SinonSpy; + /** + * Returns true if the spy was always called with @param obj as this. + * @param obj + */ + alwaysCalledOn(obj: any): boolean; + /** + * Returns true if spy was always called with the provided arguments (and possibly others). + */ + alwaysCalledWith(...args: MatchArguments): boolean; + /** + * Returns true if spy was always called with the exact provided arguments. + * @param args + */ + alwaysCalledWithExactly(...args: MatchArguments): boolean; + /** + * Returns true if spy was always called with matching arguments (and possibly others). + * This behaves the same as spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...). + * @param args + */ + alwaysCalledWithMatch(...args: TArgs): boolean; + /** + * Returns true if the spy/stub was never called with the provided arguments. + * @param args + */ + neverCalledWith(...args: MatchArguments): boolean; + /** + * Returns true if the spy/stub was never called with matching arguments. + * This behaves the same as spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...). + * @param args + */ + neverCalledWithMatch(...args: TArgs): boolean; + /** + * Returns true if spy always threw an exception. + */ + alwaysThrew(): boolean; + /** + * Returns true if spy always threw an exception of the provided type. + */ + alwaysThrew(type: string): boolean; + /** + * Returns true if spy always threw the provided exception object. + */ + alwaysThrew(obj: any): boolean; + /** + * Returns true if spy always returned the provided value. + * @param obj + */ + alwaysReturned(obj: any): boolean; + /** + * Invoke callbacks passed to the stub with the given arguments. + * If the stub was never called with a function argument, yield throws an error. + * Returns an Array with all callbacks return values in the order they were called, if no error is thrown. + */ + invokeCallback(...args: TArgs): void; + /** + * Set the displayName of the spy or stub. + * @param name + */ + named(name: string): SinonSpy; + /** + * Returns the nth call. + * Accessing individual calls helps with more detailed behavior verification when the spy is called more than once. + * @param n + */ + getCall(n: number): SinonSpyCall; + /** + * Returns an Array of all calls recorded by the spy. + */ + getCalls(): Array>; + /** + * Resets the state of a spy. + */ + resetHistory(): void; + /** + * Returns the passed format string with the following replacements performed: + * * %n - the name of the spy "spy" by default) + * * %c - the number of times the spy was called, in words ("once", "twice", etc.) + * * %C - a list of string representations of the calls to the spy, with each call prefixed by a newline and four spaces + * * %t - a comma-delimited list of this values the spy was called on + * * %n - the formatted value of the nth argument passed to printf + * * %* - a comma-delimited list of the (non-format string) arguments passed to printf + * * %D - a multi-line list of the arguments received by all calls to the spy + * @param format + * @param args + */ + printf(format: string, ...args: any[]): string; + /** + * Replaces the spy with the original method. Only available if the spy replaced an existing method. + */ + restore(): void; + } + + interface SinonSpyStatic { + /** + * Creates an anonymous function that records arguments, this value, exceptions and return values for all calls. + */ + (): SinonSpy; + /** + * Spies on the provided function + */ + (func: Function): SinonSpy; + /** + * Creates a spy for object.method and replaces the original method with the spy. + * An exception is thrown if the property is not already a function. + * The spy acts exactly like the original method in all cases. + * The original method can be restored by calling object.method.restore(). + * The returned spy is the function object which replaced the original method. spy === object.method. + */ + (obj: T, method: K): T[K] extends ( + ...args: infer TArgs + ) => infer TReturnValue + ? SinonSpy + : SinonSpy; + } + + interface SinonStub + extends SinonSpy { + /** + * Resets the stub’s behaviour to the default behaviour + * You can reset behaviour of all stubs using sinon.resetBehavior() + */ + resetBehavior(): void; + /** + * Resets both behaviour and history of the stub. + * This is equivalent to calling both stub.resetBehavior() and stub.resetHistory() + * Updated in sinon@2.0.0 + * Since sinon@5.0.0 + * As a convenience, you can apply stub.reset() to all stubs using sinon.reset() + */ + reset(): void; + /** + * Causes the stub to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. + * Returns the stub to allow chaining. + */ + usingPromise(promiseLibrary: any): SinonStub; + + /** + * Makes the stub return the provided @param obj value. + * @param obj + */ + returns(obj: TReturnValue): SinonStub; + /** + * Causes the stub to return the argument at the provided @param index. + * stub.returnsArg(0); causes the stub to return the first argument. + * If the argument at the provided index is not available, prior to sinon@6.1.2, an undefined value will be returned; + * starting from sinon@6.1.2, a TypeError will be thrown. + * @param index + */ + returnsArg(index: number): SinonStub; + /** + * Causes the stub to return its this value. + * Useful for stubbing jQuery-style fluent APIs. + */ + returnsThis(): SinonStub; + /** + * Causes the stub to return a Promise which resolves to the provided value. + * When constructing the Promise, sinon uses the Promise.resolve method. + * You are responsible for providing a polyfill in environments which do not provide Promise. + * The Promise library can be overwritten using the usingPromise method. + * Since sinon@2.0.0 + */ + resolves(value?: any): SinonStub; + /** + * Causes the stub to return a Promise which resolves to the argument at the provided index. + * stub.resolvesArg(0); causes the stub to return a Promise which resolves to the first argument. + * If the argument at the provided index is not available, a TypeError will be thrown. + */ + resolvesArg(index: number): SinonStub; + /** + * Causes the stub to return a Promise which resolves to its this value. + */ + resolvesThis(): SinonStub; + /** + * Causes the stub to throw an exception (Error). + * @param type + */ + throws(type?: string): SinonStub; + /** + * Causes the stub to throw the provided exception object. + */ + throws(obj: any): SinonStub; + /** + * Causes the stub to throw the argument at the provided index. + * stub.throwsArg(0); causes the stub to throw the first argument as the exception. + * If the argument at the provided index is not available, a TypeError will be thrown. + * Since sinon@2.3.0 + * @param index + */ + throwsArg(index: number): SinonStub; + throwsException(type?: string): SinonStub; + throwsException(obj: any): SinonStub; + /** + * Causes the stub to return a Promise which rejects with an exception (Error). + * When constructing the Promise, sinon uses the Promise.reject method. + * You are responsible for providing a polyfill in environments which do not provide Promise. + * The Promise library can be overwritten using the usingPromise method. + * Since sinon@2.0.0 + */ + rejects(): SinonStub; + /** + * Causes the stub to return a Promise which rejects with an exception of the provided type. + * Since sinon@2.0.0 + */ + rejects(errorType: string): SinonStub; + /** + * Causes the stub to return a Promise which rejects with the provided exception object. + * Since sinon@2.0.0 + */ + rejects(value: any): SinonStub; + /** + * Causes the stub to call the argument at the provided index as a callback function. + * stub.callsArg(0); causes the stub to call the first argument as a callback. + * If the argument at the provided index is not available or is not a function, a TypeError will be thrown. + */ + callsArg(index: number): SinonStub; + /** + * Causes the original method wrapped into the stub to be called when none of the conditional stubs are matched. + */ + callThrough(): SinonStub; + /** + * Like stub.callsArg(index); but with an additional parameter to pass the this context. + * @param index + * @param context + */ + callsArgOn(index: number, context: any): SinonStub; + /** + * Like callsArg, but with arguments to pass to the callback. + * @param index + * @param args + */ + callsArgWith(index: number, ...args: any[]): SinonStub; + /** + * Like above but with an additional parameter to pass the this context. + * @param index + * @param context + * @param args + */ + callsArgOnWith( + index: number, + context: any, + ...args: any[] + ): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param index + */ + callsArgAsync(index: number): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param index + * @param context + */ + callsArgOnAsync(index: number, context: any): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + */ + callsArgWithAsync(index: number, ...args: any[]): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + */ + callsArgOnWithAsync( + index: number, + context: any, + ...args: any[] + ): SinonStub; + /** + * Makes the stub call the provided @param func when invoked. + * @param func + */ + callsFake(func: (...args: TArgs) => TReturnValue): SinonStub; + /** + * Replaces a new getter for this stub. + */ + get(func: () => any): SinonStub; + /** + * Defines a new setter for this stub. + * @param func + */ + set(func: (v: any) => void): SinonStub; + /** + * Defines the behavior of the stub on the @param n call. Useful for testing sequential interactions. + * There are methods onFirstCall, onSecondCall,onThirdCall to make stub definitions read more naturally. + * onCall can be combined with all of the behavior defining methods in this section. In particular, it can be used together with withArgs. + * @param n + */ + onCall(n: number): SinonStub; + /** + * Alias for stub.onCall(0); + */ + onFirstCall(): SinonStub; + /** + * Alias for stub.onCall(1); + */ + onSecondCall(): SinonStub; + /** + * Alias for stub.onCall(2); + */ + onThirdCall(): SinonStub; + /** + * Defines a new value for this stub. + * @param val + */ + value(val: any): SinonStub; + /** + * Set the displayName of the spy or stub. + * @param name + */ + named(name: string): SinonStub; + /** + * Similar to callsArg. + * Causes the stub to call the first callback it receives with the provided arguments (if any). + * If a method accepts more than one callback, you need to use callsArg to have the stub invoke other callbacks than the first one. + */ + yields(...args: any[]): SinonStub; + /** + * Like above but with an additional parameter to pass the this context. + */ + yieldsOn(context: any, ...args: any[]): SinonStub; + yieldsRight(...args: any[]): SinonStub; + /** + * Causes the spy to invoke a callback passed as a property of an object to the spy. + * Like yields, yieldsTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments. + * @param property + * @param args + */ + yieldsTo(property: string, ...args: any[]): SinonStub; + /** + * Like above but with an additional parameter to pass the this context. + */ + yieldsToOn( + property: string, + context: any, + ...args: any[] + ): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param args + */ + yieldsAsync(...args: any[]): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param context + * @param args + */ + yieldsOnAsync(context: any, ...args: any[]): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param property + * @param args + */ + yieldsToAsync(property: string, ...args: any[]): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param property + * @param context + * @param args + */ + yieldsToOnAsync( + property: string, + context: any, + ...args: any[] + ): SinonStub; + /** + * Stubs the method only for the provided arguments. + * This is useful to be more expressive in your assertions, where you can access the spy with the same call. + * It is also useful to create a stub that can act differently in response to different arguments. + * @param args + */ + withArgs(...args: MatchArguments): SinonStub; + } + + interface SinonStubStatic { + /** + * Creates an anonymous stub function + */ + (): SinonStub; + /** + * Stubs all the object’s methods. + * Note that it’s usually better practice to stub individual methods, particularly on objects that you don’t understand or control all the methods for (e.g. library dependencies). + * Stubbing individual methods tests intent more precisely and is less susceptible to unexpected behavior as the object’s code evolves. + * If you want to create a stub object of MyConstructor, but don’t want the constructor to be invoked, use this utility function. + */ + (obj: T): SinonStubbedInstance; + /** + * Replaces obj.method with a stub function. + * An exception is thrown if the property is not already a function. + * The original function can be restored by calling object.method.restore(); (or stub.restore();). + */ + (obj: T, method: K): T[K] extends ( + ...args: infer TArgs + ) => infer TReturnValue + ? SinonStub + : SinonStub; + } + + interface SinonExpectation extends SinonStub { + /** + * Specify the minimum amount of calls expected. + */ + atLeast(n: number): SinonExpectation; + /** + * Specify the maximum amount of calls expected. + * @param n + */ + atMost(n: number): SinonExpectation; + /** + * Expect the method to never be called. + */ + never(): SinonExpectation; + /** + * Expect the method to be called exactly once. + */ + once(): SinonExpectation; + /** + * Expect the method to be called exactly twice. + */ + twice(): SinonExpectation; + /** + * Expect the method to be called exactly thrice. + */ + thrice(): SinonExpectation; + /** + * Expect the method to be called exactly @param n times. + */ + exactly(n: number): SinonExpectation; + /** + * Expect the method to be called with the provided arguments and possibly others. + * An expectation instance only holds onto a single set of arguments specified with withArgs. + * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different), + * so it is generally not intended that this method be invoked more than once per test case. + * @param args + */ + withArgs(...args: any[]): SinonExpectation; + /** + * Expect the method to be called with the provided arguments and no others. + * An expectation instance only holds onto a single set of arguments specified with withExactArgs. + * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different), + * so it is generally not intended that this method be invoked more than once per test case. + * @param args + */ + withExactArgs(...args: any[]): SinonExpectation; + on(obj: any): SinonExpectation; + /** + * Verifies all expectations on the mock. + * If any expectation is not satisfied, an exception is thrown. + * Also restores the mocked methods. + */ + verify(): SinonExpectation; + /** + * Restores all mocked methods. + */ + restore(): void; + } + + interface SinonExpectationStatic { + /** + * Creates an expectation without a mock object, basically an anonymous mock function. + * Method name is optional and is used in exception messages to make them more readable. + * @param methodName + */ + create(methodName?: string): SinonExpectation; + } + + interface SinonMock { + /** + * Overrides obj.method with a mock function and returns it. + */ + expects(method: string): SinonExpectation; + /** + * Restores all mocked methods. + */ + restore(): void; + /** + * Verifies all expectations on the mock. + * If any expectation is not satisfied, an exception is thrown. + * Also restores the mocked methods. + */ + verify(): void; + } + + interface SinonMockStatic { + (): SinonExpectation; + /** + * Creates a mock for the provided object. + * Does not change the object, but returns a mock object to set expectations on the object’s methods. + */ + (obj: any): SinonMock; + } + + type SinonTimerId = number | { id: number }; + + interface SinonFakeTimers { + now: number; + + setTimeout( + callback: (...args: any[]) => void, + timeout: number, + ...args: any[] + ): SinonTimerId; + clearTimeout(id: SinonTimerId): void; + setInterval( + callback: (...args: any[]) => void, + timeout: number, + ...args: any[] + ): SinonTimerId; + clearInterval(id: SinonTimerId): void; + setImmediate( + callback: (...args: any[]) => void, + ...args: any[] + ): SinonTimerId; + clearImmediate(id: SinonTimerId): void; + requestAnimationFrame(callback: (...args: any[]) => void): number; + cancelAnimationFrame(id: number): void; + nextTick(callback: () => void): void; + + /** + * Tick the clock ahead time milliseconds. + * Causes all timers scheduled within the affected time range to be called. + * time may be the number of milliseconds to advance the clock by or a human-readable string. + * Valid string formats are “08” for eight seconds, “01:00” for one minute and “02:34:10” for two hours, 34 minutes and ten seconds. + * time may be negative, which causes the clock to change but won’t fire any callbacks. + * @param ms + */ + tick(ms: number | string): void; + /** + * Advances the clock to the the moment of the first scheduled timer, firing it. + */ + next(): void; + /** + * This runs all pending timers until there are none remaining. If new timers are added while it is executing they will be run as well. + * This makes it easier to run asynchronous tests to completion without worrying about the number of timers they use, or the delays in those timers. + */ + runAll(): void; + runToLast(): void; + reset(): void; + runMicrotasks(): void; + runToFrame(): void; + + Date(): Date; + Date(year: number): Date; + Date(year: number, month: number): Date; + Date(year: number, month: number, day: number): Date; + Date(year: number, month: number, day: number, hour: number): Date; + Date( + year: number, + month: number, + day: number, + hour: number, + minute: number + ): Date; + Date( + year: number, + month: number, + day: number, + hour: number, + minute: number, + second: number + ): Date; + Date( + year: number, + month: number, + day: number, + hour: number, + minute: number, + second: number, + ms: number + ): Date; + + /** + * Restore the faked methods. + * Call in e.g. tearDown. + */ + restore(): void; + uninstall(): void; + + /** + * Simulate the user changing the system clock while your program is running. It changes the 'now' timestamp + * without affecting timers, intervals or immediates. + * @param now The new 'now' in unix milliseconds + */ + setSystemTime(now: number): void; + /** + * Simulate the user changing the system clock while your program is running. It changes the 'now' timestamp + * without affecting timers, intervals or immediates. + * @param now The new 'now' as a JavaScript Date + */ + setSystemTime(date: Date): void; + } + + interface SinonFakeTimersConfig { + now: number | Date; + toFake: string[]; + shouldAdvanceTime: boolean; + } + + interface SinonFakeUploadProgress { + 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; + } + + interface SinonFakeXMLHttpRequest { + // Properties + /** + * 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: SinonFakeUploadProgress; + /** + * 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; + + // Methods + /** + * 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; + onerror(): void; + } + + interface SinonFakeXMLHttpRequestStatic { + new (): SinonFakeXMLHttpRequest; + /** + * 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: SinonFakeXMLHttpRequest): void; + /** + * Restore original function(s). + */ + restore(): void; + } + + interface SinonFakeServer extends SinonFakeServerOptions { + // Properties + /** + * 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: SinonFakeXMLHttpRequest): 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: SinonFakeXMLHttpRequest[]; + + // Methods + /** + * 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: SinonFakeXMLHttpRequest) => 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: SinonFakeXMLHttpRequest) => 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: SinonFakeXMLHttpRequest) => 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: SinonFakeXMLHttpRequest) => 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: SinonFakeXMLHttpRequest) => void + ): 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; + } + + interface SinonFakeServerOptions { + /** + * 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; + } + + interface SinonFakeServerStatic { + create(options?: Partial): SinonFakeServer; + } + + interface SinonExposeOptions { + prefix: string; + includeFail: boolean; + } + + interface SinonAssert { + // Properties + /** + * Defaults to AssertError. + */ + failException: string; + /** + * Every assertion fails by calling this method. + * By default it throws an error of type sinon.assert.failException. + * If the test framework looks for assertion errors by checking for a specific exception, you can simply override the kind of exception thrown. + * If that does not fit with your testing framework of choice, override the fail method to do the right thing. + */ + fail(message?: string): void; // Overridable + /** + * Called every time assertion passes. + * Default implementation does nothing. + */ + pass(assertion: any): void; // Overridable + + // Methods + /** + * Passes if spy was never called + * @param spy + */ + notCalled(spy: SinonSpy): void; + /** + * Passes if spy was called at least once. + */ + called(spy: SinonSpy): void; + /** + * Passes if spy was called once and only once. + */ + calledOnce(spy: SinonSpy): void; + /** + * Passes if spy was called exactly twice. + */ + calledTwice(spy: SinonSpy): void; + /** + * Passes if spy was called exactly three times. + */ + calledThrice(spy: SinonSpy): void; + /** + * Passes if spy was called exactly num times. + */ + callCount(spy: SinonSpy, count: number): void; + /** + * Passes if provided spies were called in the specified order. + * @param spies + */ + callOrder(...spies: SinonSpy[]): void; + /** + * Passes if spy was ever called with obj as its this value. + * It’s possible to assert on a dedicated spy call: sinon.assert.calledOn(spy.firstCall, arg1, arg2, ...);. + */ + calledOn(spyOrSpyCall: SinonSpy | SinonSpyCall, obj: any): void; + /** + * Passes if spy was always called with obj as its this value. + */ + alwaysCalledOn(spy: SinonSpy, obj: any): void; + /** + * Passes if spy was called with the provided arguments. + * It’s possible to assert on a dedicated spy call: sinon.assert.calledWith(spy.firstCall, arg1, arg2, ...);. + * @param spyOrSpyCall + * @param args + */ + calledWith(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; + /** + * Passes if spy was always called with the provided arguments. + * @param spy + * @param args + */ + alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was never called with the provided arguments. + * @param spy + * @param args + */ + neverCalledWith(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was called with the provided arguments and no others. + * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithExactly(spy.getCall(1), arg1, arg2, ...);. + * @param spyOrSpyCall + * @param args + */ + calledWithExactly( + spyOrSpyCall: SinonSpy | SinonSpyCall, + ...args: any[] + ): void; + /** + * Passes if spy was always called with the provided arguments and no others. + */ + alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was called with matching arguments. + * This behaves the same way as sinon.assert.calledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). + * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithMatch(spy.secondCall, arg1, arg2, ...);. + */ + calledWithMatch( + spyOrSpyCall: SinonSpy | SinonSpyCall, + ...args: any[] + ): void; + /** + * Passes if spy was always called with matching arguments. + * This behaves the same way as sinon.assert.alwaysCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). + */ + alwaysCalledWithMatch(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was never called with matching arguments. + * This behaves the same way as sinon.assert.neverCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). + * @param spy + * @param args + */ + neverCalledWithMatch(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was called with the new operator. + * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithNew(spy.secondCall, arg1, arg2, ...);. + * @param spyOrSpyCall + */ + calledWithNew(spyOrSpyCall: SinonSpy | SinonSpyCall): void; + /** + * Passes if spy threw any exception. + */ + threw(spyOrSpyCall: SinonSpy | SinonSpyCall): void; + /** + * Passes if spy threw the given exception. + * The exception is an actual object. + * It’s possible to assert on a dedicated spy call: sinon.assert.threw(spy.thirdCall, exception);. + */ + threw(spyOrSpyCall: SinonSpy | SinonSpyCall, exception: string): void; + /** + * Passes if spy threw the given exception. + * The exception is a String denoting its type. + * It’s possible to assert on a dedicated spy call: sinon.assert.threw(spy.thirdCall, exception);. + */ + threw(spyOrSpyCall: SinonSpy | SinonSpyCall, exception: any): void; + /** + * Like threw, only required for all calls to the spy. + */ + alwaysThrew(spy: SinonSpy): void; + /** + * Like threw, only required for all calls to the spy. + */ + alwaysThrew(spy: SinonSpy, exception: string): void; + /** + * Like threw, only required for all calls to the spy. + */ + alwaysThrew(spy: SinonSpy, exception: any): void; + /** + * Uses sinon.match to test if the arguments can be considered a match. + */ + match(actual: any, expected: any): void; + /** + * Exposes assertions into another object, to better integrate with the test framework. + * For instance, JsTestDriver uses global assertions, and to make Sinon.JS assertions appear alongside them, you can do. + * @example sinon.assert.expose(this); + * This will give you assertCalled(spy),assertCallOrder(spy1, spy2, ...) and so on. + * The method accepts an optional options object with two options. + */ + expose(obj: any, options?: Partial): void; + } + + interface SinonMatcher { + /** + * All matchers implement and and or. This allows to logically combine mutliple matchers. + * The result is a new matchers that requires both (and) or one of the matchers (or) to return true. + * @example var stringOrNumber = sinon.match.string.or(sinon.match.number); + * var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); + */ + and(expr: SinonMatcher): SinonMatcher; + /** + * All matchers implement and and or. This allows to logically combine mutliple matchers. + * The result is a new matchers that requires both (and) or one of the matchers (or) to return true. + * @example var stringOrNumber = sinon.match.string.or(sinon.match.number); + * var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); + */ + or(expr: SinonMatcher): SinonMatcher; + test(val: any): boolean; + } + + interface SinonArrayMatcher extends SinonMatcher { + /** + * Requires an Array to be deep equal another one. + */ + deepEquals(expected: any[]): SinonMatcher; + /** + * Requires an Array to start with the same values as another one. + */ + startsWith(expected: any[]): SinonMatcher; + /** + * Requires an Array to end with the same values as another one. + */ + endsWith(expected: any[]): SinonMatcher; + /** + * Requires an Array to contain each one of the values the given array has. + */ + contains(expected: any[]): SinonMatcher; + } + + interface SimplifiedSet { + has(el: any): boolean; + } + + interface SimplifiedMap extends SimplifiedSet { + get(key: any): any; + } + + interface SinonMapMatcher extends SinonMatcher { + /** + * Requires a Map to be deep equal another one. + */ + deepEquals(expected: SimplifiedMap): SinonMatcher; + /** + * Requires a Map to contain each one of the items the given map has. + */ + contains(expected: SimplifiedMap): SinonMatcher; + } + + interface SinonSetMatcher extends SinonMatcher { + /** + * Requires a Set to be deep equal another one. + */ + deepEquals(expected: SimplifiedSet): SinonMatcher; + /** + * Requires a Set to contain each one of the items the given set has. + */ + contains(expected: SimplifiedSet): SinonMatcher; + } + + interface SinonMatch { + /** + * Requires the value to be == to the given number. + */ + (value: number): SinonMatcher; + /** + * Requires the value to be a string and have the expectation as a substring. + */ + (value: string): SinonMatcher; + /** + * Requires the value to be a string and match the given regular expression. + */ + (expr: RegExp): SinonMatcher; + /** + * See custom matchers. + */ + (callback: (value: any) => boolean, message?: string): SinonMatcher; + /** + * Requires the value to be not null or undefined and have at least the same properties as expectation. + * This supports nested matchers. + */ + (obj: object): SinonMatcher; + /** + * Matches anything. + */ + any: SinonMatcher; + /** + * Requires the value to be defined. + */ + defined: SinonMatcher; + /** + * Requires the value to be truthy. + */ + truthy: SinonMatcher; + /** + * Requires the value to be falsy. + */ + falsy: SinonMatcher; + /** + * Requires the value to be a Boolean + */ + bool: SinonMatcher; + /** + * Requires the value to be a Number. + */ + number: SinonMatcher; + /** + * Requires the value to be a String. + */ + string: SinonMatcher; + /** + * Requires the value to be an Object. + */ + object: SinonMatcher; + /** + * Requires the value to be a Function. + */ + func: SinonMatcher; + /** + * Requires the value to be a Map. + */ + map: SinonMapMatcher; + /** + * Requires the value to be a Set. + */ + set: SinonSetMatcher; + /** + * Requires the value to be an Array. + */ + array: SinonArrayMatcher; + /** + * Requires the value to be a regular expression. + */ + regexp: SinonMatcher; + /** + * Requires the value to be a Date object. + */ + date: SinonMatcher; + /** + * Requires the value to be a Symbol. + */ + symbol: SinonMatcher; + /** + * Requires the value to strictly equal ref. + */ + same(obj: any): SinonMatcher; + /** + * Requires the value to be of the given type, where type can be one of "undefined", "null", "boolean", "number", "string", "object", "function", "array", "regexp", "date" or "symbol". + */ + typeOf(type: string): SinonMatcher; + /** + * Requires the value to be an instance of the given type. + */ + instanceOf(type: any): SinonMatcher; + /** + * Requires the value to define the given property. + * The property might be inherited via the prototype chain. + * If the optional expectation is given, the value of the property is deeply compared with the expectation. + * The expectation can be another matcher. + * @param property + * @param expect + */ + has(property: string, expect?: any): SinonMatcher; + /** + * Same as sinon.match.has but the property must be defined by the value itself. Inherited properties are ignored. + * @param property + * @param expect + */ + hasOwn(property: string, expect?: any): SinonMatcher; + /** + * Requires the value to define the given propertyPath. Dot (prop.prop) and bracket (prop[0]) notations are supported as in Lodash.get. + * The propertyPath might be inherited via the prototype chain. + * If the optional expectation is given, the value at the propertyPath is deeply compared with the expectation. + * The expectation can be another matcher. + */ + hasNested(path: string, expect?: any): SinonMatcher; + /** + * Requires every element of an Array, Set or Map, or alternatively every value of an Object to match the given matcher. + */ + every(matcher: SinonMatcher): SinonMatcher; + /** + * Requires any element of an Array, Set or Map, or alternatively any value of an Object to match the given matcher. + */ + some(matcher: SinonMatcher): SinonMatcher; + } + + interface SinonSandboxConfig { + /** + * The sandbox’s methods can be injected into another object for convenience. + * The injectInto configuration option can name an object to add properties to. + */ + injectInto: object | null; + /** + * What properties to inject. + * Note that simply naming “server” here is not sufficient to have a server property show up in the target object, + * you also have to set useFakeServer to true. + */ + properties: string[]; + /** + * If set to true, the sandbox will have a clock property. + * You can optionally pass in a configuration object that follows the specification for fake timers, such as { toFake: ["setTimeout", "setInterval"] }. + */ + useFakeTimers: boolean | Partial; + /** + * If true, server and requests properties are added to the sandbox. Can also be an object to use for fake server. + * The default one is sinon.fakeServer, but if you’re using jQuery 1.3.x or some other library that does not set the XHR’s onreadystatechange handler, + * you might want to do: + */ + useFakeServer: boolean | SinonFakeServer; + } + + /** + * Stubbed type of an object with members replaced by stubs. + * + * @template TType Type being stubbed. + */ + type StubbableType = Function & { prototype: TType }; + + /** + * An instance of a stubbed object type with functions replaced by stubs. + * + * @template TType Object type being stubbed. + */ + type SinonStubbedInstance = { + [P in keyof TType]: SinonStubbedMember + }; + + /** + * Replaces a type with a Sinon stub if it's a function. + */ + type SinonStubbedMember = T extends Function ? SinonStub : T; + + interface SinonFake { + /** + * Creates a basic fake, with no behavior + */ + (): SinonSpy; + /** + * Wraps an existing Function to record all interactions, while leaving it up to the func to provide the behavior. + * This is useful when complex behavior not covered by the sinon.fake.* methods is required or when wrapping an existing function or method. + */ + (fn: Function): SinonSpy; + /** + * Creates a fake that returns the val argument + * @param val Returned value + */ + returns(val: any): SinonSpy; + /** + * Creates a fake that throws an Error with the provided value as the message property. + * If an Error is passed as the val argument, then that will be the thrown value. If any other value is passed, then that will be used for the message property of the thrown Error. + * @param val Returned value or throw value if an Error + */ + throws(val: Error | string): SinonSpy; + /** + * Creates a fake that returns a resolved Promise for the passed value. + * @param val Resolved promise + */ + resolves(val: any): SinonSpy; + /** + * Creates a fake that returns a rejected Promise for the passed value. + * If an Error is passed as the value argument, then that will be the value of the promise. + * If any other value is passed, then that will be used for the message property of the Error returned by the promise. + * @param val Rejected promise + */ + rejects(val: any): SinonSpy; + /** + * fake expects the last argument to be a callback and will invoke it with the given arguments. + */ + yields(...args: any[]): SinonSpy; + /** + * fake expects the last argument to be a callback and will invoke it asynchronously with the given arguments. + */ + yieldsAsync(...args: any[]): SinonSpy; + } + + interface SinonSandbox { + /** + * A convenience reference for sinon.assert + * Since sinon@2.0.0 + */ + assert: SinonAssert; + clock: SinonFakeTimers; + requests: SinonFakeXMLHttpRequest[]; + server: SinonFakeServer; + /** + * Works exactly like sinon.spy + */ + spy: SinonSpyStatic; + /** + * Works exactly like sinon.stub. + */ + stub: SinonStubStatic; + /** + * Works exactly like sinon.mock + */ + mock: SinonMockStatic; + + /** + * * No param : Causes Sinon to replace the global setTimeout, clearTimeout, setInterval, clearInterval, setImmediate, clearImmediate, process.hrtime, performance.now(when available) + * and Date with a custom implementation which is bound to the returned clock object. + * Starts the clock at the UNIX epoch (timestamp of 0). + * * Now : As above, but rather than starting the clock with a timestamp of 0, start at the provided timestamp now. + * Since sinon@2.0.0 + * You can also pass in a Date object, and its getTime() will be used for the starting timestamp. + * * Config : As above, but allows further configuration options, some of which are: + * * config.now - Number/Date - installs lolex with the specified unix epoch (default: 0) + * * config.toFake - String[ ] - an array with explicit function names to fake. + * By default lolex will automatically fake all methods except process.nextTick. You could, however, still fake nextTick by providing it explicitly + * * config.shouldAdvanceTime - Boolean - tells lolex to increment mocked time automatically based on the real system time shift (default: false) + * * Please visit the lolex.install documentation for the full feature set. + * * Important note: when faking nextTick, normal calls to process.nextTick() would not execute automatically as they would during normal event-loop phases. + * You would have to call either clock.next(), clock.tick(), clock.runAll() or clock.runToLast() (see example below). Please refer to the lolex documentation for more information. + * @param config + */ + useFakeTimers( + config?: number | Date | Partial + ): SinonFakeTimers; + /** + * Causes Sinon to replace the native XMLHttpRequest object in browsers that support it with a custom implementation which does not send actual requests. + * In browsers that support ActiveXObject, this constructor is replaced, and fake objects are returned for XMLHTTP progIds. + * Other progIds, such as XMLDOM are left untouched. + * The native XMLHttpRequest object will be available at sinon.xhr.XMLHttpRequest + */ + useFakeXMLHttpRequest(): SinonFakeXMLHttpRequestStatic; + /** + * Fakes XHR and binds a server object to the sandbox such that it too is restored when calling sandbox.restore(). + * Access requests through sandbox.requests and server through sandbox.server + */ + useFakeServer(): SinonFakeServer; + /** + * Restores all fakes created through sandbox. + */ + restore(): void; + /** + * Resets the internal state of all fakes created through sandbox. + */ + reset(): void; + /** + * Resets the history of all stubs created through the sandbox. + * Since sinon@2.0.0 + */ + resetHistory(): void; + /** + * Resets the behaviour of all stubs created through the sandbox. + * Since sinon@2.0.0 + */ + resetBehavior(): void; + /** + * Causes all stubs created from the sandbox to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. + * Returns the stub to allow chaining. + * Since sinon@2.0.0 + */ + usingPromise(promiseLibrary: any): SinonSandbox; + /** + * Verifies all mocks created through the sandbox. + */ + verify(): void; + /** + * Verifies all mocks and restores all fakes created through the sandbox. + */ + verifyAndRestore(): void; + + /** + * Replaces property on object with replacement argument. Attempts to replace an already replaced value cause an exception. + * replacement can be any value, including spies, stubs and fakes. + * This method only works on non-accessor properties, for replacing accessors, use sandbox.replaceGetter() and sandbox.replaceSetter(). + */ + replace( + obj: T, + prop: TKey, + replacement: T[TKey] + ): T[TKey]; + /** + * Replaces getter for property on object with replacement argument. Attempts to replace an already replaced getter cause an exception. + * replacement must be a Function, and can be instances of spies, stubs and fakes. + * @param obj + * @param prop + * @param replacement + */ + replaceGetter( + obj: T, + prop: TKey, + replacement: () => T[TKey] + ): () => T[TKey]; + /** + * Replaces setter for property on object with replacement argument. Attempts to replace an already replaced setter cause an exception. + * replacement must be a Function, and can be instances of spies, stubs and fakes. + * @param obj + * @param prop + * @param replacement + */ + replaceSetter( + obj: T, + prop: TKey, + replacement: (val: T[TKey]) => void + ): (val: T[TKey]) => void; + + /** + * Creates a new object with the given functions as the prototype and stubs all implemented functions. + * + * @template TType Type being stubbed. + * @param constructor Object or class to stub. + * @returns A stubbed version of the constructor. + * @remarks The given constructor function is not invoked. See also the stub API. + */ + createStubInstance( + constructor: StubbableType + ): SinonStubbedInstance; + } + + interface SinonApi { + fake: SinonFake; + match: SinonMatch; + spyCall(...args: any[]): SinonSpyCall; + expectation: SinonExpectationStatic; + + clock: { + create(now: number | Date): SinonFakeTimers; + }; + + FakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; + + fakeServer: SinonFakeServerStatic; + fakeServerWithClock: SinonFakeServerStatic; + + /** + * Creates a new sandbox object with spies, stubs, and mocks. + * @param config + */ + createSandbox(config?: Partial): SinonSandbox; + defaultConfig: Partial; + } + + interface LegacySandbox { + sandbox: { + /** + * @deprecated Since 5.0, use `sinon.createSandbox` instead + */ + create(config?: Partial): SinonSandbox; + }; + } + + type SinonStatic = SinonSandbox & LegacySandbox & SinonApi; +} + +declare const Sinon: Sinon.SinonStatic; + +export = Sinon; +export as namespace sinon; diff --git a/types/sinon/ts3.1/sinon-tests.ts b/types/sinon/ts3.1/sinon-tests.ts new file mode 100644 index 0000000000..b892f22980 --- /dev/null +++ b/types/sinon/ts3.1/sinon-tests.ts @@ -0,0 +1,488 @@ +import sinon = require("sinon"); + +function testSandbox() { + const obj = {}; + + sinon.createSandbox({ + injectInto: obj, + properties: ['spy', 'stub'], + useFakeTimers: true, + useFakeServer: true + }); + sinon.createSandbox({ + injectInto: null + }); + sinon.createSandbox({ + useFakeTimers: { + now: 1000, + shouldAdvanceTime: false + }, + useFakeServer: sinon.fakeServer.create() + }); + sinon.createSandbox(sinon.defaultConfig); + sinon.sandbox.create(); + sinon.sandbox.create(sinon.defaultConfig); + + const sb = sinon.createSandbox(); + + sb.assert.pass('foo'); + sb.clock.tick(1000); + sb.spy(); + sb.stub(); + sb.mock(obj); + + sb.useFakeTimers(); + sb.useFakeTimers(1000); + sb.useFakeTimers(new Date()); + sb.useFakeTimers({ + now: 1000 + }); + + const xhr = sb.useFakeXMLHttpRequest(); + xhr.useFilters = true; + xhr.restore(); + + const server = sb.useFakeServer(); + server.respondWith('foo'); + + sb.restore(); + sb.reset(); + sb.resetHistory(); + sb.resetBehavior(); + sb.usingPromise(Promise); + sb.verify(); + sb.verifyAndRestore(); + + const replaceMe = { + prop: 5, + method() { return 6; }, + get getter() { return 7; }, + get setter() { return true; }, + set setter(val) { } + }; + + sb.replace(replaceMe, 'prop', 10); + sb.replace(replaceMe, 'method', sb.spy()); + sb.replaceGetter(replaceMe, 'getter', () => 14); + sb.replaceSetter(replaceMe, 'setter', (v) => { }); + + const cls = class { + foo() { } + bar: number; + }; + const PrivateFoo = class { + private constructor() { } + foo() { } + bar: number; + static create() { + return new PrivateFoo(); + } + }; + + const stubInstance = sb.createStubInstance(cls); + const privateFooStubbedInstance = sb.createStubInstance(PrivateFoo); + stubInstance.foo.calledWith('foo'); + privateFooStubbedInstance.foo.calledWith('foo'); + const clsFoo: sinon.SinonStub = stubInstance.foo; + const privateFooFoo: sinon.SinonStub = privateFooStubbedInstance.foo; + const clsBar: number = stubInstance.bar; + const privateFooBar: number = privateFooStubbedInstance.bar; +} + +function testFakeServer() { + let s = sinon.fakeServer.create(); + s = sinon.fakeServerWithClock.create(); + + sinon.fakeServer.create({ + autoRespond: true, + autoRespondAfter: 3, + fakeHTTPMethods: true, + respondImmediately: false + }); + + sinon.fakeServer.create({ + autoRespond: true, + autoRespondAfter: 3 + }); +} + +function testXHR() { + const xhr = new sinon.FakeXMLHttpRequest(); + const headers = xhr.getAllResponseHeaders(); + const header = xhr.getResponseHeader('foo'); + + xhr.setResponseHeaders({ 'Content-Type': 'text/html' }); + xhr.setResponseBody('foo'); + xhr.respond(200, { 'Content-Type': 'foo' }, 'bar'); + xhr.error(); + + sinon.FakeXMLHttpRequest.useFilters = true; + sinon.FakeXMLHttpRequest.addFilter((method, url, async, user, pass) => true); + sinon.FakeXMLHttpRequest.onCreate = (xhr) => { }; + sinon.FakeXMLHttpRequest.restore(); +} + +function testClock() { + let clock = sinon.clock.create(1000); + clock = sinon.clock.create(new Date()); + + let now = 0; + now = clock.now; + + const fn = () => { }; + + clock.setTimeout(fn, 0); + clock.setTimeout(fn, 0, 'a', 'b'); + clock.setInterval(fn, 0); + clock.setInterval(fn, 0, 'a', 'b'); + clock.setImmediate(fn); + clock.setImmediate(fn, 'a', 'b'); + clock.requestAnimationFrame(fn); + + let timer = clock.setTimeout(fn, 0); + clock.clearTimeout(timer); + timer = clock.setInterval(fn, 0); + clock.clearInterval(timer); + timer = clock.setImmediate(fn); + clock.clearImmediate(timer); + + const animTimer = clock.requestAnimationFrame(fn); + clock.cancelAnimationFrame(animTimer); + + clock.nextTick(fn); + clock.tick(1); + clock.tick('00:10'); + clock.next(); + clock.runAll(); + clock.runToLast(); + clock.reset(); + clock.runMicrotasks(); + clock.runToFrame(); + clock.restore(); + clock.uninstall(); + clock.setSystemTime(1000); + clock.setSystemTime(new Date()); +} + +function testExpectation() { + const obj = {}; + + let ex = sinon.expectation.create(); + ex = sinon.expectation.create('some name'); + + ex.atLeast(5).atMost(10); + ex.never(); + ex.once(); + ex.twice(); + ex.thrice(); + ex.exactly(5); + ex.withArgs('a', 'b'); + ex.withExactArgs('a', 'b'); + ex.on(obj); + ex.verify(); + ex.restore(); +} + +function testMatch() { + const obj = {}; + const fn = () => { }; + + sinon.match(5).test(5); + sinon.match('str').test('foo'); + sinon.match(/foo/).test('foo'); + sinon.match({ a: 5, b: 6 }).test({}); + sinon.match((v) => true).test('foo'); + sinon.match((v) => true, 'some message').test('foo'); + sinon.match.any.test('foo'); + sinon.match.defined.test('foo'); + sinon.match.truthy.test('foo'); + sinon.match.falsy.test('foo'); + sinon.match.bool.test('foo'); + sinon.match.number.test('foo'); + sinon.match.string.test('foo'); + sinon.match.object.test('foo'); + sinon.match.func.test(fn); + sinon.match.map.test(new Map([['a', 1], ['b', 2]])); + sinon.match.set.test(new Set([1, 2, 3])); + sinon.match.array.test([1, 2, 3]); + sinon.match.regexp.test('foo'); + sinon.match.date.test('foo'); + sinon.match.symbol.test('foo'); + sinon.match.same(obj); + sinon.match.typeOf('string').test('foo'); + sinon.match.instanceOf(fn).test('foo'); + sinon.match.has('prop').test(obj); + sinon.match.has('prop', 123).test(obj); + sinon.match.hasOwn('prop').test(obj); + sinon.match.hasOwn('prop', 123).test(obj); + sinon.match.hasNested('prop.foo.bar').test(obj); + sinon.match.hasNested('prop.foo.bar', 123).test(obj); + sinon.match.every(sinon.match.number).test([1, 2, 'three']); + sinon.match.some(sinon.match.number).test([1, 2, 'three']); + sinon.match.array.deepEquals([{ a: 'b' }]).test([]); + sinon.match.array.startsWith([{ a: 'b' }]).test([]); + sinon.match.array.deepEquals([{ a: 'b' }]).test([]); + sinon.match.array.contains([{ a: 'b' }]).test([]); + sinon.match.map.deepEquals(new Map([['a', true], ['b', false]])).test(new Map()); + sinon.match.map.contains(new Map([['a', true]])).test(new Map()); +} + +function testFake() { + const fn = () => { }; + let fake = sinon.fake(); + + fake = sinon.fake(() => true); + fake = sinon.fake.returns(5); + fake = sinon.fake.throws('foo'); + fake = sinon.fake.throws(new Error('foo')); + fake = sinon.fake.resolves('foo'); + fake = sinon.fake.rejects('foo'); + fake = sinon.fake.yields(1, 2, fn); + fake = sinon.fake.yieldsAsync(1, 2, fn); + + fake.calledWith('foo'); +} + +function testAssert() { + const spy = sinon.spy(); + const spyTwo = sinon.spy(); + const obj = {}; + + sinon.assert.fail(); + sinon.assert.fail('foo'); + sinon.assert.pass('foo'); + sinon.assert.notCalled(spy); + sinon.assert.called(spy); + sinon.assert.calledOnce(spy); + sinon.assert.calledTwice(spy); + sinon.assert.calledThrice(spy); + sinon.assert.callCount(spy, 3); + sinon.assert.callOrder(spy, spyTwo); + sinon.assert.calledOn(spy, obj); + sinon.assert.calledOn(spy.firstCall, obj); + sinon.assert.alwaysCalledOn(spy, obj); + sinon.assert.alwaysCalledWith(spy, 'a', 'b', 'c'); + sinon.assert.neverCalledWith(spy, 'a', 'b', 'c'); + sinon.assert.calledWithExactly(spy, 'a', 'b', 'c'); + sinon.assert.alwaysCalledWithExactly(spy, 'a', 'b', 'c'); + sinon.assert.calledWithMatch(spy, 'a', 'b', 'c'); + sinon.assert.calledWithMatch(spy.firstCall, 'a', 'b', 'c'); + sinon.assert.alwaysCalledWithMatch(spy, 'a', 'b', 'c'); + sinon.assert.neverCalledWithMatch(spy, 'a', 'b', 'c'); + sinon.assert.calledWithNew(spy); + sinon.assert.calledWithNew(spy.firstCall); + sinon.assert.threw(spy); + sinon.assert.threw(spy.firstCall); + sinon.assert.threw(spy, 'foo error'); + sinon.assert.threw(spy.firstCall, 'foo error'); + sinon.assert.threw(spy, new Error('foo')); + sinon.assert.threw(spy.firstCall, new Error('foo')); + sinon.assert.alwaysThrew(spy); + sinon.assert.alwaysThrew(spy, 'foo error'); + sinon.assert.alwaysThrew(spy, new Error('foo')); + sinon.assert.match('a', 'b'); + sinon.assert.match(1, 1 + 1); + sinon.assert.match({ a: 1 }, { b: 2, c: 'abc' }); + sinon.assert.expose(obj); + sinon.assert.expose(obj, { prefix: 'blah' }); + sinon.assert.expose(obj, { includeFail: true }); +} + +function testTypedSpy() { + const cls = class { + foo(a: number, b: string): number { + return 3; + } + }; + + const instance = new cls(); + const spy = sinon.spy(instance, 'foo'); + + spy.calledWith(5, 'x'); + spy.calledWith(sinon.match(5), 'x'); + spy.calledWithExactly(5, 'x'); + spy.calledWithExactly(5, sinon.match('x')); + spy.calledOnceWith(5, 'x'); + spy.calledOnceWith(sinon.match(5), 'x'); + spy.notCalledWith(5, 'x'); + spy.notCalledWith(sinon.match(5), 'x'); + spy.returned(5); + spy.returned(sinon.match(5)); + + spy.withArgs(sinon.match(5), 'x').calledWith(5, 'x'); + spy.alwaysCalledWith(sinon.match(5), 'x'); + spy.alwaysCalledWith(5, 'x'); + spy.alwaysCalledWithExactly(sinon.match(5), 'x'); + spy.alwaysCalledWithExactly(5, 'x'); + spy.neverCalledWith(sinon.match(5), 'x'); + spy.neverCalledWith(5, 'x'); + + const stub = sinon.stub(instance, 'foo'); + + stub.withArgs(5, 'x').returns(3); + stub.withArgs(sinon.match(5), 'x').returns(5); +} + +function testSpy() { + const fn = () => { }; + const obj = class { + foo() { } + }; + const instance = new obj(); + + let spy = sinon.spy(); + const spyTwo = sinon.spy().named('spyTwo'); + + spy = sinon.spy(fn); + spy = sinon.spy(instance, 'foo'); + + let count = 0; + count = spy.callCount; + + let called = false; + called = spy.called; + called = spy.notCalled; + called = spy.calledOnce; + called = spy.calledTwice; + called = spy.calledThrice; + + let arr: any[] = []; + arr = spy.thisValues; + arr = spy.args; + arr = spy.exceptions; + arr = spy.returnValues; + + spy('a', 'b'); + spy(1, 2); + spy(true); + + spy.calledBefore(spyTwo); + spy.calledAfter(spyTwo); + spy.calledImmediatelyBefore(spyTwo); + spy.calledImmediatelyAfter(spyTwo); + spy.calledWithNew(); + spy.withArgs('a', 1).calledBefore(spyTwo); + spy.alwaysCalledOn(instance); + spy.alwaysCalledWith('a', 1); + spy.alwaysCalledWith('a'); + spy.alwaysCalledWithExactly('a', 1); + spy.alwaysCalledWithMatch('foo'); + spy.neverCalledWith('b', 2); + spy.neverCalledWith('b'); + spy.neverCalledWithMatch('foo', 'bar'); + spy.alwaysThrew(); + spy.alwaysThrew('foo'); + spy.alwaysThrew(new Error('foo')); + spy.alwaysReturned('foo'); + spy.invokeCallback('a', 'b'); + spy.calledOn(instance); + spy.calledWith('a', 2); + spy.calledWithExactly('a', 2); + spy.calledOnceWith('a', 2); + spy.calledOnceWithExactly('a', 2); + spy.calledWithMatch('bar', 2); + spy.notCalledWith('a', 2); + spy.notCalledWithMatch('a', 2); + spy.returned(true); + spy.returned('foo'); + spy.returned(2); + spy.threw(); + spy.threw('foo'); + spy.threw(new Error('foo')); + spy.callArg(1); + spy.callArgOn(1, instance); + spy.callArgOn(1, instance, 'a', 2); + spy.callArgWith(1, 'a', 2); + spy.callArgOnWith(1, instance, 'a', 2); + spy.yield('a', 2); + spy.yieldOn(instance, 'a', 2); + spy.yieldTo('prop', 'a', 2); + spy.yieldToOn('prop', instance, 'a', 2); + + let call = spy.firstCall; + call = spy.secondCall; + call = spy.thirdCall; + call = spy.lastCall; + call = spy.getCall(1); + call = spy.getCalls()[0]; + + call.calledBefore(call); + call.calledAfter(call); + call.calledWithNew(); + + spy.resetHistory(); + spy.restore(); +} + +function testStub() { + const obj = class { + foo() { } + }; + const instance = new obj(); + + let stub = sinon.stub(); + stub = sinon.stub(instance, 'foo').named('namedStub'); + + const spy: sinon.SinonSpy = stub; + + sinon.stub(instance); + + stub.reset(); + stub.resetBehavior(); + stub.usingPromise(Promise); + + stub.returns(true); + stub.returns(5); + stub.returns('foo'); + stub.returnsArg(1); + stub.returnsThis(); + stub.resolves(); + stub.resolves('foo'); + stub.resolvesArg(1); + stub.resolvesThis(); + stub.throws(); + stub.throws('err'); + stub.throws(new Error('err')); + stub.throwsArg(1); + stub.throwsException('err'); + stub.throwsException(new Error('err')); + stub.rejects(); + stub.rejects('TypeError'); + stub.rejects(1234); + stub.callsArg(1); + stub.callThrough(); + stub.callsArgOn(1, instance); + stub.callsArgWith(1, 'a', 2); + stub.callsArgAsync(1); + stub.callsArgOnAsync(1, instance); + stub.callsArgWithAsync(1, 'a', 2); + stub.callsArgOnWithAsync(1, instance, 'a', 2); + stub.callsFake((s1, s2, s3) => { }); + stub.callsFake(() => { }); + stub.get(() => true); + stub.set((v) => { }); + stub.onCall(1).returns(true); + stub.onFirstCall().resolves('foo'); + stub.onSecondCall().resolves('foo'); + stub.onThirdCall().resolves('foo'); + stub.value('foo'); + stub.yields('a', 2); + stub.yieldsOn(instance, 'a', 2); + stub.yieldsRight('a', 2); + stub.yieldsTo('foo', 'a', 2); + stub.yieldsToOn('foo', instance, 'a', 2); + stub.yieldsAsync('a', 2); + stub.yieldsOnAsync(instance, 'a', 2); + stub.yieldsToAsync('foo', 'a', 2); + stub.yieldsToOnAsync('foo', instance, 'a', 2); + stub.withArgs('a', 2).returns(true); +} + +function testMock() { + const obj = {}; + const mock = sinon.mock(obj); + + mock.expects('method').atLeast(2).atMost(5); + mock.restore(); + mock.verify(); +} diff --git a/types/sinon/ts3.1/tsconfig.json b/types/sinon/ts3.1/tsconfig.json new file mode 100644 index 0000000000..7468efa8bf --- /dev/null +++ b/types/sinon/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "target": "es5", + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sinon-tests.ts" + ] +} diff --git a/types/sinon/ts3.1/tslint.json b/types/sinon/ts3.1/tslint.json new file mode 100644 index 0000000000..1b62a88e52 --- /dev/null +++ b/types/sinon/ts3.1/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "unified-signatures": false + } +} diff --git a/types/sip.js/index.d.ts b/types/sip.js/index.d.ts index 65466ee840..7ca7c2eb98 100644 --- a/types/sip.js/index.d.ts +++ b/types/sip.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for sip.js 0.8 +// Type definitions for sip.js 0.9 // Project: http://sipjs.com // Definitions by: Kir Dergachev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -75,6 +75,8 @@ export namespace C { export type DescriptionModifier = (description: RTCSessionDescription) => Promise; export interface SessionDescriptionHandler { + peerConnection: any; + getDescription(options: SessionDescriptionHandlerParameters, modifiers: DescriptionModifier[]): Promise; setDescription(sessionDescription: string, options: SessionDescriptionHandlerParameters, modifiers: DescriptionModifier[]): Promise; hasDescription: (contentType: string) => boolean; @@ -128,11 +130,16 @@ export interface Session { on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; on(name: 'failed' | 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; - on(name: 'cancel' | string, callback: () => void): void; - on(name: 'replaced', callback: (newSession: Session) => void): void; + on(name: 'cancel' | 'directionChanged' | 'trackAdded' | 'SessionDescriptionHandler-created' | string, callback: () => void): void; + on(name: 'replaced' | 'reinvite', callback: (newSession: Session) => void): void; on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; on(name: 'muted' | 'unmuted', callback: (data: Session.Muted) => void): void; - on(name: 'refer' | 'bye', callback: (request: IncomingRequest) => void): void; + on(name: 'refer' | 'bye' | 'notify', callback: (request: IncomingRequest) => void): void; + on(name: 'referRequested', callback: (request: ClientContext | ServerContext) => void): void; + + /* these come from the ClientContext that is on the session somehow */ + on(name: 'referAccepted' | 'referRejected' | 'referRequestAccepted' | 'referRequestRejected' | 'referProgress', + callback: (ClientContext: ClientContext) => void): void; } export namespace Session { @@ -164,7 +171,10 @@ export namespace Session { }; } - interface DTMF extends Object { } + interface DTMF extends Object { + direction: string | 'incoming'; + tone: any; + } interface Muted { audio?: boolean; @@ -364,27 +374,40 @@ export interface Subscription extends ClientContext { } /* Context */ -export interface Context { +export class Context { ua: UA; method: string; request: OutgoingRequest; localIdentity: NameAddrHeader; remoteIdentity: NameAddrHeader; data: {}; +} + +export class ClientContext extends Context { + cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; + + // This exists on all Context, but I cant make it work right on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; on(name: 'notify', callback: (request: IncomingRequest) => void): void; on(name: string, callback: () => void): void; + + on(name: 'referAccepted' | 'referRejected' | 'referRequestAccepted' | 'referRequestRejected' | 'referProgress', + callback: (ClientContext: ClientContext) => void): void; } -export interface ClientContext extends Context { - cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; -} - -export interface ServerContext extends Context { +export class ServerContext extends Context { progress(options?: Session.ProgressOptions): void; accept(options?: Session.AcceptOptions): void; reject(options?: Session.CommonOptions): void; reply(options?: Session.CommonOptions): void; + + // This exists on all Context, but I cant make it work right + on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'notify', callback: (request: IncomingRequest) => void): void; + on(name: string, callback: () => void): void; + + on(name: 'referRequestAccepted' | 'referRequestRejected' | 'referInviteSent' | 'referProgress' | 'referAccepted' | 'referRejected', + callback: (ServerContext: ServerContext) => void): void; } /* Request */ @@ -398,6 +421,7 @@ export interface OutgoingRequest extends Request { } export interface IncomingResponse extends Request { + reason_phrase: string | 'Ringing'; } export interface IncomingMessage extends Request { diff --git a/types/sketchapp/index.d.ts b/types/sketchapp/index.d.ts new file mode 100644 index 0000000000..6d9776aaa7 --- /dev/null +++ b/types/sketchapp/index.d.ts @@ -0,0 +1,516 @@ +// Type definitions for the SketchApp 1.0 +// Project: https://github.com/xlayers/xlayers +// Definitions by: Wassim Chegham +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type SketchMSBorderPositionEnum = 0 | 1 | 2 | 3; +type SketchMSBorderLineCapStyle = 0 | 1 | 2; +type SketchMSBorderLineJoinStyle = 0 | 1 | 2; +type SketchMSFillTypeEnum = 0 | 1 | 4 | 5; +type SketchMSPatternFillTypeEnum = 0 | 1 | 2 | 3; +type SketchMSBlendModeEnum = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15; +type SketchMSLineDecorationTypeEnum = 0 | 1 | 2 | 3; +type SketchMSBooleanOperation = -1 | 0 | 1 | 2 | 3; +type SketchMSCurveMode = 0 | 1 | 2 | 3 | 4; +type SketchMSResizingType = 0 | 1 | 2 | 3; +type SketchMSLayerListExpandedType = 0 | 1 | 2; +type SketchMSEncodedBase64BinaryPlist = string; +type SketchMSNSColorArchive = SketchMSKeyValueArchive; +type SketchMSLayer = SketchMSPage | SketchMSSymbolMaster; +interface SketchMSNestedSymbolOverride { + symbolID: string; +} +interface SketchMSStringAttribute { + _class: 'stringAttribute'; + attributes: { + MSAttributedStringFontAttribute: { + _class: 'fontDescriptor'; + attributes: { + name: string; + size: number; + } + }; + paragraphStyle: { + _class: 'paragraphStyle', + allowsDefaultTighteningForTruncation: number + }, + foregroundColor: SketchMSKeyValueArchive + }; +} +interface SketchMSAttributedString { + _class: 'attributedString'; + string: string; + attributes: SketchMSStringAttribute[]; + archivedAttributedString?: SketchMSKeyValueArchive; +} +interface SketchMSKeyValueArchive { + _archive: SketchMSEncodedBase64BinaryPlist; +} +interface SketchMSFontAttribute { + _class: 'fontDescriptor'; + _archive?: string; + attributes: { + name: string; + size: number; + }; +} +interface SketchMSBorder { + _class: 'border'; + isEnabled: boolean; + color: SketchMSColor; + fillType: SketchMSFillTypeEnum; + position: SketchMSBorderPositionEnum; + thickness: number; +} +interface SketchMSBorderOptions { + _class: 'borderOptions'; + isEnabled: boolean; + dashPattern: number[]; + lineCapStyle: SketchMSBorderLineCapStyle; + lineJoinStyle: SketchMSBorderLineJoinStyle; +} + +interface SketchMSImageDataReference { + _class: 'jSONOriginalDataReference'; + _ref: string; + _ref_class: 'imageData'; + data: { + _data: string; + }; + sha1: { + _data: string; + }; +} +type SketchMSPointString = string; +interface SketchMSPath { + _class: 'path'; + isClosed: boolean; + points: SketchMSCurvePoint[]; +} +interface SketchMSCurvePoint { + _class: 'curvePoint'; + cornerRadius: number; + curveFrom: SketchMSPointString; + curveMode: SketchMSCurveMode; + curveTo: SketchMSPointString; + hasCurveFrom: boolean; + hasCurveTo: boolean; + point: SketchMSPointString; +} + +interface SketchMSFill { + _class: 'fill'; + isEnabled: boolean; + color?: SketchMSColor; + fillType: SketchMSFillTypeEnum; + image?: SketchMSImageDataReference; + noiseIndex: number; + noiseIntensity: number; + patternFillType: SketchMSPatternFillTypeEnum; + patternTileScale: number; +} +interface SketchMSShadow { + _class: 'shadow' | 'MSInnerShadow'; + isEnabled: boolean; + blurRadius: number; + color: SketchMSColor; + contextSettings: SketchMSGraphicsContextSettings; + offsetX: number; + offsetY: number; + spread: number; +} +interface SketchMSImageCollection { + do_objectID?: string; + _class: 'imageCollection'; + images: any[]; +} +interface SketchMSAssetCollection { + do_objectID?: string; + _class: 'assetCollection'; + gradients: any[]; + colors: any[]; + imageCollection: SketchMSImageCollection; + images: any[]; +} +interface SketchMSStyleBorder { + position: number; + color: SketchMSColor; + do_objectID?: string; + _class: 'styleBorder'; + gradient: SketchMSGradient; + fillType: number; + thickness: number; + contextSettings: SketchMSGraphicsContextSettings; + isEnabled: number; +} +interface SketchMSGradientStop { + do_objectID?: string; + _class: 'gradientStop'; + color: SketchMSColor; + position: number; +} +interface SketchMSGradient { + from: { + x: number; + y: number; + }; + shouldSmoothenOpacity: boolean; + gradientType: number; + do_objectID?: string; + _class: 'gradient'; + stops: SketchMSGradientStop[]; + to: { + x: number; + y: number; + }; + elipseLength: number; +} +interface SketchMSStyleFill { + contextSettings: SketchMSGraphicsContextSettings; + color: SketchMSColor; + do_objectID?: string; + _class: 'styleFill'; + gradient: SketchMSGradient; + fillType: number; + noiseIntensity: number; + patternFillType: number; + patternTileScale: number; + noiseIndex: number; + isEnabled: number; +} +interface SketchMSStyleShadow { + spread: number; + color: SketchMSColor; + offsetY: number; + offsetX: number; + do_objectID?: string; + _class: 'styleShadow'; + blurRadius: number; + contextSettings: SketchMSGraphicsContextSettings; + isEnabled: number; +} +interface SketchMSSharedStyle { + do_objectID?: string; + _class: 'sharedStyle'; + value: SketchMSStyle; + objectID: string; + name: string; +} +interface SketchMSTextStyle { + _class: 'textStyle'; + encodedAttributes: { + MSAttributedStringColorAttribute?: SketchMSColor; + NSColor: SketchMSKeyValueArchive; + MSAttributedStringFontAttribute?: SketchMSFontAttribute; + NSParagraphStyle?: SketchMSKeyValueArchive; + NSKern: number; + }; +} +interface SketchMSSharedStyleContainer { + do_objectID?: string; + _class: 'sharedStyleContainer'; + objects: SketchMSSharedStyle[]; +} +interface SketchMSStyleBorderOptions { + lineJoinStyle: number; + do_objectID?: string; + _class: 'styleBorderOptions'; + isEnabled: number; + lineCapStyle: number; + dashPattern: any[]; +} +interface SketchMSGraphicsContextSettings { + do_objectID?: string; + _class: 'graphicsContextSettings'; + opacity: number; + blendMode: number; +} +interface SketchMSStyleBlur { + radius: number; + do_objectID?: string; + _class: 'styleBlur'; + motionAngle: number; + isEnabled: number; + type: number; + center: { + x: number; + y: number; + }; +} +interface SketchMSStyleReflection { + do_objectID?: string; + _class: 'styleReflection'; + strength: number; + isEnabled: number; + distance: number; +} +interface SketchMSStyleColorControls { + hue: number; + do_objectID?: string; + _class: 'styleColorControls'; + brightness: number; + contrast: number; + isEnabled: number; + saturation: number; +} +interface SketchMSStyle { + startDecorationType: number; + borderOptions: SketchMSStyleBorderOptions; + endDecorationType: number; + contextSettings: SketchMSGraphicsContextSettings; + blur: SketchMSStyleBlur; + textStyle: SketchMSTextStyle; + reflection: SketchMSStyleReflection; + do_objectID?: string; + _class: 'style'; + miterLimit: number; + colorControls: SketchMSStyleColorControls; + fills: SketchMSStyleFill[]; + borders: SketchMSStyleBorder[]; + innerShadows: SketchMSStyleShadow[]; + shadows: SketchMSStyleShadow[]; +} +interface SketchMSRulerData { + do_objectID?: string; + _class: 'rulerData'; + base: number; + guides: any[]; +} +interface SketchMSRect { + y: number; + do_objectID?: string; + _class: 'rect'; + constrainProportions: boolean; + height: number; + width: number; + x: number; +} +interface SketchMSExportOptions { + shouldTrim: boolean; + do_objectID?: string; + _class: 'exportOptions'; + includedLayerIds: any[]; + layerOptions: number; + exportFormats: any[]; +} +interface SketchMSColor { + do_objectID?: string; + _class: 'color'; + + /** + * ex: "#FFFFFF" + * ex: rgb(1,0,1) + */ + value: string; + red: number; + green: number; + blue: number; + alpha: number; +} +interface SketchMSSimpleGrid { + do_objectID?: string; + _class: 'simpleGrid'; + thickGridTimes: number; + objectID: string; + isEnabled: number; + gridSize: number; +} +interface SketchMSLayoutGrid { + columnWidth: number; + totalWidth: number; + drawHorizontalLines: number; + objectID: string; + gutterWidth: number; + horizontalOffset: number; + isEnabled: number; + do_objectID?: string; + _class: 'layoutGrid'; + gutterHeight: number; + drawHorizontal: number; + guttersOutside: number; + numberOfColumns: number; + drawVertical: number; + rowHeightMultiplication: number; +} +interface SketchMSSymbolMaster { + isFlippedHorizontal: number; + includeBackgroundColorInInstance: number; + objectID: string; + horizontalRulerData: SketchMSRulerData; + frame: SketchMSRect; + hasClickThrough: number; + includeInCloudUpload: number; + exportOptions: SketchMSExportOptions; + hasBackgroundColor: number; + layerListExpandedType: number; + resizesContent: number; + backgroundColor: SketchMSColor; + rotation: number; + style: SketchMSStyle; + verticalRulerData: SketchMSRulerData; + constrainProportions: boolean; + isFlippedVertical: number; + do_objectID?: string; + _class: 'symbolMaster'; + attributedString: SketchMSAttributedString; + name: string; + layers: SketchMSLayer[]; + isVisible: boolean; + nameIsFixed: boolean; + grid: SketchMSSimpleGrid; + resizingType: number; + userInfo: any; + isLocked: boolean; + layout: SketchMSLayoutGrid; + shouldBreakMaskChain: number; + resizingConstraint: 63 | number; + includeBackgroundColorInExport: number; + flow?: SketchMSImmutableFlowConnection; + + // add this property to hold all CSS properties + // of the current layer + css?: { [key: string]: string }; +} +interface SketchMSSymbolInstanceLayer { + _class: 'symbolInstance'; + frame: SketchMSRect; + horizontalSpacing: number; + verticalSpacing: number; + masterInfluenceEdgeMinXPadding?: number; + masterInfluenceEdgeMaxXPadding?: number; + masterInfluenceEdgeMinYPadding?: number; + masterInfluenceEdgeMaxYPadding?: number; + symbolID: string; + overrides?: { + [objectId: string]: string | SketchMSNestedSymbolOverride | SketchMSImageDataReference; + }; + isFlippedHorizontal: number; + includeBackgroundColorInInstance: number; + objectID: string; + horizontalRulerData: SketchMSRulerData; + hasClickThrough: number; + includeInCloudUpload: number; + exportOptions: SketchMSExportOptions; + hasBackgroundColor: number; + layerListExpandedType: number; + resizesContent: number; + backgroundColor: SketchMSColor; + rotation: number; + style: SketchMSStyle; + verticalRulerData: SketchMSRulerData; + isFlippedVertical: number; + do_objectID?: string; + name: string; + layers: SketchMSLayer[]; + isVisible: boolean; + nameIsFixed: boolean; + grid: SketchMSSimpleGrid; + resizingType: number; + userInfo: any; + isLocked: boolean; + layout: SketchMSLayoutGrid; + shouldBreakMaskChain: number; + resizingConstraint: 63 | number; + includeBackgroundColorInExport: number; + flow?: SketchMSImmutableFlowConnection; +} +interface SketchMSPage { + isFlippedHorizontal: number; + style: SketchMSStyle; + horizontalRulerData: SketchMSRulerData; + frame: SketchMSRect; + hasClickThrough: number; + includeInCloudUpload: number; + exportOptions: SketchMSExportOptions; + objectID: string; + id: string; + rotation: number; + layerListExpandedType: number; + verticalRulerData: SketchMSRulerData; + isFlippedVertical: number; + resizingType: number; + do_objectID?: string; + _class: 'page' | 'layer'; + layers: SketchMSLayer[]; + isVisible: boolean; + nameIsFixed: number; + name: string; + constrainProportions: boolean; + attributedString: SketchMSAttributedString; + isLocked: boolean; + shouldBreakMaskChain: number; + resizingConstraint: number; + fixedRadius: number; + + // add this property to hold all CSS properties + // of the current layer + css?: { [key: string]: string }; +} +interface SketchMSSharedTextStyleContainer { + do_objectID?: string; + _class: 'sharedTextStyleContainer'; + objects: any[]; +} +interface SketchMSSymbolContainers { + do_objectID?: string; + _class: 'symbolContainer'; + objects: any[]; +} +interface SketchMSDocumentData { + assets: SketchMSAssetCollection; + currentPageIndex: number; + foreignSymbols: any[]; + layerStyles: SketchMSSharedStyleContainer; + pages: SketchMSPage[]; + enableSliceInteraction: number; + do_objectID?: string; + _class: 'documentData'; + layerTextStyles: SketchMSSharedTextStyleContainer; + enableLayerInteraction: number; + layerSymbols: SketchMSSymbolContainers; + objectID: string; +} +interface SketchMSArtboards { + name: string; + artboards: SketchMSArtboard; +} +interface SketchMSArtboard { + frame: SketchMSRect; + backgroundColor: SketchMSColor; + hasBackgroundColor: boolean; + horizontalRulerData?: SketchMSRulerData; + verticalRulerData?: SketchMSRulerData; + includeBackgroundColorInExport?: boolean; + includeInCloudUpload?: boolean; + isFlowHome?: boolean; +} +interface SketchMSPagesAndArtboards { + [key: string]: SketchMSArtboards; +} +interface SketchMSMetadata { + commit: string; + pagesAndArtboards: SketchMSPagesAndArtboards; + version: number; + fonts: string[]; + compatibilityVersion: number; + app: string; + autosaved: number; + variant: string; + created: { + commit: string; + appVersion: string; + build: number; + app: string; + compatibilityVersion: number; + version: number; + variant: string; + }; + saveHistory: string[]; + appVersion: string; + build: number; +} +interface SketchMSImmutableFlowConnection { + _class: 'immutableFlowConnection'; + animationType: number; + destinationArtboardID?: string | 'back'; +} diff --git a/types/sketchapp/sketchapp-tests.ts b/types/sketchapp/sketchapp-tests.ts new file mode 100644 index 0000000000..14a2be96a9 --- /dev/null +++ b/types/sketchapp/sketchapp-tests.ts @@ -0,0 +1,5 @@ +console.log(` +In order to test thie SketchApp types, we need to parse a SketchApp file. +See the following repo for a real worl test case: +https://github.com/xlayers/xlayers/blob/develop/src/app/editor/viewer/lib/parsers/sketch-style-parser.service.spec.ts +`); diff --git a/types/sketchapp/tsconfig.json b/types/sketchapp/tsconfig.json new file mode 100644 index 0000000000..6f22fec54b --- /dev/null +++ b/types/sketchapp/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sketchapp-tests.ts" + ] +} diff --git a/types/sketchapp/tslint.json b/types/sketchapp/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sketchapp/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/skin-tone/index.d.ts b/types/skin-tone/index.d.ts new file mode 100644 index 0000000000..e167a10cd5 --- /dev/null +++ b/types/skin-tone/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for skin-tone 1.0 +// Project: https://github.com/sindresorhus/skin-tone#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = skinTone; + +declare function skinTone(emoji: string, type: 0 | 1 | 2 | 3 | 4 | 5): string; + +declare namespace skinTone { + const NONE: 0; + const WHITE: 1; + const CREAM_WHITE: 2; + const LIGHT_BROWN: 3; + const BROWN: 4; + const DARK_BROWN: 5; +} diff --git a/types/skin-tone/skin-tone-tests.ts b/types/skin-tone/skin-tone-tests.ts new file mode 100644 index 0000000000..95052393a8 --- /dev/null +++ b/types/skin-tone/skin-tone-tests.ts @@ -0,0 +1,10 @@ +import skinTone = require('skin-tone'); + +// $ExpectType string +skinTone('👍', 4); +skinTone('👍', skinTone.NONE); +skinTone('👍', skinTone.WHITE); +skinTone('👍', skinTone.CREAM_WHITE); +skinTone('👍', skinTone.LIGHT_BROWN); +skinTone('👍', skinTone.BROWN); +skinTone('👍', skinTone.DARK_BROWN); diff --git a/types/skin-tone/tsconfig.json b/types/skin-tone/tsconfig.json new file mode 100644 index 0000000000..c879628e0e --- /dev/null +++ b/types/skin-tone/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", + "skin-tone-tests.ts" + ] +} diff --git a/types/skin-tone/tslint.json b/types/skin-tone/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/skin-tone/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/skyway/index.d.ts b/types/skyway/index.d.ts index eb73937178..044768a08e 100644 --- a/types/skyway/index.d.ts +++ b/types/skyway/index.d.ts @@ -1,185 +1,153 @@ -// Type definitions for SkyWay -// Project: http://nttcom.github.io/skyway/ +// Type definitions for SkyWay@1.1.17 +// Project: https://github.com/skyway/skyway-js-sdk // Definitions by: Toshiya Nakakura +// Atsushi Izumihara // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 -/// - -declare namespace PeerJs{ - interface PeerJSOption{ - key?: string; - host?: string; - port?: number; - path?: string; - secure?: boolean; - turn?: boolean; - config?: RTCPeerConnectionConfig; - debug?: number; - } - - interface PeerConnectOption{ - label?: string; - metadata?: any; - serialization?: string; - reliable?: boolean; - } - - interface DataConnection{ - send(data: any): void; - close(): void; - on(event: string, cb: ()=>void): void; - on(event: 'data', cb: (data: any)=>void): void; - on(event: 'open', cb: ()=>void): void; - on(event: 'close', cb: ()=>void): void; - on(event: 'error', cb: (err: any)=>void): void; - off(event: string, fn: Function, once?: boolean): void; - bufferSize: number; - dataChannel: RTCDataChannel; - label: string; - metadata: any; - open: boolean; - peerConnection: any; - peer: string; - reliable: boolean; - serialization: string; - type: string; - } - - interface MediaConnection{ - answer(stream?: any): void; - close(): void; - on(event: string, cb: ()=>void): void; - on(event: 'stream', cb: (stream: any)=>void): void; - on(event: 'close', cb: ()=>void): void; - on(event: 'error', cb: (err: any)=>void): void; - off(event: string, fn: Function, once?: boolean): void; - open: boolean; - metadata: any; - peer: string; - type: string; - } - - interface utilSupportsObj { - audioVideo: boolean; - data: boolean; - binary: boolean; - reliable: boolean; - } - - interface util{ - browser: string; - supports: utilSupportsObj; - } - - export interface Peer{ - /** - * - * @param id The brokering ID of the remote peer (their peer.id). - * @param options for specifying details about Peer Connection - */ - connect(id: string, options?: PeerJs.PeerConnectOption): PeerJs.DataConnection; - /** - * Connects to the remote peer specified by id and returns a data connection. - * @param id The brokering ID of the remote peer (their peer.id). - * @param stream The caller's media stream - */ - call(id: string, stream: any): PeerJs.MediaConnection; - /** - * Calls the remote peer specified by id and returns a media connection. - * @param event Event name - * @param cb Callback Function - */ - on(event: string, cb: ()=>void): void; - /** - * Emitted when a connection to the PeerServer is established. - * @param event Event name - * @param cb id is the brokering ID of the peer - */ - on(event: 'open', cb: (id: string)=>void): void; - /** - * Emitted when a new data connection is established from a remote peer. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'connection', cb: (dataConnection: PeerJs.DataConnection)=>void): void; - /** - * Emitted when a remote peer attempts to call you. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'call', cb: (mediaConnection: PeerJs.MediaConnection)=>void): void; - /** - * Emitted when the peer is destroyed and can no longer accept or create any new connections. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'close', cb: ()=>void): void; - /** - * Emitted when the peer is disconnected from the signalling server - * @param event Event name - * @param cb Callback Function - */ - on(event: 'disconnected', cb: ()=>void): void; - /** - * Errors on the peer are almost always fatal and will destroy the peer. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'error', cb: (err: any)=>void): void; - /** - * Remove event listeners.(EventEmitter3) - * @param {String} event The event we want to remove. - * @param {Function} fn The listener that we need to find. - * @param {Boolean} once Only remove once listeners. - */ - off(event: string, fn: Function, once?: boolean): void; - /** - * Close the connection to the server, leaving all existing data and media connections intact. - */ - disconnect(): void; - /** - * Close the connection to the server and terminate all existing connections. - */ - destroy(): void; - /** - * Get a list of available peer IDs - * @param callback - */ - listAllPeers(callback: (peerIds: Array)=>void): void; - - /** - * The brokering ID of this peer - */ - id: string; - /** - * A hash of all connections associated with this peer, keyed by the remote peer's ID. - */ - connections: any; - /** - * false if there is an active connection to the PeerServer. - */ - disconnected: boolean; - /** - * true if this peer and all of its connections can no longer be used. - */ - destroyed: boolean; - } +interface Options { + key: string; + debug?: number; + turn?: boolean; + credential?: Credential; + config?: RTCConfiguration; } -declare var Peer: { - prototype: RTCIceServer; - /** - * A peer can connect to other peers and listen for connections. - * @param id Other peers can connect to this peer using the provided ID. - * If no ID is given, one will be generated by the brokering server. - * @param options for specifying details about PeerServer - */ - new (id: string, options?: PeerJs.PeerJSOption): PeerJs.Peer; +interface Credential { + timestamp?: number; + ttl?: number; + authToken?: string; +} - /** - * A peer can connect to other peers and listen for connections. - * @param options for specifying details about PeerServer - */ - new (options: PeerJs.PeerJSOption): PeerJs.Peer; -}; +interface CallOptions { + metadata?: any; + videoBandWidth?: number; + audioBandwidth?: number; + videoCodec?: string; + audioCodec?: string; + videoReceiveEnabled?: boolean; + audioReceiveEnabled?: boolean; + label?: string; +} + +interface ConnectOptions { + metadata?: any; + serialization?: string; + dcInit?: RTCDataChannelInit; + label?: string; +} + +interface RoomOptions { + mode?: string; + stream?: MediaStream; + videoBandwidth?: number; + audioBandwidth?: number; + videoCodec?: string; + audioCodec?: string; + videoReceiveEnabled?: boolean; + audioReceiveEnabled?: boolean; +} + +interface AnswerOptions { + videoBandwidth?: number; + audioBandwidth?: number; + videoCodec?: string; + audioCodec?: string; +} + +declare class Peer { + constructor(id: string, options: Options); + constructor(options: Options); + + connections: any; + id: string; + open: boolean; + rooms: any; + + call(peerId: string, stream?: MediaStream, options?: CallOptions): MediaConnection | undefined; + connect(peerId: string, options?: ConnectOptions): DataConnection | undefined; + destroy(): undefined; + disconnect(): undefined; + joinRoom(roomName: string, roomOptions?: RoomOptions): SFURoom | MeshRoom | undefined | null; + listAllPeers(cb: (peerIds: Array) => void): void; + updateCredential(newCredential: Credential): undefined; + + on(event: string, cb: (ret: any) => void): void; + on(event: 'open', cb: (id: string) => void): void; + on(event: 'call', cb: (call: MediaConnection) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'connection', cb: (connection: DataConnection) => void): void; + on(event: 'disconnected', cb: (id: string) => void): void; + on(event: 'error', cb: (err: any) => void): void; +} + +declare class MediaConnection { + metadata: any; + open: boolean; + remoteId: string; + peer: string; + + answer(stream: MediaStream, options?: AnswerOptions): undefined; + close(): void | undefined; + replaceStream(stream: MediaStream): undefined; + + on(event: string, cb: () => void): void; + on(event: 'stream', cb: (stream: MediaStream) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'removeStream', cb: (reamoteStream: MediaStream) => void): void; +} + +declare class DataConnection { + metadata: any; + open: boolean; + remoteId: string; + peer: string; + + send(data: any): void; + close(): void | undefined; + + on(event: string, cb: () => void): void; + on(event: 'data', cb: (data: any) => void): void; + on(event: 'close', cb: () => void): void; +} + +interface DataObject { + src: string; + data: any; +} + +declare class MeshRoom { + close(): undefined; + getLog(): undefined; + replaceStream(stream: MediaSource): undefined; + send(data: any): undefined; + + on(event: string, cb: () => void): void; + on(event: 'open', cb: () => void): void; + on(event: 'peerJoin', cb: (peerId: string) => void): void; + on(event: 'peerLeave', cb: (peerId: string) => void): void; + on(event: 'log', cb: (logs: Array) => void): void; + once(event: 'log', cb: (logs: Array) => void): void; + on(event: 'stream', cb: (stream: MediaStream) => void): void; + on(event: 'data', cb: (object: DataObject) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'removeStream', cb: (stream: MediaStream) => void): void; +} + +declare class SFURoom { + close(): undefined; + getLog(): undefined; + replaceStream(stream: MediaSource): undefined; + send(data: any): undefined; + + on(event: string, cb: () => void): void; + on(event: 'open', cb: () => void): void; + on(event: 'peerJoin', cb: (peerId: string) => void): void; + on(event: 'peerLeave', cb: (peerId: string) => void): void; + on(event: 'log', cb: (logs: Array) => void): void; + once(event: 'log', cb: (logs: Array) => void): void; + on(event: 'stream', cb: (stream: MediaStream) => void): void; + on(event: 'data', cb: (object: DataObject) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'removeStream', cb: (stream: MediaStream) => void): void; +} diff --git a/types/skyway/skyway-tests.ts b/types/skyway/skyway-tests.ts index 2731192f75..702a05e709 100644 --- a/types/skyway/skyway-tests.ts +++ b/types/skyway/skyway-tests.ts @@ -1,44 +1,37 @@ -var peerByOption: PeerJs.Peer = new Peer({ +const peerByOption: Peer = new Peer({ key: 'peerKey', - debug: 3, + debug: 3 }); -peerByOption.listAllPeers(function(items){ - for(var i in items){ - console.log(decodeURI(items[i])); +peerByOption.listAllPeers((items) => { + for (let item in items) { + console.log(decodeURI(items[item])); } }); -var peerById: PeerJs.Peer = new Peer("peerid"); +const peerByIdAndOption: Peer = new Peer('peerid', { + key: 'peerKey', + debug: 3 +}); -var peerByIdAndOption: PeerJs.Peer = new Peer( - "peerId", - { - key: 'peerKey', - debug: 3, - }); - -var id = peerByOption.id; -var connections = peerByOption.connections; -var flag = peerByOption.disconnected; -flag = peerByOption.destroyed; +let id = peerByOption.id; +let connections = peerByOption.connections; peerByOption.disconnect(); peerByOption.destroy(); -var connection = peerById.connect("id", { +let connection = peerByOption.connect("id", { label: 'chat', serialization: 'none', - metadata: {message: 'hi i want to chat with you!'} + metadata: { message: 'hi i want to chat with you!' } }); -var call = peerById.call('callto-id', (window).localStream); +let call = peerByOption.call('callto-id', (window as any).localStream); -var openHandler=()=> console.log("open"); -peerById.on("open", openHandler); -peerById.on("connection", (c)=> console.log("connection")); -peerById.on("call", (media)=> console.log("call")); -peerById.on("close", ()=> console.log("close")); -peerById.on("disconnected", ()=> console.log("disconnected")); -peerById.on("error", (err)=> console.log(err)); -peerById.off("open", openHandler); +let openHandler = () => console.log("open"); +peerByOption.on("open", openHandler); +peerByOption.on("connection", (c) => console.log("connection")); +peerByOption.on("call", (media) => console.log("call")); +peerByOption.on("close", () => console.log("close")); +peerByOption.on("disconnected", () => console.log("disconnected")); +peerByOption.on("error", (err) => console.log(err)); diff --git a/types/slate-react/index.d.ts b/types/slate-react/index.d.ts index 540316befc..30e54f2a02 100644 --- a/types/slate-react/index.d.ts +++ b/types/slate-react/index.d.ts @@ -6,7 +6,7 @@ // Patrick Sachs // Brandon Shelton // Irwan Fario Subastian -// Sebastian Greaves +// Hanna Greaves // Francesco Agnoletto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -18,8 +18,7 @@ import { Block, Inline, Operations, - Schema, - Stack, + SchemaProperties, Value, Operation, MarkProperties, @@ -112,7 +111,7 @@ export interface BasicEditorProps { plugins?: Plugin[]; readOnly?: boolean; role?: string; - schema?: Schema; + schema?: SchemaProperties; spellCheck?: boolean; style?: React.CSSProperties; tabIndex?: number; @@ -121,15 +120,11 @@ export interface BasicEditorProps { export type EditorProps = BasicEditorProps & Plugin; export interface EditorState { - schema: Schema; value: Value; - stack: Stack; } export class Editor extends React.Component implements Controller { controller: CoreEditor; - schema: Schema; - stack: Stack; readonly plugins: Plugin[]; readonly operations: Immutable.List; @@ -137,7 +132,7 @@ export class Editor extends React.Component implements readonly value: Value; // Instance methods - resolveController(plugins: Plugin[], schema: Schema, commands: any[], queries: any[]): void; + resolveController(plugins: Plugin[], schema: SchemaProperties, commands: any[], queries: any[]): void; // Controller addMark: CoreEditor['addMark']; diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index 5656c58bb3..2538bea6f9 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -7,7 +7,7 @@ // Kalley Powell // Francesco Agnoletto // Irwan Fario Subastian -// Sebastian Greaves +// Hanna Greaves // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as Immutable from "immutable"; @@ -53,39 +53,9 @@ export interface SchemaProperties { inlines?: RulesByNodeType; } -export class Schema extends Immutable.Record({}) { - stack: Stack; - rules: Rules[]; - - static create(properties: SchemaProperties | Schema): Schema; - static fromJSON(object: SchemaProperties): Schema; - static fromJS(object: SchemaProperties): Schema; - static isSchema(maybeSchema: any): maybeSchema is Schema; - - validateNode(node: Node): Error | void; - testNode(node: Node): boolean; - assertNode(node: Node): boolean; - getNodeRules(node: Node): any[]; - isVoid(node: Node): boolean; - isAtomic(mark: Mark): boolean; - normalizeNode(node: Node): () => void; - testRules(object: any, rules: object | any[]): boolean; - validateRules( - object: any, - rule: object | any[], - rules: any[] | null, - options?: object - ): Error | void; - - toJSON(): SchemaProperties; - toJS(): SchemaProperties; -} - export interface ValueProperties { document?: Document; selection?: Selection; - history?: History; - schema?: Schema; data?: Data; decorations?: Immutable.List | null; } @@ -93,8 +63,6 @@ export interface ValueProperties { export interface ValueJSON { document?: DocumentJSON; selection?: Selection; - history?: History; - schema?: Schema; data?: Data; decorations?: Immutable.List | null; object?: "value"; @@ -105,8 +73,6 @@ export type Path = Immutable.List | string; export class Value extends Immutable.Record({}) { document: Document; selection: Selection; - history: History; - schema: Schema; data: Data; object: "value"; decorations: Immutable.List; @@ -319,7 +285,7 @@ export class Text extends Immutable.Record({}) { addMark(index: number, length: number, mark: Mark): Text; addMarks(index: number, lenght: number, marks: Immutable.Set): Text; getLeaves(decorations?: Range[]): Immutable.List; - getActiveMarksBetweenOffset( + getActiveMarksBetweenOffsets( startOffset: number, endOffset: number ): Immutable.Set; @@ -350,9 +316,6 @@ export class Text extends Immutable.Record({}) { ): Text; splitText(offset: number): Text[]; mergeText(text: Text): Text; - normalize(schema: Schema): () => void | null; - validate(schema: Schema): Error | null; - getFirstInvalidNode(schema: Schema): Text | null; setLeaves(leaves: Immutable.List): Text; } @@ -446,13 +409,12 @@ declare class BaseNode< getChild(path: Path): Node | null; getClosestBlock(path: Path): Block | null; getClosestInline(path: Path): Inline | null; - getClosestVoid(path: Path, schema: Schema): Node | null; + getClosestVoid(key: string | Path): Node | null; getClosest(path: Path, iterator: (node: Node) => boolean): Node | null; getCommonAncestor(a: Path, b: Path): Node; - getDecorations(stack: Stack): Immutable.List; + getDecorations(editor: Editor): Immutable.List; getDepth(path: Path, startAt?: number): number; getDescendant(path: Path): Node | null; - getFirstInvalidNode(schema: Schema): Node | null; getFirstText(): Text | null; getFragmentAtRange(range: Range): Document; getFurthest(path: Path, iterator: (node: Node) => boolean): Node | null; @@ -514,7 +476,7 @@ declare class BaseNode< hasInlineChildren(): boolean; hasDescendant(path: Path): boolean; hasNode(path: Path): boolean; - hasVoidParent(path: Path, schema: Schema): boolean; + hasVoidParent(path: Path, editor: Editor): boolean; insertNode(path: Path, node: Node): Node; insertText( path: Path, @@ -528,7 +490,7 @@ declare class BaseNode< mapDescendants(iterator: () => void): Node; mergeNode(path: Path): Node; moveNode(path: Path, newPath: Path, newIndex?: number): Node; - normalize(schema: Schema): () => void | void; + normalize(editor: Editor): () => void | void; refinedNOde(path: Path, key: string): Node | null; refindPath(path: Path, key: string): Immutable.List | null; regenerateKey(): Node; @@ -548,7 +510,7 @@ declare class BaseNode< properties: MarkProperties ): Node; splitNode(path: Path, position: number, properties: NodeProperties): Node; - validate(schema: Schema): Error | void; + validate(editor: Editor): Error | void; } export interface MarkProperties { @@ -914,61 +876,6 @@ export interface Operations { invert: (operation: Operation) => Operation; } -export interface StackProperties { - plugins?: any[]; -} - -export interface StackJSON { - object: "stack"; - plugins: any[]; -} - -export class Stack extends Immutable.Record({}) { - object: "stack"; - plugins: any[]; - - static create(attrs: StackProperties): Stack; - static isStack(maybeStack: any): maybeStack is Stack; - - static fromJSON(properties: StackJSON): Stack; - static fromJS(properties: StackJSON): Stack; - toJSON(options: any): object; -} - -export interface HistoryProperties { - undos?: Operation[]; - redos?: Operation[]; -} - -export interface HistoryJSON { - object: "history"; - undos: any[]; - redos: any[]; -} - -export interface HistoryOptions { - merge?: boolean; - skip?: boolean; -} - -export class History extends Immutable.Record({}) { - redos: Stack; - undos: Stack; - object: "history"; - - static create(attrs: History | HistoryProperties): History; - static createOperationsList( - oeprations?: Immutable.List | Operation[] - ): Immutable.List; - static fromJSON(object: HistoryJSON): History; - static fromJS(object: HistoryJSON): History; - static isHistory(maybeHistory: any): maybeHistory is History; - - save(operation: Operation, options?: HistoryOptions): History; - toJSON(): HistoryJSON; - toJS(): HistoryJSON; -} - export type ErrorCode = | "child_object_invalid" | "child_required" diff --git a/types/snakecase-keys/index.d.ts b/types/snakecase-keys/index.d.ts new file mode 100644 index 0000000000..d9afe0a2fd --- /dev/null +++ b/types/snakecase-keys/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for snakecase-keys 2.1 +// Project: https://github.com/bendrucker/snakecase-keys#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = snakecaseKeys; + +declare function snakecaseKeys( + obj: object, + options?: snakecaseKeys.Options +): { [key: string]: any }; + +declare namespace snakecaseKeys { + interface Options { + deep?: boolean; + exclude?: Array; + } +} diff --git a/types/snakecase-keys/snakecase-keys-tests.ts b/types/snakecase-keys/snakecase-keys-tests.ts new file mode 100644 index 0000000000..e74d13404f --- /dev/null +++ b/types/snakecase-keys/snakecase-keys-tests.ts @@ -0,0 +1,5 @@ +import snakecaseKeys = require('snakecase-keys'); + +snakecaseKeys({ fooBar: 'baz' }); +snakecaseKeys({ fooBar: 'baz' }, { deep: false }); +snakecaseKeys({ fooBar: 'baz' }, { exclude: ['fooBax', /Foo$/] }); diff --git a/types/snakecase-keys/tsconfig.json b/types/snakecase-keys/tsconfig.json new file mode 100644 index 0000000000..6d944fa502 --- /dev/null +++ b/types/snakecase-keys/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", + "snakecase-keys-tests.ts" + ] +} diff --git a/types/snakecase-keys/tslint.json b/types/snakecase-keys/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/snakecase-keys/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/socket.io/index.d.ts b/types/socket.io/index.d.ts index f5e6c5fd00..4ea2e0cbde 100644 --- a/types/socket.io/index.d.ts +++ b/types/socket.io/index.d.ts @@ -142,6 +142,17 @@ declare namespace SocketIO { */ origins( v: string|string[] ): Server; + /** + * Provides a function taking two arguments origin:String + * and callback(error, success), where success is a boolean + * value indicating whether origin is allowed or not. If + * success is set to false, error must be provided as a string + * value that will be appended to the server response, e.g. “Origin not allowed”. + * @param fn The function that will be called to check the origin + * return This Server + */ + origins( fn: ( origin: string, callback: ( error: string | null, success: boolean ) => void ) => void ): Server; + /** * Attaches socket.io to a server * @param srv The http.Server that we want to attach to @@ -169,7 +180,7 @@ declare namespace SocketIO { listen( port: number, opts?: ServerOptions ): Server; /** - * Binds socket.io to an engine.io intsance + * Binds socket.io to an engine.io instance * @param src The Engine.io (or compatible) server to bind to * @return This Server */ diff --git a/types/socket.io/v1/index.d.ts b/types/socket.io/v1/index.d.ts index 95a9ff1b4f..191680df46 100644 --- a/types/socket.io/v1/index.d.ts +++ b/types/socket.io/v1/index.d.ts @@ -169,7 +169,7 @@ declare namespace SocketIO { listen( port: number, opts?: ServerOptions ): Server; /** - * Binds socket.io to an engine.io intsance + * Binds socket.io to an engine.io instance * @param src The Engine.io (or compatible) server to bind to * @return This Server */ diff --git a/types/socketcluster-client/index.d.ts b/types/socketcluster-client/index.d.ts new file mode 100644 index 0000000000..9c15a45465 --- /dev/null +++ b/types/socketcluster-client/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for socketcluster-client 13.0 +// Project: https://github.com/SocketCluster/socketcluster-client +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCAuthEngine } from "sc-auth"; +import { SCServer } from "socketcluster-server"; + +export import SCClientSocket = require("./lib/scclientsocket"); + +export function create(options?: SCClientSocket.ClientOptions): SCClientSocket; + +/** @deprecated */ +export function connect(options?: SCClientSocket.ClientOptions): SCClientSocket; + +export function destroy(socket: SCClientSocket): void; + +export const clients: { + [id: string]: SCClientSocket; +}; + +export const version: string; diff --git a/types/socketcluster-client/lib/scclientsocket.d.ts b/types/socketcluster-client/lib/scclientsocket.d.ts new file mode 100644 index 0000000000..19552bd102 --- /dev/null +++ b/types/socketcluster-client/lib/scclientsocket.d.ts @@ -0,0 +1,251 @@ +import Emitter = require("component-emitter"); +import { SCServer } from "socketcluster-server"; +import { SCAuthEngine } from "sc-auth"; +import { SCChannel, SCChannelOptions, ChannelState } from "sc-channel"; +import WebSocket = require("ws"); + +declare class SCClientSocket extends Emitter { + constructor(opts: SCClientSocket.ClientOptions); + + id: string; + + channels: { + [channelName: string]: SCChannel; + }; + + CONNECTING: "connecting"; + OPEN: "open"; + CLOSED: "closed"; + + state: SCClientSocket.States; + getState(): SCClientSocket.States; + + AUTHENTICATED: "authenticated"; + UNAUTHENTICATED: "unauthenticated"; + + authState: SCClientSocket.AuthStates; + + PENDING: "pending"; + + pendingReconnect: boolean; + pendingReconnectTimeout: number; + + getBytesReceived(): number; + + deauthenticate(callback?: (err: Error) => void): void; + + connect(): void; + open(): void; + disconnect(code?: number, data?: string | object): void; + reconnect(code?: number, data?: string | object): void; + destroy(code?: number, data?: string | object): void; + + decodeBase64(encodedString: string): string; + encodeBase64(decodedString: string): string; + + getAuthToken(): object | null; + authToken: object | null; + + getSignedAuthToken(): string | null; + signedAuthToken: string | null; + + // Perform client-initiated authentication by providing an encrypted token string. + authenticate(signedAuthToken: string, callback?: (err: Error, authStatus: SCClientSocket.AuthStatus) => void): void; + + decode(message: any): any; + encode(object: any): any; + + send(data: any): void; + + emit(event: string, data: any, callback?: (err: Error, responseData: any) => void): void; + + publish(channelName: string, data: any, callback?: (err: Error, ackData: any) => void): void; + + subscribe(channelName: string, options?: SCChannelOptions): SCChannel; + unsubscribe(channelName: string): void; + + channel(channelName: string, options?: SCChannelOptions): SCChannel; + + destroyChannel(channelName: string): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channelName: string, includePending?: boolean): boolean; + + processPendingSubscriptions(): void; + + watch(channelName: string, handler: SCClientSocket.WatcherFunction): void; + unwatch(channelName: string, handler?: SCClientSocket.WatcherFunction): void; + watchers(channelName: string): SCClientSocket.WatcherFunction[]; + + on(event: "connecting", listener: () => void): this; + on(event: "connect", listener: (status: SCClientSocket.ConnectStatus, processSubscriptions: () => void) => void): this; + on(event: "connectAbort" | "disconnect" | "close", listener: (code: number, data: string | object) => void): this; + + on(event: "kickOut", listener: (message: string, channelName: string) => void): this; + + on(event: "authenticate", listener: (signedAuthToken: string | null) => void): this; + on(event: "deauthenticate", listener: (oldSignedToken: string | null) => void): this; + on(event: "authStateChange", listener: (stateChangeData: SCClientSocket.AuthStateChangeData) => void): this; + on(event: "removeAuthToken", listener: (oldToken: object | null) => void): this; + + on(event: "subscribe" | "subscribeRequest", listener: (channelName: string, subscriptionOptions: SCChannelOptions) => void): this; + on(event: "subscribeStateChange", listener: (stateChangeData: SCClientSocket.SubscribeStateChangeData) => void): this; + on(event: "subscribeFail", listener: (err: Error, channelName: string, subscriptionOptions: SCChannelOptions) => void): this; + on(event: "unsubscribe", listener: (channelName: string) => void): this; + + on(event: "error", listener: (err: Error) => void): this; + + on(event: "raw", listener: (data: any) => void): this; + on(event: "message", listener: (message: WebSocket.Data) => void): this; + + // Implements Emitter interface + + // tslint:disable:ban-types + // tslint:disable:adjacent-overload-signatures + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + off(event?: string, listener?: Function): this; + emit(event: string, ...args: any[]): boolean; + listeners(event: string): Function[]; + hasListeners(event: string): boolean; + // tslint:enable:adjacent-overload-signatures + // tslint:enable:ban-types +} + +export = SCClientSocket; + +declare namespace SCClientSocket { + interface ClientOptions { + host?: string; + + // Defaults to the current host (read from the URL). + hostname?: string; + + // Defaults to false. + secure?: boolean; + + // Defaults to 80 if !secure otherwise defaults to 443. + port?: number; + + // The URL which SC uses to make the initial handshake for the WebSocket. Defaults to '/socketcluster/'. + path?: string; + + // A map of key-value pairs which will be used as query parameters for the initial HTTP handshake which will initiate the WebSocket connection. + query?: string | { [key: string]: string }; + + // (milliseconds) - This is the timeout for getting a response to a SCSocket emit event (when a callback is provided). + ackTimeout?: number; + + // (milliseconds) + connectTimeout?: number; + + // Whether or not to automatically connect the socket as soon as it is created. Default is true. + autoConnect?: boolean; + + // Whether or not to automatically reconnect the socket when it loses the connection. + autoReconnect?: boolean; + + // Valid properties are: initialDelay (milliseconds), randomness (milliseconds), multiplier (decimal; default is 1.5) and maxDelay (milliseconds). + autoReconnectOptions?: AutoReconnectOptions; + + // Whether or not a client automatically disconnects on page unload. If enabled, the client will disconnect when a user navigates away from the page. + // This can happen when a user closes the tab/window, clicks a link to leave the page, or types a new URL into the address bar. Defaults to true. + disconnectOnUnload?: boolean; + + // Turn on/off per-message deflate compression. If this is true, you need to make sure that this property is also set to true on the server-side. + // Note that this option is only relevant when running the client from Node.js. Most modern browsers will automatically use perMessageDeflate so + // you only need to turn it on from the server-side. + perMessageDeflate?: boolean; + + // Defaults to true; multiplexing allows you to reuse a socket instead of creating a second socket to the same address. + multiplex?: boolean; + + // Defaults to null (0 milliseconds); this property affects channel subscription batching; it determines the period in milliseconds for batching + // multiple subscription requests together. It only affects channels that have the batch option set to true. A value of null or 0 means that all + // subscribe or unsubscribe requests which were made within the same call stack will be batched together. This property was introduced on the + // client-side in SC version 8 (both the client and server versions need to be >= 8.0.0). Note that there is also a separate property with the + // same name which can be configured on the server. + pubSubBatchDuration?: number; + + // Whether or not to add a timestamp to the WebSocket handshake request. + timestampRequests?: boolean; + + // The query parameter name to use to hold the timestamp. + timestampParam?: string; + + // A custom engine to use for storing and loading JWT auth tokens on the client side. + authEngine?: SCAuthEngine | null; + + // The name of the JWT auth token (provided to the authEngine - By default this is the localStorage variable name); defaults to 'socketCluster.authToken'. + authTokenName?: string; + + // The type to use to represent binary on the client. Defaults to 'arraybuffer'. + binaryType?: string; + + // Set this to false during debugging - Otherwise client connection will fail when using self-signed certificates. + rejectUnauthorized?: boolean; + + // If you set this to true, any data/objects/arrays that you pass to the client socket will be cloned before being sent/queued up. If the socket + // is disconnected and you emit an event, it will be added to a queue which will be processed upon reconnection. The cloneData option is false + // by default; this means that if you emit/publish an object and that object changes somewhere else in your code before the queue is processed, + // then the changed version of that object will be sent out to the server. + cloneData?: boolean; + + // This is true by default. If you set this to false, then the socket will not automatically try to subscribe to pending subscriptions on + // connect - Instead, you will have to manually invoke the processSubscriptions callback from inside the 'connect' event handler on the client side. + // See SCSocket Client API. This gives you more fine-grained control with regards to when pending subscriptions are processed after the socket + // connection is established (or re-established). + autoSubscribeOnConnect?: boolean; + + // Lets you set a custom codec engine. This allows you to specify how data gets encoded before being sent over the wire and how it gets decoded + // once it reaches the other side. The codecEngine must be an object which exposes an encode(object) and a decode(encodedData) function. + // The encode function can return any data type - Commonly a string or a Buffer/ArrayBuffer. The decode function needs to return a JavaScript + // object which adheres to the SC protocol. The idea of using a custom codec is that it allows you to compress SC packets in any format you like + // (optimized for any use case) - By decoding these packets back into their original protocol form, SC will be able process them appropriately. + // Note that if you provide a codecEngine when creating a client socket see 'codecEngine', you will need to make sure that the server uses the + // same codec by passing the same engine to `worker.scServer.setCodecEngine(codecEngine)` when your SC worker initializes on the server side + // (see 'setCodecEngine' method here). The default codec engine used by SC is here. + codecEngine?: SCServer.SCCodecEngine | null; + + // A prefix to add to the channel names. + channelPrefix?: string | null; + + subscriptionRetryOptions?: object | null; + } + + interface AutoReconnectOptions { + initialDelay?: number; + randomness?: number; + multiplier?: number; + maxDelay?: number; + } + + interface AuthStatus { + isAuthenticated: AuthStates; + authError: Error; + } + + interface AuthStateChangeData { + oldState: AuthStates; + newState: AuthStates; + } + + interface ConnectStatus { + id: string; + pingTimeout: number; + isAuthenticated: boolean; + authToken?: object; + authError?: Error; + } + + interface SubscribeStateChangeData { + channel: string; + oldState: ChannelState; + newState: ChannelState; + subscriptionOptions: SCChannelOptions; + } + + type WatcherFunction = (data: any) => void; + type AuthStates = "authenticated" | "unauthenticated"; + type States = "connecting" | "open" | "closed"; +} diff --git a/types/socketcluster-client/socketcluster-client-tests.ts b/types/socketcluster-client/socketcluster-client-tests.ts new file mode 100644 index 0000000000..527385a5eb --- /dev/null +++ b/types/socketcluster-client/socketcluster-client-tests.ts @@ -0,0 +1,75 @@ +// Adapted from README + +import { create, destroy } from "socketcluster-client"; +import { ClientOptions } from "socketcluster-client/lib/scclientsocket"; + +const secureClientOptions: ClientOptions = { + hostname: "securedomain.com", + secure: true, + port: 443, + rejectUnauthorized: false +}; + +let socket = create(secureClientOptions); + +socket.on("connect", () => { + console.log("CONNECTED"); +}); + +// Listen to an event called 'rand' from the server +socket.on("rand", (num: any) => { + console.log("RANDOM: " + num); +}); + +const options: ClientOptions = { + path: "/socketcluster/", + port: 8000, + hostname: "127.0.0.1", + autoConnect: true, + secure: false, + rejectUnauthorized: false, + connectTimeout: 10000, // milliseconds + ackTimeout: 10000, // milliseconds + channelPrefix: null, + disconnectOnUnload: true, + multiplex: true, + autoReconnectOptions: { + initialDelay: 10000, // milliseconds + randomness: 10000, // milliseconds + multiplier: 1.5, // decimal + maxDelay: 60000 // milliseconds + }, + authEngine: null, + codecEngine: null, + subscriptionRetryOptions: {}, + query: { + yourparam: "hello" + } +}; +socket = create(options); + +socket.on("subscribe", channelname => { + console.log("subscribe:" + channelname); +}); + +socket.on("subscribeFail", channelname => { + console.log("subscribeFail:" + channelname); +}); + +socket.on("unsubscribe", channelname => { + console.log("unsubscribe:" + channelname); +}); + +socket.on("subscribeStateChange", data => { + console.log("subscribeStateChange:" + JSON.stringify(data)); +}); + +socket.on("message", data => { + console.log("message:" + data); +}); + +const channels = socket.channels; +const testChannel = channels["test"]; +const state = testChannel.getState(); + +destroy(socket); diff --git a/types/socketcluster-client/tsconfig.json b/types/socketcluster-client/tsconfig.json new file mode 100644 index 0000000000..54fc6ea8af --- /dev/null +++ b/types/socketcluster-client/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 + }, + "files": [ + "index.d.ts", + "lib/scclientsocket.d.ts", + "socketcluster-client-tests.ts" + ] +} diff --git a/types/socketcluster-client/tslint.json b/types/socketcluster-client/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster-client/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/socketcluster-server/index.d.ts b/types/socketcluster-server/index.d.ts new file mode 100644 index 0000000000..7466d1daed --- /dev/null +++ b/types/socketcluster-server/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for socketcluster-server 13.1 +// Project: https://github.com/SocketCluster/socketcluster-server +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Server } from "http"; + +export import SCServer = require("./scserver"); +export import SCServerSocket = require("./scserversocket"); + +export function listen(port?: number, options?: SCServer.SCServerOptions, listeningListener?: () => void): SCServer; +export function listen(port?: number, listeningListener?: () => void): SCServer; + +export function attach(server: Server, options?: SCServer.SCServerOptions): SCServer; diff --git a/types/socketcluster-server/scserver.d.ts b/types/socketcluster-server/scserver.d.ts new file mode 100644 index 0000000000..a7147aa2dd --- /dev/null +++ b/types/socketcluster-server/scserver.d.ts @@ -0,0 +1,315 @@ +import { EventEmitter } from "events"; +import { Secret } from "jsonwebtoken"; +import { ServerOptions } from "https"; +import { IncomingMessage, Server } from "http"; +import { SCAuthEngine } from "sc-auth"; +import { SCExchange } from "sc-broker-cluster"; +import WebSocket = require("ws"); + +import SCServerSocket = require("./scserversocket"); + +declare class SCServer extends EventEmitter { + readonly MIDDLEWARE_HANDSHAKE_WS: "handshakeWS"; + readonly MIDDLEWARE_HANDSHAKE_SC: "handshakeSC"; + readonly MIDDLEWARE_AUTHENTICATE: "authenticate"; + readonly MIDDLEWARE_SUBSCRIBE: "subscribe"; + readonly MIDDLEWARE_PUBLISH_IN: "publishIn"; + readonly MIDDLEWARE_PUBLISH_OUT: "publishOut"; + readonly MIDDLEWARE_EMIT: "emit"; + + options: SCServer.SCServerOptions; + exchange: SCExchange; + + clients: { + [id: string]: SCServerSocket; + }; + clientsCount: number; + + pendingClients: { + [id: string]: SCServerSocket; + }; + pendingClientsCount: number; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "connection", listener: SCServer.connectionListenerFunction): this; + + addMiddleware(type: "handshakeWS", middlewareFn: (req: IncomingMessage, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "handshakeSC", middlewareFn: (req: SCServer.HandshakeSCRequest, next: SCServer.nextHandshakeSCMiddlewareFunction) => void): void; + addMiddleware(type: "authenticate", middlewareFn: (req: SCServer.AuthenticateRequest, next: SCServer.nextAuthenticateMiddlewareFunction) => void): void; + addMiddleware(type: "subscribe", middlewareFn: (req: SCServer.SubscribeRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "publishIn", middlewareFn: (req: SCServer.PublishInRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "publishOut", middlewareFn: (req: SCServer.PublishOutRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "emit", middlewareFn: (req: SCServer.EmitRequest, next: SCServer.nextMiddlewareFunction) => void): void; + + setAuthEngine(authEngine: SCAuthEngine): void; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; +} + +export = SCServer; + +declare namespace SCServer { + interface AuthToken { + [x: string]: any; + } + + interface SCServerOptions { + // The port on which to listen for outside connections/requests + port?: number; + + // Number of worker processes + workers?: number; + + // Number of broker processes + brokers?: number; + + // Should be either 'dev' or 'prod' - This affects the shutdown procedure + // when a 'SIGUSR2' signal is received by master. In 'dev', a SIGUSR2 will + // trigger an immediate shutdown of workers. In 'prod' workers will + // be terminated progressively in accordance with processTermTimeout. + environment?: string; + + // Setting this to true will cause the master process to shut down when + // it receives a SIGUSR2 signal (instead of just the workers). + // If you're using nodemon, set this to true. + killMasterOnSignal?: boolean; + + // A unique name for your app (this is used internally for + // various things such as the directory name in which to store socket + // file descriptors) - If you don't provide an appName, SC will + // generate a random one (UUID v4) + appName?: string; + + // This can be the name of an npm module or a path to a Node.js module + // to use as the WebSocket server engine. + // You can now set this to 'sc-uws' for a massive speedup of at least 2x! + wsEngine?: string; + + // An ID to associate with this specific instance of SC + // this may be useful if you are running an SC app on multiple + // hosts - You can access the instanceId from the Broker object + // (inside brokerController) - If you don't provide an instanceId, + // SC will generate a random one (UUID v4) + instanceId?: string; + + // A key which various SC processes will use to interact with + // scBroker broker processes securely, defaults to a 256 bits + // cryptographically random hex string + secretKey?: string; + + // The key which SC will use to encrypt/decrypt authTokens, defaults + // to a 256 bits cryptographically random hex string + // The default JWT algorithm used is 'HS256'. + // If you want to use RSA or ECDSA, you should provide a authPrivateKey + // and authPublicKey instead of authKey. + authKey?: Secret; + + // perMessageDeflate compression. Note that this option is passed directly to the wsEngine's + // Server object. So if you're using 'ws' as the engine, you can pass an object instead of + // a boolean. Search for perMessageDeflate here: + // https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback + // Note that by default, per-message deflate only kicks in for messages > 1024 bytes. + perMessageDeflate?: boolean; + + // If using an RSA or ECDSA algorithm to sign the authToken, you will need + // to provide an authPrivateKey and authPublicKey in PEM format (string or Buffer). + authPrivateKey?: Secret; + authPublicKey?: Secret; + + // The default expiry for auth tokens in seconds + authDefaultExpiry?: number; + + // The algorithm to use to sign and verify JWT tokens. + authAlgorithm?: string; + + // Crash workers when an error happens - This is the most sensible default + crashWorkerOnError?: boolean; + + // Reboot workers when they crash - This is a necessity + // in production but can be turned off for debugging + rebootWorkerOnCrash?: boolean; + + // Kill/respawn a worker process if its memory consumption exceeds this + // threshold (in bytes) - If this is null (default), this behavior + // will be switched off + killWorkerMemoryThreshold?: number; + + // Can be 'http' or 'https' + protocol?: "http" | "https"; + + // This is the same as the object provided to Node.js's https server + protocolOptions?: ServerOptions; + + // A log level of 3 will log everything, 2 will show notices and errors, + // 1 will only log errors, 0 will log nothing + logLevel?: 0 | 1 | 2 | 3; + + // In milliseconds, how long a client has to connect to SC before timing out + connectTimeout?: number; + + // In milliseconds - If the socket handshake hasn't been completed before + // this timeout is reached, the new connection attempt will be terminated. + handshakeTimeout?: number; + + // In milliseconds, the timeout for calling res(err, data) when + // your emit() call expects an ACK response from the other side + // (when callback is provided to emit) + ackTimeout?: number; + + // In milliseconds, the timeout for calling res(err, data) when + // your sendToWorker, sendToBroker or sendToMaster (IPC) call + // expects an ACK response from the other process + // (when callback is provided) + ipcAckTimeout?: number; + + // In milliseconds - If the socket cannot upgrade transport + // within this period, it will stop trying + socketUpgradeTimeout?: number; + + // Origins which are allowed to connect to the real-time scServer + origins?: string; + + // The maximum number of unique channels which a single + // socket can subscribe to + socketChannelLimit?: number; + + // The interval in milliseconds on which to + // send a ping to the client to check that + // it is still alive + pingInterval?: number; + + // How many milliseconds to wait without receiving a ping + // before closing the socket + pingTimeout?: number; + + // Maximum amount of milliseconds to wait before force-killing + // a process after it was passed a 'SIGTERM' or 'SIGUSR2' signal + processTermTimeout?: number; + + // Whether or not errors from child processes (workers and brokers) + // should be passed to the current master process + propagateErrors?: boolean; + + // Whether or not warnings from child processes (workers and brokers) + // should be passed to the current master process + propagateWarnings?: number; + + // Whether or not a 'warning' event should be emitted (and logged to console) + // whenever an action is blocked by a middleware function + middlewareEmitWarnings?: number; + + // Lets you specify a host name to bind to - Defaults to + // 127.0.0.1 (localhost) + host?: string; + + // The path to a file used to bootstrap worker processes + workerController?: string; + + // The path to a file used to bootstrap broker processes + brokerController?: string; + + // The path to a file used to bootstrap the workerCluster process + workerClusterController?: string; + + // By default, SC will reboot all workers when it receives a 'SIGUSR2' signal - + // This can be used for updating workers with fresh source code in production + rebootOnSignal?: boolean; + + // If you run your master process (server.js) as super user, this option + // lets you downgrade worker and broker processes to run under + // the specified user (with fewer permissions than master) - You can provide + // a Linux UID or username + downgradeToUser?: number | string; + + // The URL path reserved by SocketCluster clients to interact with the server + path?: string; + + // The root directory in which to store your socket files in Linux. + socketRoot?: string; + + // Defaults to "rr", but can be set to "none" + schedulingPolicy?: "rr" | "none"; + + // Whether or not clients are allowed to publish messages to channels + allowClientPublish?: boolean; + + // This option is passed to the Node.js HTTP server if provided + tcpSynBacklog?: number; + + // SC keeps track of request per minutes internally - This allows you to change + // how often this gets updated + workerStatusInterval?: number; + + // This allows you to batch multiple messages together when passing them across + // message brokers. This may improve the efficiency of your pub/sub operations. + // This value is in milliseconds. 5 is generally a safe value to set this to. + pubSubBatchDuration?: number; + + // The default clustering/brokering engine (Node.js module name) which provides the + // SCWorker.exchange object and manages brokers behind the scenes. + // You shouldn't need to change this unless you want to build your own + // process clustering engine (which is difficult to do). + brokerEngine?: string; + + wsEngineServerOptions?: WebSocket.ClientOptions; + maxPayload?: number; + pingTimeoutDisabled?: boolean; + authSignAsync?: boolean; + authVerifyAsync?: boolean; + httpServer?: Server; + } + + interface SCServerSocketStatus { + id: string; + pingTimeout: number; + } + + interface HandshakeSCRequest { + socket: SCServerSocket; + } + + interface AuthenticateRequest { + socket: SCServerSocket; + authToken: AuthToken; + } + + interface SubscribeRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + channel?: string; + waitForAuth?: boolean; + data?: any; + } + + interface PublishInRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + channel?: string; + data?: any; + ackData?: any; + } + + interface PublishOutRequest { + socket: SCServerSocket; + channel?: string; + data?: any; + useCache?: boolean; + } + + interface EmitRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + event: string; + data?: any; + } + + type nextMiddlewareFunction = (error?: true | string | Error) => void; + type nextHandshakeSCMiddlewareFunction = (error?: true | string | Error | null, statusCode?: number) => void; + type nextAuthenticateMiddlewareFunction = (error?: true | string | Error | null, isBadToken?: boolean) => void; + type connectionListenerFunction = (scSocket: SCServerSocket, serverSocketStatus: SCServerSocketStatus) => void; + + interface SCCodecEngine { + decode: (input: any) => any; + ncode: (object: any) => any; + } +} diff --git a/types/socketcluster-server/scserversocket.d.ts b/types/socketcluster-server/scserversocket.d.ts new file mode 100644 index 0000000000..7b32cef72c --- /dev/null +++ b/types/socketcluster-server/scserversocket.d.ts @@ -0,0 +1,43 @@ +import Emitter = require("component-emitter"); +import { IncomingMessage } from "http"; +import { SCExchange } from "sc-broker-cluster"; +import { SignOptions } from "jsonwebtoken"; +import WebSocket = require("ws"); + +import SCServer = require("./scserver"); + +declare class SCServerSocket extends Emitter { + readonly CONNECTING: "connecting"; + readonly OPEN: "open"; + readonly CLOSED: "closed"; + + readonly AUTHENTICATED: "authenticated"; + readonly UNAUTHENTICATED: "unauthenticated"; + + id: string; + request: IncomingMessage; + + remoteAddress: string; + remoteFamily: string; + remotePort: number; + + exchange: SCExchange; + + state: "connecting" | "open" | "closed"; + authState: "authenticated" | "unauthenticated"; + authToken?: SCServer.AuthToken; + + constructor(id: string, server: SCServer, socket: WebSocket); + + getState(): "connecting" | "open" | "closed"; + disconnect(code?: number, data?: any): void; + send(data: any, options: { mask?: boolean; binary?: boolean; compress?: boolean; fin?: boolean }): void; + getAuthToken(): SCServer.AuthToken; + setAuthToken(data: SCServer.AuthToken, options?: SignOptions): void; + deauthenticate(): void; + kickOut(channel?: string, message?: string, callback?: () => void): void; + subscriptions(): string[]; + isSubscribed(channel?: string): boolean; +} + +export = SCServerSocket; diff --git a/types/socketcluster-server/socketcluster-server-tests.ts b/types/socketcluster-server/socketcluster-server-tests.ts new file mode 100644 index 0000000000..3d62fe9041 --- /dev/null +++ b/types/socketcluster-server/socketcluster-server-tests.ts @@ -0,0 +1,39 @@ +// Adapted from README + +// Using with basic http(s) module (example) + +import http = require("http"); +import * as socketClusterServer from "socketcluster-server"; + +let httpServer = http.createServer(); +let scServer = socketClusterServer.attach(httpServer); + +scServer.on("connection", socket => { + // ... Handle new socket connections here +}); + +httpServer.listen(8000); + +// Using with Express (example) + +import serveStatic = require("serve-static"); +import path = require("path"); +import express = require("express"); + +const app = express(); + +app.use(serveStatic(path.resolve(__dirname, "public"))); + +httpServer = http.createServer(); + +// Attach express to our httpServer +httpServer.on("request", app); + +// Attach socketcluster-server to our httpServer +scServer = socketClusterServer.attach(httpServer); + +scServer.on("connection", socket => { + // ... Handle new socket connections here +}); + +httpServer.listen(8000); diff --git a/types/socketcluster-server/tsconfig.json b/types/socketcluster-server/tsconfig.json new file mode 100644 index 0000000000..be1a6bdcb0 --- /dev/null +++ b/types/socketcluster-server/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "scserver.d.ts", + "scserversocket.d.ts", + "socketcluster-server-tests.ts" + ] +} diff --git a/types/socketcluster-server/tslint.json b/types/socketcluster-server/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster-server/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/socketcluster/fsutil.d.ts b/types/socketcluster/fsutil.d.ts new file mode 100644 index 0000000000..bcfcbfc59f --- /dev/null +++ b/types/socketcluster/fsutil.d.ts @@ -0,0 +1,11 @@ +import { PathLike } from "fs"; + +export function fileExists(filePath: PathLike, callback: (exists: boolean) => void): void; + +export function waitForFile( + filePath: PathLike, + checkInterval: number, + startTime: number, + maxWaitDuration: number, + timeoutErrorMessage?: string +): Promise; diff --git a/types/socketcluster/index.d.ts b/types/socketcluster/index.d.ts new file mode 100644 index 0000000000..0ec8485cfa --- /dev/null +++ b/types/socketcluster/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for socketcluster 14.0 +// Project: https://github.com/SocketCluster/socketcluster +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { EventEmitter } from "events"; +import { SCServer } from "socketcluster-server"; +import { ChildProcess } from "child_process"; + +interface WorkerStartInfo { + id: number; + pid: number; + respawn: boolean; +} + +interface WorkerClusterStartInfo { + pid: number; + childProcess: ChildProcess; +} + +interface WorkerClusterReadyInfo { + pid: number; + childProcess: ChildProcess; +} + +interface WorkerClusterExitInfo { + pid: number; + code: number; + signal: string; + childProcess: ChildProcess; +} + +export = SocketCluster; + +declare class SocketCluster extends EventEmitter { + readonly EVENT_FAIL: "fail"; + readonly EVENT_WARNING: "warning"; + readonly EVENT_READY: "ready"; + readonly EVENT_WORKER_START: "workerStart"; + readonly EVENT_WORKER_EXIT: "workerExit"; + readonly EVENT_BROKER_START: "brokerStart"; + readonly EVENT_BROKER_EXIT: "brokerExit"; + readonly EVENT_WORKER_CLUSTER_START: "workerClusterStart"; + readonly EVENT_WORKER_CLUSTER_READY: "workerClusterReady"; + readonly EVENT_WORKER_CLUSTER_EXIT: "workerClusterExit"; + + options: SCServer.SCServerOptions; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "fail", listener: (err: Error) => void): this; + on(event: "warning", listener: (warning: Error) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "workerStart", listener: (workerInfo: WorkerStartInfo) => void): this; + on(event: "workerExit", listener: (workerInfo: SocketCluster.WorkerExitInfo) => void): this; + on(event: "brokerStart", listener: (brokerInfo: SocketCluster.BrokerStartInfo) => void): this; + on(event: "brokerExit", listener: (brokerInfo: SocketCluster.BrokerExitInfo) => void): this; + on(event: "workerClusterStart", listener: (workerClusterInfo: WorkerClusterStartInfo) => void): this; + on(event: "workerClusterReady", listener: (workerClusterInfo: WorkerClusterReadyInfo) => void): this; + on(event: "workerClusterExit", listener: (workerClusterInfo: WorkerClusterExitInfo) => void): this; +} + +declare namespace SocketCluster { + interface WorkerExitInfo { + id: number; + pid: number; + code: number; + signal: string; + } + + interface BrokerStartInfo { + id: number; + pid: number; + respawn: boolean; + } + + interface BrokerExitInfo { + id: number; + pid: number; + code: number; + signal: string; + } +} diff --git a/types/socketcluster/scbroker.d.ts b/types/socketcluster/scbroker.d.ts new file mode 100644 index 0000000000..461801aa63 --- /dev/null +++ b/types/socketcluster/scbroker.d.ts @@ -0,0 +1,3 @@ +import SCBroker = require("sc-broker-cluster/scbroker"); + +export = SCBroker; diff --git a/types/socketcluster/scworker.d.ts b/types/socketcluster/scworker.d.ts new file mode 100644 index 0000000000..48502692be --- /dev/null +++ b/types/socketcluster/scworker.d.ts @@ -0,0 +1,63 @@ +import { EventEmitter } from "events"; +import { Server as httpServer } from "http"; +import { Server as httpsServer } from "https"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import { SCAuthEngine } from "sc-auth"; +import { SCExchange } from "sc-broker-cluster"; + +export = SCWorker; + +type middlewareFunction = (options: SCServer.SCServerOptions, next: (error?: string | Error) => void) => void; + +declare class SCWorker extends EventEmitter { + readonly EVENT_ERROR: "error"; + readonly EVENT_WARNING: "warning"; + readonly EVENT_EXIT: "exit"; + readonly EVENT_READY: "ready"; + readonly EVENT_CONNECTION: "connection"; + + readonly MIDDLEWARE_START: "start"; + + id: number; + isLeader: boolean; + options: SCServer.SCServerOptions; + httpServer: httpServer | httpsServer; + scServer: SCServer; + exchange: SCExchange; + auth: SCAuthEngine; + + constructor(options?: SCServer.SCServerOptions); + + run(): void; + + getSCServer(): SCServer; + getHTTPServer(): httpServer | httpsServer; + getSocketPath(): string; + + setAuthEngine(authEngine: SCAuthEngine): void; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; + + open(): void; + close(callback?: () => void): void; + + addMiddleware(type: "start", middlewareFn: middlewareFunction): void; + removeMiddleware(type: "start", middlewareFn: middlewareFunction): void; + + startHTTPServer(): void; + start(): Promise; + + getStatus(): { + clientCount: any; + httpRPM: number; + wsRPM: number; + }; + + sendToMaster(data: any, callback: (err: Error | null, data: any) => void): void; + respondToMaster(err: Error | null, data: any, rid: number): void; + + on(event: "connection", listener: (scSocket: SCServerSocket) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "warning", listener: (warning: Error) => void): this; + on(event: "masterMessage", listener: (data: any, respond: (err: Error | null, responseData: any) => void) => void): this; +} diff --git a/types/socketcluster/socketcluster-tests.ts b/types/socketcluster/socketcluster-tests.ts new file mode 100644 index 0000000000..85ad9c3d05 --- /dev/null +++ b/types/socketcluster/socketcluster-tests.ts @@ -0,0 +1,76 @@ +import * as fsutil from "socketcluster/fsutil"; +import SocketCluster = require("socketcluster"); +import { SCServer } from "socketcluster-server"; +import { ChildProcess } from "child_process"; + +//////////////////////////////////////////////////// +/// SocketCluster tests +//////////////////////////////////////////////////// + +{ + const options: SCServer.SCServerOptions = { port: 80 }; + + let sc = new SocketCluster(); + sc = new SocketCluster(options); + sc.options = { environment: "prod" }; + + sc.on(sc.EVENT_FAIL, err => { + const error: Error = err; + }); + sc.on(sc.EVENT_WARNING, warning => { + const warn: Error = warning; + }); + + sc.on(sc.EVENT_READY, () => {}); + + sc.on(sc.EVENT_WORKER_START, workerInfo => { + const id: number = workerInfo.id; + const pid: number = workerInfo.pid; + const respawn: boolean = workerInfo.respawn; + }); + sc.on(sc.EVENT_WORKER_EXIT, workerInfo => { + const id: number = workerInfo.id; + const pid: number = workerInfo.pid; + const code: number = workerInfo.code; + const signal: string = workerInfo.signal; + }); + + sc.on(sc.EVENT_BROKER_START, brokerInfo => { + const id: number = brokerInfo.id; + const pid: number = brokerInfo.pid; + const respawn: boolean = brokerInfo.respawn; + }); + sc.on(sc.EVENT_BROKER_EXIT, brokerInfo => { + const id: number = brokerInfo.id; + const pid: number = brokerInfo.pid; + const code: number = brokerInfo.code; + const signal: string = brokerInfo.signal; + }); + + sc.on(sc.EVENT_WORKER_CLUSTER_START, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); + sc.on(sc.EVENT_WORKER_CLUSTER_READY, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); + sc.on(sc.EVENT_WORKER_CLUSTER_EXIT, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const code: number = workerClusterInfo.code; + const signal: string = workerClusterInfo.signal; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); +} + +//////////////////////////////////////////////////// +/// fsutil tests +//////////////////////////////////////////////////// + +{ + fsutil.fileExists("/path/to/folder", err => {}); + fsutil.fileExists(Buffer.from(""), err => {}); + + const pathPromise: Promise = fsutil.waitForFile("/path/to/folder", 100, 0, 100); + const bufferPromise: Promise = fsutil.waitForFile(Buffer.from(""), 0, 0, 0, "timeout"); +} diff --git a/types/socketcluster/tsconfig.json b/types/socketcluster/tsconfig.json new file mode 100644 index 0000000000..1a0267f5f0 --- /dev/null +++ b/types/socketcluster/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 + }, + "files": [ + "index.d.ts", + "fsutil.d.ts", + "scbroker.d.ts", + "scworker.d.ts", + "socketcluster-tests.ts" + ] +} diff --git a/types/socketcluster/tslint.json b/types/socketcluster/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/space-pen/tslint.json b/types/space-pen/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/space-pen/tslint.json +++ b/types/space-pen/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/spectacle/index.d.ts b/types/spectacle/index.d.ts index e00b5dd3c0..621f08f67e 100644 --- a/types/spectacle/index.d.ts +++ b/types/spectacle/index.d.ts @@ -1,164 +1,321 @@ -// Type definitions for Spectacle 1.2.0 -// Project: https://github.com/FormidableLabs/victory +// Type definitions for Spectacle 5.2.2 +// Project: https://github.com/FormidableLabs/spectacle // Definitions by: Zachary Maybury +// Kylie Stewart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// declare module "spectacle" { - import * as React from "react"; + import * as React from "react"; + import * as CSS from "csstype"; + /** + * Alignment Types for Spectacle + */ + type alignType = + | "flex-start flex-start" + | "flex-start center" + | "flex-start flex-end" + | "center flex-start" + | "center center" + | "center flex-end" + | "flex-end flex-start" + | "flex-end center" + | "flex-end flex-end"; - /** - * Transition Types for Spectacle - */ - type transitionType = "slide"|"zoom"|"fade"|"spin"; + /** + * Animation Types for Spectacle + */ + type easeType = + | "back" + | "backIn" + | "backOut" + | "backInOut" + | "bounce" + | "bounceIn" + | "bounceOut" + | "bounceInOut" + | "circle" + | "circleIn" + | "circleOut" + | "circleInOut" + | "linear" + | "linearIn" + | "linearOut" + | "linearInOut" + | "cubic" + | "cubicIn" + | "cubicOut" + | "cubicInOut" + | "elastic" + | "elasticIn" + | "elasticOut" + | "elasticInOut" + | "exp" + | "expIn" + | "expOut" + | "expInOut" + | "poly" + | "polyIn" + | "polyOut" + | "polyInOut" + | "quad" + | "quadIn" + | "quadOut" + | "quadInOut" + | "sin" + | "sinIn" + | "sinOut" + | "sinInOut"; - /** - * Progress Types for Spectacle - */ - type progressType = "pacman"|"bar"|"number"|"none"; + /** + * Progress Types for Spectacle + */ + type progressType = "pacman" | "bar" | "number" | "none"; - /** - * Alignment Types for Spectacle - */ - type alignType = - "flex-start flex-start"|"flex-start center"|"flex-start flex-end"| - "center flex-start"|"center center"|"center flex-end"| - "flex-end flex-start"|"flex-end center"|"flex-end flex-end"; + /** + * S Types for StyledS in Spectacle + */ + type sType = "italic" | "bold" | "line-through" | "underline"; - /** - * Base props for many Spectacle components - */ - export interface BaseProps { - italic?:boolean, - bold?:boolean, - caps?:boolean, - margin?:number|string, - padding?:number|string, - textColor?:string, - textSize?:string, - textAlign?:string, - textFont?:string, - bgColor?:string, - bgImage?:string, - bgDarken?:number - } + /** + * Target Types for links + */ + type targetType = "_blank" | "_self" | "_parent" | "_top"; - export type Theme = { [key: string ]: string | number } + /** + * Theme Types for CodePane in Spectacle + */ + type themeType = "dark" | "light" | "external"; - export interface SpectacleProps { - theme?: Theme - } + /** + * Transition Types for Spectacle + */ + type transitionType = "slide" | "zoom" | "fade" | "spin"; - export interface DeckProps { - transition?:transitionType[], - transitionDuration?:number, - progress?:progressType, - controls?:boolean, - theme?: Theme - } + /** + * All available DOM style properties and their types + * https://www.npmjs.com/package/csstype + */ + export interface CSSProperties extends CSS.Properties {} - export interface SlideProps extends BaseProps { - align?:alignType, - transition?:transitionType[], - transitionDuration?:number, - notes?:string, - id?:string - } + export interface AnimProps { + easing: easeType; + fromStyle: CSSProperties | CSSProperties[]; + onAnim?: (forwards?: boolean, animIndex?: number) => void; + order?: number; + route?: object; + style?: CSSProperties; + toStyle: CSSProperties | CSSProperties[]; + transitionDuration: number; + } - export interface MarkdownProps { - source?:string, - mdastConfig?:{ [key: string ]: string | number } - } + export interface AppearProps { + easing?: easeType; + endValue?: object; + fid?: string; + order?: number; + startValue?: object; + style?: BaseProps["style"]; + transitionDuration?: number; + } - export interface CodePaneProps extends BaseProps { - lang?:string, - source?:string - } + /** + * Base props for many Spectacle components + */ + export interface BaseProps { + bgColor?: string; + bgDarken?: number; + bgImage?: string; + bold?: boolean; + caps?: boolean; + className?: string; + italic?: boolean; + margin?: number | string; + padding?: number | string; + style?: CSSProperties; + textAlign?: string; + textColor?: string; + textFont?: string; + textSize?: string; + } + export interface CodePaneProps { + className?: BaseProps["className"]; + contentEditable?: boolean; + lang?: string; + source?: string; + style?: BaseProps["style"]; + theme?: themeType; + } - export interface HeadingProps extends BaseProps { - fit?:boolean, - lineHeight?:number - size?:number; - } + export interface ComponentPlaygroundProps { + code?: string; + previewBackgroundColor?: string; + scope?: object; + theme?: themeType; + transformCode?: (code: string) => string; + } - export interface ImageProps extends BaseProps { - display?:string, - height?:number, - src?:string, - width?:number|string - } + export interface DeckProps { + autoplay?: boolean; + autoplayDuration?: number; + autoplayLoop?: boolean; + controls?: boolean; + globalStyles?: boolean; + history?: any; // Needs a type, see https://github.com/ReactTraining/history + progress?: progressType; + theme?: Theme; + transition?: transitionType[]; + transitionDuration?: number; + } - export interface LinkProps extends BaseProps { - href?:string - } + export interface FillProps { + className?: string; + style?: CSSProperties; + } - export interface SProps extends BaseProps { - type?:string - } + export interface FitProps extends FillProps {} - export interface TextProps extends BaseProps { - fit?:boolean, - lineHeight?:number - } + export interface GoToActionProps { + margin?: BaseProps["margin"]; + padding?: BaseProps["padding"]; + render?: (goToSlide?: (slide: number | string) => void) => void; + slide?: number | string; + style?: BaseProps["style"]; + } - export class Spectacle extends React.Component {} + export interface HeadingProps extends BaseProps { + fit?: boolean; + lineHeight?: number; + size?: number; + } - export class Deck extends React.Component {} + export interface ImageProps { + alt?: string; + className?: BaseProps["className"]; + display?: string; + height?: number | string; + margin?: BaseProps["margin"]; + padding?: BaseProps["padding"]; + src?: string; + width?: number | string; + } - export class Slide extends React.Component {} + export interface LayoutProps { + style?: CSSProperties; + } - export class Layout extends React.Component {} + export interface LinkProps extends BaseProps { + href?: string; + target?: targetType; + } - export class Fit extends React.Component {} + export interface MarkdownProps { + mdastConfig?: { [key: string]: number | string }; + source?: string; + } - export class Fill extends React.Component {} + export interface SlideProps extends BaseProps { + align?: alignType; + contentStyles?: CSSProperties; + controlColor?: string; + dispatch?: () => void; + hash?: number | string; + progressColor?: string; + history?: any; // Needs a type, see https://github.com/ReactTraining/history + id?: string; + lastSlideIndex?: number; + notes?: string; + onActive?: (slideIndex: string | number) => void; + slideIndex?: number; + transition?: transitionType[]; + transitionDuration?: number; + transitionIn?: transitionType[]; + transitionOut?: transitionType[]; + } - export class Markdown extends React.Component {} + export interface SProps extends BaseProps { + type?: sType | sType[]; + } - export class Appear extends React.Component {} + export interface TextProps extends BaseProps { + fit?: boolean; + lineHeight?: number; + } - export class BlockQuote extends React.Component {} + export type Theme = { [key: string]: number | string }; - export class Quote extends React.Component {} + export class Anim extends React.Component {} - export class Cite extends React.Component {} + export class Appear extends React.Component {} - export class CodePane extends React.Component {} + export class BlockQuote extends React.Component {} - export class Code extends React.Component {} + export class Cite extends React.Component {} - export class Heading extends React.Component {} + export class Code extends React.Component {} - export class Image extends React.Component {} + export class CodePane extends React.Component {} - export class Link extends React.Component {} + export class ComponentPlayground extends React.Component< + ComponentPlaygroundProps + > {} - export class List extends React.Component {} + export class Deck extends React.Component {} - export class ListItem extends React.Component {} + export class Fill extends React.Component {} - export class S extends React.Component {} + export class Fit extends React.Component {} - export class Table extends React.Component {} + export class GoToAction extends React.Component {} - export class TableRow extends React.Component {} + export class Heading extends React.Component {} - export class TableHeaderItem extends React.Component {} + export class Image extends React.Component {} - export class TableItem extends React.Component {} + export class Layout extends React.Component {} - export class Text extends React.Component {} + export class Link extends React.Component {} + + export class List extends React.Component {} + + export class ListItem extends React.Component {} + + export class Markdown extends React.Component {} + + export class Notes extends React.Component {} + + export class Quote extends React.Component {} + + export class S extends React.Component {} + + export class Slide extends React.Component {} + + export class SlideSet extends React.Component {} + + export class Table extends React.Component {} + + export class TableBody extends React.Component {} + + export class TableHeader extends React.Component {} + + export class TableHeaderItem extends React.Component {} + + export class TableItem extends React.Component {} + + export class TableRow extends React.Component {} + + export class Text extends React.Component {} } declare module "spectacle/lib/utils/preloader" { - const preloader: (obj: object) => void; - export default preloader; + const preloader: (obj: object) => void; + export default preloader; } declare module "spectacle/lib/themes/default" { - import { Theme } from "spectacle"; - const createTheme: (...args: object[]) => Theme; - export default createTheme; + import { Theme } from "spectacle"; + const createTheme: (...args: object[]) => Theme; + export default createTheme; } diff --git a/types/spectacle/package.json b/types/spectacle/package.json new file mode 100644 index 0000000000..9de3dd17fa --- /dev/null +++ b/types/spectacle/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "csstype": "^2.2.0" + } + } diff --git a/types/spectacle/spectacle-tests.tsx b/types/spectacle/spectacle-tests.tsx index f0a0b65e5a..04c3403f41 100644 --- a/types/spectacle/spectacle-tests.tsx +++ b/types/spectacle/spectacle-tests.tsx @@ -1,133 +1,377 @@ -/** - * Spectacle Test Examples - * - */ - -import * as React from 'react'; +import * as React from "react"; import { - Appear, - BlockQuote, - Cite, - Deck, - Fill, - Heading, - Layout, - Link, - ListItem, - List, - Quote, - Slide, - Spectacle, - Text + Anim, + Appear, + BlockQuote, + Cite, + CodePane, + ComponentPlayground, + Deck, + Fill, + GoToAction, + Heading, + Image, + Layout, + Link, + List, + ListItem, + Markdown, + Notes, + Quote, + Slide, + SlideSet, + Table, + TableBody, + TableHeader, + TableHeaderItem, + TableItem, + TableRow, + Text } from "spectacle"; // Import image preloader util -import preloader from 'spectacle/lib/utils/preloader' +import preloader from "spectacle/lib/utils/preloader"; // Import theme -import createTheme from 'spectacle/lib/themes/default' +import createTheme from "spectacle/lib/themes/default"; const images = { - city: 'a-url' -} + city: "a-url", + logo: "another-url" +}; -preloader(images) +preloader(images); -const theme = createTheme({ - primary: 'white', - secondary: '#1F2022', - tertiary: '#03A9FC', - quartenary: '#CECECE' -}, { - primary: 'Montserrat', - secondary: 'Helvetica' -}) +const theme = createTheme( + { + primary: "white", + secondary: "#1F2022", + tertiary: "#03A9FC", + quartenary: "#CECECE" + }, + { + primary: "Montserrat", + secondary: "Helvetica" + } +); export class SpectacleTest extends React.Component { - callback() { - alert('Callback: ' + JSON.stringify(arguments)); - } - - public render() { - return ( - - - - Spectacle - - - A ReactJS Presentation Library - - - Where You Can Write Your Decks In JSX - - - View on Github - - Hit Your Right Arrow To Begin! - - - - Wait what? - - - - - - Full Width - - - - - Adjustable Darkness - - - - - Background Imagery - - - - - Flexible Layouts - - - - Left - - - - - Right - - - - - -
    - Wonderfully formatted quotes - Ken Wheeler -
    -
    - - - Smooth - - - Combinable Transitions - - - - - Inline style based theme system - Autofit text - Flexbox layout system - React-Router navigation - PDF export - And... - - -
    -
    ); - } + public render() { + return ( + + + + Spectacle + + + A ReactJS Presentation Library + + + Where You Can Write Your Decks In JSX + + + + View on Github + + + + Hit Your Right Arrow To Begin! + + + + + Wait what? + + + + + + Full Width + + + + + Adjustable Darkness + + + + + Background Imagery + + + + + + + + + This is a component playground + + + + Flexible Layouts + + + + + Left + + + + + Right + + + + + + + Inline Markdown + + + {` + You can write inline images, [Markdown Links](http://commonmark.org), paragraph text and most other markdown syntax + * Lists too! + * With ~~strikethrough~~ and _italic_ + * And let's not forget **bold** + * Add some \`inline code\` to your sldes! + `} + + + + { + /* eslint-disable */ + console.log("forwards ", forwards); + console.log("animIndex ", animIndex); + /* eslint-enable */ + }} + fromStyle={{ + opacity: 0, + transform: + "translate3d(0px, -100px, 0px) scale(1) rotate(0deg)" + }} + toStyle={[ + { + opacity: 1, + transform: + "translate3d(0px, 0px, 0px) scale(1) rotate(0deg)" + }, + { + opacity: 1, + transform: + "translate3d(0px, 0px, 0px) scale(1.6) rotate(-15deg)" + }, + { + opacity: 1, + transform: + "translate3d(0px, 0px, 0px) scale(0.8) rotate(0deg)" + } + ]} + easing={"bounceOut"} + transitionDuration={500} + > + + + Flexible +
    + animations +
    +
    +
    +
    + + + Mix it up! + + + You can even jump to different slides with a standard + button or custom component! + + + Jump to Slide 8 + + ( + + )} + /> + + +
    + Wonderfully formatted quotes + Ken Wheeler +
    +
    + +
    + Wonderfully formatted quotes + Ken Wheeler +
    +
    + + + + + + Inline style based theme system + + + + Autofit text + + + Flexbox layout system + + + PDF export + + + And... + + + + + + You can even share styles with SlideSet + + + + + + Pizza Toppings + + + + + + + 2011 + 2013 + 2015 + + + + + None + 61.8% + 39.6% + 35.0% + + + Pineapple + 28.3% + 54.5% + 61.5% + + + Pepperoni + + 50.2% + 77.2% + + + Olives + + 24.9% + 55.9% + + +
    +
    +
    + + + Made with love in Seattle by + + + + + +
    + ); + } } diff --git a/types/ssh2-sftp-client/index.d.ts b/types/ssh2-sftp-client/index.d.ts index 2dcaee74e6..c568571eb5 100644 --- a/types/ssh2-sftp-client/index.d.ts +++ b/types/ssh2-sftp-client/index.d.ts @@ -1,39 +1,71 @@ -// Type definitions for ssh2-sftp-client 2.3 +// Type definitions for ssh2-sftp-client 2.4 // Project: https://www.npmjs.com/package/ssh2-sftp-client -// Definitions by: igrayson , Ascari Andrea , Kartik Malik +// Definitions by: igrayson +// Ascari Andrea +// Kartik Malik +// Michael Pertl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as ssh2 from 'ssh2'; import * as ssh2Stream from 'ssh2-streams'; + export = sftp; declare class sftp { - connect(options: ssh2.ConnectConfig): Promise; - list(remoteFilePath: string): Promise; - get(remoteFilePath: string, useCompression?: boolean, encoding?: string | null): Promise; - fastGet(remoteFilePath: string, localPath: string, options?: ssh2Stream.TransferOptions): Promise; - put(input: string | Buffer | NodeJS.ReadableStream, remoteFilePath: string, useCompression?: boolean, encoding?: string): Promise; - fastPut(localPath: string, emoteFilePath: string, options?: ssh2Stream.TransferOptions): Promise; - mkdir(remoteFilePath: string, recursive?: boolean): Promise; - rmdir(remoteFilePath: string, recursive?: boolean): Promise; - delete(remoteFilePath: string): Promise; - rename(remoteSourcePath: string, remoteDestPath: string): Promise; - end(): Promise; - on(event: string, callback: (...args: any[]) => void): void; + connect(options: ssh2.ConnectConfig): Promise; + + list(remoteFilePath: string): Promise; + + exists(remotePath: string): Promise; + + stat(remotePath: string): Promise; + + get(remoteFilePath: string, useCompression?: boolean, encoding?: string | null): Promise; + + fastGet(remoteFilePath: string, localPath: string, options?: ssh2Stream.TransferOptions): Promise; + + put(input: string | Buffer | NodeJS.ReadableStream, remoteFilePath: string, useCompression?: boolean, encoding?: string): Promise; + + fastPut(localPath: string, emoteFilePath: string, options?: ssh2Stream.TransferOptions): Promise; + + mkdir(remoteFilePath: string, recursive?: boolean): Promise; + + rmdir(remoteFilePath: string, recursive?: boolean): Promise; + + delete(remoteFilePath: string): Promise; + + rename(remoteSourcePath: string, remoteDestPath: string): Promise; + + chmod(remotePath: string, mode: number | string): Promise; + + end(): Promise; + + on(event: string, callback: (...args: any[]) => void): void; } + declare namespace sftp { - interface FileInfo { - type: string; - name: string; - size: number; - modifyTime: number; - accessTime: number; - rights: { - user: string; - group: string; - other: string; - }; - owner: number; - group: number; - } + interface FileInfo { + type: string; + name: string; + size: number; + modifyTime: number; + accessTime: number; + rights: { + user: string; + group: string; + other: string; + }; + owner: number; + group: number; + } + + interface FileStats { + mode: number; + permissions?: any; + owner: number; + group: number; + size: number; + accessTime: number; + modifyTime: number; + } } diff --git a/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts b/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts index 8a9c99fde1..d59e552990 100644 --- a/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts +++ b/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts @@ -1,5 +1,6 @@ import Client = require('ssh2-sftp-client'); import * as fs from 'fs'; + const client = new Client(); client.connect({ @@ -11,6 +12,10 @@ client.connect({ client.list('/remote/path').then(() => null); +client.exists('/remote/path').then(() => null); + +client.stat('/remote/path').then(() => null); + client.get('/remote/path').then(stream => stream.read(0)); client.get('/remote/path', true, 'utf8').then(stream => stream.read(0)); client.get('/remote/path', true, null).then(stream => stream.read(0)); @@ -30,6 +35,8 @@ client.delete('remote/path').then(() => null); client.rename('/remote/from', '/remote/to').then(() => null); +client.chmod('/remote/path', 777).then(() => null); + client.end().then(() => null); client.on('event', () => null); diff --git a/types/ssh2-streams/index.d.ts b/types/ssh2-streams/index.d.ts index a780273591..df1e001e0a 100644 --- a/types/ssh2-streams/index.d.ts +++ b/types/ssh2-streams/index.d.ts @@ -1044,6 +1044,24 @@ export class SFTPStream extends stream.Transform { */ fastPut(localPath: string, remotePath: string, callback: (err: any) => void): void; + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, options: ReadFileOptions, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, encoding: string, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, callback: (err: any, handle: Buffer) => void): void; + /** * (Client-only) * Returns a new readable stream for `path`. @@ -1680,4 +1698,9 @@ export interface ParsedKey { publicOrig: Buffer; ppk?: boolean; privateMAC?: string; +} + +export interface ReadFileOptions { + encoding?: string; + flag?: string; } \ No newline at end of file diff --git a/types/ssh2/index.d.ts b/types/ssh2/index.d.ts index 25bcfef52e..cf88fff5f1 100644 --- a/types/ssh2/index.d.ts +++ b/types/ssh2/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Qubo // Ron Buckton // Will Boyce +// Lucas Motta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -21,6 +22,7 @@ import { Attributes, Stats, TransferOptions, + ReadFileOptions, ReadStreamOptions, WriteStreamOptions, FileEntry @@ -1273,6 +1275,24 @@ export interface SFTPWrapper extends events.EventEmitter { */ fastPut(localPath: string, remotePath: string, callback: (err: any) => void): void; + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, options: ReadFileOptions, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, encoding: string, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, callback: (err: any, handle: Buffer) => void): void; + /** * (Client-only) * Returns a new readable stream for `path`. diff --git a/types/storybook__addon-options/index.d.ts b/types/storybook__addon-options/index.d.ts index 61f9f11def..968b003543 100644 --- a/types/storybook__addon-options/index.d.ts +++ b/types/storybook__addon-options/index.d.ts @@ -1,10 +1,14 @@ -// Type definitions for @storybook/addon-options 3.2 +// Type definitions for @storybook/addon-options 4.0 // Project: https://github.com/storybooks/storybook // Definitions by: Joscha Feth // Simon Helle Nielsen // A.MacLeay +// Gaetan Maisse +// Adam Misiorny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 + +import { StoryDecorator } from '@storybook/react'; export interface Options { name?: string; @@ -20,7 +24,14 @@ export interface Options { sortStoriesByKind?: boolean; hierarchySeparator?: RegExp | string; hierarchyRootSeparator?: RegExp | string; + sidebarAnimations?: boolean; selectedAddonPanel?: string; + enableShortcuts?: boolean; } +/** + * @deprecated Use withOptions instead + */ export function setOptions(options: Options): void; + +export function withOptions(options: Options): StoryDecorator; diff --git a/types/storybook__addon-options/storybook__addon-options-tests.ts b/types/storybook__addon-options/storybook__addon-options-tests.ts index a3003c913f..4321ecd72d 100644 --- a/types/storybook__addon-options/storybook__addon-options-tests.ts +++ b/types/storybook__addon-options/storybook__addon-options-tests.ts @@ -1,4 +1,23 @@ -import { setOptions } from '@storybook/addon-options'; +import { addDecorator } from '@storybook/react'; +import { setOptions, withOptions } from '@storybook/addon-options'; + +addDecorator( + withOptions({ + name: 'My Storybook', + url: 'https://example.com', + goFullScreen: false, + showStoriesPanel: false, + showAddonPanel: false, + showSearchBox: false, + addonPanelInRight: false, + sortStoriesByKind: false, + hierarchySeparator: /\//, + hierarchyRootSeparator: /\|/, + sidebarAnimations: false, + selectedAddonPanel: 'storybook/actions/action-panel', + enableShortcuts: false + }) +); setOptions({ name: 'My Storybook', @@ -11,7 +30,9 @@ setOptions({ sortStoriesByKind: false, hierarchySeparator: /\//, hierarchyRootSeparator: /\|/, + sidebarAnimations: false, selectedAddonPanel: 'storybook/actions/action-panel', + enableShortcuts: false }); setOptions({ diff --git a/types/storybook__addon-options/tsconfig.json b/types/storybook__addon-options/tsconfig.json index 936a535725..df1a88f769 100644 --- a/types/storybook__addon-options/tsconfig.json +++ b/types/storybook__addon-options/tsconfig.json @@ -15,6 +15,9 @@ "paths": { "@storybook/addon-options": [ "storybook__addon-options" + ], + "@storybook/react": [ + "storybook__react" ] }, "types": [], @@ -25,4 +28,4 @@ "index.d.ts", "storybook__addon-options-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/storybook__addon-viewport/index.d.ts b/types/storybook__addon-viewport/index.d.ts new file mode 100644 index 0000000000..2576ab85cc --- /dev/null +++ b/types/storybook__addon-viewport/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for @storybook/addon-viewport 4.1 +// Project: https://github.com/storybooks/storybook/tree/master/addons/viewport +// Definitions by: Vincent Tunru +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { StoryDecorator } from '@storybook/react'; + +export type ViewportName = string; + +export interface ViewportProperties { + name: ViewportName; + styles: { + width?: string, + height?: string, + [styleName: string]: any, + }; + type?: 'desktop' | 'tablet' | 'mobile' | string; +} +export interface ViewportDecoratorOptions { + /** + * Default viewport + */ + name?: ViewportName; + /** + * Called whenever different viewport is selected from the dropdown + */ + onViewportChange: (change: { viewport: ViewportProperties }) => void; +} +export interface ViewportDefinitions { + [viewportKey: string]: ViewportProperties; +} +export type Viewport = ViewportName | ViewportDecoratorOptions; + +export interface ViewportConfiguration { + viewports?: ViewportDefinitions; + defaultViewport?: ViewportName; +} + +export const INITIAL_VIEWPORTS: ViewportDefinitions; +export function configureViewport(configuration: ViewportConfiguration): void; +export function withViewport(viewport?: Viewport): StoryDecorator; diff --git a/types/storybook__addon-viewport/storybook__addon-viewport-tests.ts b/types/storybook__addon-viewport/storybook__addon-viewport-tests.ts new file mode 100644 index 0000000000..dce6671b2d --- /dev/null +++ b/types/storybook__addon-viewport/storybook__addon-viewport-tests.ts @@ -0,0 +1,33 @@ +import { configureViewport, INITIAL_VIEWPORTS, withViewport } from '@storybook/addon-viewport'; + +import { storiesOf } from '@storybook/react'; + +const minimalViewport = { + name: 'Viewport with minimal amount of configuration', + styles: { + width: '450px', + height: '150px', + }, +}; +const maximalViewport = { + name: 'Viewport that also sets its type', + styles: { + width: '230px', + height: '300px', + }, + type: 'desktop', +}; +configureViewport({ + viewports: { ...INITIAL_VIEWPORTS, minimalViewport, maximalViewport }, +}); +configureViewport({ + defaultViewport: 'minimalViewport', +}); + +const stories = storiesOf('Example of Knobs', module); + +stories.addDecorator(withViewport()); +stories.addDecorator(withViewport('viewportName')); +stories.addDecorator(withViewport({ + onViewportChange: ({ viewport }) => `Viewport changed: ${viewport.name} (${viewport.type})`, +})); diff --git a/types/storybook__addon-viewport/tsconfig.json b/types/storybook__addon-viewport/tsconfig.json new file mode 100644 index 0000000000..30f31fb5d3 --- /dev/null +++ b/types/storybook__addon-viewport/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@storybook/addon-viewport": [ + "storybook__addon-viewport" + ], + "@storybook/react": [ + "storybook__react" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "storybook__addon-viewport-tests.ts" + ] +} diff --git a/types/storybook__addon-viewport/tslint.json b/types/storybook__addon-viewport/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/storybook__addon-viewport/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/storybook__react-native/index.d.ts b/types/storybook__react-native/index.d.ts index 3f46866129..fc308fa69b 100644 --- a/types/storybook__react-native/index.d.ts +++ b/types/storybook__react-native/index.d.ts @@ -4,18 +4,98 @@ // Anton Izmailov // Alec Hill // Kyle Roach +// Ceyhun Ozugur // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; export interface StorybookUIOptions { + /** + * display navigator and addons on the device + * + * @default true + */ onDeviceUI?: boolean; + + /** + * allows to display stories without running storybook server. Should be used with onDeviceUI + * + * @default false + */ disableWebsockets?: boolean; + + /** + * use wss/https instead of ws/http + * + * @default false + */ secured?: boolean; + + /** + * host to use + * + * @default NativeModules.SourceCode.scriptURL + */ host?: string; + + /** + * port to use + * + * @default 7007 + */ port?: number; + + /** + * additional query string to pass to websockets + * + * @default "" + */ query?: string; + + /** + * should the ui be closed initialy. + * + * @default false + */ + isUIHidden?: boolean; + + /** + * which tab should be open. -1 Navigator, 0 Preview, 1 Addons + * + * @default 0 + */ + tabOpen?: number; + + /** + * initialize storybook with a specific story. + * In case a valid object is passed, it will take precedence over `shouldPersistSelection`. + * ex: `{ kind: 'Knobs', story: 'with knobs' }` + * + * @default null + */ + initialSelection?: object; + + /** + * initialize storybook with the last selected story. + * + * @default true + */ + shouldPersistSelection?: boolean; + + /** + * disable KeyboardAvoidingView wrapping Storybook's view + * + * @default false + */ + shouldDisableKeyboardAvoidingView?: boolean; + + /** + * this will set the keyboardverticaloffset (https://facebook.github.io/react-native/docs/keyboardavoidingview#keyboardverticaloffset) value for KeyboardAvoidingView wrapping Storybook's view + * + * @default 0 + */ + keyboardAvoidingViewVerticalOffset?: number; } export function getStorybookUI( diff --git a/types/string-length/index.d.ts b/types/string-length/index.d.ts new file mode 100644 index 0000000000..4f4ce92f3c --- /dev/null +++ b/types/string-length/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for string-length 2.0 +// Project: https://github.com/sindresorhus/string-length#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = stringLength; + +declare function stringLength(input: string): number; diff --git a/types/string-length/string-length-tests.ts b/types/string-length/string-length-tests.ts new file mode 100644 index 0000000000..aea7a4a4ce --- /dev/null +++ b/types/string-length/string-length-tests.ts @@ -0,0 +1,4 @@ +import stringLength = require('string-length'); + +stringLength('🐴'); // $ExpectType number +stringLength('\u001B[1municorn\u001B[22m'); // $ExpectType number diff --git a/types/string-length/tsconfig.json b/types/string-length/tsconfig.json new file mode 100644 index 0000000000..33d5f5e197 --- /dev/null +++ b/types/string-length/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", + "string-length-tests.ts" + ] +} diff --git a/types/string-length/tslint.json b/types/string-length/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/string-length/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/stringify-attributes/index.d.ts b/types/stringify-attributes/index.d.ts new file mode 100644 index 0000000000..0d4ef1cecb --- /dev/null +++ b/types/stringify-attributes/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for stringify-attributes 1.0 +// Project: https://github.com/sindresorhus/stringify-attributes#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = stringifyAttributes; + +declare function stringifyAttributes(attributes: stringifyAttributes.Attributes): string; + +declare namespace stringifyAttributes { + interface Attributes { + [attrName: string]: string | number | boolean | Array; + } +} diff --git a/types/stringify-attributes/stringify-attributes-tests.ts b/types/stringify-attributes/stringify-attributes-tests.ts new file mode 100644 index 0000000000..3b7ff11aab --- /dev/null +++ b/types/stringify-attributes/stringify-attributes-tests.ts @@ -0,0 +1,18 @@ +import stringifyAttributes = require('stringify-attributes'); + +// $ExpectType string +stringifyAttributes({ + unicorn: '🦄', +}); +// $ExpectType string +stringifyAttributes({ + rainbow: true, +}); +// $ExpectType string +stringifyAttributes({ + number: 1, +}); +// $ExpectType string +stringifyAttributes({ + multiple: ['a', 1], +}); diff --git a/types/stringify-attributes/tsconfig.json b/types/stringify-attributes/tsconfig.json new file mode 100644 index 0000000000..40f5d75976 --- /dev/null +++ b/types/stringify-attributes/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", + "stringify-attributes-tests.ts" + ] +} diff --git a/types/stringify-attributes/tslint.json b/types/stringify-attributes/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/stringify-attributes/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/strip-indent/index.d.ts b/types/strip-indent/index.d.ts new file mode 100644 index 0000000000..33348bbb22 --- /dev/null +++ b/types/strip-indent/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for strip-indent 2.0 +// Project: https://github.com/sindresorhus/strip-indent#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = stripIndent; + +declare function stripIndent(str: string): string; diff --git a/types/strip-indent/strip-indent-tests.ts b/types/strip-indent/strip-indent-tests.ts new file mode 100644 index 0000000000..b8c6439be4 --- /dev/null +++ b/types/strip-indent/strip-indent-tests.ts @@ -0,0 +1,5 @@ +import stripIndent = require('strip-indent'); + +const str = '\tunicorn\n\t\tcake'; +// $ExpectType string +stripIndent(str); diff --git a/types/strip-indent/tsconfig.json b/types/strip-indent/tsconfig.json new file mode 100644 index 0000000000..ecaa642b92 --- /dev/null +++ b/types/strip-indent/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", + "strip-indent-tests.ts" + ] +} diff --git a/types/strip-indent/tslint.json b/types/strip-indent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/strip-indent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/styled-components/cssprop.d.ts b/types/styled-components/cssprop.d.ts new file mode 100644 index 0000000000..e19b03dc2c --- /dev/null +++ b/types/styled-components/cssprop.d.ts @@ -0,0 +1,19 @@ +import {} from "react"; +import { CSSProp } from "."; + +declare module "react" { + interface Attributes { + // NOTE: unlike the plain javascript version, it is not possible to get access + // to the element's own attributes inside function interpolations. + // Only theme will be accessible, and only with the DefaultTheme due to the global + // nature of this declaration. + // If you are writing this inline you already have access to all the attributes anyway, + // no need for the extra indirection. + /** + * If present, this React element will be converted by + * `babel-plugin-styled-components` into a styled component + * with the given css as its styles. + */ + css?: CSSProp; + } +} diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 1b26568498..ca3ff22c0e 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -73,7 +73,7 @@ export type SimpleInterpolation = | InterpolationValue | FlattenSimpleInterpolation; // must be an interface to be self-referential -interface FlattenSimpleInterpolation +export interface FlattenSimpleInterpolation extends ReadonlyArray {} export type InterpolationFunction

    = (props: P) => Interpolation

    ; @@ -176,10 +176,9 @@ export interface ThemedStyledFunctionBase< ( first: | TemplateStringsArray - | NonNullable< - Interpolation< - ThemedStyledProps & O, T> - > + | CSSObject + | InterpolationFunction< + ThemedStyledProps & O, T> >, ...rest: Array< Interpolation< @@ -187,17 +186,12 @@ export interface ThemedStyledFunctionBase< > > ): StyledComponent; - // at least the first argument is required, whatever it is ( first: | TemplateStringsArray - | NonNullable< - Interpolation< - ThemedStyledProps< - StyledComponentPropsWithRef & O & U, - T - > - > + | CSSObject + | InterpolationFunction< + ThemedStyledProps & O & U, T> >, ...rest: Array< Interpolation< @@ -288,19 +282,21 @@ export type StyledInterface = ThemedStyledInterface; export interface BaseThemedCssFunction { ( - first: TemplateStringsArray | NonNullable, + first: TemplateStringsArray | CSSObject, ...interpolations: SimpleInterpolation[] ): FlattenSimpleInterpolation; ( first: | TemplateStringsArray - | NonNullable>>, + | CSSObject + | InterpolationFunction>, ...interpolations: Array>> ): FlattenInterpolation>;

    ( first: | TemplateStringsArray - | NonNullable>>, + | CSSObject + | InterpolationFunction>, ...interpolations: Array>> ): FlattenInterpolation>; } @@ -333,7 +329,8 @@ export interface ThemedStyledComponentsModule< createGlobalStyle

    ( first: | TemplateStringsArray - | NonNullable>>, + | CSSObject + | InterpolationFunction>, ...interpolations: Array>> ): GlobalStyleComponent; @@ -405,7 +402,8 @@ export function keyframes( export function createGlobalStyle

    ( first: | TemplateStringsArray - | NonNullable>>, + | CSSObject + | InterpolationFunction>, ...interpolations: Array>> ): GlobalStyleComponent; @@ -440,4 +438,35 @@ export class StyleSheetManager extends React.Component< StyleSheetManagerProps > {} +/** + * The CSS prop is not declared by default in the types as it would cause 'css' to be present + * on the types of anything that uses styled-components indirectly, even if they do not use the + * babel plugin. + * + * You can load a default declaration by using writing this special import from + * a typescript file. This module does not exist in reality, which is why the {} is important: + * + * ```ts + * import {} from 'styled-components/cssprop' + * ``` + * + * Or you can declare your own module augmentation, which allows you to specify the type of Theme: + * + * ```ts + * import { CSSProp } from 'styled-components' + * + * interface MyTheme {} + * + * declare module 'react' { + * interface Attributes { + * css?: CSSProp + * } + * } + * ``` + */ +// ONLY string literals and inline invocations of css`` are supported, anything else crashes the plugin +export type CSSProp> = + | string + | FlattenInterpolation>; + export default styled; diff --git a/types/styled-components/macro.d.ts b/types/styled-components/macro.d.ts index 08cee96a96..51f6cced26 100644 --- a/types/styled-components/macro.d.ts +++ b/types/styled-components/macro.d.ts @@ -1,2 +1,7 @@ export { default } from '.'; export * from '.'; + +/** + * Recommended: also `import {} from 'styled-components/cssprop'`, + * or augment react's `Attribute` interface with your own version. + */ diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index 50a17b7069..d382b42628 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -14,8 +14,12 @@ import styled, { withTheme, ThemeConsumer, StyledComponent, - ThemedStyledComponentsModule + ThemedStyledComponentsModule, + FlattenSimpleInterpolation, + SimpleInterpolation, + FlattenInterpolation } from "styled-components"; +import {} from "styled-components/cssprop"; /** * general usage @@ -100,13 +104,13 @@ const fadeIn = keyframes` `; const showAnimation = css` - opacity: 1; - transform: scale(1) translateY(0); + opacity: 1; + transform: scale(1) translateY(0); `; const hideAnimation = css` - opacity: 0; - transform: scale(0.95, 0.8) translateY(20px); + opacity: 0; + transform: scale(0.95, 0.8) translateY(20px); `; const entryAnimation = keyframes` @@ -187,7 +191,6 @@ const styledButton = styled.button` const name = "hey"; const ThemedMyButton = withTheme(MyButton); - ; /** @@ -305,7 +308,6 @@ const ObjectStylesBox = styled.div` fontSize: 2 }}; `; - ; /** @@ -337,7 +339,6 @@ const AttrsWithOnlyNewProps = styled.h2.attrs({ as: "h1" })` `; const AttrsInputExtra = styled(AttrsInput).attrs({ autoComplete: "off" })``; - ; /** @@ -434,10 +435,8 @@ const Component = (props: WithThemeProps) => ( ); const ComponentWithTheme = withTheme(Component); - ; // ok ; // ok - {theme => }; /** @@ -625,7 +624,6 @@ const divFnRef = (ref: HTMLDivElement | null) => { const divRef = React.createRef(); const StyledDiv = styled.div``; - ; ; ; // $ExpectError @@ -699,6 +697,8 @@ async function typedThemes() { return props.theme.color; }}; `; + // can't use a FlattenInterpolation as the first argument, would make broken css + // $ExpectError const ThemedDiv4 = styled.div(themedCss); const themedCssWithNesting = css(props => ({ @@ -719,7 +719,6 @@ async function typedThemes() { - {theme => { // $ExpectType string @@ -786,3 +785,164 @@ async function themeAugmentation() { ); } + +// NOTE: this is needed for some tests inside cssProp, +// but actually running this module augmentation will cause +// tests elsewhere to break, and there is no way to contain it. +// Uncomment out as needed to run tests. + +// declare module "styled-components" { +// interface DefaultTheme { +// background: string; +// } +// } + +function cssProp() { + function Custom(props: React.ComponentPropsWithoutRef<"div">) { + return

    ; + } + + const myCss = "background: blue;"; + + return ( + <> +
    + {/* + For some reason $ExpectError doesn't work on this expression. + Only strings work, objects crash the plugin. +
    + */} +
    +
    +
    +
    +
    "blue"}; + `} + /> +
    { + // This requires the DefaultTheme augmentation + // // $ExpectType string + // props.theme.background; + return props.theme.background; + }}; + `} + /> + + + + "blue"}; + `} + /> + { + // This requires the DefaultTheme augmentation + // // $ExpectType string + // props.theme.background; + return props.theme.background; + }}; + `} + /> + + ); +} + +function validateArgumentsAndReturns() { + const t1: FlattenSimpleInterpolation[] = [ + css({ color: "blue" }), + css` + color: blue; + `, + css` + color: ${"blue"}; + ` + ]; + const t4: FlattenInterpolation = [ + css` + color: ${() => "blue"}; + `, + css(() => ({ color: "blue" })), + css( + () => + css` + color: "blue"; + ` + ) + ]; + + // if the first argument is array-like it's always treated as a string[], this breaks things + css( + // $ExpectError + css` + ${{ color: "blue" }} + ` + ); + // _technically_ valid as styled-components doesn't look at .raw but best not to support it + // $ExpectError + css([]); + + styled.div({ color: "blue" }); + styled.div(props => ({ color: props.theme.color })); + styled.div` + color: ${"blue"}; + `; + // These don't work for the same reason css doesn't work + styled.div( + // $ExpectError + css` + ${{ color: "blue" }} + ` + ); + // $ExpectError + styled.div([]); + + createGlobalStyle({ + ":root": { + color: "blue" + } + }); + createGlobalStyle` + :root { + color: blue; + } + `; + createGlobalStyle(() => ({ + ":root": { + color: "blue" + } + })); + // these are invalid for the same reason as in styled.div + // $ExpectError + createGlobalStyle(css` + :root { + color: ${() => "blue"}; + } + `); + // $ExpectError + createGlobalStyle([]); +} diff --git a/types/styled-components/tsconfig.json b/types/styled-components/tsconfig.json index 22af0d4a13..fb9b5a0f7b 100644 --- a/types/styled-components/tsconfig.json +++ b/types/styled-components/tsconfig.json @@ -3,20 +3,26 @@ "baseUrl": "../", "forceConsistentCasingInFileNames": true, "jsx": "react", - "lib": ["es6", "dom"], + "lib": [ + "es6", + "dom" + ], "module": "commonjs", "noEmit": true, "noImplicitAny": true, "noImplicitThis": true, "strictFunctionTypes": true, "strictNullChecks": true, - "typeRoots": ["../"], + "typeRoots": [ + "../" + ], "types": [] }, "files": [ "index.d.ts", "macro.d.ts", + "cssprop.d.ts", "test/index.tsx", "test/macro.tsx" ] -} +} \ No newline at end of file diff --git a/types/subsume/index.d.ts b/types/subsume/index.d.ts index 7ec2f9d568..e42c97cd4f 100644 --- a/types/subsume/index.d.ts +++ b/types/subsume/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for subsume 1.0 +// Type definitions for subsume 2.0 // Project: https://github.com/sindresorhus/subsume#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,6 +7,7 @@ export = Subsume; declare class Subsume { static parse(text: string, id: string): Subsume.ParseResult; + static parseAll(text: string, ids?: string[]): Subsume.ParseResults; id: string; prefix: string; @@ -23,4 +24,9 @@ declare namespace Subsume { data?: string; rest: string; } + + interface ParseResults { + data: Map; + rest: string; + } } diff --git a/types/subsume/subsume-tests.ts b/types/subsume/subsume-tests.ts index 263553733a..56234d275b 100644 --- a/types/subsume/subsume-tests.ts +++ b/types/subsume/subsume-tests.ts @@ -18,5 +18,13 @@ res; // $ExpectType ParseResult res.data; // $ExpectType string | undefined res.rest; // $ExpectType string -const input = 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## random text'; -Subsume.parse(text, '7febcd0b3806fbc48c01d7cea4ed1219'); // $ExpectType ParseResult +const input = + 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## random text'; +Subsume.parse(input, '7febcd0b3806fbc48c01d7cea4ed1219'); // $ExpectType ParseResult + +const input2 = + 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## ' + + 'random@@[7febcd0b3806fbc48c01d7cea4ed1218]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1218]## ' + + 'text@@[7febcd0b3806fbc48c01d7cea4ed1217]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1217]##'; +Subsume.parseAll(input2); // $ExpectType ParseResults +Subsume.parseAll(input2, ['7febcd0b3806fbc48c01d7cea4ed1219']); // $ExpectType ParseResults diff --git a/types/subsume/tsconfig.json b/types/subsume/tsconfig.json index b29ec71ee8..7eefbf76e9 100644 --- a/types/subsume/tsconfig.json +++ b/types/subsume/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "subsume-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/subsume/v1/index.d.ts b/types/subsume/v1/index.d.ts new file mode 100644 index 0000000000..7ec2f9d568 --- /dev/null +++ b/types/subsume/v1/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for subsume 1.0 +// Project: https://github.com/sindresorhus/subsume#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Subsume; + +declare class Subsume { + static parse(text: string, id: string): Subsume.ParseResult; + + id: string; + prefix: string; + postfix: string; + regex: RegExp; + + constructor(id?: string); + compose(text: string): string; + parse(text: string): Subsume.ParseResult; +} + +declare namespace Subsume { + interface ParseResult { + data?: string; + rest: string; + } +} diff --git a/types/subsume/v1/subsume-tests.ts b/types/subsume/v1/subsume-tests.ts new file mode 100644 index 0000000000..263553733a --- /dev/null +++ b/types/subsume/v1/subsume-tests.ts @@ -0,0 +1,22 @@ +import Subsume = require('subsume'); + +const subsume = new Subsume(); +new Subsume('foo'); + +subsume.id; // $ExpectType string +subsume.prefix; // $ExpectType string +subsume.postfix; // $ExpectType string +subsume.regex; // $ExpectType RegExp + +const text = subsume.compose('🦄'); +text; // $ExpectType string + +const output = `some${text} random text`; + +const res = subsume.parse(output); +res; // $ExpectType ParseResult +res.data; // $ExpectType string | undefined +res.rest; // $ExpectType string + +const input = 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## random text'; +Subsume.parse(text, '7febcd0b3806fbc48c01d7cea4ed1219'); // $ExpectType ParseResult diff --git a/types/subsume/v1/tsconfig.json b/types/subsume/v1/tsconfig.json new file mode 100644 index 0000000000..0e0565e161 --- /dev/null +++ b/types/subsume/v1/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "subsume": [ + "subsume/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "subsume-tests.ts" + ] +} diff --git a/types/subsume/v1/tslint.json b/types/subsume/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/subsume/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index 971cc3c4c2..7c1898cdc2 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -6,6 +6,7 @@ // Shrey Jain // Alec Zopf // Adam Haglund +// Lukas Elmer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -45,7 +46,7 @@ declare namespace request { // tslint:disable-next-line:unified-signatures (method: string, url: string): SuperAgentRequest; - agent(): SuperAgent; + agent(): this & Request; serialize: { [type: string]: Serializer }; parse: { [type: string]: Parser }; } diff --git a/types/superagent/superagent-tests.ts b/types/superagent/superagent-tests.ts index c063c819be..44ef7cf773 100644 --- a/types/superagent/superagent-tests.ts +++ b/types/superagent/superagent-tests.ts @@ -421,3 +421,16 @@ request .get('/echo') .use(echoPlugin) .end(); + +async function testDefaultOptions() { + // Default options for multiple requests + const agentWithDefaultOptions = request + .agent() + .use(() => null) + .auth('digest', 'secret', { type: 'auto' }); + + await agentWithDefaultOptions.get('/with-plugin-and-auth'); + await agentWithDefaultOptions.get('/also-with-plugin-and-auth'); +} + +testDefaultOptions(); diff --git a/types/supertest/index.d.ts b/types/supertest/index.d.ts index 77418352f9..5ac03df42d 100644 --- a/types/supertest/index.d.ts +++ b/types/supertest/index.d.ts @@ -24,7 +24,7 @@ declare namespace supertest { serverAddress(app: any, path: string): string; expect(status: number, callback?: CallbackHandler): this; expect(status: number, body: any, callback?: CallbackHandler): this; - expect(checker: (res: Response) => any): this; + expect(checker: (res: Response) => any, callback?: CallbackHandler): this; expect(body: string, callback?: CallbackHandler): this; expect(body: RegExp, callback?: CallbackHandler): this; expect(body: Object, callback?: CallbackHandler): this; diff --git a/types/swiper/index.d.ts b/types/swiper/index.d.ts index 9e77516978..74b8d928b9 100644 --- a/types/swiper/index.d.ts +++ b/types/swiper/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for Swiper 4.2 +// Type definitions for Swiper 4.4 // Project: https://github.com/nolimits4web/Swiper // Definitions by: Sebastián Galiano // Luca Trazzi // Eugene Matseruk // Luiz M. // Justin Abene +// Asif Rahman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 @@ -221,6 +222,7 @@ export interface SwiperOptions { slidesOffsetBefore?: number; slidesOffsetAfter?: number; normalizeSlideIndex?: boolean; + centerInsufficientSlides?: boolean; // Grab Cursor grabCursor?: boolean; @@ -238,6 +240,8 @@ export interface SwiperOptions { followFinger?: boolean; allowTouchMove?: boolean; threshold?: number; + touchStartPreventDefault?: boolean; + touchStartForcePreventDefault?: boolean; touchMoveStopPropagation?: boolean; iOSEdgeSwipeDetection?: boolean; iOSEdgeSwipeThreshold?: number; @@ -249,11 +253,12 @@ export interface SwiperOptions { resistanceRatio?: number; // Swiping / No swiping + preventInteractionOnTransition?: boolean; allowSlidePrev?: boolean; allowSlideNext?: boolean; noSwiping?: boolean; noSwipingClass?: string; - // noSwipingSelector?: string; + noSwipingSelector?: string; swipeHandler?: SelectableElement; // Clicks @@ -289,6 +294,7 @@ export interface SwiperOptions { breakpoints?: { [index: number]: SwiperOptions; }; + breakpointsInverse?: boolean; // Observer observer?: boolean; @@ -1073,6 +1079,44 @@ export default class Swiper { */ slideTo(index: number, speed?: number, runCallbacks?: boolean): void; + /** + * Does the same as .slideTo but for the case when used with enabled loop. So this + * method will slide to slides with realIndex matching to passed index + * + * @param index Index number of slide. + * @param speed Transition duration (in ms). + * @param runCallbacks Set it to false (by default it is true) and transition will + * not produce transition events. + */ + slideToLoop(index: number, speed?: number, runCallbacks?: boolean): void; + + /** + * Reset swiper position to currently active slide for the duration equal to 'speed' + * parameter. + * + * @param speed Transition duration (in ms). + * @param runCallbacks Set it to false (by default it is true) and transition will + * not produce transition events. + */ + slideReset(speed?: number, runCallbacks?: boolean): void; + + /** + * Reset swiper position to closest slide/snap point for the duration equal to 'speed' parameter. + * + * @param speed Transition duration (in ms). + * @param runCallbacks Set it to false (by default it is true) and transition will + * not produce transition events. + */ + slideToClosest(speed?: number, runCallbacks?: boolean): void; + + /** + * Force swiper to update its height (when autoHeight enabled) for the duration equal to + * 'speed' parameter + * + * @param speed Transition duration (in ms). + */ + updateAutoHeight(speed?: number): void; + /** * You should call it after you add/remove slides * manually, or after you hide/show it, or do any @@ -1162,6 +1206,17 @@ export default class Swiper { */ prependSlide(slides: HTMLElement | string | string[]): void; + /** + * Add new slides to the required index. slides could be HTMLElement or HTML string with new slide or array with such slides, for example: + * + * @example addSlide(1, '
    Slide 10"
    ') + * @example addSlide(1, [ + * '
    Slide 10"
    ', + * '
    Slide 11"
    ' + * ]); + */ + addSlide(index: number, slides: HTMLElement | string | string[]): void; + /** * Remove selected slides. slideIndex could be a number with slide index to remove or array with indexes. * @@ -1171,6 +1226,11 @@ export default class Swiper { */ removeSlide(slideIndex: number | number[]): void; + /** + * Remove all slides + */ + removeAllSlides(): any; + /** * Set custom css3 transform's translate value for swiper wrapper */ diff --git a/types/syntax-error/index.d.ts b/types/syntax-error/index.d.ts new file mode 100644 index 0000000000..68bbba8346 --- /dev/null +++ b/types/syntax-error/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for syntax-error 1.4 +// Project: https://github.com/browserify/syntax-error +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as acorn from "acorn"; + +/** + * Check the source code string 'src' for syntax errors. Optionally you can specify a filename + * file that will show up in the output. + * If 'src' has a syntax error, return an error object err that can be printed or stringified. + * If there are no syntax errors in 'src', return undefined. + * Options will be passed through to acorn-node. acorn-node defaults to options + * that match the most recent Node versions. + */ +declare function syntaxError(src: any, file?: string, opts?: acorn.Options): (SyntaxError & { line: number; column: number; annotated: string; inspect(): string }) | undefined; + +export = syntaxError; diff --git a/types/syntax-error/syntax-error-tests.ts b/types/syntax-error/syntax-error-tests.ts new file mode 100644 index 0000000000..39a35b345f --- /dev/null +++ b/types/syntax-error/syntax-error-tests.ts @@ -0,0 +1,12 @@ +import syntaxError = require("syntax-error"); + +function test(): SyntaxError | undefined { + const res1 = syntaxError("(function(){ console.log('do something!'); }());", "motivation.js"); + const res2 = syntaxError("(function(){ console.log('do something!'); }());", "motivation.js", { ecmaVersion: 2015, sourceType: "script" }); + if (res2 != null) { + if (res2.line === 1) { + const msg = `${res2.name} (${res2.line}:${Math.abs(res2.column)}): ${res2.message}\n${res2.stack}`; + } + } + return res1 || res2; +} diff --git a/types/syntax-error/tsconfig.json b/types/syntax-error/tsconfig.json new file mode 100644 index 0000000000..4f9ec03802 --- /dev/null +++ b/types/syntax-error/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", + "syntax-error-tests.ts" + ] +} \ No newline at end of file diff --git a/types/syntax-error/tslint.json b/types/syntax-error/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/syntax-error/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/tabtab/index.d.ts b/types/tabtab/index.d.ts index eba5a58c3a..05291613b2 100644 --- a/types/tabtab/index.d.ts +++ b/types/tabtab/index.d.ts @@ -1,89 +1,143 @@ -// Type definitions for tabtab 0.0.4 +// Type definitions for tabtab 3.0.2 // Project: https://github.com/mklabs/node-tabtab // Definitions by: Vojtěch Habarta +// Kamontat Chantrachirathumrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - +// TypeScript Version: 2.0 /** - * Main completion method, has support for installation and actual completion. - * @param name Name of the command to complete. - * @param cb Get called when a tab-completion command happens. + * Install option + * + * @param name is a name of the cli command + * @param completer Somethings, you want to complete another program that's where the `completer` option might come handy. */ -export declare function complete(name: string, cb: CallBack): void; +export type InstallOption = { + name: string; + completer: string; +}; /** - * Main completion method, has support for installation and actual completion. - * @param name Name of the command to complete. - * @param completer Name of the command to call on completion. - * @param cb Get called when a tab-completion command happens. + * Uninstall option + * + * @param name is a name of the cli command */ -export declare function complete(name: string, completer: string, cb: CallBack): void; +export type UninstallOption = { + name: string; +}; /** - * Simple helper function to know if the script is run in the context of a completion command. + * This type represent object (Json object) */ -export declare function isComplete(): boolean; +export type Json = { + [key: string]: string; +}; /** - * Helper to return the list of short and long options, parsed from the usual --help output of a command (cake/rake -H, vagrant, commander -h, optimist.help(), ...). + * Tabtab environment data that return from {@link parseEnv} method + * + * @param complete A Boolean indicating whether we act in "plumbing mode" or not + * @param words The Number of words in the completed line + * @param point A Number indicating cursor position + * @param line The String input line + * @param partial The String part of line preceding cursor position + * @param last The last String word of the line + * @param lastPartial The last word String of partial + * @param prev The String word preceding last */ -export declare function parseOut(str: string): { shorts: string[]; longs: string[] }; - -/** - * Same purpose as parseOut, but for parsing tasks from an help command (cake/rake -T, vagrant, etc.). - */ -export declare function parseTasks(str: string, prefix: string, reg?: RegExp | string): string[]; - -/** - * Helper to return completion output and log to standard output. - * @param values Array of values to complete against. - * @param data The data object returned by the complete callback, used mainly to filter results accordingly upon the text that is supplied by the user. - * @param prefix A prefix to add to the completion results, useful for options to add dashes (eg. - or --). - */ -export declare function log(values: string[], data: Data, prefix?: string): void; - -interface CallBack { - (error?: Error, data?: Data, text?: string): any; -} - -/** - * Holds interesting values to drive the output of the completion. - */ -interface Data { - +export type TabtabEnv = { /** - * full command being completed + * A Boolean indicating whether we act in "plumbing mode" or not */ - line: string; + complete: boolean; /** - * number of words + * The Number of words in the completed line */ words: number; /** - * cursor position + * A Number indicating cursor position */ point: number; /** - * tabing in the middle of a word: foo bar baz bar foobarrrrrrr + * The String input line + */ + line: string; + + /** + * The String part of line preceding cursor position */ partial: string; /** - * last word of the line + * The last String word of the line */ last: string; /** - * last partial of the line + * The last word String of partial */ lastPartial: string; - /** - * the previous word + * The String word preceding last */ prev: string; -} +}; + +/** + * this is a item to show when completion enable, + * + * @param name usually is a subcommand name or option name + * @param description this is a optional description of the completion + */ +export type CompleteItem = { + name: string; + description?: string; +}; + +export type CompleteItemOrString = string | CompleteItem; + +/** + * Install and enable completion on user system. + * + * @param option install option + * + */ +export function install(option: InstallOption): Promise; + +/** + * Uninstall and remove all completion on user system + * + * @param option uninstall option + */ +export function uninstall(option: UninstallOption): Promise; + +/** + * Public: Main utility to extract information from command line arguments and + * Environment variables, namely COMP args in "plumbing" mode. + * + * @param env environment (usually will be process.env) + * @returns env is a object of completion environment + * + * @example + * const env = tabtab.parseEnv(process.env); + */ +export function parseEnv(env: Json): TabtabEnv; + +/** + * Helper to normalize String and Objects when logging out. + */ +export function completionItem(item: CompleteItemOrString): CompleteItem; + +/** + * Main logging utility to pass completion items. + * This is simply an helper to log to stdout with each item separated by a new + * line. + * + * Bash needs in addition to filter out the args for the completion to work + * (zsh, fish don't need this). + * + * @param args Strings or Objects with name and description property. + */ +export function log(args: string[] | CompleteItem[] | CompleteItemOrString[]): void; diff --git a/types/tabtab/tabtab-tests.ts b/types/tabtab/tabtab-tests.ts index e0187662ff..7f8e5b4b9c 100644 --- a/types/tabtab/tabtab-tests.ts +++ b/types/tabtab/tabtab-tests.ts @@ -1,30 +1,83 @@ - /// -import tabtab = require('tabtab'); -import child_process = require('child_process'); -import string_decoder = require('string_decoder'); +import { install, log, TabtabEnv, uninstall, parseEnv } from "tabtab"; -if (process.argv.slice(2)[0] === 'completion') { - tabtab.complete('pkgname', function(err, data) { - if (err || !data) return; - if (/^--\w?/.test(data.last)) return tabtab.log(['help', 'version'], data, '--'); - if (/^-\w?/.test(data.last)) return tabtab.log(['n', 'o', 'd', 'e'], data, '-'); - tabtab.log(['list', 'of', 'commands'], data); +const opts = require("minimist")(process.argv.slice(2), { + string: ["foo", "bar"], + boolean: ["help", "version", "loglevel"] +}); - child_process.exec('rake -H', {encoding: null}, function(err, stdout, stderr) { - if (err) return; - var decoder = new string_decoder.StringDecoder('utf8'); - var parsed = tabtab.parseOut(decoder.write(stdout)); - if (/^--\w?/.test(data.last)) return tabtab.log(parsed.longs, data, '--'); - if (/^-\w?/.test(data.last)) return tabtab.log(parsed.shorts, data, '-'); +const args = opts._; + +const completion = (env: TabtabEnv) => { + if (!env.complete) return; + + // Write your completions there + + if (env.prev === "foo") { + return log(["is", "this", "the", "real", "life"]); + } + + if (env.prev === "bar") { + return log(["is", "this", "just", "fantasy"]); + } + + if (env.prev === "--loglevel") { + return log(["error", "warn", "info", "notice", "verbose"]); + } + + return log([ + "--help", + "--version", + "--loglevel", + "foo", + "bar", + "install-completion", + "completion", + "someCommand:someCommand is some kind of command with a description", + { + name: "someOtherCommand:hey", + description: 'You must add a description for items with ":" in them' + }, + "anotherOne" + ]); +}; + +const run = (): Promise => { + const cmd = args[0]; + + // Write your CLI there + + // Here we install for the program `tabtab-test` (this file), with + // completer being the same program. Sometimes, you want to complete + // another program that's where the `completer` option might come handy. + if (cmd === "install-completion") { + return install({ + name: "tabtab-test", + completer: "tabtab-test" }); + } - child_process.exec('cake', {encoding: null}, function(err, stdout, stderr) { - if (err) return; - var decoder = new string_decoder.StringDecoder('utf8'); - var tasks = tabtab.parseTasks(decoder.write(stdout), 'cake'); - tabtab.log(tasks, data); + if (cmd === "uninstall-completion") { + // Here we uninstall for the program `tabtab-test` (this file). + return uninstall({ + name: "tabtab-test" }); - }); -} + } + + // The completion command is added automatically by tabtab when the program + // is completed. + if (cmd === "completion") { + return new Promise(res => { + const env = parseEnv(process.env); + completion(env); + res(); + }); + } + + return new Promise((_, rej) => rej()); +}; + +run().catch(e => { + console.error(e); +}); diff --git a/types/temp-dir/index.d.ts b/types/temp-dir/index.d.ts new file mode 100644 index 0000000000..17d54fc71c --- /dev/null +++ b/types/temp-dir/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for temp-dir 1.0 +// Project: https://github.com/sindresorhus/temp-dir#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = tempDir; + +declare const tempDir: string; diff --git a/types/temp-dir/temp-dir-tests.ts b/types/temp-dir/temp-dir-tests.ts new file mode 100644 index 0000000000..ac62106e9c --- /dev/null +++ b/types/temp-dir/temp-dir-tests.ts @@ -0,0 +1,4 @@ +import tempDir = require('temp-dir'); + +// $ExpectType string +tempDir; diff --git a/types/temp-dir/tsconfig.json b/types/temp-dir/tsconfig.json new file mode 100644 index 0000000000..850b81d95a --- /dev/null +++ b/types/temp-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", + "temp-dir-tests.ts" + ] +} diff --git a/types/temp-dir/tslint.json b/types/temp-dir/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/temp-dir/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/term-size/index.d.ts b/types/term-size/index.d.ts new file mode 100644 index 0000000000..bf1eb9a2c5 --- /dev/null +++ b/types/term-size/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for term-size 1.2 +// Project: https://github.com/sindresorhus/term-size#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = termSize; + +declare function termSize(): termSize.TermSize; + +declare namespace termSize { + interface TermSize { + columns: number; + rows: number; + } +} diff --git a/types/term-size/term-size-tests.ts b/types/term-size/term-size-tests.ts new file mode 100644 index 0000000000..ed67a7e7fe --- /dev/null +++ b/types/term-size/term-size-tests.ts @@ -0,0 +1,7 @@ +import termSize = require('term-size'); + +const size: termSize.TermSize = termSize(); +// $ExpectType number +size.columns; +// $ExpectType number +size.rows; diff --git a/types/term-size/tsconfig.json b/types/term-size/tsconfig.json new file mode 100644 index 0000000000..7e473f47a9 --- /dev/null +++ b/types/term-size/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", + "term-size-tests.ts" + ] +} diff --git a/types/term-size/tslint.json b/types/term-size/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/term-size/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/terminal-image/index.d.ts b/types/terminal-image/index.d.ts new file mode 100644 index 0000000000..7b52d962d2 --- /dev/null +++ b/types/terminal-image/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for terminal-image 0.1 +// Project: https://github.com/sindresorhus/terminal-image#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export function buffer(imageBuffer: Buffer): Promise; +export function file(filePath: string): Promise; diff --git a/types/terminal-image/terminal-image-tests.ts b/types/terminal-image/terminal-image-tests.ts new file mode 100644 index 0000000000..89779ca377 --- /dev/null +++ b/types/terminal-image/terminal-image-tests.ts @@ -0,0 +1,6 @@ +import terminalImage = require('terminal-image'); + +// $ExpectType Promise +terminalImage.file('unicorn.jpg'); +// $ExpectType Promise +terminalImage.buffer((null as any) as Buffer); diff --git a/types/terminal-image/tsconfig.json b/types/terminal-image/tsconfig.json new file mode 100644 index 0000000000..a5a5b662bd --- /dev/null +++ b/types/terminal-image/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", + "terminal-image-tests.ts" + ] +} diff --git a/types/terminal-image/tslint.json b/types/terminal-image/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/terminal-image/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/terminal-link/index.d.ts b/types/terminal-link/index.d.ts new file mode 100644 index 0000000000..b7772ab581 --- /dev/null +++ b/types/terminal-link/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for terminal-link 1.1 +// Project: https://github.com/sindresorhus/terminal-link#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = terminalLink; + +declare function terminalLink(text: string, url: string, options?: terminalLink.Options): string; + +declare namespace terminalLink { + function isSupported(): boolean; + + interface Options { + fallback?: (text: string, url: string) => string; + } +} diff --git a/types/terminal-link/terminal-link-tests.ts b/types/terminal-link/terminal-link-tests.ts new file mode 100644 index 0000000000..25bf536d0e --- /dev/null +++ b/types/terminal-link/terminal-link-tests.ts @@ -0,0 +1,16 @@ +import terminalLink = require('terminal-link'); + +// $ExpectType string +terminalLink('My Website', 'https://sindresorhus.com'); +terminalLink('My Website', 'https://sindresorhus.com', { + fallback(text, url) { + // $ExpectType string + text; + // $ExpectType string + url; + return text; + }, +}); + +// $ExpectType boolean +terminalLink.isSupported(); diff --git a/types/terminal-link/tsconfig.json b/types/terminal-link/tsconfig.json new file mode 100644 index 0000000000..fd40995e6f --- /dev/null +++ b/types/terminal-link/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", + "terminal-link-tests.ts" + ] +} diff --git a/types/terminal-link/tslint.json b/types/terminal-link/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/terminal-link/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/theming/index.d.ts b/types/theming/index.d.ts index d2c0d1ee40..e2525b3ce6 100644 --- a/types/theming/index.d.ts +++ b/types/theming/index.d.ts @@ -40,7 +40,7 @@ export interface ThemeListener { callback: (theme: Theme) => void ): SubscriptionId; unsubscribe(context: ContextWithTheme, id: SubscriptionId): void; - contextTypes: React.ValidationMap>; + contextTypes: React.ValidationMap; } /** * ThemeListener for the default channel diff --git a/types/three-tds-loader/index.d.ts b/types/three-tds-loader/index.d.ts new file mode 100644 index 0000000000..33e679a377 --- /dev/null +++ b/types/three-tds-loader/index.d.ts @@ -0,0 +1,202 @@ +// Type definitions for three-tds-loader 1.1 +// Project: https://github.com/codetheorist/three-tds-loader +// Definitions by: Konstantin Lukaschenko +// Stefan Schönsee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as THREE from 'three'; + +export = TDSLoader; + +declare class TDSLoader { + constructor(three: typeof THREE); + + /** + * Load 3ds file from url. + * + * @param url URL for the file. + * @param onLoad onLoad callback, receives group object3D as argument. + * @param onProgress onProgress callback. + * @param onError onError callback. + */ + load: (url: string, onLoad: (object3D: THREE.Object3D) => void, onProgress?: (progress: ProgressEvent) => void, onError?: (event: ErrorEvent) => void) => void; + + /** + * Parse arraybuffer data and load 3ds file. + * + * @param arraybuffer Arraybuffer data to be loaded. + * @param path Path for external resources. + * @return Group loaded from 3ds file. + */ + parse: (arraybuffer: ArrayBuffer, path: string) => THREE.Object3D; + + /** + * Decode file content to read 3ds data. + * + * @param arraybuffer Arraybuffer data to be loaded. + */ + readFile: (arraybuffer: ArrayBuffer, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMeshData: (data: DataView, path: string) => void; + + /** + * Read named object chunk. + * + * @param data Dataview in use. + */ + readNamedobject: (data: DataView) => void; + + /** + * Read material data chunk and add it to the material list. + * + * @param data Dataview in use. + */ + readMaterialEntry: (data: DataView, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMesh: (data: DataView) => void; + + /** + * Read face array data chunk. + * + * @param data Dataview in use. + * @param mesh Mesh to be filled with the data read. + */ + readFaceArray: (data: DataView, mesh: THREE.Mesh) => void; + + /** + * Read texture map data chunk. + * + * @param data Dataview in use. + * @return Texture read from this data chunk. + */ + readMap: (data: DataView, path: string) => THREE.Texture; + + /** + * Read material group data chunk. + * + * @param data Dataview in use. + * @return object with name and index of the object. + */ + readMaterialGroup: (data: DataView) => object; + + /** + * Read a color value. + * + * @param data Dataview. + * @return Color value read.. + */ + readColor: (data: DataView) => THREE.Color; + + /** + * Read next chunk of data. + * + * @param data Dataview. + * @return Chunk of data read. + */ + readChunk: (data: DataView) => object; + + /** + * Set position to the end of the current chunk of data. + * + * @param chunk Data chunk. + */ + endChunk: (chunk: object) => void; + + /** + * Move to the next data chunk. + * + * @param data Dataview. + * @param chunk Data chunk. + */ + nextChunk: (data: DataView, chunk: object) => number; + + /** + * Reset dataview position. + */ + resetPosition: () => void; + + /** + * Read byte value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readByte: (data: DataView) => number; + + /** + * Read 32 bit float value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readFloat: (data: DataView) => number; + + /** + * Read 32 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readInt: (data: DataView) => number; + + /** + * Read 16 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readShort: (data: DataView) => number; + + /** + * Read 64 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readDWord: (data: DataView) => number; + + /** + * Read 32 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readWord: (data: DataView) => number; + + /** + * Read string value. + * + * @param data Dataview to read data from. + * @param maxLength Max size of the string to be read. + * @return Data read from the dataview. + */ + readString: (data: DataView, maxLength: number) => string; + + /** + * Set resource path used to determine the file path to attached resources. + * + * @param path Path to resources. + * @return Self for chaining. + */ + setPath: (path: string) => TDSLoader; + + /** + * Print debug message to the console. + * + * Is controlled by a flag to show or hide debug messages. + * + * @param message Debug message to print to the console. + */ + debugMessage: (message: string) => void; +} diff --git a/types/three-tds-loader/three-tds-loader-tests.ts b/types/three-tds-loader/three-tds-loader-tests.ts new file mode 100644 index 0000000000..a4e9d61797 --- /dev/null +++ b/types/three-tds-loader/three-tds-loader-tests.ts @@ -0,0 +1,15 @@ +import * as THREE from 'three'; +import TDSLoader = require('three-tds-loader'); + +const loader = new TDSLoader(THREE); + +const onSuccess = (object3D: THREE.Object3D) => {}; +const onProgress = (progress: ProgressEvent) => {}; +const onError = (event: ErrorEvent) => {}; + +loader.load( + 'folder/file.3ds', + onSuccess, + onProgress, + onError +); diff --git a/types/three-tds-loader/tsconfig.json b/types/three-tds-loader/tsconfig.json new file mode 100644 index 0000000000..cab037513c --- /dev/null +++ b/types/three-tds-loader/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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", + "three-tds-loader-tests.ts" + ] +} diff --git a/types/three-tds-loader/tslint.json b/types/three-tds-loader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/three-tds-loader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/three/index.d.ts b/types/three/index.d.ts index b8c5dfa961..08b64250c8 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -23,6 +23,8 @@ // Dilip Ramirez // Julian Strecker // Zhang Hao +// Konstantin Lukaschenko +// Daniel Yim // Definitions: https://github.com//DefinitelyTyped // TypeScript Version: 2.8 @@ -34,6 +36,7 @@ export * from "./three-copyshader"; export * from "./three-css3drenderer"; export * from "./three-ctmloader"; export * from "./three-ddsloader"; +export * from "./three-tdsloader"; export * from "./three-dragcontrols"; export * from "./three-editorcontrols"; export * from "./three-effectcomposer"; @@ -43,6 +46,7 @@ export * from "./three-FirstPersonControls"; export * from "./three-gltfexporter"; export * from "./three-gltfloader"; export * from "./three-lensflare"; +export * from "./three-mapcontrols"; export * from "./three-maskpass"; export * from "./three-mtlloader"; export * from "./three-objloader"; diff --git a/types/three/test/css3d/css3d_periodictable.ts b/types/three/test/css3d/css3d_periodictable.ts index 5c8cb68614..40a29a1ea5 100644 --- a/types/three/test/css3d/css3d_periodictable.ts +++ b/types/three/test/css3d/css3d_periodictable.ts @@ -181,8 +181,8 @@ // var object = new THREE.Object3D(); - object.position.x = (table[i + 3] * 140) - 1330; - object.position.y = - (table[i + 4] * 180) + 990; + object.position.x = ((table[i + 3] as number) * 140) - 1330; + object.position.y = - ((table[i + 4] as number) * 180) + 990; targets.table.push(object); @@ -354,4 +354,4 @@ renderer.render(scene, camera); } -} \ No newline at end of file +} diff --git a/types/three/test/examples/loaders/tdsloader.ts b/types/three/test/examples/loaders/tdsloader.ts new file mode 100644 index 0000000000..72666d4003 --- /dev/null +++ b/types/three/test/examples/loaders/tdsloader.ts @@ -0,0 +1,14 @@ +import * as THREE from '../../../index' + +const onSuccess = (object3D: THREE.Object3D) => {}; +const onProgress = (progress: ProgressEvent) => {}; +const onError = (event: ErrorEvent) => {}; + +() => { + new THREE.TDSLoader(THREE).load( + 'folder/file.3ds', + onSuccess, + onProgress, + onError + ); +} \ No newline at end of file diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 955eb45faf..003c6a70f6 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -3562,7 +3562,7 @@ export class Euler { fromArray(xyzo: any[]): Euler; toArray(array?: number[], offset?: number): number[]; toVector3(optionalResult?: Vector3): Vector3; - onChange(callback: Function): void; + onChange(callback: Function): this; static RotationOrders: string[]; static DefaultOrder: string; diff --git a/types/three/three-mapcontrols.d.ts b/types/three/three-mapcontrols.d.ts new file mode 100644 index 0000000000..66ff8a0982 --- /dev/null +++ b/types/three/three-mapcontrols.d.ts @@ -0,0 +1,71 @@ +import { + Camera, + EventDispatcher, + MOUSE, + Object3D, + Vector3 +} from "./three-core"; + +export class MapControls extends EventDispatcher { + constructor(object: Camera, domElement?: HTMLElement); + + object: Camera; + domElement: HTMLElement | HTMLDocument; + + // API + enabled: boolean; + target: Vector3; + + enableZoom: boolean; + zoomSpeed: number; + minDistance: number; + maxDistance: number; + enableRotate: boolean; + rotateSpeed: number; + enablePan: boolean; + keyPanSpeed: number; + maxZoom: number; + minZoom: number; + panSpeed: number; + autoRotate: boolean; + autoRotateSpeed: number; + minPolarAngle: number; + maxPolarAngle: number; + minAzimuthAngle: number; + maxAzimuthAngle: number; + enableKeys: boolean; + screenSpacePanning: boolean; + keys: { LEFT: number; UP: number; RIGHT: number; BOTTOM: number }; + mouseButtons: { LEFT: MOUSE; MIDDLE: MOUSE; RIGHT: MOUSE }; + enableDamping: boolean; + dampingFactor: number; + target0: Vector3; + position0: Vector3; + zoom0: number; + + rotateLeft(angle?: number): void; + + rotateUp(angle?: number): void; + + panLeft(distance?: number): void; + + panUp(distance?: number): void; + + pan(deltaX: number, deltaY: number): void; + + dollyIn(dollyScale: number): void; + + dollyOut(dollyScale: number): void; + + saveState(): void; + + update(): boolean; + + reset(): void; + + dispose(): void; + + getPolarAngle(): number; + + getAzimuthalAngle(): number; +} diff --git a/types/three/three-tdsloader.d.ts b/types/three/three-tdsloader.d.ts new file mode 100644 index 0000000000..c1911a7003 --- /dev/null +++ b/types/three/three-tdsloader.d.ts @@ -0,0 +1,195 @@ +// https://github.com/codetheorist/three-tds-loader/blob/master/src/index.js + +import * as THREE from "./index"; + +export class TDSLoader { + constructor(three: typeof THREE); + + /** + * Load 3ds file from url. + * + * @param url URL for the file. + * @param onLoad onLoad callback, receives group object3D as argument. + * @param onProgress onProgress callback. + * @param onError onError callback. + */ + load: (url: string, onLoad: (object3D: THREE.Object3D) => void, onProgress?: (progress: ProgressEvent) => void, onError?: (event: ErrorEvent) => void) => void; + + /** + * Parse arraybuffer data and load 3ds file. + * + * @param arraybuffer Arraybuffer data to be loaded. + * @param path Path for external resources. + * @return Group loaded from 3ds file. + */ + parse: (arraybuffer: ArrayBuffer, path: string) => THREE.Object3D; + + /** + * Decode file content to read 3ds data. + * + * @param arraybuffer Arraybuffer data to be loaded. + */ + readFile: (arraybuffer: ArrayBuffer, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMeshData: (data: DataView, path: string) => void; + + /** + * Read named object chunk. + * + * @param data Dataview in use. + */ + readNamedobject: (data: DataView) => void; + + /** + * Read material data chunk and add it to the material list. + * + * @param data Dataview in use. + */ + readMaterialEntry: (data: DataView, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMesh: (data: DataView) => void; + + /** + * Read face array data chunk. + * + * @param data Dataview in use. + * @param mesh Mesh to be filled with the data read. + */ + readFaceArray: (data: DataView, mesh: THREE.Mesh) => void; + + /** + * Read texture map data chunk. + * + * @param data Dataview in use. + * @return Texture read from this data chunk. + */ + readMap: (data: DataView, path: string) => THREE.Texture; + + /** + * Read material group data chunk. + * + * @param data Dataview in use. + * @return object with name and index of the object. + */ + readMaterialGroup: (data: DataView) => object; + + /** + * Read a color value. + * + * @param data Dataview. + * @return Color value read.. + */ + readColor: (data: DataView) => THREE.Color; + + /** + * Read next chunk of data. + * + * @param data Dataview. + * @return Chunk of data read. + */ + readChunk: (data: DataView) => object; + + /** + * Set position to the end of the current chunk of data. + * + * @param chunk Data chunk. + */ + endChunk: (chunk: object) => void; + + /** + * Move to the next data chunk. + * + * @param data Dataview. + * @param chunk Data chunk. + */ + nextChunk: (data: DataView, chunk: object) => number; + + /** + * Reset dataview position. + */ + resetPosition: () => void; + + /** + * Read byte value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readByte: (data: DataView) => number; + + /** + * Read 32 bit float value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readFloat: (data: DataView) => number; + + /** + * Read 32 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readInt: (data: DataView) => number; + + /** + * Read 16 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readShort: (data: DataView) => number; + + /** + * Read 64 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readDWord: (data: DataView) => number; + + /** + * Read 32 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readWord: (data: DataView) => number; + + /** + * Read string value. + * + * @param data Dataview to read data from. + * @param maxLength Max size of the string to be read. + * @return Data read from the dataview. + */ + readString: (data: DataView, maxLength: number) => string; + + /** + * Set resource path used to determine the file path to attached resources. + * + * @param path Path to resources. + * @return Self for chaining. + */ + setPath: (path: string) => TDSLoader; + + /** + * Print debug message to the console. + * + * Is controlled by a flag to show or hide debug messages. + * + * @param message Debug message to print to the console. + */ + debugMessage: (message: string) => void; +} \ No newline at end of file diff --git a/types/three/tsconfig.json b/types/three/tsconfig.json index a7a79e68f5..814dd8f824 100644 --- a/types/three/tsconfig.json +++ b/types/three/tsconfig.json @@ -57,6 +57,7 @@ "test/examples/ctm/ctmloader.ts", "test/examples/octree.ts", "test/examples/loaders/webgl_loader_obj_mtl.ts", + "test/examples/loaders/tdsloader.ts", "test/examples/exporters/gltf-exporter.ts", "test/webvr/webvr.ts" ] diff --git a/types/tildify/index.d.ts b/types/tildify/index.d.ts new file mode 100644 index 0000000000..a0dd100bf9 --- /dev/null +++ b/types/tildify/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for tildify 1.2 +// Project: https://github.com/sindresorhus/tildify#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = tildify; + +declare function tildify(str: string): string; diff --git a/types/tildify/tildify-tests.ts b/types/tildify/tildify-tests.ts new file mode 100644 index 0000000000..109f5f6c6e --- /dev/null +++ b/types/tildify/tildify-tests.ts @@ -0,0 +1,4 @@ +import tildify = require('tildify'); + +// $ExpectType string +tildify('/Users/sindresorhus/dev'); diff --git a/types/tildify/tsconfig.json b/types/tildify/tsconfig.json new file mode 100644 index 0000000000..4375409ba0 --- /dev/null +++ b/types/tildify/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", + "tildify-tests.ts" + ] +} diff --git a/types/tildify/tslint.json b/types/tildify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/tildify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/timing-safe-equal/index.d.ts b/types/timing-safe-equal/index.d.ts new file mode 100644 index 0000000000..e1bf8f16d8 --- /dev/null +++ b/types/timing-safe-equal/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for timing-safe-equal 1.0 +// Project: https://github.com/crypto-browserify/timing-safe-equal +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = timingSafeEqual; + +declare function timingSafeEqual(a: Buffer, b: Buffer): boolean; diff --git a/types/timing-safe-equal/timing-safe-equal-tests.ts b/types/timing-safe-equal/timing-safe-equal-tests.ts new file mode 100644 index 0000000000..cc8069de3b --- /dev/null +++ b/types/timing-safe-equal/timing-safe-equal-tests.ts @@ -0,0 +1,5 @@ +import timingSafeEqual = require('timing-safe-equal'); + +const buffer: Buffer = new Buffer([1, 2, 3, 4, 5]); +// $ExpectType boolean +timingSafeEqual(buffer, buffer); diff --git a/types/timing-safe-equal/tsconfig.json b/types/timing-safe-equal/tsconfig.json new file mode 100644 index 0000000000..f12ec7b09e --- /dev/null +++ b/types/timing-safe-equal/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", + "timing-safe-equal-tests.ts" + ] +} diff --git a/types/timing-safe-equal/tslint.json b/types/timing-safe-equal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/timing-safe-equal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/toastr/tslint.json b/types/toastr/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/toastr/tslint.json +++ b/types/toastr/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/toobusy-js/index.d.ts b/types/toobusy-js/index.d.ts index 2d7f2688a7..2e6aca6c4b 100644 --- a/types/toobusy-js/index.d.ts +++ b/types/toobusy-js/index.d.ts @@ -1,19 +1,66 @@ // Type definitions for toobusy-js 0.5 // Project: https://github.com/STRML/node-toobusy // Definitions by: Arne Schubert +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = toobusy_js; +/** + * Main export function. + * @return True if node process is too busy. + */ declare function toobusy_js(): boolean; declare namespace toobusy_js { - function interval(newInterval: number): number; + /** + * Sets or gets the current check interval. + * If you want more sensitive checking, set a faster (lower) interval. A lower maxLag can also create a more + * sensitive check. + * @param [newInterval] New interval to set. If not provided, will return the existing interval. + * @return New or existing interval. + */ + function interval(newInterval?: number): number; + /** + * Returns last lag reading from last check interval. + * @return Lag in ms. + */ function lag(): number; - function maxLag(newLag: number): number; - function smoothingFactor(newFactor: number): number; + /** + * Set or get the current max latency threshold. Default is 70ms. + * + * Note that if event loop lag goes over this threshold, the process is not always 'too busy' - the farther + * it goes over the threshold, the more likely the process will be considered too busy. + * + * The percentage is equal to the percent over the max lag threshold. So 1.25x over the maxLag will indicate + * too busy 25% of the time. 2x over the maxLag threshold will indicate too busy 100% of the time. + * @param [newLag] New maxLag (highwater) threshold. + * @return New or existing maxLag (highwater) threshold. + */ + function maxLag(newLag?: number): number; + /** + * Set or get the smoothing factor. Default is 0.3333.... + * + * The smoothing factor per the standard exponential smoothing formula "αtn + (1-α)tn-1" + * See: https://en.wikipedia.org/wiki/Exponential_smoothing + * + * @param [newFactor] New smoothing factor. + * @return New or existing smoothing factor. + */ + function smoothingFactor(newFactor?: number): number; + /** + * Shuts down toobusy. + * + * Not necessary to call this manually, only do this if you know what you're doing. `unref()` is called + * on toobusy's check interval, so it will never keep the server open. + */ function shutdown(): void; + /** + * Registers an event listener for lag events, + * optionally specify a minimum value threshold for events being emitted + * @param fn Function of form onLag(value: number) => void + * @param [threshold=maxLag] Optional minimum lag value for events to be emitted + */ function onLag(fn: (lag: number) => void, threshold?: number): void; - function started(): boolean; } diff --git a/types/toobusy-js/toobusy-js-tests.ts b/types/toobusy-js/toobusy-js-tests.ts index 121b84ddb4..2678dcc777 100644 --- a/types/toobusy-js/toobusy-js-tests.ts +++ b/types/toobusy-js/toobusy-js-tests.ts @@ -1,4 +1,4 @@ -import toobusy = require("toobusy-js"); +import toobusy = require('toobusy-js'); let numberValue = 1; let booleanValue = true; @@ -7,11 +7,19 @@ booleanValue = toobusy(); booleanValue = toobusy.started(); numberValue = toobusy.interval(numberValue); +numberValue = toobusy.interval(); numberValue = toobusy.lag(); numberValue = toobusy.maxLag(numberValue); +numberValue = toobusy.maxLag(); numberValue = toobusy.smoothingFactor(numberValue); - -toobusy.onLag((duration: number) => {}); -toobusy.onLag((duration: number) => {}, numberValue); - +numberValue = toobusy.smoothingFactor(); toobusy.shutdown(); + +toobusy.onLag(duration => { + // $ExpectType number + duration; +}); +toobusy.onLag(duration => { + // $ExpectType number + duration; +}, numberValue); diff --git a/types/ua-string/index.d.ts b/types/ua-string/index.d.ts new file mode 100644 index 0000000000..c9928a8709 --- /dev/null +++ b/types/ua-string/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for ua-string 2.0 +// Project: https://github.com/sindresorhus/ua-string#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = uaString; + +declare const uaString: string; diff --git a/types/ua-string/tsconfig.json b/types/ua-string/tsconfig.json new file mode 100644 index 0000000000..8186c1b708 --- /dev/null +++ b/types/ua-string/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", + "ua-string-tests.ts" + ] +} diff --git a/types/ua-string/tslint.json b/types/ua-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ua-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ua-string/ua-string-tests.ts b/types/ua-string/ua-string-tests.ts new file mode 100644 index 0000000000..3cdbf6b553 --- /dev/null +++ b/types/ua-string/ua-string-tests.ts @@ -0,0 +1,4 @@ +import uaString = require('ua-string'); + +// $ExpectType string +uaString; diff --git a/types/underscore.string/index.d.ts b/types/underscore.string/index.d.ts index 2d067679d5..eb0774b49a 100644 --- a/types/underscore.string/index.d.ts +++ b/types/underscore.string/index.d.ts @@ -207,7 +207,7 @@ declare module 'underscore' { * ('-moz-transform') => 'MozTransform' * @param str */ - camelize(str: string): string; + camelize(str: string, decapitalize?: boolean): string; /** * Converts a camelized or dasherized string into an underscored one. diff --git a/types/underscore.string/underscore.string-tests.ts b/types/underscore.string/underscore.string-tests.ts index 545f6362d6..5b827cd880 100644 --- a/types/underscore.string/underscore.string-tests.ts +++ b/types/underscore.string/underscore.string-tests.ts @@ -52,6 +52,7 @@ _.succ('A'); _.titleize('my name is epeli'); _.camelize('-moz-transform'); +_.camelize('-moz-transform', true); _.classify('some_class_name'); diff --git a/types/unique-random-array/index.d.ts b/types/unique-random-array/index.d.ts new file mode 100644 index 0000000000..7e4ddacb0f --- /dev/null +++ b/types/unique-random-array/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for unique-random-array 1.0 +// Project: https://github.com/sindresorhus/unique-random-array#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = uniqueRandomArray; + +declare function uniqueRandomArray(input: T[]): () => T; diff --git a/types/unique-random-array/tsconfig.json b/types/unique-random-array/tsconfig.json new file mode 100644 index 0000000000..40257f7e47 --- /dev/null +++ b/types/unique-random-array/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", + "unique-random-array-tests.ts" + ] +} diff --git a/types/unique-random-array/tslint.json b/types/unique-random-array/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/unique-random-array/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/unique-random-array/unique-random-array-tests.ts b/types/unique-random-array/unique-random-array-tests.ts new file mode 100644 index 0000000000..de4563532c --- /dev/null +++ b/types/unique-random-array/unique-random-array-tests.ts @@ -0,0 +1,6 @@ +import uniqueRandomArray = require('unique-random-array'); + +// $ExpectType () => number +uniqueRandomArray([1, 2, 3, 4]); +// $ExpectType () => string | number +uniqueRandomArray(["1", 2, 3, 4]); diff --git a/types/unique-string/index.d.ts b/types/unique-string/index.d.ts new file mode 100644 index 0000000000..cedb0dd5b9 --- /dev/null +++ b/types/unique-string/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for unique-string 1.0 +// Project: https://github.com/sindresorhus/unique-string#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = uniqueString; + +declare function uniqueString(): string; diff --git a/types/unique-string/tsconfig.json b/types/unique-string/tsconfig.json new file mode 100644 index 0000000000..03e2e6e75e --- /dev/null +++ b/types/unique-string/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", + "unique-string-tests.ts" + ] +} diff --git a/types/unique-string/tslint.json b/types/unique-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/unique-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/unique-string/unique-string-tests.ts b/types/unique-string/unique-string-tests.ts new file mode 100644 index 0000000000..c51176b20c --- /dev/null +++ b/types/unique-string/unique-string-tests.ts @@ -0,0 +1,4 @@ +import uniqueString = require('unique-string'); + +// $ExpectType string +uniqueString(); diff --git a/types/unist-util-is/index.d.ts b/types/unist-util-is/index.d.ts new file mode 100644 index 0000000000..82e6e1fdc8 --- /dev/null +++ b/types/unist-util-is/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for unist-util-is 2.1 +// Project: https://github.com/syntax-tree/unist-util-is#readme +// Definitions by: Junyoung Choi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +/// + +import * as Unist from 'unist'; + +declare namespace unistUtilIs { + /** + * @param node Node to test + * @param index Position of node in parent + * @param parent Parent of node + */ + type TestFunction = (node: unknown, index?: number, parent?: Unist.Parent) => boolean | void; + type Test = TestFunction | Partial | string | null; +} + +/** + * Unist utility to check if a node passes a test. + * + * @param test When not given, checks if `node` is a `Node`. + * When `string`, works like passing `function (node) {return node.type === test}`. + * When `array`, checks any one of the subtests pass. + * When `object`, checks that all keys in test are in node, and that they have (strictly) equal values + * @param node Node to check. `false` is returned + * @param index Position of `node` in `parent` + * @param parent Parent of `node` + * @param context Context object to invoke `test` with + * @returns Whether test passed and `node` is a `Node` (object with `type` set to non-empty `string`). + */ +declare function unistUtilIs(test: unistUtilIs.Test | unistUtilIs.Test[], node: unknown, index?: number, parent?: Unist.Parent, context?: any): boolean; + +export = unistUtilIs; diff --git a/types/unist-util-is/tsconfig.json b/types/unist-util-is/tsconfig.json new file mode 100644 index 0000000000..dbe499fef0 --- /dev/null +++ b/types/unist-util-is/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", + "unist-util-is-tests.ts" + ] +} diff --git a/types/unist-util-is/tslint.json b/types/unist-util-is/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/unist-util-is/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/unist-util-is/unist-util-is-tests.ts b/types/unist-util-is/unist-util-is-tests.ts new file mode 100644 index 0000000000..9f3eecc680 --- /dev/null +++ b/types/unist-util-is/unist-util-is-tests.ts @@ -0,0 +1,26 @@ +import is = require('unist-util-is'); + +const node = {type: 'strong'}; +const parent = {type: 'paragraph', children: [node]}; + +function test(node: unknown, n?: number) { + return n === 5; +} + +is(null, {children: []}); +is(null, node); +is('strong', node); +is('emphasis', node); + +is(node, node); +is({type: 'paragraph'}, parent); +is({type: 'strong'}, parent); + +is(test, node); +is(test, node, 4, parent); +is(test, node, 5, parent); + +function testFunc(node: unknown) {} +is(testFunc, node); + +const wrongTestFunc: is.TestFunction = (node: unknown, n: string) => {}; // $ExpectError diff --git a/types/unist/index.d.ts b/types/unist/index.d.ts index 7433ddcc13..2d7d37e17f 100644 --- a/types/unist/index.d.ts +++ b/types/unist/index.d.ts @@ -2,39 +2,97 @@ // Project: https://github.com/syntax-tree/unist // Definitions by: bizen241 // Jun Lu +// Hernan Rajchert +// Titus Wormer +// Junyoung Choi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 3.0 +/** + * Syntactic units in unist syntax trees are called nodes. + */ export interface Node { + /** + * The variant of a node. + */ type: string; + + /** + * Information from the ecosystem. + */ data?: Data; + + /** + * Location of a node in a source document. + * Must not be present if a node is generated. + */ position?: Position; + + [key: string]: unknown; } +/** + * Information associated by the ecosystem with the node. + * Space is guaranteed to never be specified by unist or specifications + * implementing unist. + */ export interface Data { - [key: string]: any; + [key: string]: unknown; } +/** + * Location of a node in a source file. + */ export interface Position { + /** + * Place of the first character of the parsed source region. + */ start: Point; + + /** + * Place of the first character after the parsed source region. + */ end: Point; - /** >= 1 */ + + /** + * Start column at each index (plus start line) in the source region, + * for elements that span multiple lines. + */ indent?: number[]; } +/** + * One place in a source file. + */ export interface Point { - /** >= 1 */ + /** + * Line in a source file (1-indexed integer). + */ line: number; - /** >= 1 */ + + /** + * Column in a source file (1-indexed integer). + */ column: number; - /** >= 0 */ + /** + * Character in a source file (0-indexed integer). + */ offset?: number; } +/** + * Nodes containing other nodes. + */ export interface Parent extends Node { + /** + * List representing the children of a node. + */ children: Node[]; } +/** + * Nodes containing a value. + */ export interface Literal extends Node { - value: any; + value: unknown; } diff --git a/types/unist/unist-tests.ts b/types/unist/unist-tests.ts index 3cb69bcc76..1c27db2a58 100644 --- a/types/unist/unist-tests.ts +++ b/types/unist/unist-tests.ts @@ -1,6 +1,6 @@ -import * as Unist from 'unist'; +import { Data, Point, Position, Node, Literal, Parent } from 'unist'; -const data: Unist.Data = { +const data: Data = { string: 'string', number: 1, object: { @@ -11,32 +11,32 @@ const data: Unist.Data = { null: null }; -const point: Unist.Point = { +const point: Point = { line: 1, column: 1, offset: 0 }; -const position: Unist.Position = { +const position: Position = { start: point, end: point, indent: [1] }; -const node: Unist.Node = { +const node: Node = { type: 'node', data, position }; -const text: Unist.Literal = { +const text: Literal = { type: 'text', data, position, value: 'value' }; -const parent: Unist.Parent = { +const parent: Parent = { type: 'parent', data, position, diff --git a/types/universal-router/index.d.ts b/types/universal-router/index.d.ts index eb698fc8bf..8dd2357f03 100644 --- a/types/universal-router/index.d.ts +++ b/types/universal-router/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for universal-router 6.0 +// Type definitions for universal-router 7.0 // Project: https://github.com/kriasoft/universal-router // Definitions by: Jack Moore // Tomek Łaziuk // Lodin +// acidghost // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -101,7 +102,7 @@ export interface Options { context?: C; baseUrl?: string; resolveRoute?: (context: ActionContext & C, params: Params) => any; - errorHandler?: (error: Error & { context: C, code: number }) => any; + errorHandler?: (error: Error & { status: number }, context: C) => any; } /** diff --git a/types/universal-router/universal-router-tests.ts b/types/universal-router/universal-router-tests.ts index 02c79fb062..40b5ac32c1 100644 --- a/types/universal-router/universal-router-tests.ts +++ b/types/universal-router/universal-router-tests.ts @@ -12,10 +12,10 @@ new UniversalRouter( user: 'name', }, baseUrl: '/base', - errorHandler: (error) => { + errorHandler: (error, context) => { console.error(error); - console.dir(error.context); - return error.code === 404 + console.dir(context); + return error.status === 404 ? '

    Page Not Found

    ' : '

    Oops! Something went wrong

    '; }, diff --git a/types/url-assembler/index.d.ts b/types/url-assembler/index.d.ts index 3f33bf921a..e27fbbe58d 100644 --- a/types/url-assembler/index.d.ts +++ b/types/url-assembler/index.d.ts @@ -7,8 +7,8 @@ interface UrlAssembler { template(template: string): UrlAssembler; prefix(subPath: string): UrlAssembler; segment(subPathTemplate: string): UrlAssembler; - param(key: string, value: string, strict: boolean): UrlAssembler; - param(params: {[s: string]: any}, strict: boolean): UrlAssembler; + param(key: string, value: string, strict?: boolean): UrlAssembler; + param(params: {[s: string]: any}, strict?: boolean): UrlAssembler; query(key: string, value: any): UrlAssembler; query(params: {[s: string]: any}): UrlAssembler; toString(): string; diff --git a/types/v8flags/index.d.ts b/types/v8flags/index.d.ts new file mode 100644 index 0000000000..409b51d60b --- /dev/null +++ b/types/v8flags/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for v8flags 3.1 +// Project: https://github.com/tkellen/node-v8flags +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = v8flags; + +declare function v8flags(cb: (err: any, flags: string[]) => void): void; + +declare namespace v8flags { + const configfile: string; + const configPath: string; +} diff --git a/types/v8flags/tsconfig.json b/types/v8flags/tsconfig.json new file mode 100644 index 0000000000..e0673d15d0 --- /dev/null +++ b/types/v8flags/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", + "v8flags-tests.ts" + ] +} diff --git a/types/v8flags/tslint.json b/types/v8flags/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/v8flags/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/v8flags/v8flags-tests.ts b/types/v8flags/v8flags-tests.ts new file mode 100644 index 0000000000..cc95ac734d --- /dev/null +++ b/types/v8flags/v8flags-tests.ts @@ -0,0 +1,6 @@ +import v8flags = require('v8flags'); + +v8flags((err, results) => { + // $ExpectType string[] + results; +}); diff --git a/types/validator/index.d.ts b/types/validator/index.d.ts index 1b51669d14..8ee398d850 100644 --- a/types/validator/index.d.ts +++ b/types/validator/index.d.ts @@ -83,7 +83,7 @@ declare namespace ValidatorJS { isEmail(str: string, options?: IsEmailOptions): boolean; // check if the string has a length of zero. - isEmpty(str: string): boolean; + isEmpty(str: string, options?: IsEmptyOptions): boolean; // check if the string is a fully qualified domain name (e.g. domain.com). isFQDN(str: string, options?: IsFQDNOptions): boolean; @@ -310,6 +310,11 @@ declare namespace ValidatorJS { require_tld?: boolean; } + // options for isEmpty + interface IsEmptyOptions { + ignore_whitespace?: boolean; + } + // options for isFQDN interface IsFQDNOptions { require_tld?: boolean; diff --git a/types/validator/validator-tests.ts b/types/validator/validator-tests.ts index 61c1c59e92..09a9a7ba17 100644 --- a/types/validator/validator-tests.ts +++ b/types/validator/validator-tests.ts @@ -425,7 +425,9 @@ let any: any; result = validator.isEmail('sample'); result = validator.isEmail('sample', isEmailOptions); + let isEmptyOptions: ValidatorJS.IsEmptyOptions = {}; result = validator.isEmpty('sample'); + result = validator.isEmpty('sample', isEmptyOptions); let isFQDNOptions: ValidatorJS.IsFQDNOptions = {}; result = validator.isFQDN('sample'); diff --git a/types/vfile-message/index.d.ts b/types/vfile-message/index.d.ts new file mode 100644 index 0000000000..5f4467e007 --- /dev/null +++ b/types/vfile-message/index.d.ts @@ -0,0 +1,75 @@ +// Type definitions for vfile-message 1.0 +// Project: https://github.com/vfile/vfile-message#readme +// Definitions by: Junyoung Choi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +/// + +import * as Unist from 'unist'; + +declare namespace vfileMessage { + /** + * Create a virtual message. + */ + interface VFileMessage extends Error { + /** + * Constructor of a message for `reason` at `position` from `origin`. + * When an error is passed in as `reason`, copies the `stack`. + * + * @param reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given. + * @param position Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional). + * @param origin Place in code the message originates from (`string`, optional). + */ + (reason: string | Error, position?: Unist.Node | Unist.Position | Unist.Point, origin?: string): VFileMessage; + /** + * Category of message. + */ + ruleId: string | null; + /** + * Reason for message. + */ + reason: string; + /** + * Starting line of error. + */ + line: number | null; + /** + * Starting column of error. + */ + column: number | null; + /** + * Full range information, when available. + * Has start and end properties, both set to an object with line and column, set to number?. + */ + location: Unist.Position; + /** + * Namespace of warning. + */ + source: string | null; + /** + * If true, marks associated file as no longer processable. + */ + fatal?: boolean | null; + /** + * You may add a file property with a path of a file (used throughout the VFile ecosystem). + */ + file?: string; + /** + * You may add a note property with a long form description of the message (supported by vfile-reporter). + */ + note?: string; + /** + * You may add a url property with a link to documentation for the message. + */ + url?: string; + /** + * It’s OK to store custom data directly on the VMessage, some of those are handled by utilities. + */ + [key: string]: unknown; + } +} + +declare const vfileMessage: vfileMessage.VFileMessage; + +export = vfileMessage; diff --git a/types/vfile-message/tsconfig.json b/types/vfile-message/tsconfig.json new file mode 100644 index 0000000000..9e35438c08 --- /dev/null +++ b/types/vfile-message/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", + "vfile-message-tests.ts" + ] +} diff --git a/types/vfile-message/tslint.json b/types/vfile-message/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/vfile-message/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/vfile-message/vfile-message-tests.ts b/types/vfile-message/vfile-message-tests.ts new file mode 100644 index 0000000000..ed9086631f --- /dev/null +++ b/types/vfile-message/vfile-message-tests.ts @@ -0,0 +1,32 @@ +import vfileMessage = require('vfile-message'); + +const message = vfileMessage('Error!'); +vfileMessage(new Error()); +vfileMessage('Error!', { + type: 'random node' +}); +vfileMessage('Error!', { + start: { + line: 1, + column: 1 + }, + end: { + line: 1, + column: 1 + } +}); +vfileMessage('Error!', { + line: 1, + column: 1 +}); +vfileMessage('Error!', undefined, 'test'); + +message.file = ''; +message.name = ''; +message.reason = ''; +message.message = ''; +message.stack = ''; +message.fatal = null; +message.fatal = true; +message.column = 1; +message.line = 1; diff --git a/types/vfile/index.d.ts b/types/vfile/index.d.ts index df729e0a49..aec7ca88f9 100644 --- a/types/vfile/index.d.ts +++ b/types/vfile/index.d.ts @@ -8,15 +8,11 @@ /// import * as Unist from 'unist'; +import * as vfileMessage from 'vfile-message'; declare namespace vfile { type VFileContents = string | Buffer; - interface NodeWithPosition extends Unist.Node { - position: Unist.Position; - [key: string]: any; - } - interface VFileOptions { contents?: VFileContents; path?: string; @@ -29,86 +25,18 @@ declare namespace vfile { [key: string]: any; } - /** - * File-related message describing something at certain position. - */ - interface VFileMessage { - /** - * File-path, when the message was triggered. - */ - file: string; - /** - * Category of message. - */ - ruleId: string | null; - /** - * Reason for message. - */ - reason: string; - /** - * Starting line of error. - */ - line: number | null; - /** - * Starting column of error. - */ - column: number | null; - /** - * Full range information, when available. - * Has start and end properties, both set to an object with line and column, set to number?. - */ - location: Unist.Position; - /** - * Namespace of warning. - */ - source: string | null; - /** - * If true, marks associated file as no longer processable. - */ - fatal?: boolean | null; - } - - /** - * Associates a message with the file for `reason` at `position`. - * When an error is passed in as `reason`, copies the stack. - * Each message has a `fatal` property which by default is set to `false` (ie. `warning`). - * @param reason Reason for message. Uses the stack and message of the error if given. - * @param position Place at which the message occurred in `vfile`. - * @param ruleId Category of message. - */ - type Message = (reason: string, position?: Unist.Point | Unist.Position | NodeWithPosition, ruleId?: string) => VFileMessage; - /** - * Associates a fatal message with the file, then immediately throws it. - * Note: fatal errors mean a file is no longer processable. - * Calls `message()` internally. - * @param reason Reason for message. Uses the stack and message of the error if given. - * @param position Place at which the message occurred in `vfile`. - * @param ruleId Category of message. - */ - type Fail = (reason: string, position?: Unist.Point | Unist.Position | NodeWithPosition, ruleId?: string) => never; - /** - * Associates an informational message with the file, where `fatal` is set to `null`. - * Calls `message()` internally. - * @param reason Reason for message. Uses the stack and message of the error if given. - * @param position Place at which the message occurred in `vfile`. - * @param ruleId Category of message. - */ - type Info = (reason: string, position?: Unist.Point | Unist.Position | NodeWithPosition, ruleId?: string) => void; - - /** - * Convert contents of `vfile` to string. - * @param encoding If `contents` is a buffer, `encoding` is used to stringify buffers (default: `'utf8'`). - */ - type ToString = (encoding?: BufferEncoding) => string; - interface VFile { /** + * Create a new virtual file. If `options` is `string` or `Buffer`, treats it as `{contents: options}`. + * If `options` is a `VFile`, returns it. All other options are set on the newly created `vfile`. + * + * Path related properties are set in the following order (least specific to most specific): `history`, `path`, `basename`, `stem`, `extname`, `dirname`. + * + * It’s not possible to set either `dirname` or `extname` without setting either `history`, `path`, `basename`, or `stem` as well. + * * @param options If `options` is `string` or `Buffer`, treats it as `{contents: options}`. If `options` is a `VFile`, returns it. All other options are set on the newly created `vfile`. */ (input?: VFileContents | F | VFileOptions): F; - message: Message; - fail: Fail; - info: Info; /** * List of file-paths the file moved between. */ @@ -121,7 +49,7 @@ declare namespace vfile { /** * List of messages associated with the file. */ - messages: VFileMessage[]; + messages: vfileMessage.VFileMessage[]; /** * Raw value. */ @@ -157,15 +85,40 @@ declare namespace vfile { * Defaults to `process.cwd()`. */ cwd: string; - toString: ToString; + /** + * Convert contents of `vfile` to string. + * @param encoding If `contents` is a buffer, `encoding` is used to stringify buffers (default: `'utf8'`). + */ + toString: (encoding?: BufferEncoding) => string; + /** + * Associates a message with the file for `reason` at `position`. + * When an error is passed in as `reason`, copies the stack. + * Each message has a `fatal` property which by default is set to `false` (ie. `warning`). + * @param reason Reason for message. Uses the stack and message of the error if given. + * @param position Place at which the message occurred in `vfile`. + * @param ruleId Category of message. + */ + message: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => vfileMessage.VFileMessage; + /** + * Associates a fatal message with the file, then immediately throws it. + * Note: fatal errors mean a file is no longer processable. + * Calls `message()` internally. + * @param reason Reason for message. Uses the stack and message of the error if given. + * @param position Place at which the message occurred in `vfile`. + * @param ruleId Category of message. + */ + fail: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => never; + /** + * Associates an informational message with the file, where `fatal` is set to `null`. + * Calls `message()` internally. + * @param reason Reason for message. Uses the stack and message of the error if given. + * @param position Place at which the message occurred in `vfile`. + * @param ruleId Category of message. + */ + info: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => vfileMessage.VFileMessage; } } -/** - * Create a new virtual file. - * Path related properties are set in the following order (least specific to most specific): `history`, `path`, `basename`, `stem`, `extname`, `dirname`. - * It’s not possible to set either `dirname` or `extname` without setting either `history`, `path`, `basename`, or `stem` as well. - */ declare const vfile: vfile.VFile; export = vfile; diff --git a/types/vfile/vfile-tests.ts b/types/vfile/vfile-tests.ts index 5c14c8502b..b89df6db23 100644 --- a/types/vfile/vfile-tests.ts +++ b/types/vfile/vfile-tests.ts @@ -1,5 +1,6 @@ import vfile = require('vfile'); import * as Unist from 'unist'; +import vfileMessage = require('vfile-message'); // Instantiation const file: vfile.VFile = vfile(); @@ -15,24 +16,7 @@ file.dirname = '~'; file.extname = '.md'; file.basename = 'test.text'; file.history = ['~/test.txt']; // => ['~/example.txt', '~/example.md', '~/index.text'] -file.messages = [{ - file: '~/test.txt', - ruleId: '', - reason: '', - line: 1, - column: 1, - location: { - start: { - line: 1, - column: 1, - }, - end: { - line: 1, - column: 1, - } - }, - source: '' -}]; +file.messages = [vfileMessage('random error')]; const startPoint: Unist.Point = { line: 1, @@ -46,7 +30,7 @@ const position: Unist.Position = { }, }; -file.message('test', startPoint); +const message: vfileMessage.VFileMessage = file.message('test', startPoint, 'test origin'); file.message('test', position); file.message('test', { type: 'ramdom node', @@ -56,6 +40,10 @@ file.message('test', { file.message('test', { start: 'invalid point' }); // $ExpectError +file.fail('test'); + +const infoMessage: vfileMessage.VFileMessage = file.info('test'); + // Using `data` prop interface CustomData { message: string; diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 5670547317..d002a3d695 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Victory 0.9.3 +// Type definitions for Victory 31.0 // Project: https://github.com/FormidableLabs/victory // Definitions by: Alexey Svetliakov // snerks @@ -269,16 +269,16 @@ declare module "victory" { */ cursorLabel?: (point: CursorData) => void; /** - * The cursorLabelComponent prop takes a component instance which will be - * used to render a label for the cursor. The new element created from the passed + * The cursorLabelComponent prop takes a component instance which will be + * used to render a label for the cursor. The new element created from the passed * cursorLabelComponent will be supplied with the following props: x, y, * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. * @default cursorLabelComponent={} */ cursorLabelComponent?: React.ReactElement; /** - * The cursorLabelOffset prop determines the pixel offset of the cursor label - * from the cursor point. This prop should be an Object with x and y properties, or a + * The cursorLabelOffset prop determines the pixel offset of the cursor label + * from the cursor point. This prop should be an Object with x and y properties, or a * number to be used for both dimensions. * @default "{ x: 5, y: -10 }" */ @@ -315,45 +315,45 @@ declare module "victory" { */ allowDrag?: boolean; /** - * The optional allowResize prop accepts a boolean that enables resizing the + * The optional allowResize prop accepts a boolean that enables resizing the * highlighted brush area. Dragging will still be enabled when the allowResize * prop is set to false, but the dimensions of the brush area will be fixed. * @default true */ allowResize?: boolean; /** - * The brushComponent prop specifies the component to be rendered for the - * highlighted area. This component will be supplied with the following props: x, y, + * The brushComponent prop specifies the component to be rendered for the + * highlighted area. This component will be supplied with the following props: x, y, * width, height, and style. When this prop is not specified, a will be rendered. * @default brushComponent={} */ brushComponent?: React.ReactElement; /** - * When the brushDimension prop is set, brushing will only be specific to the to - * the given dimension (either "x" or "y"), and the entire domain of the other + * When the brushDimension prop is set, brushing will only be specific to the to + * the given dimension (either "x" or "y"), and the entire domain of the other * dimension will be highlighted. When this prop is not specified, highlighting will * occur along both dimensions. * @example brushDimension="x" */ brushDimension?: 'x' | 'y'; /** - * The optional brushDomain prop describes the highlighted state. This prop is an - * object that specifies separate arrays for x and y. Each array is a tuple that - * describes the minimum and maximum values to render. If this prop is not provided - * initially, the chart will render with the entire domain highlighted. When this prop + * The optional brushDomain prop describes the highlighted state. This prop is an + * object that specifies separate arrays for x and y. Each array is a tuple that + * describes the minimum and maximum values to render. If this prop is not provided + * initially, the chart will render with the entire domain highlighted. When this prop * changes, the chart will render with a new highlighted domain. * @example brushDomain={{ x: [50, 100], y: [0, 100] }} */ brushDomain?: DomainPropType; /** - * The brushStyle adds custom styles to the brushComponent. This prop + * The brushStyle adds custom styles to the brushComponent. This prop * should be given as an object of SVG style attributes. * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" */ brushStyle?: React.CSSProperties; /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the * prop is set to "all", the entire domain will be selected. When the prop is set to "none", * no new region will be selected, and any existing active brush will be cleared. When * the prop is set to "disable" the new selected region will default to the current active brush. @@ -364,8 +364,8 @@ declare module "victory" { */ disable?: boolean; /** - * The handleComponent prop specifies the component to be rendered for each - * handle for the highlighted area. This component will be supplied with the following + * The handleComponent prop specifies the component to be rendered for each + * handle for the highlighted area. This component will be supplied with the following * props: x, y, width, height, cursor, and style. When this prop is not * specified, a will be rendered. * @default handleComponent={} @@ -373,7 +373,7 @@ declare module "victory" { handleComponent?: React.ReactElement; /** * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. - * + * * Handles refer to the region on each highlighted area where the area may be * expanded. Only handles relevant to the given dimension will be rendered. For * example, when brushDimension="x" only "left" and "right" handles will be @@ -382,8 +382,8 @@ declare module "victory" { */ handleStyle?: React.CSSProperties; /** - * The optional onBrushDomainChange prop accepts an function to be called on - * each update to the highlighted domain. The function accepts the parameters of + * The optional onBrushDomainChange prop accepts an function to be called on + * each update to the highlighted domain. The function accepts the parameters of * domain (the updated domain), and props (the props used by VictoryBrushContainer). * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} */ @@ -394,7 +394,7 @@ declare module "victory" { export interface VictoryZoomContainerProps extends VictoryContainerProps { /** - * The optional allowPan prop accepts a boolean that enables the panning + * The optional allowPan prop accepts a boolean that enables the panning * functionality. Zooming will still be enabled when the allowPan prop is set to false. * @default true */ @@ -406,7 +406,7 @@ declare module "victory" { */ allowZoom?: boolean; /** - * VictoryZoomContainer works by clipping data outside of a given domain. + * VictoryZoomContainer works by clipping data outside of a given domain. * VictoryZoomContainer uses VictoryClipContainer by default. * This prop should not be replaced with a custom component, but you may want to set * props on VictoryClipContainer, such as clipPadding. @@ -414,30 +414,30 @@ declare module "victory" { */ clipContainerComponent?: React.ReactElement; /** - * When the zoomDimension prop is set, panning and zooming will be restricted to - * the given dimension (either x or y), and the domain of the other dimension will + * When the zoomDimension prop is set, panning and zooming will be restricted to + * the given dimension (either x or y), and the domain of the other dimension will * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. * @example zoomDimension="x" */ zoomDimension?: 'x' | 'y'; /** - * The zoomDomain prop describes the zoomed state. This prop is an object that - * specifies separate arrays for x and y. Each array is a tuple that describes the - * minimum and maximum values to render. If this prop is not provided initially, the - * chart will render without an initial zoom, displaying the entire dataset. Updates to + * The zoomDomain prop describes the zoomed state. This prop is an object that + * specifies separate arrays for x and y. Each array is a tuple that describes the + * minimum and maximum values to render. If this prop is not provided initially, the + * chart will render without an initial zoom, displaying the entire dataset. Updates to * zoomDomain will trigger a re-render of the chart with the new domain. * @example zoomDomain={{x: [0, 100]}} */ zoomDomain?: DomainPropType; /** - * The brushStyle adds custom styles to the brushComponent. This prop + * The brushStyle adds custom styles to the brushComponent. This prop * should be given as an object of SVG style attributes. * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" */ brushStyle?: React.CSSProperties; /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the * prop is set to "all", the entire domain will be selected. When the prop is set to "none", * no new region will be selected, and any existing active brush will be cleared. When * the prop is set to "disable" the new selected region will default to the current active brush. @@ -452,10 +452,10 @@ declare module "victory" { */ downsample?: number | boolean; /** - * The minimumZoom prop sets a minimum domain extent for the zoomed chart. + * The minimumZoom prop sets a minimum domain extent for the zoomed chart. * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom * in either dimension, the component will stop responding to events that would normally trigger zooming in. - * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum + * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object * with numeric values for x and y. * @example minimumZoom={{x: 1, y: 0.01}} @@ -650,10 +650,10 @@ declare module "victory" { */ y?: number; } - - + + /** - * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. + * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. * VictoryTooltip renders text as well as a configurable Flyout container. */ export class VictoryTooltip extends React.Component< @@ -1317,6 +1317,21 @@ declare module "victory" { * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} */ style?: VictoryStyleInterface; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; } /** diff --git a/types/victory/tslint.json b/types/victory/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/victory/tslint.json +++ b/types/victory/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/victory/victory-tests.tsx b/types/victory/victory-tests.tsx index 3b882c7583..d7ddd7c33b 100644 --- a/types/victory/victory-tests.tsx +++ b/types/victory/victory-tests.tsx @@ -253,6 +253,8 @@ test = ( {x: 4, y: 2}, {x: 5, y: 1} ]} + barWidth={20} + barRatio={100} /> ); diff --git a/types/vis/index.d.ts b/types/vis/index.d.ts index 0f4a4f0f4e..84ff769270 100644 --- a/types/vis/index.d.ts +++ b/types/vis/index.d.ts @@ -11,6 +11,7 @@ // Oleksii Kachura // dcop // Avraham Essoudry +// Dmitriy Trifonov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { MomentInput, MomentFormatSpecification, Moment } from 'moment'; @@ -244,6 +245,7 @@ export interface TimelineOptions { multiselectPerGroup?: boolean; onAdd?: TimelineOptionsItemCallbackFunction; onAddGroup?: TimelineOptionsGroupCallbackFunction; + onInitialDrawComplete?: (() => void); onUpdate?: TimelineOptionsItemCallbackFunction; onMove?: TimelineOptionsItemCallbackFunction; onMoveGroup?: TimelineOptionsGroupCallbackFunction; diff --git a/types/w3c-css-typed-object-model-level-1/index.d.ts b/types/w3c-css-typed-object-model-level-1/index.d.ts new file mode 100644 index 0000000000..f1d68b2e94 --- /dev/null +++ b/types/w3c-css-typed-object-model-level-1/index.d.ts @@ -0,0 +1,289 @@ +// Type definitions for css-typed-object-model-level-1 20180410.0 +// Project: https://www.w3.org/TR/css-typed-om-1/ +// Definitions by: Dmitry Guketlev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +declare class CSSStyleValue { + static parse(property: string, cssText: string): CSSStyleValue; + static parseAll(property: string, cssText: string): CSSStyleValue[]; + toString(): string; +} + +declare class CSSVariableReferenceValue { + constructor(variable: string, fallback?: CSSUnparsedValue) + variable: string; + readonly fallback?: CSSUnparsedValue; +} + +type CSSUnparsedSegment = string | CSSVariableReferenceValue; + +declare class CSSUnparsedValue extends CSSStyleValue { + constructor(members: CSSUnparsedSegment[]); + [Symbol.iterator](): IterableIterator; + readonly length: number; + [idx: number]: CSSUnparsedSegment; +} + +declare class CSSKeywordValue extends CSSStyleValue { + constructor(value: string); + value: string; +} + +type CSSNumberish = number | CSSNumericValue; + +declare enum CSSNumericBaseType { + 'length', + 'angle', + 'time', + 'frequency', + 'resolution', + 'flex', + 'percent', +} + +interface CSSNumericType { + length: number; + angle: number; + time: number; + frequency: number; + resolution: number; + flex: number; + percent: number; + percentHint: CSSNumericBaseType; +} + +declare class CSSNumericValue extends CSSStyleValue { + add(...values: CSSNumberish[]): CSSNumericValue; + sub(...values: CSSNumberish[]): CSSNumericValue; + mul(...values: CSSNumberish[]): CSSNumericValue; + div(...values: CSSNumberish[]): CSSNumericValue; + min(...values: CSSNumberish[]): CSSNumericValue; + max(...values: CSSNumberish[]): CSSNumericValue; + + equals(...values: CSSNumberish[]): boolean; + + to(unit: string): CSSUnitValue; + toSum(...units: string[]): CSSMathSum; + type(): CSSNumericType; + + static parse(cssText: string): CSSNumericValue; +} + +declare class CSSUnitValue extends CSSNumericValue { + constructor(value: number, unit: string); + value: number; + readonly unit: string; +} + +declare class CSSMathValue extends CSSNumericValue { + readonly operator: CSSMathOperator; +} + +declare class CSSMathSum extends CSSMathValue { + constructor(...args: CSSNumberish[]); + readonly values: CSSNumericArray; +} + +declare class CSSMathProduct extends CSSMathValue { + constructor(...args: CSSNumberish[]) + readonly values: CSSNumericArray; +} + +declare class CSSMathNegate extends CSSMathValue { + constructor(arg: CSSNumberish) + readonly value: CSSNumericValue; +} + +declare class CSSMathInvert extends CSSMathValue { + constructor(arg: CSSNumberish) + readonly value: CSSNumericValue; +} + +declare class CSSMathMin extends CSSMathValue { + constructor(...args: CSSNumberish[]) + readonly values: CSSNumericArray; +} + +declare class CSSMathMax extends CSSMathValue { + constructor(...args: CSSNumberish[]) + readonly values: CSSNumericArray; +} + +// TODO(yavanosta): conflict with base class properties +// Since there is no support for this class in any browser, it's better +// wait for the implementation. +// declare class CSSMathClamp extends CSSMathValue { +// constructor(min: CSSNumberish, val: CSSNumberish, max: CSSNumberish); +// readonly min: CSSNumericValue; +// readonly val: CSSNumericValue; +// readonly max: CSSNumericValue; +// }; + +declare class CSSNumericArray { + [Symbol.iterator](): IterableIterator; + readonly length: number; + readonly [index: number]: CSSNumericValue; +} + +declare enum CSSMathOperator { + 'sum', + 'product', + 'negate', + 'invert', + 'min', + 'max', + 'clamp', +} + +declare class CSSTransformValue extends CSSStyleValue { + constructor(transforms: CSSTransformComponent[]); + [Symbol.iterator](): IterableIterator; + readonly length: number; + [index: number]: CSSTransformComponent; + readonly is2D: boolean; + toMatrix(): DOMMatrix; +} + +declare class CSSTransformComponent { + is2D: boolean; + toMatrix(): DOMMatrix; + toString(): string; +} + +declare class CSSTranslate extends CSSTransformComponent { + constructor(x: CSSNumericValue, y: CSSNumericValue, z?: CSSNumericValue); + x: CSSNumericValue; + y: CSSNumericValue; + z: CSSNumericValue; +} + +declare class CSSRotate extends CSSTransformComponent { + constructor(angle: CSSNumericValue); + constructor(x: CSSNumberish, y: CSSNumberish, z: CSSNumberish, angle: CSSNumericValue) + x: CSSNumberish; + y: CSSNumberish; + z: CSSNumberish; + angle: CSSNumericValue; +} + +declare class CSSScale extends CSSTransformComponent { + constructor(x: CSSNumberish, y: CSSNumberish, z?: CSSNumberish) + x: CSSNumberish; + y: CSSNumberish; + z: CSSNumberish; +} + +declare class CSSSkew extends CSSTransformComponent { + constructor(ax: CSSNumericValue, ay: CSSNumericValue) + ax: CSSNumericValue; + ay: CSSNumericValue; +} + +declare class CSSSkewX extends CSSTransformComponent { + constructor(ax: CSSNumericValue) + ax: CSSNumericValue; +} + +declare class CSSSkewY extends CSSTransformComponent { + constructor(ay: CSSNumericValue) + ay: CSSNumericValue; +} + +/* Note that skew(x,y) is *not* the same as skewX(x) skewY(y), + thus the separate interfaces for all three. */ + +declare class CSSPerspective extends CSSTransformComponent { + constructor(length: CSSNumericValue) + length: CSSNumericValue; +} + +declare class CSSMatrixComponent extends CSSTransformComponent { + constructor(matrix: DOMMatrixReadOnly, options?: CSSMatrixComponentOptions) + matrix: DOMMatrix; +} + +interface CSSMatrixComponentOptions { + is2D: boolean; +} + +declare class CSSImageValue extends CSSStyleValue { +} + +declare class StylePropertyMapReadOnly { + [Symbol.iterator](): IterableIterator<[string, CSSStyleValue[]]>; + + get(property: string): CSSStyleValue | undefined; + getAll(property: string): CSSStyleValue[]; + has(property: string): boolean; + readonly size: number; +} + +declare class StylePropertyMap extends StylePropertyMapReadOnly { + set(property: string, ...values: Array): void; + append(property: string, ...values: Array): void; + delete(property: string): void; + clear(): void; +} + +interface Element { + computedStyleMap(): StylePropertyMapReadOnly; +} + +interface CSSStyleRule { + readonly styleMap: StylePropertyMap; +} + +interface ElementCSSInlineStyle { + readonly attributeStyleMap: StylePropertyMap; +} + +interface CSS { + number(value: number): CSSUnitValue; + percent(value: number): CSSUnitValue; + + // + em(value: number): CSSUnitValue; + ex(value: number): CSSUnitValue; + ch(value: number): CSSUnitValue; + ic(value: number): CSSUnitValue; + rem(value: number): CSSUnitValue; + lh(value: number): CSSUnitValue; + rlh(value: number): CSSUnitValue; + vw(value: number): CSSUnitValue; + vh(value: number): CSSUnitValue; + vi(value: number): CSSUnitValue; + vb(value: number): CSSUnitValue; + vmin(value: number): CSSUnitValue; + vmax(value: number): CSSUnitValue; + cm(value: number): CSSUnitValue; + mm(value: number): CSSUnitValue; + Q(value: number): CSSUnitValue; + in(value: number): CSSUnitValue; + pt(value: number): CSSUnitValue; + pc(value: number): CSSUnitValue; + px(value: number): CSSUnitValue; + + // + deg(value: number): CSSUnitValue; + grad(value: number): CSSUnitValue; + rad(value: number): CSSUnitValue; + turn(value: number): CSSUnitValue; + + //