diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 5121e1095e..df45a8a9e7 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,6 +3,7 @@ # See https://github.com/DefinitelyTyped/DefinitelyTyped#edit-an-existing-package /types/a-big-triangle/ @MathiasPaumgarten +/types/a11y-dialog/ @Goyatuzo /types/abbrev/ @BendingBender /types/abs/ @AyaMorisawa /types/absolute/ @AyaMorisawa @@ -15,7 +16,7 @@ /types/ace-diff/ @innovation-team /types/acl/ @tkQubo /types/acorn/ @RReverser @e-cloud -/types/actioncable/ @zhu1230 +/types/actioncable/ @zhu1230 @szechyjs /types/actions-on-google/ @joelhegg /types/activedirectory2/ @pasthelod /types/activex-access/ @zspitz @@ -52,11 +53,14 @@ /types/aggregate-error/ @BendingBender /types/agora-rtc-sdk/ @menthays /types/ajv-errors/ @afshawnlotfi +/types/ale-url-parser/ @msn0 /types/alertify/ @jjeffery /types/alexa-sdk/ @petebeegle @hoo29 @pascalwhoop @blforce @rk-7 @alexmalcoci /types/alexa-voice-service/ @dolanmiu /types/algebra.js/ @CaselIT -/types/algoliasearch/ @cbaptiste @haroenv @aherve @samouss +/types/algoliasearch/ @cbaptiste @haroenv @aherve @samouss @keichinger +/types/ali-app/ @taoqf +/types/ali-oss/ @ptrdu /types/allure-js-commons/ @zaqqaz /types/almost-equal/ @cmaddalozzo /types/alt/ @Shearerbeard @@ -68,7 +72,7 @@ /types/amphtml-validator/ @kevincharm /types/amplify/ @joeriks /types/amplify-deferred/ @joeriks @laurentiustamate94 -/types/amplitude-js/ @Asido +/types/amplitude-js/ @Asido @danmana /types/amqp/ @seikho @jonnysparkplugs /types/amqp-connection-manager/ @rogierschouten /types/amqp-rpc/ @wokim @@ -149,6 +153,7 @@ /types/animation-frame/ @qinfchen /types/animejs/ @A-Babin /types/annyang/ @hisham @theluk +/types/ansi/ @Gustavo6046 /types/ansi-colors/ @rogierschouten /types/ansi-escape-sequences/ @aomarks /types/ansi-escapes/ @jacobbubu @@ -161,6 +166,7 @@ /types/any-db-transaction/ @rogierschouten /types/anybar/ @khoomeister /types/anymatch/ @BendingBender +/types/aos/ @shermendev /types/apex.js/ @y13i /types/aphrodite/ @asvetliakov /types/api-error-handler/ @tkrotoff @@ -168,6 +174,7 @@ /types/apigee-access/ @CasperSkydt /types/apollo-codegen/ @bradleyayers @kostspielig /types/apollo-upload-client/ @Slessi +/types/apostrophe/ @afholderman /types/app-root-dir/ @chenyang-biu /types/app-root-path/ @shantmarouti /types/appdmg/ @unindented @@ -195,18 +202,22 @@ /types/array-sort/ @DanielMSchmidt /types/array-uniq/ @DanielRosenwasser /types/array-unique/ @CSLTech +/types/array.prototype.flatmap/ @hallettj /types/arrify/ @wanganjun /types/artillery/ @kmccoan-allocadia /types/asana/ @tkqubo /types/asap/ @fpascutti +/types/ascii-art/ @lukaselmer /types/ascii2mathml/ @RagibHasin /types/asenv/ @remisery /types/asn1js/ @microshine /types/aspnet-identity-pw/ @jt000 +/types/assert/ @nicoabie /types/assert-equal-jsx/ @seryl /types/assert-plus/ @KostyaTretyak /types/assertsharp/ @brunolm /types/assets-webpack-plugin/ @kryops +/types/astring/ @nkappler /types/async/ @borisyankov @kern0 @Penryn @fenying @pascalmartin /types/async-cache/ @BendingBender /types/async-lock/ @elisee @afharo @rhymmor @@ -214,6 +225,7 @@ /types/async-retry/ @albertywu @MeLlamoPablo /types/async.nexttick/ @pyrho /types/asynciterator/ @rubensworks +/types/athenajs/ @warpdesign /types/atlaskit__button/ @dijimsta /types/atlaskit__calendar/ @lstanden /types/atlaskit__inline-edit/ @lstanden @@ -227,7 +239,8 @@ /types/atom-mocha-test-runner/ @GlenCFL /types/atpl/ @soywiz /types/audiosprite/ @Perlmint -/types/auth0/ @wbhob @westy92 @amiram +/types/auth-header/ @ForbesLindesay +/types/auth0/ @westy92 /types/auth0-angular/ @homesar /types/auth0-js/v7/ @advancedrei /types/auth0-js/ @adrianchia @mdurrant @peterblazejewicz @@ -238,12 +251,12 @@ /types/auto-sni/ @janwo /types/autobahn/ @darkl @valepu /types/autolinker/ @leonyu -/types/autoprefixer/ @odnamrataizem +/types/autoprefixer/ @odnamrataizem @murt /types/autosize/ @kingdango @keika299 @NeekSandhu /types/autosuggest-highlight/ @senukartur /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 +/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 /types/aws-serverless-express/ @threesquared @jcaffey @mattmeye @albertovasquez /types/aws4/ @ajcrites /types/axe-webdriverjs/ @JoshuaKGoldberg @@ -301,10 +314,11 @@ /types/bases/ @harikv /types/bash-glob/ @mrmlnc /types/basic-auth/ @moonpyk @vesse +/types/basicauth-middleware/ @nchaulet /types/batch-stream/ @drudge /types/bazinga-translator/ @alexndlm /types/bcrypt/ @codeanimal @IOAyman @dstapleton92 -/types/bcryptjs/ @RafaelKr +/types/bcryptjs/ @RafaelKr @branoholy /types/bdfjs/ @jeremejevs /types/beats/ @urish /types/bech32/ @micksatana @@ -314,10 +328,10 @@ /types/bencode/ @tobenna /types/better-curry/ @pocesar /types/better-queue/ @maozedong -/types/better-scroll/ @stoneChen +/types/better-scroll/ @stoneChen @cnjack /types/better-sqlite3/ @Morfent @matrumz /types/bezier-easing/ @ptlis -/types/bezier-js/ @danmarshall +/types/bezier-js/ @danmarshall @Epskampie /types/bgiframe/ @sumegizoltan /types/bidirectional-map/ @helenanderson /types/big.js/ @nycdotnet @googol @@ -338,9 +352,8 @@ /types/bitcoinjs-lib/ @mhegazy @dlebrecht @rbuckton @micksatana @youssefgh @kento1218 /types/bitcore-lib/ @lautarodragan /types/bittorrent-protocol/ @feross @tlaziuk -/types/bitwise/ @danwbyrne /types/bitwise-xor/ @rogierschouten -/types/bl/ @Bartvds +/types/bl/ @Bartvds @reconbot /types/blacklist/ @mhegazy /types/blazy/ @julienpa /types/blessed/ @brynbellomy @skellock @@ -371,7 +384,7 @@ /types/boom/ @rogatty @AJamesPhillips @jineshshah36 @TimonVS @danielmachado /types/bootbox/ @vbortone @konpikwastaken @kanup @icereed @trodi @stannynuytkens @renjfk /types/bootpag/ @rdeneau -/types/bootstrap/v3/ @borisyankov +/types/bootstrap/v3/ @borisyankov @denisname /types/bootstrap/ @denisname /types/bootstrap-3-typeahead/ @AndersonFriaca /types/bootstrap-datepicker/ @borisyankov @@ -383,6 +396,7 @@ /types/bootstrap-slider/ @dbeckwith @leonard-thieu /types/bootstrap-switch/ @johnmbaughman /types/bootstrap-table/ @talatbaig +/types/bootstrap-toggle/ @gricey432 /types/bootstrap-touchspin/ @albinsunnanbo /types/bootstrap-treeview/ @jbtronics /types/bootstrap-validator/ @BradyLiles @@ -401,6 +415,7 @@ /types/breeze/ @borisyankov /types/bricks.js/ @kondi /types/bro-fs/ @ffflorian +/types/broccoli-plugin/ @dfreeman /types/brorand/ @chrootsu /types/browser-bunyan/ @PaulLockwood @kryops /types/browser-fingerprint/ @LKay @@ -409,7 +424,7 @@ /types/browser-report/ @JTOne123 /types/browser-resolve/ @marionebl /types/browser-sync/ @joeskeen @aznnomness -/types/browserify/ @AndrewGaspar @jvilk @leonard-thieu +/types/browserify/ @AndrewGaspar @jvilk @leonard-thieu @LinusU /types/bs58/ @chrootsu /types/bson/ @horiuchi @CaselIT /types/btoa/ @johngeorgewright @@ -423,7 +438,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 +/types/bull/ @bgrieder @JProgrammer @marshall007 @weeco @blaugold @iamolegga @koblas @bondz @wuha-team @aleccool213 @danmana /types/bump-regex/ @silkentrance /types/bunnymq/ @cyrilschumacher /types/bunyan/ @amikhalev @@ -439,9 +454,11 @@ /types/byline/ @reppners /types/bytebuffer/ @cappellin /types/bytes/ @danny8002 @believer +/types/bytewise/ @danwbyrne /types/c3/ @mcliment @gerinjacob @denyo @dmitryshindin @timn /types/cache-manager/ @GausSim /types/cal-heatmap/ @RetroChrisB +/types/caller/ @ignocide /types/callsite/ @newclear /types/callsites/ @BendingBender /types/calq/ @eirikhm @@ -450,6 +467,7 @@ /types/camelcase-keys/ @mhegazy /types/camo/ @lucasmciruzzi /types/cancan/ @Vincent-Pang +/types/caniuse-api/ @davecardwell /types/cannon/ @clark-stevenson @Gelio /types/canvas-confetti/ @matracey /types/canvas-gauges/ @Mikhus @@ -475,6 +493,7 @@ /types/chai-datetime/ @cliffburger @mattbishop /types/chai-dom/ @mattlewis92 /types/chai-enzyme/ @asvetliakov +/types/chai-fs/ @dimitardanailov /types/chai-fuzzy/ @Bartvds /types/chai-http/ @Nemo157 @G1itcher @CaselIT @bas-l /types/chai-jest-snapshot/ @mattvperry @@ -493,7 +512,7 @@ /types/chardet/ @Gebatzens /types/charm/ @Xananax /types/charset/ @cspotcode -/types/chart.js/ @anuti @FabienLavocat @KentarouTakeda @larrybahr @mernen @josefpaij @danmana @guillaume-ro-fr @archy-bold @braincore @gebeto @frabnt @alexdor @mahnuh +/types/chart.js/ @anuti @FabienLavocat @KentarouTakeda @larrybahr @mernen @josefpaij @danmana @guillaume-ro-fr @archy-bold @braincore @frabnt @alexdor @mahnuh @Conrad777 /types/chartist/ @mtgibbs @psimonski @clottman @affilnost @sunnyrjuneja /types/chartmogul-node/ @chartmogul /types/chayns/ @HenningKuehl @@ -506,6 +525,7 @@ /types/chessboardjs/ @sliverb @davidmpaz /types/chmodr/ @BendingBender /types/chokidar/ @reppners @felixfbecker @bayssmekanique +/types/chordsheetjs/ @adamsbloom /types/chosen-js/ @borisyankov @denisname /types/chownr/ @BendingBender /types/chroma-js/v0/ @invliD @@ -533,6 +553,7 @@ /types/cleave.js/ @clentfort @jasongi-at-sportsbet @sashashakun /types/cli/ @kayahr /types/cli-color/ @ChaosinaCan +/types/cli-interact/ @ffflorian /types/cli-progress/ @mhegazy /types/cli-spinner/ @janslow /types/cli-table/ @arylo @@ -573,18 +594,20 @@ /types/color-namer/ @in19farkt /types/color-string/ @BendingBender @danmarshall /types/colorbrewer/ @mtraynham +/types/colresizable/ @gilleswaeber /types/com.darktalker.cordova.screenshot/ @akarienta /types/com.wikitude.phonegap.wikitudeplugin/ @zbarbuto /types/combine-source-map/ @TeamworkGuy2 /types/combined-stream/ @felixge @tlaziuk /types/combokeys/ @iclanton -/types/cometd/ @derekcicerone +/types/cometd/ @derekcicerone @unindented @alxHenry /types/command-line-args/v4/ @CzBuCHi @75lb /types/command-line-args/ @75lb /types/command-line-commands/ @CzBuCHi /types/command-line-usage/ @matrumz @Dvorsky /types/commangular/ @hiraash /types/comment-json/ @Jason3S +/types/commercetools__enzyme-extensions/ @screendriver /types/common-errors/ @icopp /types/common-prefix/ @seangenabe /types/common-tags/ @zuzusik @tzupengwang @@ -592,7 +615,7 @@ /types/commonmark/ @nicojs @leonard-thieu /types/compare-version/ @jpevarnek /types/compare-versions/ @LogvinovLeon -/types/complex/ @AyaMorisawa +/types/complex/ @AyaMorisawa @pavasich /types/component-emitter/ @psnider /types/compose-function/ @denis-sokolov /types/compressible/ @BendingBender @@ -612,6 +635,7 @@ /types/confit/ @ethanresnick /types/connect/ @SomaticIT @EvanHahn /types/connect-busboy/ @pinguet62 +/types/connect-datadog/ @moshegood /types/connect-ensure-login/ @0x6368656174 /types/connect-flash/ @AndreasGassmann /types/connect-history-api-fallback/ @douglasduteil @@ -623,8 +647,10 @@ /types/connect-redis/ @xstoudi @morcerf /types/connect-slashes/ @samherrmann /types/connect-timeout/ @cyrilschumacher +/types/consola/ @Jungwoo-An /types/console-log-level/ @ofrobots /types/console-stamp/ @ericbyers @guusdegraeve +/types/console-ui/ @dfreeman /types/consolidate/ @soywiz @theosherry @nicolashenry /types/consul/ @chrootsu /types/content-disposition/ @bomret @@ -651,6 +677,7 @@ /types/cordova-plugin-background-mode/ @Lordnoname /types/cordova-plugin-badge/ @timbru31 /types/cordova-plugin-ble-central/ @gjunge +/types/cordova-plugin-bluetoothclassic-serial/ @tuvokki /types/cordova-plugin-canvascamera/ @lordazzi /types/cordova-plugin-device-name/ @larrybahr /types/cordova-plugin-file-opener2/ @cyrilgandon @@ -669,17 +696,19 @@ /types/cordova_app_version_plugin/ @larrybahr /types/cordovarduino/ @hendrikmaus /types/core-js/ @rbuckton @mfdeveloper +/types/core-object/ @dfreeman /types/correlation-id/ @natemara /types/cors/ @pluma /types/cosmiconfig/v4/ @ozum /types/cosmiconfig/ @ozum @szeck87 @saadq @jinwoo -/types/cote/ @makepost +/types/cote/ @makepost @roblabat /types/couchbase/ @maouida @fluggo /types/countdown/ @gjuchault /types/counterpart/ @santiagodoldan /types/countries-and-timezones/ @zero51 /types/country-list/ @iRoachie /types/country-select-js/ @humrochagf +/types/countup.js/ @shermendev /types/coverup/ @bevalorous /types/cp-file/ @BendingBender /types/cpx/ @alan-agius4 @@ -694,12 +723,14 @@ /types/createjs-lib/ @evilangelist @gyohk /types/credential/ @phuvo /types/credit-card-type/ @LKay +/types/critters-webpack-plugin/ @JuanJoseGonGi /types/cron/ @horiuchi @winup /types/cropperjs/ @stepancar /types/croppie/ @connor4312 @dklmuc @sarunint @knuthelgesen /types/cross-spawn/ @Alorel /types/crossfilter/ @schmuli @iebaker @nordfjord /types/crossroads/ @diullei +/types/crpc/ @0xdeafcafe /types/cryptiles/ @awendland /types/crypto-js/ @misak113 /types/crypto-random-string/ @MrManny @@ -725,16 +756,16 @@ /types/cucumber/ @abraaoalves @jan-molak @isoung @BendingBender @ErikSchierboom /types/currency-formatter/ @mhegazy @davidmpaz /types/custom-error-generator/ @thmiceli -/types/custom-functions-runtime/ @OfficeDev @Zlatkovsky @mscharlock @kbrandl +/types/custom-functions-runtime/ @OfficeDev @Zlatkovsky @mscharlock /types/cwise/ @taoqf /types/cwise-compiler/ @taoqf /types/cwise-parser/ @taoqf /types/cybozulabs-md5/ @pine613 /types/cytoscape/ @phreed @wy193777 @ypconstante @janniclas @cerberuser /types/d3/v3/ @gustavderdrache @borisyankov @MatthiasJobst -/types/d3/v4/ @tomwanzek @gustavderdrache @borisyankov -/types/d3/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-array/ @gustavderdrache @borisyankov @tomwanzek +/types/d3/v4/ @tomwanzek @gustavderdrache @borisyankov @denisname +/types/d3/ @tomwanzek @gustavderdrache @borisyankov @denisname +/types/d3-array/ @gustavderdrache @borisyankov @tomwanzek @denisname /types/d3-axis/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-box/ @lk-chen /types/d3-brush/ @tomwanzek @gustavderdrache @borisyankov @@ -752,10 +783,11 @@ /types/d3-force/ @tomwanzek @gustavderdrache @borisyankov /types/d3-format/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-geo/ @ledragon @tomwanzek @gustavderdrache @borisyankov +/types/d3-graphviz/ @DomParfitt /types/d3-hexbin/ @uncovertruth @tomwanzek @denisname /types/d3-hierarchy/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-hsv/ @arrayjam @denisname -/types/d3-interpolate/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-interpolate/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-path/ @tomwanzek @gustavderdrache @borisyankov /types/d3-polygon/ @tomwanzek @gustavderdrache @borisyankov /types/d3-quadtree/ @tomwanzek @gustavderdrache @borisyankov @denisname @@ -766,12 +798,12 @@ /types/d3-scale/v1/ @tomwanzek @gustavderdrache @borisyankov /types/d3-scale/ @tomwanzek @gustavderdrache @borisyankov /types/d3-scale-chromatic/ @Ledragon @gustavderdrache @borisyankov @henriquefm -/types/d3-selection/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-selection/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-selection-multi/ @gustavderdrache @borisyankov /types/d3-shape/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-time/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-time/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-time-format/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-timer/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-timer/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-tip/ @brspnnggrt /types/d3-transition/ @tomwanzek @gustavderdrache @borisyankov /types/d3-voronoi/ @tomwanzek @gustavderdrache @borisyankov @denisname @@ -803,6 +835,7 @@ /types/datejs/ @rupertavery /types/daterangepicker/ @SirMartin @smasala @nertzy /types/dav/ @ToastHawaii +/types/dayzed/ @samhh /types/db-migrate-base/ @nickiannone /types/db-migrate-pg/ @nickiannone /types/db.js/ @cgwrench @@ -810,8 +843,8 @@ /types/dd-trace/ @ColinBradley @alloy /types/deasync/ @Sicilica /types/debessmann/ @vkorehov -/types/debounce/ @denis-sokolov -/types/debug/ @swook @galtalmor @zamb3zi +/types/debounce/ @denis-sokolov @joshuakgoldberg +/types/debug/ @swook @galtalmor @zamb3zi @brasten /types/decamelize/ @samverschueren /types/decay/ @enaeseth /types/decompress/ @plantain-00 @jbethke @@ -825,7 +858,6 @@ /types/deep-freeze/ @Bartvds @aluanhaddad /types/deep-freeze-es6/ @mattbishop /types/deep-freeze-strict/ @mhegazy -/types/deepmerge/ @marvinscharle @syy1125 @AppLover69 /types/defaults/ @IbtihelCHNAB /types/defer-promise/ @niklasf /types/define-lazy-prop/ @BendingBender @@ -858,7 +890,9 @@ /types/detect-pointer/ @thomastilkema /types/detect-port/ @lith-light-g /types/detect-touch-events/ @thomastilkema -/types/detox/ @TareqElMasri +/types/detective/ @TeamworkGuy2 +/types/detox/ @TareqElMasri @stevechun +/types/dev-ip/ @mike-engel /types/devexpress-aspnetcore-bootstrap/ @devexpress @skubarenko /types/df-visible/ @Litee /types/dhtmlxgantt/ @mkozhukh @chriscamicas @@ -867,8 +901,9 @@ /types/di-lite/ @dcrusader /types/diacritics/ @otociulis /types/dialogflow/ @dyladan -/types/diff/ @vvakame @szdc +/types/diff/ @vvakame @szdc @moc-yuto /types/diff2html/ @rtfpessoa +/types/digibyte/ @lautarodragan @werewolfe /types/dir-resolve/ @andy-ms /types/discontinuous-range/ @OiCMudkips /types/discourse-sso/ @championswimmer @@ -887,10 +922,11 @@ /types/dojo/ @vansimke /types/dom-clipboard-api/ @43081j /types/dom-inputevent/ @diagramatics +/types/dom-loaded/ @ltetzlaff /types/dom-to-image/ @JipSterk /types/dom4/ @adidahiya @giladgray /types/domo/ @Steve-Fenton -/types/dompurify/ @bazuzi +/types/dompurify/ @bazuzi @FlowCrypt /types/domready/ @dotnetnerd /types/donna/ @vvakame /types/dookie/ @swanest @@ -917,6 +953,7 @@ /types/draggabilly/ @jaydubu /types/dragster/ @zskovacs /types/dragula/ @pwelter34 @abruzzihraig +/types/dropbox-chooser/ @quas94 /types/dropboxjs/ @Steve-Fenton @xperiments /types/dropkickjs/ @VorobeY1326 /types/dropzone/v4/ @nvivo @outring @renuo @Hikariii @@ -924,7 +961,7 @@ /types/dts-generator/ @mtraynham /types/duplexer2/ @Goldsmith42 /types/duplexer3/ @BendingBender -/types/duplexify/ @strax +/types/duplexify/ @strax @kinwa91 /types/duplicate-package-checker-webpack-plugin/ @mtraynham /types/durandal/ @BlueSpire /types/dustjs-linkedin/ @mdezem @@ -960,6 +997,7 @@ /types/ejs/ @benliddicott /types/ejs-locals/ @jt000 /types/ejson/ @shantanubhadoria +/types/elastic-apm-node/ @shahaed /types/elasticsearch/ @CasperSkydt @bfsmith @ddunkin @pushplay @mlamp @ahmadferdous @SimonSchick @brabster @deerawan /types/electron-config/ @mrfunkycold @unindented /types/electron-debug/ @unindented @@ -1025,6 +1063,7 @@ /types/emojione/ @dbrgn /types/empower/ @vvakame /types/emscripten/ @zakki @periklis +/types/encoding-down/ @MeirionHughes @danwbyrne /types/end-of-stream/ @strax /types/engine.io/ @KentarouTakeda /types/engine.io-client/ @KentarouTakeda @@ -1107,7 +1146,8 @@ /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/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki +/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__status-bar-height/ @dawnmist /types/expo__vector-icons/ @incleaf /types/express/ @borisyankov @@ -1138,6 +1178,7 @@ /types/express-mung/ @cyrilschumacher /types/express-myconnection/ @Cellule /types/express-mysql-session/ @Akim95 +/types/express-ntlm/ @forivall /types/express-oauth-server/ @atd-schubert /types/express-openapi/ @mugeso /types/express-paginate/ @AmirTugi @@ -1150,12 +1191,14 @@ /types/express-sanitized/ @cjbarth /types/express-serve-static-core/ @borisyankov @19majkel94 @kacepe @micksatana @samijaber /types/express-session/ @horiuchi @jacobbogers @builtinnya @ry7n +/types/express-sitemap-xml/ @ffflorian /types/express-socket.io-session/ @AylaJK /types/express-to-koa/ @xiaohanzhang /types/express-unless/ @wokim /types/express-wechat-access/ @simmons8616 /types/express-winston/ @bricka /types/express-ws/ @ajliv +/types/express-ws-routes/ @gstamac /types/express-xml-bodyparser/ @noticeMaker @macedigital /types/extend/ @reppners /types/extjs/ @brian428 @@ -1169,8 +1212,9 @@ /types/f1/ @neolwc /types/fabric/ @oklemencic @joewashear007 @mrand01 @NotWoods @bmartinson @RogerioTeixeira @BradleyHill /types/facebook-instant-games/ @menushka @oyvindjam -/types/facebook-js-sdk/ @amritk @mahmoudzohdi +/types/facebook-js-sdk/ @amritk @mahmoudzohdi @fluidsonic /types/facebook-pixel/ @noctishsu +/types/factory-girl/ @stackbuilders @sestrella @elcuy /types/faker/v3/ @Kuniwak /types/faker/ @bensw @basp @Kuniwak @mattbishop /types/falcor/ @Quramy @@ -1187,6 +1231,10 @@ /types/fast-list/ @BendingBender /types/fast-stats/ @rogierschouten /types/fastclick/ @shinnn +/types/fastify-cors/ @jannikkeye +/types/fastify-jwt/ @jannikkeye +/types/fastify-multipart/ @jannikkeye +/types/fastify-static/ @leomelzer /types/favico.js/ @drowse314-dev-ymat /types/favicons/ @mohsen1 /types/fb/ @JoshStrobl @@ -1213,7 +1261,7 @@ /types/feedme/ @codeanimal /types/feedparser/ @cortopy /types/fetch-jsonp/ @tkrotoff -/types/fetch-mock/ @asvetliakov @tamird @merrywhether @chrissinclair @matttennison @quentinbouygues +/types/fetch-mock/ @asvetliakov @tamird @merrywhether @chrissinclair @matttennison @quentinbouygues @mtsmfm /types/fetch.io/ @newraina /types/ffi/ @loyd @waitingsong /types/ffi-napi/ @keerthi16 @KiranNiranjan @@ -1248,7 +1296,7 @@ /types/firebase-token-generator/ @dotdotcommadot /types/firebird/ @karak /types/firefox/ @vvakame -/types/firefox-webext-browser/ @bomjacob +/types/firefox-webext-browser/ @jsmnbom /types/firmata/ @troywweber7 /types/first-mate/ @GlenCFL /types/fixed-data-table/ @pepaar @stephenjelfs @@ -1266,6 +1314,7 @@ /types/flush-write-stream/ @djcsdy /types/flux/ @stkb @GiedriusGrabauskas /types/fluxible/ @xbim +/types/fluxible-addons-react/ @xbim /types/fluxible-router/ @xbim /types/fluxxor/ @mrk21 /types/fm-websync/ @markusmauch @@ -1290,6 +1339,7 @@ /types/foundation/ @borisyankov /types/fpsmeter/ @alampros /types/framebus/ @kbukum +/types/franc/ @wlegate /types/frctl__fractal/ @pmccloghrylaing /types/freedom/ @jpevarnek /types/freeport/ @atd-schubert @@ -1329,6 +1379,7 @@ /types/fxn/ @charrondev /types/gae.channel.api/ @vvakame /types/gamedig/ @ivansieder +/types/gamepad/ @Lange /types/gamequery/ @Laubi /types/ganache-core/ @LogvinovLeon /types/gandi-livedns/ @xstoudi @@ -1491,9 +1542,11 @@ /types/get-stdin/ @DanielRosenwasser /types/get-stream/ @douglasduteil @BendingBender /types/get-value/ @DanielRosenwasser +/types/getenv/ @impankratov /types/getopts/ @azasypkin /types/getos/ @BendingBender /types/gettext.js/ @jucrouzet +/types/gh-pages/ @DanielRosenwasser /types/gifffer/ @gatimus /types/gijgo/ @atatanasov /types/giraffe/ @darthapo @@ -1501,6 +1554,7 @@ /types/git-branch/ @rynclark /types/git-config/ @stpettersens /types/git-remote-origin-url/ @janslow +/types/git-rev-sync/ @khoi-fish /types/git-url-parse/ @ajafff /types/github-url-to-object/ @ajafff /types/github-username-regex/ @BehindTheMath @@ -1510,7 +1564,8 @@ /types/gl-texture2d/ @MathiasPaumgarten /types/gldatepicker/ @qcz /types/glidejs/ @milanjaros -/types/glob/ @vvakame @voy +/types/glob/v5/ @vvakame @voy +/types/glob/ @vvakame @voy @ajafff /types/glob-base/ @alan-agius4 /types/glob-expand/ @vvakame /types/glob-parent/ @mrmlnc @@ -1521,8 +1576,9 @@ /types/globalize-compiler/ @iclanton /types/globby/ @douglasduteil @ikatyang /types/globule/ @durad +/types/glue/v4/ @gjednaszewski /types/glue/ @garfty -/types/gm/ @ChaosinaCan @maartenvanvliet +/types/gm/ @ChaosinaCan @maartenvanvliet @mlejva /types/go/ @NorthwoodsSoftware /types/google-adwords-scripts/ @jafaircl /types/google-apps-script/ @motemen @grant @@ -1543,17 +1599,20 @@ /types/google.geolocation/ @vbortone /types/google.picker/ @grapswiz /types/google.visualization/ @danludwig @gmoore-sjcorg @danmana @mlcheng @IvanBisultanov @glebm +/types/google__maps/ @indrimuska /types/googlemaps/ @cgwrench @nertzy @xaolas @mrmcnerd @martincostello @svenkreiss @bolatovumar @gauthierm /types/googlemaps.infobubble/ @Dashue -/types/googlepay/ @Fluccioni @Radu-Raicea -/types/got/ @BendingBender @LinusU @ikokostya +/types/googlepay/ @Fluccioni @Radu-Raicea @fstanis +/types/got/v8/ @BendingBender @LinusU @ikokostya +/types/got/ @BendingBender @LinusU @ikokostya @stijnvn /types/graceful-fs/v2/ @Bartvds /types/graceful-fs/ @Bartvds @BendingBender /types/gradient-string/ @Ailrun /types/graham_scan/ @hberntsen /types/gramps__rest-helpers/ @claude /types/graphite-udp/ @EricByers -/types/graphql/ @TonyPythoneer @calebmer @intellix @firede @kepennar @freiksenet @IvanGoncharov @DxCx @rportugal @tgriesser @dyst5422 @adnsio @divyenduz @bradzacher @clayne11 +/types/graphlib-dot/ @DomParfitt +/types/graphql/ @TonyPythoneer @calebmer @intellix @firede @kepennar @freiksenet @IvanGoncharov @DxCx @rportugal @tgriesser @dyst5422 @adnsio @divyenduz @bradzacher @clayne11 @JCMais /types/graphql-date/ @enaeseth /types/graphql-deduplicator/ @lfades /types/graphql-depth-limit/ @eritikass @@ -1562,6 +1621,7 @@ /types/graphql-query-complexity/ @abhikmitra /types/graphql-relay/ @arvitaly @nitintutlani @Grelinfo /types/graphql-resolve-batch/ @nayni +/types/graphql-resolvers/ @mike-engel /types/graphql-type-json/ @schfkt /types/graphviz/ @mhfrantz /types/grasp/ @agnoster @@ -1571,12 +1631,11 @@ /types/grecaptcha/v0/ @brentj73 /types/grecaptcha/ @DethAriel @rafaeltavares /types/gregorian-calendar/ @cwalv -/types/grid-styled/ @antonvasin @vittorio @lhache /types/gridfs-stream/ @liorm /types/gridstack/ @PascalSenn @ZoolWay @Sl1MBoy /types/grpc-error/ @danwbyrne /types/grunt/ @jeffmay @basarat -/types/gsap/ @codebelt @ProbablePrime @philipbulley +/types/gsap/ @codebelt @ProbablePrime @philipbulley @leomeloxp /types/gtin/ @RafaelKr /types/guid/ @maroy1986 /types/gulp/ @GiedriusGrabauskas @@ -1722,6 +1781,8 @@ /types/holderjs/ @renjfk /types/hooker/ @misak113 /types/hopscotch/ @pimterry @Aurimas1 +/types/host-validation/ @dintopple +/types/hosted-git-info/ @OiyouYeahYou /types/howler/ @xperiments @tdukart @alien35 @nicholashza /types/hpp/ @kryops /types/html-entities/ @xstoudi @@ -1733,7 +1794,7 @@ /types/html-void-elements/ @rhysd /types/html-webpack-plugin/ @deevus @bumbleblym @tlaziuk /types/html-webpack-template/ @bumbleblym -/types/html2canvas/ @rwhepburn @tan9 @sschocke +/types/html2canvas/ @rwhepburn @tan9 @sschocke @Ristaaf /types/htmlbars-inline-precompile/ @chriskrycho /types/htmlparser2/ @staticfunction @LinusU /types/htmltojsx/ @basarat @@ -1745,7 +1806,7 @@ /types/http-graceful-shutdown/ @dlee-nvisia /types/http-link-header/ @screendriver /types/http-proxy/ @SomaticIT @Raigen @DanielMSchmidt -/types/http-proxy-agent/ @mrmlnc +/types/http-proxy-agent/ @mrmlnc @steprescott /types/http-proxy-middleware/ @zebMcCorkle @BendingBender /types/http-rx/ @L2jLiga /types/http-server/ @plantain-00 @@ -1764,9 +1825,11 @@ /types/hypertext-application-language/ @maks3w /types/hystrixjs/ @igorsechyn /types/i18n/ @SomaticIT @FindQ +/types/i18n-abide/ @smbell /types/i18n-js/ @ypresto /types/i18next/v2/ @mxl @deerawan @GiedriusGrabauskas -/types/i18next/ @mxl @deerawan @GiedriusGrabauskas +/types/i18next/v8/ @mxl @deerawan @GiedriusGrabauskas +/types/i18next/ @mxl @deerawan @GiedriusGrabauskas @lenovouser @qqilihq @butchyyyy /types/i18next-browser-languagedetector/v0/ @cyrilschumacher @GiedriusGrabauskas /types/i18next-browser-languagedetector/ @cyrilschumacher @GiedriusGrabauskas /types/i18next-express-middleware/ @cyrilschumacher @@ -1792,6 +1855,7 @@ /types/ignore-styles/ @tai2 /types/iltorb/ @Alorel @reconbot /types/image-size/ @elisee +/types/image-type/ @ffflorian /types/imagemagick/ @soywiz /types/imagemagick-native/ @horiuchi /types/imagemapster/ @delphinus35 @@ -1807,7 +1871,7 @@ /types/imgur-rest-api/ @lukewestby /types/imperium/ @gaetansenn /types/impress/ @borisyankov -/types/in-app-purchase/ @l-jonas +/types/in-app-purchase/ @l-jonas @IchordeDionysos /types/in-range/ @DanielRosenwasser /types/inboxsdk/ @rdoursenaud @amiram /types/incremental-dom/ @basarat @lanthaler @vvakame @@ -1819,9 +1883,11 @@ /types/inherits/ @chrootsu /types/ini/ @marcinporebski /types/iniparser/ @chrootsu +/types/init-package-json/ @kfarnung /types/inline-css/ @philipisapain -/types/inline-style-prefixer/ @ahz @dpetrezselyova +/types/inline-style-prefixer/ @ahz @dpetrezselyova @franklixuefei /types/inquirer/ @tkQubo @ppathan @jouderianjr @bang88 @bitjson @synarque @jrockwood @kwkelly @Ailrun +/types/inquirer-npm-name/ @manuth /types/insert-module-globals/ @leonard-thieu /types/insight/ @vvakame /types/integer/ @Morfent @@ -1842,7 +1908,7 @@ /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 +/types/ioredis/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot @funthing @iamolegga /types/iota.lib.js/ @fogsh /types/ip/ @codeanimal /types/ip-address/ @icopp @danwbyrne @@ -1860,10 +1926,11 @@ /types/is-ci/ @atd-schubert /types/is-color/ @VitorLuizC /types/is-compressed/ @mhegazy +/types/is-docker/ @YashdalfTheGray /types/is-empty/ @termosa /types/is-finite/ @mhegazy /types/is-glob/ @mrmlnc -/types/is-hotkey/ @petester42 +/types/is-hotkey/ @petester42 @kalley /types/is-ip/ @coderslagoon /types/is-mobile/ @LogvinovLeon /types/is-my-json-valid/ @kruncher @@ -1886,6 +1953,7 @@ /types/is-url-superb/ @kryops /types/is-uuid/ @tedre191 /types/is-windows/ @mizunashi-mana +/types/isaac/ @mo /types/isbn-utils/ @elhaard /types/iscroll/ @csrakowski @devlato /types/ismobilejs/ @Ty3uK @@ -1909,6 +1977,7 @@ /types/japanese-holidays/ @syamatoo /types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B /types/jasmine-ajax/ @lgrignon +/types/jasmine-data-provider/ @tlaziuk /types/jasmine-data_driven_tests/ @AnthonyMacKinnon /types/jasmine-enzyme/ @bolatovumar /types/jasmine-es6-promise-matchers/ @stephenlautier @@ -1919,7 +1988,7 @@ /types/jasmine-node/ @svi3c /types/jasmine-promise-matchers/ @matthewjh /types/jasmine_dom_matchers/ @devoto13 -/types/jasminewd2/ @sjelin +/types/jasminewd2/ @sjelin @gkalpak /types/java/ @jimlloyd @hrl7 @darti /types/java-applet/ @cyrilschumacher /types/javascript-astar/ @ptlis @@ -1931,8 +2000,9 @@ /types/jdataview/ @RReverser /types/jdenticon/ @mtr /types/jest/v16/ @NoHomey @jwbay -/types/jest/ @NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang @wsmd @JamieMason @douglasduteil @ahnpnl @joshuakgoldberg @UselessPickles @r3nya @hotell @sebald +/types/jest/ @NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang @wsmd @JamieMason @douglasduteil @ahnpnl @joshuakgoldberg @UselessPickles @r3nya @hotell @sebald @andys8 /types/jest-axe/ @JoshuaKGoldberg +/types/jest-cli/ @lifeiscontent /types/jest-diff/ @myabc /types/jest-docblock/ @ikatyang /types/jest-each/ @theutz @nickmccurdy @@ -1957,6 +2027,7 @@ /types/johnny-five/ @nakakura @ujvzolee @workshop2 /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 /types/joi/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @dankraus @wanganjun @rafaelkallis @aconanlai @zaphoyd @thewillg @SimonSchick /types/joigoose/ @boothwhack /types/josa/ @vichyssoise @@ -1968,7 +2039,7 @@ /types/jqrangeslider/ @qcz /types/jquery/v1/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu /types/jquery/v2/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu -/types/jquery/ @leonard-thieu @borisyankov @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @johnnyreilly @DickvdBrink @King2500 +/types/jquery/ @leonard-thieu @borisyankov @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @johnnyreilly @DickvdBrink @King2500 @terrymun /types/jquery-ajax-chain/ @humana-fragilitas /types/jquery-alertable/ @stever /types/jquery-animate-scroll/ @AndersonFriaca @@ -1983,6 +2054,7 @@ /types/jquery-editable-select/ @baywet /types/jquery-focus-exit/ @AndersonFriaca /types/jquery-focusable/ @AndersonFriaca +/types/jquery-formatdatetime/ @AndersonFriaca /types/jquery-fullscreen/ @bgrieder /types/jquery-galleria/ @rimig /types/jquery-gray/ @AndersonFriaca @@ -2105,7 +2177,7 @@ /types/js-yaml/ @Bartvds @sclausen /types/js.spec/ @mattbishop /types/jsbn/ @Evgenus @al2xed -/types/jschannel/ @yitzchok +/types/jschannel/ @yitzchok @McFlat /types/jscrollpane/ @qcz /types/jsdeferred/ @minodisk /types/jsdom/ @leonard-thieu @palmfjord @@ -2113,7 +2185,7 @@ /types/jsend/ @CaselIT /types/jsesc/ @Bartvds /types/jsfl/ @soywiz -/types/jsforce/ @dolanmiu @netes @amphro @tnoonan-salesforce @whiteabelincoln +/types/jsforce/ @dolanmiu @netes @amphro @tnoonan-salesforce @whiteabelincoln @borys-kupar /types/jsftp/ @xyleen /types/jsgraph/ @rosinbum /types/jshamcrest/ @dharkness @@ -2126,6 +2198,7 @@ /types/json-patch-gen/ @RohdeK /types/json-pointer/ @Bartvds /types/json-query/ @mtraynham +/types/json-rpc-random-id/ @micahriggan /types/json-rpc-ws/ @npenin @mlamp /types/json-schema/ @bcherny @cyrilletuzi @lucianbuzzo @rolandjitsu /types/json-socket/ @svi3c @@ -2145,15 +2218,18 @@ /types/jsonnet/ @hookclaw /types/jsonp/ @surenkov /types/jsonpath/ @horiuchi @ikatyang +/types/jsonquery/ @JimmyBoh /types/jsonrpc-serializer/ @Akim95 @many20 /types/jsonstream/ @Bartvds /types/jsontoxml/ @benstevens48 -/types/jsonwebtoken/ @SomaticIT @danielheim @brikou @vpk +/types/jsonwebtoken/ @SomaticIT @danielheim @brikou @vpk @rlgod /types/jsonwebtoken-promisified/ @SomaticIT @danielheim @brikou @aneilbaboo +/types/jspath/ @dex4er /types/jspdf/ @amberjs /types/jsqrcode/ @lordazzi /types/jsrender/ @zakki /types/jsreport-core/ @taoqf +/types/jsreport-html-embedded-in-docx/ @taoqf /types/jsreport-html-to-xlsx/v1/ @me /types/jsreport-html-to-xlsx/ @me /types/jsreport-jsrender/ @taoqf @@ -2175,6 +2251,7 @@ /types/jui/ @easylogic /types/jui-core/ @easylogic /types/jui-grid/ @easylogic +/types/just-debounce-it/ @azizhk /types/just-extend/ @pe8ter /types/jweixin/ @taoqf @gomydodo /types/jwplayer/ @martinduparc @kutomer @philippguertler @danielmcgraw @bpdsw @@ -2185,8 +2262,10 @@ /types/jwt-express/ @nickp10 /types/jwt-simple/ @kenfdev @GaelMagnan /types/jwt-then/ @phenomax +/types/k6/ @MajorBreakfast /types/kafka-node/ @dansitu @bkim54 @sfrooster @amiram -/types/karma/ @tkrotoff @43081j +/types/karma/v1/ @tkrotoff @43081j +/types/karma/ @tkrotoff @43081j @devoto13 /types/karma-chai/ @JayAndCatchFire /types/karma-chai-sinon/ @vasek17 /types/karma-coverage/ @tkrotoff @@ -2196,11 +2275,12 @@ /types/karma-webpack/ @mtraynham /types/katex/ @mrand01 /types/kcors/ @Xstoudi @izayoiko -/types/kdbush/ @DenisCarriere +/types/kdbush/ @DenisCarriere @chrfrasco /types/keen-tracking/ @rui-ferreira /types/kefir/ @AyaMorisawa @HitoriSensei /types/kendo-ui/ @telerik -/types/keyboardjs/ @vbortone @piranha771 +/types/keyboardjs/ @vbortone @piranha771 @teoxoy +/types/keycloak-connect/ @gstamac /types/keygrip/ @jkeylu /types/keymaster/ @nitram509 /types/keymirror/ @jfahrenkrug @@ -2264,6 +2344,7 @@ /types/koa-pino-logger/ @khell /types/koa-pug/ @Xstoudi /types/koa-range/ @strax +/types/koa-ratelimit/ @OutdatedVersion /types/koa-redis/ @nsimmons /types/koa-redis-cache/ @dimamukhin /types/koa-requestid/ @sjmcdowall @@ -2276,15 +2357,17 @@ /types/koa-sslify/ @wingsbob /types/koa-static/ @hellopao @tlaziuk /types/koa-static-cache/ @JounQin +/types/koa-static-server/ @wulunyi /types/koa-views/ @brooklyndev /types/koa-webpack/ @malj @leebenson @miZyind @tlaziuk -/types/koa-websocket/ @moimael @jacogr @zdila +/types/koa-websocket/ @moimael @jacogr @zdila @Kroisse /types/koa-xml-body/ @uwinkelvos /types/koa2-cors/ @xialeistudio /types/koa2-session-redis/ @DimaMukhin /types/koa__cors/ @Xstoudi @izayoiko @stevehipwell @sjmcdowall /types/kolite/ @borisyankov /types/konami.js/ @mareek +/types/kos-core/ @ali-Kos /types/kraken-js/ @darkwebdev @micksatana /types/kramed/ @tonicblue /types/kss/ @giladgray @@ -2293,13 +2376,16 @@ /types/kuromoji/ @mzsm @kgtkr /types/lab/ @prashaantt /types/ladda/ @dflor003 @leemicw +/types/lambda-log/ @armonge +/types/lambda-tester/ @ivank @HajoAhoMantila /types/lasso/ @darkwebdev /types/later/ @jasond-s /types/latinize/ @GiedriusGrabauskas /types/latlon-geohash/ @rimig /types/launchpad/ @rictic +/types/layzr.js/ @shermendev /types/lazy-value/ @ikatyang -/types/lazy.js/ @Bartvds +/types/lazy.js/ @Bartvds @miso440 /types/lazypipe/ @tomc974 /types/ldapjs/ @cvillemure @peterkooijmans /types/leadfoot/ @theintern @@ -2315,7 +2401,7 @@ /types/leaflet-imageoverlay-rotated/ @tkleinke /types/leaflet-label/ @Nemo157 /types/leaflet-mouse-position/ @Hanyon -/types/leaflet-polylinedecorator/ @soucekv +/types/leaflet-polylinedecorator/ @soucekv @michaelfaisst /types/leaflet-providers/ @BendingBender /types/leaflet-rotatedmarker/ @robert-prib-polestar /types/leaflet-routing-machine/ @chanakadrathnayaka @@ -2330,21 +2416,28 @@ /types/leaflet.pancontrol/ @Brictarus /types/leaflet.pm/ @tkleinke /types/leaflet.polylinemeasure/ @RiON69 +/types/leakage/ @atd-schubert /types/leapmotionts/ @logotype +/types/ledgerhq__hw-transport/ @danwbyrne +/types/ledgerhq__hw-transport-node-hid/ @danwbyrne +/types/ledgerhq__hw-transport-u2f/ @danwbyrne /types/legal-eagle/ @j-f1 /types/lerna-get-packages/ @LogvinovLeon -/types/less/ @thasner @pranaygp @dwaxweiler +/types/less/ @thasner @pranaygp @dwaxweiler @chigix /types/less-middleware/ @federicobond /types/less2sass/ @gatimus /types/lestate/ @thelambdaparty /types/level-codec/ @danwbyrne /types/level-sublevel/ @basp -/types/leveldown/ @tarruda @LinusU -/types/levelup/ @blittle @tarruda +/types/leveldown/v1/ @tarruda @LinusU +/types/leveldown/ @MeirionHughes @danwbyrne +/types/levelup/v1/ @blittle @tarruda +/types/levelup/ @MeirionHughes @danwbyrne /types/leven/ @jmalonzo /types/levenshtein/ @geoffreak /types/libpq/ @Lodin /types/libsodium-wrappers/ @ffflorian +/types/libsodium-wrappers-sumo/ @ffflorian /types/libxmljs/ @fdecampredon @ComFreek /types/libxslt/ @alejo90 /types/license-checker/ @rogierschouten @unindented @@ -2354,6 +2447,7 @@ /types/line-reader/ @stpettersens /types/linear-gradient/ @Jack-Works /types/lingui__core/ @huan086 +/types/lingui__macro/ @huan086 /types/lingui__react/ @huan086 /types/linkify-it/ @praxxis /types/listr/ @durad @@ -2372,6 +2466,7 @@ /types/lockfile/v0/ @Bartvds /types/lockfile/ @Bartvds @BendingBender /types/lockr/ @droritos +/types/locks/ @flippynips /types/locutus/ @hookclaw /types/lodash/v3/ @bczengel @chrootsu /types/lodash/ @bczengel @chrootsu @stepancar @aj-r @ailrun @e-cloud @thorn0 @jtmthf @DomiR @@ -2691,6 +2786,7 @@ /types/luxon/ @colbydehart @FourwingsY @jsiebern /types/lwip/ @AyaMorisawa /types/lz-string/ @M0ns1gn0r +/types/lzma-native/ @leshow /types/magic-number/ @stpettersens /types/magicsuggest/ @leonardochaia /types/magnet-uri/ @tlaziuk @@ -2702,7 +2798,9 @@ /types/main-bower-files/ @k-kagurazaka /types/make-dir/ @ikatyang @BendingBender /types/maker.js/ @danmarshall -/types/mali/ @danwbyrne +/types/makeup-expander/ @darkwebdev +/types/makeup-floating-label/ @darkwebdev +/types/makeup-screenreader-trap/ @darkwebdev /types/mali-compose/ @danwbyrne /types/mali-onerror/ @danwbyrne /types/mandrill-api/ @pocesar @@ -2721,6 +2819,7 @@ /types/markdown-it/ @rapropos /types/markdown-it-anchor/ @seryl /types/markdown-it-container/ @hronex +/types/markdown-it-lazy-headers/ @knom /types/markdown-pdf/ @MonsieurMan /types/markdownlint/ @ark120202 /types/marked/ @worr @BendingBender @CrossR @@ -2731,7 +2830,8 @@ /types/maskedinput/ @lokeshpeta /types/masonry-layout/ @m-a-wilson @warriorrocker /types/massive/v3/ @swissspidy @clarenceh -/types/massive/ @swissspidy @clarenceh @AmazingTurtle +/types/massive/v4/ @swissspidy @clarenceh @AmazingTurtle +/types/massive/ @swissspidy @clarenceh @AmazingTurtle @mike-engel /types/match-media-mock/ @asvetliakov /types/match-sorter/ @claasahl /types/material-components-web/ @BrentDouglas @ckosti @@ -2773,6 +2873,7 @@ /types/maxmind/ @geoffreak /types/mcustomscrollbar/ @flurg /types/md5/ @arcdev1 @jprogrammer +/types/md5-file/ @BamButz /types/mdns/ @reppners /types/mdurl/ @rokt33r /types/media-typer/ @BendingBender @@ -2801,11 +2902,12 @@ /types/messenger/ @derekcicerone /types/meteor/ @barbatus @fullflavedave @orefalo @dagatsoin @birkskyum @ardatan @stefanholzapfel @andrei-markeev @lmachens /types/meteor-accounts-phone/ @DAB0mB +/types/meteor-astronomy/ @Deadly0 /types/meteor-collection-hooks/ @twastvedt /types/meteor-jboulhous-dev/ @vangorra /types/meteor-persistent-session/ @vangorra /types/meteor-prime8consulting-oauth2/ @vangorra -/types/meteor-publish-composite/ @vangorra +/types/meteor-publish-composite/ @vangorra @mrz5018 /types/meteor-roles/ @vangorra @mattmm3d /types/meteor-universe-i18n/ @mathewmeconry /types/method-override/ @santialbo @@ -2842,12 +2944,13 @@ /types/mitm/ @alejo90 /types/mixpanel/ @hjellek @Manduro /types/mixto/ @vvakame -/types/mjml/ @aahoughton +/types/mjml/ @aahoughton @marpstar /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 @@ -2864,6 +2967,7 @@ /types/modernizr/ @borisyankov @theodorejb @leonyu @lucax88x @nhardy /types/modesl/ @neeschit /types/module-alias/ @KevinRamharak +/types/module-deps/ @TeamworkGuy2 /types/moji/ @yasupeke /types/moment-business/ @wonbyte /types/moment-business-time/ @swist @@ -2878,11 +2982,11 @@ /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 +/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-memory-server/ @dmitryrogozhny /types/mongodb-uri/ @mernxl /types/mongoose/v4/ @simonxca @horiuchi @sindrenm @lukasz-zak -/types/mongoose/ @horiuchi @sindrenm @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @jussikinnula @ondratra @alfirin @idandrd @various89 +/types/mongoose/ @horiuchi @sindrenm @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @jussikinnula @ondratra @alfirin @idandrd @various89 @Fazendaaa @NormanPerrin @danmana @stablio /types/mongoose-auto-increment/ @AyaMorisawa /types/mongoose-deep-populate/ @AyaMorisawa /types/mongoose-geojson-schema/ @bondz @@ -2894,6 +2998,7 @@ /types/mongoose-simple-random/ @rsxdalv /types/mongoose-unique-validator/ @stevehipwell /types/mongorito/ @pinguet62 +/types/mongration/ @soulthreads /types/moo/ @deltaidea @MofX /types/moonjs/ @DanielRosenwasser /types/morgan/ @staticfunction @pscanf @@ -2903,6 +3008,7 @@ /types/motor-hat/ @muntyan /types/mousetrap/ @qcz /types/move-concurrently/ @mgroenhoff +/types/moveto/ @shermendev /types/moviedb/ @basarat @0x6368656174 /types/moxios/ @itoasuka /types/mozilla-readability/ @charlesvdv @@ -2919,6 +3025,7 @@ /types/muicss/ @samuelneff /types/multer/ @jt000 @DavidBR-SW @mxl @hyunseob /types/multer-gridfs-storage/v1/ @devconcept +/types/multer-gridfs-storage/v2/ @devconcept /types/multer-gridfs-storage/ @devconcept /types/multer-s3/ @tcaesvk @galtalmor @terski /types/multi-typeof/ @mhegazy @@ -2933,10 +3040,11 @@ /types/murmurhash3js/ @dlee-nvisia /types/musicmetadata/ @Xstoudi /types/mustache/ @markashleybell @manuth +/types/mutexify/ @maistho /types/mv/ @nenadalm /types/mysql/ @wjohnsto @kacepe @kpping @jdmunro /types/mz/ @ThomasHickman -/types/n3/ @phreed @rubensworks +/types/n3/ @phreed @rubensworks @LaurensRietveld /types/named-regexp-groups/ @jewbre /types/named-routes/ @qqilihq /types/nanoajax/ @nathancahill @@ -2974,11 +3082,13 @@ /types/network-interfaces/ @anderswestberg /types/new-relic-browser/ @renehamburger @piotrkubisa /types/newline-remove/ @OpenByteDev -/types/newman/ @LogvinovLeon -/types/newrelic/ @mastermatt +/types/newman/ @LogvinovLeon @Graham42 +/types/newrelic/ @mastermatt @brookspatton /types/nexpect/ @vvakame -/types/next/ @dru89 @brikou @jthegedus @resir014 @scottdj92 @joaovieira +/types/next/ @dru89 @brikou @jthegedus @resir014 @scottdj92 @joaovieira @ajliv +/types/next-redux-saga/ @leocavalcante /types/next-redux-wrapper/ @stevegeek @Jungwoo-An +/types/next-server/ @dru89 @brikou @jthegedus @resir014 @scottdj92 @joaovieira @ajliv /types/ng-command/ @stephenlautier /types/ng-cordova/ @ksachdeva /types/ng-dialog/ @stephenlautier @@ -3007,25 +3117,27 @@ /types/noble/ @swook @shantanubhadoria @lukel99 @bioball @keton @thegecko /types/nock/ @bonnici @horiuchi @afharo @mastermatt @damour @paambaati /types/nodal/ @charrondev -/types/node/v4/ @eps1lon @Archcry -/types/node/v6/ @WilcoBakker @inlined @eps1lon @Alorel @KSXGitHub @Archcry -/types/node/v7/ @parambirs @tellnes @WilcoBakker @eps1lon @KSXGitHub @Archcry -/types/node/v8/ @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/ @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/ @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 @ZaneHannanAU @ThomasdenH @eyqs +/types/node/v0/ @Microsoft @DefinitelyTyped +/types/node/v4/ @Microsoft @DefinitelyTyped @eps1lon @Archcry +/types/node/v6/ @Microsoft @DefinitelyTyped @WilcoBakker @inlined @eps1lon @Alorel @KSXGitHub @Archcry +/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-7z/ @erkie /types/node-array-ext/ @Beng89 /types/node-cache/ @chrootsu @dthunell @useltmann /types/node-calendar/ @luzianz /types/node-cleanup/ @agadar -/types/node-cron/ @maximelkin +/types/node-crate/ @gjednaszewski +/types/node-cron/ @maximelkin @burtek /types/node-dijkstra/ @nokutu /types/node-dir/ @panuhorsmalahti /types/node-dogstatsd/ @chrisbobo /types/node-emoji/ @jonestristand @styu /types/node-fetch/ @torstenwerner @nikcorg /types/node-fibers/ @caryhaynie -/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung +/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung @joeflateau /types/node-gcm/ @horiuchi /types/node-geocoder/ @rosek86 /types/node-getopt/ @kcauchy @@ -3045,6 +3157,7 @@ /types/node-pushnotifications/ @menushka /types/node-ral/ @ssddi456 /types/node-red/ @andersea @tbowmo +/types/node-redis-pubsub/ @renekeijzer /types/node-resque/ @gordey4doronin /types/node-rsa/ @alitaheri @xm /types/node-schedule/ @cyrilschumacher @flowpl @@ -3079,9 +3192,10 @@ /types/nodeunit/ @jedigo /types/noisejs/ @izmhr /types/nomnom/ @panopticoncentral +/types/nookies/ @andreasbergqvist /types/nopt/ @jbondc /types/normalize-package-data/ @jdxcode -/types/normalize-url/ @odin3 @BendingBender +/types/normalize-url/ @odin3 @BendingBender @mathieumg /types/notie/ @mateusdemboski /types/notify/ @hellochar /types/notifyjs/ @soundTricker @NateScarlet @@ -3092,13 +3206,13 @@ /types/nouislider/ @bleuarg @lagaffe /types/novnc-core/ @smithkl42 @BendingBender /types/npm/ @SomaticIT -/types/npm-package-arg/ @mgroenhoff +/types/npm-package-arg/ @mgroenhoff @OiYouYeahYou /types/npm-packlist/ @ajafff /types/npmlog/ @DanielMSchmidt @littlepiggy03 /types/ns-api/ @Archcry /types/nslog/ @unindented /types/nsqjs/ @cezaryrk -/types/nuka-carousel/ @Romic +/types/nuka-carousel/ @Romic @altaudio /types/number-is-nan/ @mhegazy /types/number-to-words/ @frederickfogerty /types/numeral/ @vbortone @BehindTheMath @klujanrosas @@ -3109,13 +3223,15 @@ /types/nvd3/ @PjMitchell /types/nw.gui/ @xperiments /types/nw.js/ @alirdn +/types/nwmatcher/ @woutervh- /types/o.js/ @IceOnFire @bradzacher @janhommes @jcchalte -/types/oauth/ @nonAlgebraic +/types/oauth/ @nonAlgebraic @EduardoAC /types/oauth.js/ @nobuoka /types/oauth2-server/ @vangorra @cirick @d-fischer /types/oauth2orize/ @wokim @heycalmdown @stevehipwell /types/obelisk.js/ @bdrupieski /types/obj-file-parser/ @benc-uk +/types/obj-str/ @saenglert /types/object-assign/ @chbrown /types/object-diff/ @rogierschouten /types/object-hash/ @misak113 @@ -3133,8 +3249,8 @@ /types/oclazyload/ @rolandzwaga /types/odata/ @janhommes @jcchalte /types/ofe/ @Morfent -/types/office-js/ @OfficeDev @LanceEA @Zlatkovsky @kbrandl @Rick-Kirkham @AlexJerabek @ElizabethSamuel-MSFT @mscharlock -/types/office-runtime/ @OfficeDev @mscharlock @kbrandl @Zlatkovsky +/types/office-js/ @OfficeDev @LanceEA @Zlatkovsky @kbrandl @Rick-Kirkham @AlexJerabek @ElizabethSamuel-MSFT +/types/office-runtime/ @Zlatkovsky @mscharlock /types/offline-js/ @cgwrench /types/oibackoff/ @geoffreak /types/oidc-token-manager/ @rosieks @@ -3144,11 +3260,12 @@ /types/omggif/ @ffflorian /types/on-finished/ @czechboy0 @BendingBender /types/on-headers/ @jjeffery @BendingBender +/types/on-wake-up/ @ajafff /types/once/ @denis-sokolov @BendingBender /types/onesignal-cordova-plugin/ @broder /types/onetime/ @BendingBender /types/oniguruma/ @smhxx -/types/onoff/ @marcel-ernst +/types/onoff/ @marcel-ernst @Kallu609 /types/ontime/ @Hirse /types/open/ @Bartvds /types/opener/ @tikurahul @@ -3159,16 +3276,18 @@ /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 +/types/openpgp/ @errietta @damonpam /types/openstack-wrapper/ @sanjaymadane /types/opentok/ @westy92 @CatGuardian /types/opentype.js/ @danmarshall @edzis /types/opn/ @shinnn @SomaticIT @tlent +/types/opossum/ @quinnlangille @lance /types/optics-agent/ @crevil /types/optimist/ @soywiz @chbrown /types/optimize-css-assets-webpack-plugin/ @odnamrataizem /types/ora/v0/ @basarat @screendriver /types/ora/ @basarat @screendriver @BendingBender @azasypkin +/types/oracle__oraclejet/ @nolakara @jingxwu /types/oracledb/ @Bigous /types/orchestrator/ @tkQubo @TeamworkGuy2 /types/orderedmap/ @bradleyayers @@ -3221,6 +3340,7 @@ /types/p-wait-for/ @BendingBender /types/p-whilst/ @BendingBender /types/p2/ @clark-stevenson +/types/p5/ @p5-types /types/package-json/ @jinwoo /types/packery/ @piraveen @hanssens /types/pad/ @mhegazy @@ -3228,10 +3348,11 @@ /types/paho-mqtt/ @amikhalev /types/pako/ @cappellin @calebegg /types/pangu/ @plantain-00 -/types/papaparse/ @torpedro @rainshen49 @jfloff @johnnyreilly @albertorestifo @BehindTheMath @3af +/types/papaparse/ @torpedro @rainshen49 @jfloff @johnnyreilly @albertorestifo @BehindTheMath @3af @jliuhtonen /types/paper/ @clark-stevenson @Xakaloz @sebaswebdev @rfried /types/parallel-transform/ @djcsdy /types/paralleljs/ @jbaldwin +/types/parcel-bundler/ @pinage404 /types/parcel-env/ @fathyb /types/parent-package-json/ @sgmccli /types/parity-pmd/ @leovujanic @jewbre @@ -3261,6 +3382,8 @@ /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-azure-ad/ @ShekharNain /types/passport-beam/ @AtlasDev /types/passport-cognito/ @mbutsykin /types/passport-discord/ @kzay @@ -3277,7 +3400,7 @@ /types/passport-local/ @SomaticIT /types/passport-local-mongoose/ @linusbrolin /types/passport-naver/ @Park9eon @zerocho -/types/passport-oauth2/ @pasieronen @WangZishi +/types/passport-oauth2/ @pasieronen @WangZishi @EduardoAC /types/passport-oauth2-client-password/ @akaNightmare /types/passport-remember-me-extended/ @AylaJK /types/passport-saml/ @cjbarth @dassennato @@ -3285,6 +3408,8 @@ /types/passport-strategy/ @liorm /types/passport-twitter/ @staticfunction /types/passport-unique-token/ @briman0094 @SomaticIT +/types/passport-vkontakte/ @soulthreads +/types/passport-windowsauth/ @forivall /types/password-hash/ @mugeso /types/password-hash-and-salt/ @alitaheri /types/path-exists/v1/ @shiwano @@ -3302,7 +3427,7 @@ /types/pbkdf2/ @timonegk /types/pdfjs-dist/ @jbaldwin /types/pdfkit/ @erichillah -/types/pdfmake/ @m1llen1um @radziksh +/types/pdfmake/ @m1llen1um @radziksh @evolkmann /types/pdfobject/ @nielsboogaard /types/pebblekitjs/ @makotokw /types/peer-dial/ @RealTYPICAL @@ -3310,6 +3435,7 @@ /types/pegjs/ @vvakame @SrTobi @siegebell /types/pem/ @tony19 @DethAriel /types/pem-jwk/ @alessiopcc +/types/permit/ @jannikkeye /types/persona/ @Nycto /types/pet-finder-api/ @me /types/pg/v6/ @pspeter3 @@ -3342,11 +3468,13 @@ /types/pidusage/ @cyrilschumacher @mx601595686 /types/pify/ @samverschueren @mad-mike @c7hm4r /types/pigpio/ @manerfan -/types/pikaday/ @MidnightDesign @wake42 +/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 +/types/pino/ @psnider @BendingBender @screendriver @paambaati @alferpal +/types/pino-http/ @screendriver /types/pino-multi-stream/ @JakeGinnivan /types/pinterest-sdk/ @adamburmister /types/pinyin/ @wanganjun @@ -3361,6 +3489,7 @@ /types/playerframework/ @ricardosabino /types/playmusic/ @nickp10 /types/pleasejs/ @nakakura +/types/plist/ @higuri /types/plotly.js/ @chrisgervang @martinduparc @frederikaalund @taoqf @Dadstart @szechyjs @MercifulCode @soorajpudiyadath @jonfreedman @meganrm /types/plugapi/ @BNedry /types/plugin-error/ @rogierschouten @@ -3382,6 +3511,9 @@ /types/popcorn/ @grapswiz /types/portscanner/ @douglasduteil /types/postal/ @lokeshpeta @myitcv +/types/postcss-calc/ @huan086 +/types/postcss-icss-values/ @huan086 +/types/postcss-modules-resolve-imports/ @huan086 /types/postman-collection/ @kbuzby /types/postmark/ @benbayard @jineshshah36 /types/pouch-redux-middleware/ @charrondev @@ -3395,7 +3527,7 @@ /types/pouchdb-adapter-node-websql/ @spaulg @geppy @fredgalvao /types/pouchdb-adapter-websql/ @spaulg @geppy @fredgalvao /types/pouchdb-browser/ @spaulg @geppy @fredgalvao -/types/pouchdb-core/ @spaulg @trubit @geppy @fredgalvao @TobiasBales @tiangolo +/types/pouchdb-core/ @spaulg @trubit @geppy @fredgalvao @TobiasBales @tiangolo @kmoe /types/pouchdb-find/ @trubit @tiangolo /types/pouchdb-http/ @spaulg @geppy @fredgalvao /types/pouchdb-mapreduce/ @spaulg @geppy @fredgalvao @@ -3445,6 +3577,7 @@ /types/prompt-sync/ @MugeSo /types/prompt-sync-history/ @MugeSo /types/promptly/ @danrspencer +/types/prompts/ @Berkays /types/prop-types/ @DovydasNavickas @ferdaber /types/proper-lockfile/ @qlonik /types/properties-reader/ @Goldsmith42 @@ -3464,7 +3597,7 @@ /types/prosemirror-tables/ @superchu @eshvedai @patsimm /types/prosemirror-transform/ @bradleyayers @davidka @timjb @patsimm /types/prosemirror-view/ @bradleyayers @davidka @timjb @patsimm -/types/proton-native/ @khanhas +/types/proton-native/ @khanhas @ltetzlaff /types/protractor-browser-logs/ @rokadias /types/protractor-helpers/ @johncant /types/protractor-http-mock/ @Crevil @@ -3485,7 +3618,8 @@ /types/pumpify/ @JustinBeckwith @aoberoi /types/pupa/ @nju33 /types/puppeteer/v0/ @marvinhagemeister @cdeutsch -/types/puppeteer/ @marvinhagemeister @cdeutsch @ksm2 +/types/puppeteer/ @marvinhagemeister @cdeutsch @ksm2 @SimonSchick +/types/puppeteer-core/ @mtsmfm /types/pure-render-decorator/ @seansfkelley /types/purl/ @danfma /types/pusher-js/ @tkqubo @cainlevy @@ -3498,7 +3632,7 @@ /types/qhistory/ @Kovensky /types/qiniu-js/ @taoqf /types/qlik/ @RubenSlabbert @AginicX -/types/qlik-engineapi/ @konne +/types/qlik-engineapi/ @konne @richardison /types/qlik-visualizationextensions/ @konne /types/qr-image/ @taoqf /types/qrcode/ @plantain-00 @@ -3519,7 +3653,7 @@ /types/rabbit.js/ @wokim /types/radium/ @alexgorbatchev @nupplaphil @asvetliakov /types/radius/ @codeanimal -/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 +/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-js/ @pistacchio /types/random-number/ @OpenByteDev /types/random-seed/ @endel @@ -3543,23 +3677,26 @@ /types/raty/ @terrawheat /types/raven/ @scttcper @1999 @shreyjain1994 /types/raven-for-redux/ @chiubaka -/types/raygun4js/ @xt0rted @BenjaminHarding +/types/raygun/ @UberMouse +/types/raygun4js/ @xt0rted @BenjaminHarding @UberMouse /types/rbac-a/ @tlaziuk /types/rc/ @DanielRosenwasser /types/rc-select/ @DenisTirilis /types/rc-slider/ @mantasmarcinkus @mattoni @paustint @j-fro @Deanna2 +/types/rc-time-picker/ @Hoff97 /types/rc-tree/ @johnnyreilly @Methuselah96 /types/rcloader/ @panuhorsmalahti /types/rdf-data-model/ @rubensworks -/types/rdf-js/ @rubensworks +/types/rdf-js/ @rubensworks @LaurensRietveld /types/rdflib/ @cenotelie /types/re-base/ @jordandrako /types/reach__router/ @kingdaro /types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz /types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei /types/react-adal/ @dkorolev1 -/types/react-albus/ @sseppola -/types/react-alert/ @ssyrell +/types/react-albus/ @sseppola @conradreuter @kuirak +/types/react-alert/v2/ @ssyrell +/types/react-alert/ @g1eny0ung /types/react-alice-carousel/ @endigo /types/react-amplitude/ @rayzor65 /types/react-animate-on-scroll/ @ralbuque @@ -3570,6 +3707,7 @@ /types/react-autosuggest/ @nicolas-schmitt @pjo256 @robessog @tbayne @cdeutsch @rosskevin /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-body-classname/ @mhegazy /types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @mretolaza @katbusch @vitosamson @LKay @aaronbeall @jrakotoharisoa @r3nya @t49tran @@ -3578,7 +3716,7 @@ /types/react-bootstrap-table/v2/ @flaub @alelode @UJosue10 /types/react-bootstrap-table/ @flaub @alelode @UJosue10 @dawnmist @Ogglas /types/react-bootstrap-typeahead/ @Guymestef @radziksh @PaitoAnderson -/types/react-breadcrumbs/ @KostyaEsmukov +/types/react-breadcrumbs/ @guoyunhe /types/react-breadcrumbs-dynamic/ @mitsuruog /types/react-broadcast/ @kandros /types/react-burger-menu/ @radziksh @@ -3587,6 +3725,7 @@ /types/react-cartographer/ @trevonmckay /types/react-circular-progressbar/ @lstanden /types/react-click-outside/ @screendriver +/types/react-close-on-escape/ @JamesAlias /types/react-codemirror/ @velveret @rudi-c /types/react-coinhive/ @sktbcbbs /types/react-collapse/ @Kimahriman @@ -3596,6 +3735,7 @@ /types/react-content-loader/ @alaatm @samwalshnz /types/react-copy-to-clipboard/ @mabels @BernabeFelix /types/react-copy-write/ @samhh @davej +/types/react-countup/ @danielbrodin /types/react-credit-cards/ @vstrimaitis @olefrank /types/react-cropper/ @stepancar /types/react-css-modules/ @KostyaEsmukov @skirsdeda @@ -3609,15 +3749,17 @@ /types/react-datagrid/ @stephenjelfs /types/react-date-range/ @Junbong /types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue @KoalaHuman @seansfkelley -/types/react-daterange-picker/ @uncovertruth @MartynasZilinskas @donaldtf +/types/react-daterange-picker/ @uncovertruth @MartynasZilinskas @donaldtf @vladflorescu94 /types/react-dates/ @ArturAmpilogov @NathanNZ /types/react-daum-postcode/ @Sa-ryong /types/react-dnd-multi-backend/ @dawnmist @beeequeue /types/react-dnd-touch-backend/ @mleko @dawnmist @beeequeue +/types/react-document-meta/ @ulrichb /types/react-document-title/ @cleverguy25 /types/react-dom/v15/ @MartynasZilinskas /types/react-dom/ @MartynasZilinskas @theruther4d /types/react-dom-factories/ @jgoz +/types/react-draft-wysiwyg/ @imechZhangLY /types/react-dragtastic/ @nscarcella /types/react-dropzone/v2/ @matdube @LynxEyes @goblindegook @benbayard /types/react-dropzone/v3/ @matdube @LynxEyes @goblindegook @benbayard @LKay @@ -3627,6 +3769,7 @@ /types/react-event-listener/ @asvetliakov /types/react-fa/ @flaub @patsissons @LKay /types/react-facebook-login/ @apare @jankarres +/types/react-facebook-login-component/ @koss-lebedev /types/react-faux-dom/ @alitaheri @cleverguy25 @deviousm @hanai /types/react-file-input/ @dmitryrogozhny /types/react-file-reader-input/ @dmitryrogozhny @alitaheri @@ -3642,6 +3785,7 @@ /types/react-gateway/ @jsonunger /types/react-geosuggest/ @brmenchl /types/react-global-configuration/ @ryokik +/types/react-google-login-component/ @koss-lebedev /types/react-google-maps-loader/ @vasilysn /types/react-google-places-suggest/ @vasilysn /types/react-google-recaptcha/ @KoalaHuman @@ -3654,38 +3798,43 @@ /types/react-helmet/ @evanbb @isman-usoh @lith-light-g @sammkj @yuit /types/react-helmet-async/ @forabi /types/react-highlight/ @joshuakgoldberg -/types/react-highlight-words/ @mhegazy @diogodca +/types/react-highlight-words/ @mhegazy @diogodca @kellyrmilligan /types/react-highlighter/ @oizie /types/react-holder/ @isman-usoh /types/react-hot-loader/ @jacekjagiello @MartynasZilinskas @DovydasNavickas /types/react-hyperscript/ @tock203 -/types/react-i18next/v1/ @KostyaEsmukov -/types/react-i18next/v4/ @GiedriusGrabauskas @netanelgilad -/types/react-i18next/ @GiedriusGrabauskas @chnoch @beheh @whtsky /types/react-icon-base/ @apare @LKay /types/react-icons/ @apare @johnnyreilly @LKay /types/react-image-crop/ @danielasy +/types/react-image-fallback/ @8enSmith /types/react-image-gallery/ @adamwpc /types/react-imageloader/ @stephenjelfs +/types/react-images/ @KonstantinLukaschenko +/types/react-imgpro/ @echoulen /types/react-infinite/ @rhysd /types/react-infinite-calendar/ @christianchown -/types/react-infinite-scroll-component/ @sroy3 @burtek @davidkevork -/types/react-infinite-scroller/ @Lapanti @psrebniak +/types/react-infinite-scroll-component/ @sroy3 @burtek @davidkevork @JoshuaScript +/types/react-infinite-scroller/ @Lapanti @psrebniak @WrathZA /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-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-redux/ @LKay -/types/react-is/ @AviVahl +/types/react-is/ @AviVahl @christianchown /types/react-is-deprecated/ @seansfkelley -/types/react-joyride/ @kdy1 +/types/react-joyride/ @kdy1 @kamranayub /types/react-js-pagination/ @netoisc /types/react-json/ @spielc /types/react-json-pretty/ @LKay /types/react-json-tree/ @gnestor -/types/react-jsonschema-form/ @iamdanfox @iplus26 @KurtPreston @phbou72 @LucianBuzzo +/types/react-jsonschema-form/ @iamdanfox @iplus26 @KurtPreston @phbou72 @LucianBuzzo @sthenault @sbusch +/types/react-jss/ @eps1lon /types/react-lazyload/ @m0a /types/react-lazylog/ @benjaminRomano /types/react-leaflet/ @danzel @davschne @yuit @@ -3693,24 +3842,26 @@ /types/react-list/ @buptyyf @tomshen /types/react-loadable/ @Kovensky @odensc @ianks @tlaziuk @iMobs /types/react-loader/ @artfuldev +/types/react-lottie/ @Kana00 @Ricki-BumbleDev /types/react-mailchimp-subscribe/ @osdiab /types/react-map-gl/ @rimig @fnberta /types/react-maskedinput/ @LKay @lavoaster @CarlosBonetti /types/react-mce/ @morphologue /types/react-mdl/ @bradzacher /types/react-measure/ @asvetliakov @marcfallows +/types/react-mentions/ @activescott /types/react-mixin/ @tkqubo -/types/react-modal/ @radziksh @drewnoakes @homburg @ttamminen @hallowatcher @peterblazejewicz +/types/react-modal/ @radziksh @drewnoakes @homburg @ttamminen @hallowatcher @peterblazejewicz @jpowell /types/react-motion/ @stepancar @asvetliakov @dimitarnestorov /types/react-motion-slider/ @asvetliakov /types/react-motion-ui-pack/ @jsonunger -/types/react-native/ @alloy @huhuanming @iRoachie @timwangdev @kamal @nelyousfi @alexdunne @swissmanu @bm-software @tkrotoff @a-tarasyuk @mvdam +/types/react-native/ @alloy @huhuanming @iRoachie @skn0tt @timwangdev @kamal @nelyousfi @alexdunne @swissmanu @bm-software @tkrotoff @a-tarasyuk @mvdam @esemesek @mrnickel /types/react-native-android-taskdescription/ @christianchown /types/react-native-auth0/ @ascariandrea /types/react-native-autocomplete-input/ @ifiokjr /types/react-native-background-timer/ @chillkroeteTTS /types/react-native-bluetooth-serial/ @RodrigoAWeber -/types/react-native-calendars/ @Tyler-Zhang @DavidNorena +/types/react-native-calendars/ @Tyler-Zhang @DavidNorena @FabianMeul /types/react-native-communications/ @huhuanming @PaitoAnderson /types/react-native-custom-tabs/ @philnova /types/react-native-datepicker/ @jacobbaskin @@ -3725,8 +3876,9 @@ /types/react-native-fbsdk/ @ifiokjr /types/react-native-fetch-blob/ @MNBuyskih /types/react-native-fs/ @pocesar @josephroque -/types/react-native-google-signin/ @j-fro +/types/react-native-google-signin/ @j-fro @bm-software @christianchown @echentw /types/react-native-htmlview/ @ifiokjr +/types/react-native-huawei-protected-apps/ @christianchown /types/react-native-i18n/ @VincentLanglet /types/react-native-indicators/ @ifiokjr /types/react-native-keep-awake/ @huhuanming @@ -3748,7 +3900,10 @@ /types/react-native-popup-dialog/ @PaitoAnderson @connectdotz @bm-software /types/react-native-push-notification/ @PaitoAnderson @tomSawkins /types/react-native-qrcode/ @plantain-00 +/types/react-native-referrer/ @christianchown +/types/react-native-restart/ @christianchown /types/react-native-safari-view/ @mrand01 +/types/react-native-scaled-image/ @Jaeger25 /types/react-native-scrollable-tab-view/ @CaiHuan @egorshulga /types/react-native-sensor-manager/ @SahinVardar /types/react-native-settings-list/ @MrLuje @@ -3758,6 +3913,7 @@ /types/react-native-sortable-list/ @sivolobov @RookY2K /types/react-native-sqlite-storage/ @dryganets @cavarzan /types/react-native-star-rating/ @iRoachie +/types/react-native-status-bar-height/ @fiznool /types/react-native-svg-charts/ @krzysztof-miemiec /types/react-native-svg-uri/ @iRoachie /types/react-native-swiper/ @CaiHuan @huhuanming @mhcgrq @@ -3766,11 +3922,12 @@ /types/react-native-text-input-mask/ @RodrigoAWeber /types/react-native-toast-native/ @bm-software /types/react-native-touch-id/ @huhuanming @gazaret @jinshin1013 +/types/react-native-uuid-generator/ @burtek /types/react-native-vector-icons/ @iRoachie @timwangdev /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 +/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-material-bottom-tabs/ @iRoachie /types/react-no-ssr/ @rafalfilipek /types/react-notification-system/ @GiedriusGrabauskas @DeividasBakanas @LKay @sztobar @@ -3778,8 +3935,9 @@ /types/react-notify-toast/ @klaascuvelier /types/react-numeric-input/ @heatherbooker @akx /types/react-onclickoutside/v5/ @LKay -/types/react-onclickoutside/ @LKay -/types/react-onsenui/ @salim7 @jemmyw +/types/react-onclickoutside/ @LKay @surgeboris +/types/react-onsenui/ @salim7 @jemmyw @lirbank +/types/react-outside-click-handler/ @zubivan /types/react-overlays/ @aaronbeall @vitosamson /types/react-owl-carousel/ @tbounsiar @igorissen @KennethanCeyer /types/react-paginate/v4/ @deevus @wouterhardeman @pegel03 @archy-bold @@ -3795,6 +3953,7 @@ /types/react-qr-reader/ @davidkevork /types/react-radio-group/ @jsonunger /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-epic/ @forabi @@ -3808,8 +3967,8 @@ /types/react-responsive/ @asvetliakov @alechill @xaviergonz /types/react-rnd/ @Ragg- @fsubal @zyh825 /types/react-router/v2/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov -/types/react-router/v3/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @ssorallen @gillchristian -/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 +/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-dom/ @tkrotoff @huy-nguyen @p-jackson @johnnyreilly @@ -3841,7 +4000,9 @@ /types/react-sparklines/ @henrinormak /types/react-spinkit/v1/ @tkqubo @mleko @pelotom /types/react-spinkit/ @tkqubo @mleko @pelotom @zzanol +/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 @@ -3851,10 +4012,11 @@ /types/react-swipe/ @DeividasBakanas /types/react-swipeable/ @GiedriusGrabauskas @mctep @horiuchi /types/react-swipeable-views/ @mxl @DeividasBakanas -/types/react-syntax-highlighter/ @NoHomey -/types/react-table/ @royxue @psakalo @Havret +/types/react-syntax-highlighter/ @NoHomey @ajgamble-milner +/types/react-table/ @royxue @psakalo @Havret @andys8 /types/react-table-filter/ @gjsln -/types/react-tabs/ @danez +/types/react-tabs/ @danez @Equationist +/types/react-tag-autocomplete/ @jlismore /types/react-tag-input/ @Ogglas @jankarres @matthewberryman /types/react-tagcloud/ @wassname /types/react-tagsinput/ @mykter @@ -3864,6 +4026,7 @@ /types/react-tether/ @ryprice /types/react-text-mask/ @guilhermehubner @cavarzan @needpower /types/react-textarea-autosize/ @asvetliakov @zry656565 +/types/react-timeago/ @koss-lebedev /types/react-timeout/ @kerwynrg /types/react-toastify/ @icopp /types/react-toastr/ @shssoichiro @DanRegazzi @@ -3882,11 +4045,13 @@ /types/react-virtual-keyboard/ @bsurai /types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @kraenhansen @Stevearzh @mgoszcz2 @brandonhall /types/react-virtualized-select/ @seansfkelley +/types/react-visibility-sensor/ @JRasmusBm /types/react-webcam/ @squat /types/react-weui/ @tairan -/types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 @r3nya @MBillemaz +/types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 @r3nya @MBillemaz @georg94 /types/react-widgets-moment/ @dawnmist /types/react-window/ @martynaskadisa +/types/react-window-size/ @jakejrichards /types/react-youtube/ @kgtkr /types/react-youtube-embed/ @charles-salmon /types/reactable/ @spielc @@ -3903,16 +4068,20 @@ /types/readline-sync/ @jonestristand /types/readline-transform/ @dex4er /types/reapop/ @Barrokgl +/types/rebass/ @ryee-dev +/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-scale/ @johnnyreilly /types/recluster/ @dex4er -/types/recompose/ @iskandersierra @mrapogee @clayne11 @Pajn @lucasterra +/types/recompose/ @iskandersierra @mrapogee @clayne11 @Pajn @lucasterra @brian-lives-outdoors /types/reconnect-core/ @thw0rted /types/reconnectingwebsocket/ @nguarracino +/types/recorder-js/ @higuri /types/recursive-readdir/v1/ @elisee /types/recursive-readdir/ @elisee @MicahZoltu -/types/redis/ @soywiz @CodeAnimal @MugeSo @UppaJung @Rokt33r @43081j @barnski +/types/redis/ @soywiz @CodeAnimal @MugeSo @UppaJung @Rokt33r @43081j @barnski @1pete /types/redis-errors/ @43081j /types/redis-mock/ @BendingBender /types/redis-rate-limiter/ @westy92 @@ -3923,7 +4092,7 @@ /types/reduce-reducers/ @huy-nguyen /types/redux-action/ @newraina /types/redux-action-utils/ @tkqubo -/types/redux-actions/ @jaysoo @alexgorbatchev @alechill @alexey-pelykh +/types/redux-actions/ @jaysoo @alexgorbatchev @alechill @alexey-pelykh @7hi4g0 /types/redux-async-queue/ @andreiho /types/redux-auth-wrapper/v1/ @LKay /types/redux-auth-wrapper/ @LKay @@ -3933,14 +4102,15 @@ /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 +/types/redux-first-router/ @Valbrand @viggyfresh @janb87 @corydeppen @jscinoz @surgeboris /types/redux-first-router-link/ @janb87 /types/redux-first-router-restore-scroll/ @icopp /types/redux-first-routing/ @tlaziuk /types/redux-form/v4/ @aikoven /types/redux-form/v6/ @carsonf @aikoven @LKay @bancek -/types/redux-form/ @carsonf @aikoven @LKay @bancek @alsiola @tehbi4 @huwmartin @ethanresnick @reggino @maddijoyce -/types/redux-immutable/ @oizie @sebald @gavingregory +/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-infinite-scroll/ @silkyfray /types/redux-injectable-store/ @unindented @@ -3982,13 +4152,15 @@ /types/relateurl/ @tkrotoff /types/relaxed-json/ @18steps /types/relay-runtime/ @voxmatt @alloy +/types/rellax/ @shermendev /types/remarkable/ @makepost /types/remote-redux-devtools/ @ColinEberhardt @unindented @mamodom @colindekker /types/remove-markdown/ @RagibHasin /types/rename/ @Aankhen /types/replace-ext/ @DeividasBakanas +/types/replacestream/ @dex4er /types/req-cwd/ @Alorel -/types/request/ @soywiz @bonnici @Bartvds @joeskeen @ccurrens @lookfirst @mastermatt @josecolella +/types/request/ @soywiz @bonnici @Bartvds @joeskeen @ccurrens @lookfirst @mastermatt @josecolella @murbanowicz /types/request-as-curl/ @atd-schubert /types/request-ip/ @mrhen /types/request-promise/ @cglantschnig @joeskeen @AyaMorisawa @mastermatt @@ -4007,7 +4179,7 @@ /types/resolve/ @marionebl @ajafff /types/resolve-from/ @unional /types/resourcejs/ @shaunluttin -/types/response-time/ @urossmolnik @TonyPythoneer +/types/response-time/ @urossmolnik @TonyPythoneer @danmana /types/rest/ @Nemo157 /types/restangular/ @borisyankov /types/restful.js/ @tkqubo @@ -4045,6 +4217,7 @@ /types/rmfr/ @pluma /types/roads/ @dancespiele /types/roads-server/ @dancespiele +/types/rocksdb/ @MeirionHughes @danwbyrne /types/roll/ @icopp /types/rolling-rate-limiter/ @l-jonas /types/rollup-plugin-json/ @asmockler @hotell @@ -4055,7 +4228,7 @@ /types/round-to/ @seangenabe /types/route-parser/ @ianks @bobbuehler /types/routie/ @Adilson -/types/royalslider/ @csrakowski +/types/royalslider/ @csrakowski @sKopheK /types/rpio/ @DominikPalo @Pencl /types/rrc/ @DeividasBakanas /types/rsmq/ @MugeSo @@ -4111,11 +4284,13 @@ /types/satnav/ @DotNetNerd /types/saywhen/ @SeanSobey /types/scalike/ @ryoppy +/types/schedule/ @Methuselah96 +/types/scheduler/ @Methuselah96 /types/schema-registry/ @bonzzy /types/schwifty/ @ozum /types/scoped-http-client/ @mattvperry @rianadon /types/screenfull/ @icholy @lionelb @joelshepherd -/types/screeps/ @MarkoSulamagi @NhanHo @bryanbecker @resir014 @Arcath @apemanzilla +/types/screeps/ @MarkoSulamagi @NhanHo @bryanbecker @resir014 @Arcath @dmarcuse /types/screeps-profiler/ @ramblurr /types/scriptjs/ @ssttevee /types/scroll-into-view/ @zivni @@ -4128,7 +4303,8 @@ /types/scryptsy/ @micksatana /types/sdp-transform/ @loc /types/seamless/ @danmana -/types/seamless-immutable/ @alex3165 @xsburg @geirsagberg +/types/seamless-immutable/ @alex3165 @xsburg @geirsagberg @RMHonor +/types/season/ @dex4er /types/secp256k1/ @anler /types/seed-random/ @l-jonas /types/seededshuffle/ @urish @@ -4171,33 +4347,36 @@ /types/send/ @MikeJerred /types/seneca/ @psnider @kevynb /types/sequelize/v3/ @samuelneff @codeanimal @drinchev @morpheusxaut @torhal -/types/sequelize/ @samuelneff @codeanimal @drinchev @babolivier @kukoo1 @oktapodia @morpheusxaut @TitaneBoy @zjy01 @nidzov @Raigen @todd @nrschultz @thomas-b +/types/sequelize/ @samuelneff @codeanimal @drinchev @babolivier @kukoo1 @oktapodia @morpheusxaut @TitaneBoy @zjy01 @nidzov @Raigen @todd @nrschultz @thomas-b @Antoine38660 /types/sequelize-cursor-pagination/ @pilagod /types/sequelize-fixtures/ @cschwarz /types/sequencify/ @npenin /types/sequester/ @Strate /types/serialize-error/ @thomasthiebaud -/types/serialize-javascript/ @lith-light-g +/types/serialize-javascript/ @lith-light-g @Pochodaydayup /types/serialport/v4/ @codefoster +/types/serialport/v6/ @codefoster @apearson /types/serialport/ @codefoster @apearson /types/serve-favicon/ @urossmolnik /types/serve-index/ @tkrotoff /types/serve-static/ @urossmolnik @LinusU /types/server/ @sant123 @iddan /types/server-destroy/ @gyszalai +/types/serverless/ @hassankhan /types/servicenow/ @bryceg /types/session-file-store/ @blendsdk @rokt33r /types/set-cookie-parser/ @nickp10 /types/set-value/ @DanielRosenwasser /types/settings/ @shreyjain1994 /types/sha1/ @arcdev1 +/types/sha256/ @nhardy /types/shallow-equals/ @rsolomon /types/shallowequal/ @seansfkelley /types/shapefile/ @DenisCarriere @Thw0rted /types/sharedb/ @soney /types/sharedworker/ @nakakura /types/sharepoint/ @gandjustas @andrei-markeev @baywet @teroarvola @dennispg -/types/sharp/ @lith-light-g @wooseopkim +/types/sharp/ @lith-light-g @wooseopkim @BTOdell /types/sheetify/ @toddself /types/shell-escape/ @nenadalm /types/shell-quote/ @jason0x43 @@ -4208,10 +4387,12 @@ /types/shipit-utils/ @cyrilschumacher /types/shopify-buy/ @openminder @straiforos @totemika /types/shortid/ @stpettersens @despairblue -/types/shot/ @AJamesPhillips +/types/shot/v3/ @AJamesPhillips @SimonSchick +/types/shot/ @AJamesPhillips @SimonSchick /types/should-sinon/ @Arylo /types/showdown/ @cbowdon @tan9 @arielsaldana /types/shrink-ray/ @forabi +/types/shuffle-seed/ @LeartS /types/siema/ @Irmiz @0x6368656174 @samnau /types/siesta/ @bquarmby /types/sigmajs/ @qinfchen @@ -4236,9 +4417,10 @@ /types/simplemde/ @Scalesoft /types/simplesmtp/ @rogierschouten /types/simplestorage.js/ @axelcostaspena @mxl +/types/sindresorhus__df/ @whatknight /types/single-line-log/ @ffflorian /types/single-spa-react/ @Garrett-Smith-iq -/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg +/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg @gjednaszewski /types/sinon-as-promised/ @igrayson /types/sinon-chai/v2/ @kazimanzurrashid @jedmao /types/sinon-chai/ @kazimanzurrashid @jedmao @elpdpt @@ -4261,12 +4443,12 @@ /types/slack-winston/ @BlueHatbRit /types/slackdown/ @nju33 /types/slackify-html/ @hypexr -/types/slate/ @andykent @majelbstoat @JanLoebel @YangusKhan @kalley @Kornil @isubasti +/types/slate/ @andykent @majelbstoat @JanLoebel @YangusKhan @kalley @Kornil @isubasti @sgreav /types/slate-base64-serializer/ @YangusKhan /types/slate-html-serializer/ @YangusKhan /types/slate-irc/ @elisee -/types/slate-plain-serializer/ @YangusKhan -/types/slate-react/ @andykent @majelbstoat @JanLoebel @PatrickSachs @YangusKhan @isubasti +/types/slate-plain-serializer/ @YangusKhan @mkiefel +/types/slate-react/ @andykent @majelbstoat @JanLoebel @PatrickSachs @YangusKhan @isubasti @sgreav /types/sleep/ @rajarz /types/slickgrid/ @jbaldwin /types/slideout/ @ToastHawaii @@ -4283,7 +4465,9 @@ /types/snazzy-info-window/ @milosd92 /types/snekfetch/ @ANekoIsFineToo @ShayBox @Dev-Yukine /types/snoowrap/ @vitosamson @TheAppleFreak +/types/snowball-stemmers/ @ryanvolum /types/snowboy/ @dolanmiu +/types/socket.io/v1/ @progre @divillysausages @florentpoujol @KentarouTakeda @gigi @BrainMaestro /types/socket.io/ @progre @divillysausages @florentpoujol @KentarouTakeda @gigi @BrainMaestro /types/socket.io-client/ @progre @divillysausages @florentpoujol /types/socket.io-p2p/ @saenglert @@ -4299,8 +4483,9 @@ /types/solidity-parser-antlr/ @LogvinovLeon @albrow /types/solr-client/ @liul85 /types/solution-center-communicator/ @dami-gg +/types/sonic-boom/ @alferpal /types/sort-array/ @mrmlnc -/types/sortablejs/ @Maw-Fox +/types/sortablejs/ @Maw-Fox @maartenstaa /types/soundmanager2/ @elton2048 /types/soupbintcp/ @jewbre /types/source-list-map/ @e-cloud @@ -4327,7 +4512,7 @@ /types/spotify-api/ @skovmand /types/spotify-web-playback-sdk/ @Festify @mraerino @NeoLegends /types/sprintf/ @soywiz @BendingBender -/types/sprintf-js/ @jasonswearingen @BendingBender +/types/sprintf-js/ @jasonswearingen @BendingBender @cdagli /types/sql-bricks/ @adn05 @paleo /types/sql.js/ @Hozuki /types/sqlanywhere/ @pkeuter @@ -4336,7 +4521,7 @@ /types/squirejs/ @bradleyayers /types/srp/ @Patman64 /types/ssh-key-decrypt/ @BendingBender -/types/ssh2/ @tkQubo @rbuckton +/types/ssh2/ @tkQubo @rbuckton @wrboyce /types/ssh2-sftp-client/ @igrayson @ascariandrea @kartik2406 /types/ssh2-streams/ @rbuckton /types/sshpk/ @mabels @@ -4348,6 +4533,8 @@ /types/stampit/v2/ @koresar /types/stampit/ @koresar @lummish /types/stamplay-js-sdk/ @ridermansb +/types/standard-error/ @roblabat +/types/standard-http-error/ @roblabat /types/starwars-names/ @claasahl /types/stat-mode/ @BendingBender /types/stats.js/ @gregolai @hberntsen @danvk @@ -4360,13 +4547,16 @@ /types/steam-totp/ @phenomax /types/steamid/ @Slessi /types/steed/ @Paul-Isache -/types/stellar-sdk/ @carl-foster @tristonj @pselden @maxbause +/types/stellar-sdk/ @carl-foster @tristonj @pselden @maxbause @charlie-wasp /types/stemmer/ @will-ockmore /types/sticky-cluster/ @paustint +/types/stompit/ @DanielRose /types/stompjs/ @jimic @Dr4k4n /types/stoppable/ @EricByers +/types/storage-helper/ @ajafff /types/store/ @vbortone @harry0000 @Ky6uk /types/storybook-addon-jsx/ @jameslnewell +/types/storybook-readme/ @lonyele /types/storybook__addon-a11y/ @hyunseob /types/storybook__addon-actions/ @joscha @jicjjang /types/storybook__addon-backgrounds/ @hyunseob @@ -4381,6 +4571,7 @@ /types/storybook__react/ @joscha @wapgear /types/storybook__react-native/ @joscha @wapgear @alechill @iRoachie /types/storybook__vue/ @pntgupta +/types/stream-array/ @Tyler-Murphy /types/stream-buffers/ @Jason3S /types/stream-chain/ @uhop /types/stream-csv-as-json/ @uhop @@ -4399,8 +4590,10 @@ /types/strftime/ @cyrilschumacher /types/strict-uri-encode/ @hoishin /types/string/ @basp +/types/string-argv/ @vladimir-tikhonov /types/string-format/ @lal12 /types/string-hash/ @ethanrubio +/types/string-replace-webpack-plugin/ @pd4d10 /types/string-similarity/ @ragtime /types/string-template/ @TonyPythoneer /types/string-width/ @jacobbubu @@ -4409,7 +4602,7 @@ /types/strip-ansi/ @mhegazy /types/strip-bom/ @mhegazy /types/strip-json-comments/ @dmoonfire -/types/stripe/ @wjohnsto @codeanimal @sampsonjoliver @LinusU @brannon @kkamperschroer @starhoshi @bruun @galtalmor @htunnicliff @squirly @tzarger +/types/stripe/ @wjohnsto @codeanimal @sampsonjoliver @LinusU @brannon @kkamperschroer @starhoshi @bruun @galtalmor @htunnicliff @squirly @tzarger @ifiokjr /types/stripe-checkout/ @cgwrench /types/stripe-v2/ @ejsmith @amritk @adamcmiel @jleider @galuszkak /types/stripe-v3/ @ejsmith @amritk @adamcmiel @jleider @galuszkak @@ -4418,16 +4611,22 @@ /types/strong-error-handler/ @blankstar85 /types/strong-log-transformer/ @azasypkin /types/strophe/ @DavidKDeutsch +/types/strophe.js/ @DavidKDeutsch /types/structured-source/ @azu -/types/styled-components/ @Igorbek @Igmat +/types/styled-components/v3/ @Igorbek @Igmat +/types/styled-components/ @Igorbek @Igmat @lavoaster /types/styled-jsx/ @R1ZZU -/types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh @lavoaster +/types/styled-react-modal/ @Lavoaster +/types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh @lavoaster @jschuler +/types/styled-theming/ @ArjanJ /types/stylelint/v7/ @alan-agius4 -/types/stylelint/ @alan-agius4 +/types/stylelint/ @alan-agius4 @filipsalpe /types/stylelint-webpack-plugin/ @bahlo +/types/stylenames/ @bengry /types/stylus/ @SomaticIT /types/subscribe-ui-event/ @wangcheng678 /types/subsume/ @BendingBender +/types/subtitle/ @jenglamlow /types/succinct/ @EnableSoftware /types/sudo-block/ @BendingBender /types/suitescript/ @darrenhillconsulting @@ -4468,7 +4667,7 @@ /types/swagger-parser/ @Tobias4872 @EricHenry /types/swagger-restify-mw/ @micmro /types/swagger-sails-hook/ @micmro -/types/swagger-schema-official/ @mohsen1 @bsouthga @nimerritt +/types/swagger-schema-official/ @mohsen1 @bsouthga @nimerritt @mauriedo /types/swagger-tools/ @bricka /types/swagger-ui-dist/ @haowen737 /types/swagger-ui-express/ @dmitryrogozhny @@ -4480,7 +4679,7 @@ /types/swig-email-templates/ @mrhen @micksatana /types/swipe/ @kant2002 /types/swiper/v3/ @sgaliano @lucax88x -/types/swiper/ @sgaliano @lucax88x @ematseruk @odahcam +/types/swiper/ @sgaliano @lucax88x @ematseruk @odahcam @jmca /types/swipeview/ @borisyankov /types/switchery/ @bgrieder @claylaut /types/swiz/ @jedigo @@ -4488,6 +4687,7 @@ /types/synaptic/ @ToastHawaii @austincummings /types/systeminformation/ @PixelcrabAT /types/systemjs/ @ludohenin @NathanWalker @GiedriusGrabauskas @aluanhaddad +/types/tabbable/ @mokkan /types/table/ @evanshortiss @mrmlnc /types/tableau/ @protip /types/tabris-plugin-firebase/ @eclipsesource @@ -4502,6 +4702,7 @@ /types/tar-stream/ @glicht /types/task-graph-runner/ @mgroenhoff /types/tcp-ping/ @stegano +/types/tcp-port-used/ @gautejohan /types/teddy/ @lannonbr /types/tedious/ @rogierschouten @cjthompson @v-suhame /types/tedious-connection-pool/ @sandorfr @@ -4509,24 +4710,29 @@ /types/temp/ @DanielRosenwasser /types/temp-write/ @BendingBender /types/tempfile/ @SamVerschueren @BendingBender -/types/tempy/ @douglasduteil +/types/tempy/ @douglasduteil @maistho /types/terminal-menu/ @aravindarun +/types/tern/ @nkappler +/types/terser/ @JordiAnderl +/types/test-console/ @roberto @guidoux @gbmoretti /types/test-listen/ @stephenmathieson /types/testingbot-api/ @timbru31 /types/tether/ @adidahiya /types/tether-drop/ @adidahiya /types/tether-shepherd/ @mtgibbs /types/text-buffer/ @GlenCFL -/types/text-encoding/ @pine613 @mohsen1 +/types/text-encoding/ @pine613 @mohsen1 @nwmqpa /types/text-encoding-utf-8/ @trxcllnt /types/text-table/ @saadq /types/textarea-caret/ @shiftkey /types/textract/ @lal12 /types/textversionjs/ @aaronosher +/types/texzilla/ @m93a /types/tgfancy/ @Dabolus /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 +/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas @NotWoods @sethk @elk941 @Methuselah96 @Dukuo @JulianSSS @devilsparta /types/thrift/ @kamek-pf @kevin-greene-ck @jessezhang91 /types/throng/ @cyrilschumacher @tatethurston /types/throttle/ @BendingBender @@ -4547,6 +4753,7 @@ /types/tinajs__tina-redux/ @Jimexist /types/tinder/ @pingec /types/tingle.js/ @ajafff +/types/tiny-async-pool/ @krlwlfrt /types/tiny-secp256k1/ @eduhenke /types/tiny-slider-react/ @screendriver /types/tinycolor2/ @M-Zuber @geertjansen @nvh @Ailrun @@ -4573,6 +4780,7 @@ /types/topojson-simplify/ @denisname @ricardo-mello /types/topojson-specification/ @denisname /types/toposort/ @danwbyrne +/types/torrent-search-api/ @ngirardin /types/torrent-stream/ @xstoudi /types/touch/ @mizunashi-mana @BendingBender /types/touch-events/ @kevinb7 @@ -4589,6 +4797,7 @@ /types/travis-fold/ @andy-ms /types/trayballoon/ @korve /types/tress/ @sindilevich +/types/trianglify/ @unindented /types/trim/ @skysteve /types/triple-beam/ @danwbyrne /types/triplesec/ @threesquared @@ -4659,9 +4868,9 @@ /types/unzip/ @coding2012 /types/unzipper/ @s73obrien @natemara @bartje321 /types/update-notifier/v1/ @vvakame @nchen63 -/types/update-notifier/ @vvakame @nchen63 @bitjson +/types/update-notifier/ @vvakame @nchen63 @bitjson @grinich /types/uploadcare/ @jineshshah36 -/types/upng-js/ @plantain-00 +/types/upng-js/ @plantain-00 @pineapplemachine /types/uppercamelcase/ @plantain-00 /types/urbanairship-cordova/ @Justin-Credible /types/uri-templates/ @Bartvds @barnski @@ -4695,6 +4904,7 @@ /types/uuid-parse/ @screendriver /types/uuid-validate/ @HiromiShikata /types/uws/ @plantain-00 @orblazer +/types/v-chart-plugin/ @natemara /types/valdr/ @ilbertz /types/valdr-message/ @ilbertz /types/valerie/ @conficient @@ -4762,6 +4972,7 @@ /types/w3c-web-usb/ @larsgk /types/waitme/ @totpero /types/wake_on_lan/ @SrTobi +/types/walk/ @poppa /types/wallabyjs/ @andrewconnell /types/wallpaper/ @BendingBender /types/wampy/ @KSDaemon @@ -4771,6 +4982,7 @@ /types/watchpack/ @e-cloud /types/waterline/ @arvitaly /types/watson-developer-cloud/ @waldo000000 @Naktibalda +/types/wavesurfer.js/ @higuri /types/waypoints/ @dominikbulaj @Koloto @evil-shrike /types/wcwidth/ @rokt33r /types/weak/ @int0h @@ -4778,7 +4990,7 @@ /types/web-animations-js/ @kritollm /types/web-bluetooth/ @urish /types/web-push/ @paullessing -/types/web3/ @simon-jentzsch @nitzantomer @zurbo @yxliang01 @phra @naddison36 @icaroharry @linusnorton @jpeletier @anneau @matrushka @andrevmatos @levino @zlumer @archangel-irk +/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 @@ -4787,14 +4999,14 @@ /types/webcl/ @NCARalph /types/webcomponents.js/ @adidahiya /types/webcrypto/ @iislucas -/types/webdriverio/ @nmalaguti @timbru31 @fsmedberg-tc @tanvirislam06 @phil-lgr +/types/webdriverio/ @nmalaguti @timbru31 @fsmedberg-tc @tanvirislam06 @daveparslow @phil-lgr /types/webfontloader/ @doskallemaskin /types/webgl-ext/ @zenmumbler /types/webgl2/ @nkemnitz @karhu /types/webidl2/ @saschanaz /types/webmidi/ @lostfictions -/types/webpack/v3/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @christophehurpeau -/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @dennispg @christophehurpeau @ZSkycat @johnnyreilly +/types/webpack/v3/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @christophehurpeau @rwaskiewicz @kuehlein +/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @dennispg @christophehurpeau @ZSkycat @johnnyreilly @rwaskiewicz @kuehlein /types/webpack-assets-manifest/ @FranklinWhale /types/webpack-bundle-analyzer/ @kryops /types/webpack-chain/ @eirikurn @psachs21 @@ -4818,9 +5030,11 @@ /types/webpack-serve/ @rynclark @Jokcy @ZSkycat /types/webpack-sources/ @e-cloud @chriseppstein /types/webpack-stream/ @iclanton @bumbleblym +/types/webpack-subresource-integrity/ @huan086 /types/webpack-validator/ @deevus /types/webpackbar/ @rynclark /types/webpagetest/ @ksm2 +/types/webprogbase-console-view/ @veetaha /types/webrtc/ @nakakura /types/webscopeio__react-textarea-autocomplete/ @michauzo /types/websequencediagrams/ @ffflorian @@ -4866,6 +5080,7 @@ /types/wnumb/ @acoreyj /types/wonder.js/ @yyc-git /types/word-list-json/ @dovidm +/types/word2vector/ @renekeijzer /types/wordcloud/ @joeskeen /types/words-to-numbers/ @James-Frowen /types/workbox-sw/ @wessberg @@ -4907,18 +5122,20 @@ /types/xsockets/ @pushplay /types/xxhashjs/ @mDibyo /types/yallist/ @BendingBender +/types/yaml/ @ikatyang @ColinBradley /types/yandex-maps/ @Delagen /types/yandex-money-sdk/ @chrootsu /types/yar/ @SimonSchick /types/yargs/v8/ @poelstra @mizunashi-mana @pushplay @jeffkenney /types/yargs/v10/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC /types/yargs/v11/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC -/types/yargs/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC +/types/yargs/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC @tkazec /types/yargs-interactive/ @szeck87 +/types/yargs-parser/ @milesj /types/yauzl/ @ffflorian /types/yauzl-promise/ @dlee-nvisia /types/yayson/ @Codesleuth -/types/yazl/ @taoqf +/types/yazl/ @taoqf @seangenabe /types/ydn-db/ @yathit @gabrielmaldi /types/yeoman-generator/ @armorik83 @janslow @ikatyang /types/yeoman-test/ @ikatyang @@ -4932,7 +5149,7 @@ /types/youtube/ @DazWilkin @JoshuaKGoldberg @eliotfallon213 @terrymun /types/youtube-dl/ @bsurai /types/yui/ @giabao -/types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola +/types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola @YashdalfTheGray /types/z-schema/ @pgonzal /types/zapier-platform-core/ @bradleyayers /types/zeit__next-typescript/ @icopp @@ -4945,6 +5162,7 @@ /types/zeromq/ @davemckeown @erikma @TitaneBoy /types/zip-webpack-plugin/ @blaise-io /types/zip.js/ @lgrignon +/types/zipcelx/ @aleburato /types/zipcodes/ @headdetect @dobesv /types/zipkin-context-cls/ @plantain-00 /types/zipkin-instrumentation-express/ @plantain-00 diff --git a/notNeededPackages.json b/notNeededPackages.json index f81984b338..4c0eb6d98a 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -540,6 +540,12 @@ "sourceRepoURL": "https://github.com/code-chris/extended-listbox", "asOfVersion": "4.0.1" }, + { + "libraryName": "fast-diff", + "typingsPackageName": "fast-diff", + "sourceRepoURL": "https://github.com/jhchen/fast-diff", + "asOfVersion": "1.2.0" + }, { "libraryName": "JSON-Patch", "typingsPackageName": "fast-json-patch", @@ -978,6 +984,12 @@ "sourceRepoURL": "https://github.com/mweststrate/mobservable-react", "asOfVersion": "1.0.0" }, + { + "libraryName": "Mobx Cookie", + "typingsPackageName": "mobx-cookie", + "sourceRepoURL": "https://github.com/will-stone/mobx-cookie", + "asOfVersion": "1.1.0" + }, { "libraryName": "Moment", "typingsPackageName": "moment", diff --git a/types/ali-app/ali-app-tests.ts b/types/ali-app/ali-app-tests.ts new file mode 100644 index 0000000000..a42301aed1 --- /dev/null +++ b/types/ali-app/ali-app-tests.ts @@ -0,0 +1,2153 @@ +(() => { + // https://docs.alipay.com/mini/api/ui-navigate + my.navigateTo({ + url: 'new_page?count=100' + }); + // test.js + Page({ + onLoad(query: any) { + my.alert({ + content: JSON.stringify(query), + }); + } + }); + my.redirectTo({ + url: 'new_page?count=100' + }); + // 注意:调用 navigateTo 跳转时,调用该方法的页面会被加入堆栈, + // 而 redirectTo 方法则不会。见下方示例代码 + + // 此处是one页面 + my.navigateTo({ + url: 'two?pageId=10000' + }); + + // 此处是two页面 + my.navigateTo({ + url: 'one?pageId=99999' + }); + + // 在three页面内 navigateBack,将返回one页面 + my.navigateBack({ + delta: 2 + }); + my.reLaunch({ + url: '/page/index' + }); + my.setNavigationBar({ + title: '你好', + backgroundColor: '#108ee9', + success() { + my.alert({ + content: '设置成功', + }); + }, + fail() { + my.alert({ + content: '设置是失败', + }); + }, + }); + my.showNavigationBarLoading(); + my.hideNavigationBarLoading(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-tabbar + my.switchTab({ + url: '/home' + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-feedback + my.alert({ + title: '亲', + content: '您本月的账单已出', + buttonText: '我知道了', + success: () => { + my.alert({ + title: '用户点击了「我知道了」', + }); + }, + }); + my.confirm({ + title: '温馨提示', + content: '您是否想查询快递单号:1234567890', + confirmButtonText: '马上查询', + cancelButtonText: '暂不需要', + success: (result) => { + my.alert({ + title: `${result.confirm}`, + }); + }, + }); + my.prompt({ + title: '标题单行', + message: '说明当前状态、提示用户解决方案,最好不要超过两行。', + placeholder: '给朋友留言', + okButtonText: '确定', + cancelButtonText: '取消', + success: (result) => { + my.alert({ + title: JSON.stringify(result), + }); + }, + }); + my.showToast({ + type: 'success', + content: '操作成功', + duration: 3000, + success: () => { + my.alert({ + title: 'toast 消失了', + }); + }, + }); + my.hideToast(); + my.showLoading({ + content: '加载中...', + delay: 1000, + }); + + my.hideLoading(); + + Page({ + onLoad() { + my.showLoading(); + const that = this; + setTimeout(() => { + my.hideLoading({ + page: that, // 防止执行时已经切换到其它页面,page指向不准确 + }); + }, 4000); + } + }); + my.showNavigationBarLoading(); + my.hideNavigationBarLoading(); + my.showActionSheet({ + title: '支付宝-ActionSheet', + items: ['菜单一', '菜单二', '菜单三', '菜单四', '菜单五'], + badges: [ + { index: 0, type: 'none' }, + { index: 1, type: 'point' }, + { index: 2, type: 'num', text: '99' }, + { index: 3, type: 'text', text: '推荐' }, + { index: 4, type: 'more' }], + cancelButtonText: '取消好了', + success: (res) => { + const btn = res.index === -1 ? '取消' : `第${res.index}个`; + my.alert({ + title: `你点了${btn}按钮` + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-pulldown + Page({ + onPullDownRefresh() { + my.stopPullDownRefresh(); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-contact + my.choosePhoneContact({ + success: (res) => { + my.alert({ + content: `姓名:${res.name}\n号码:${res.mobile}` + }); + } + }); + my.chooseAlipayContact({ + count: 2, + success: (res) => { + my.alert({ + content: 'chooseAlipayContact response: ' + JSON.stringify(res) + }); + }, + fail: (res) => { + my.alert({ + content: 'chooseAlipayContact response: ' + JSON.stringify(res) + }); + } + }); + my.chooseContact({ + chooseType: 'multi', // 多选模式 + includeMe: true, // 包含自己 + includeMobileContactMode: 'known', // 仅包含双向手机通讯录联系人,也即双方手机通讯录都存有对方号码的联系人 + multiChooseMax: 3, // 最多能选择三个联系人 + multiChooseMaxTips: '超过选择的最大人数了', + success: (res) => { + my.alert({ + content: 'chooseContact : ' + JSON.stringify(res) + }); + }, + fail: (res) => { + my.alert({ + content: 'chooseContact : ' + JSON.stringify(res) + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-city + my.chooseCity({ + cities: [ + { + city: '朝阳区', + adCode: '110105', + spell: 'chaoyang' + }, + { + city: '海淀区', + adCode: '110108', + spell: 'haidian' + }, + { + city: '丰台区', + adCode: '110106', + spell: 'fengtai' + }, + { + city: '东城区', + adCode: '110101', + spell: 'dongcheng' + }, + { + city: '西城区', + adCode: '110102', + spell: 'xicheng' + }, + { + city: '房山区', + adCode: '110111', + spell: 'fangshan' + } + ], + hotCities: [ + { + city: '朝阳区', + adCode: '110105' + }, + { + city: '海淀区', + adCode: '110108' + }, + { + city: '丰台区', + adCode: '110106' + } + ], + success: (res) => { + my.alert({ + content: `${res.city}:${res.adCode}` + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-date + my.datePicker({ + format: 'yyyy-MM-dd', + currentDate: '2012-12-12', + startDate: '2012-12-10', + endDate: '2012-12-15', + success: (res) => { + my.alert({ + content: res.date, + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-animation + const animation = my.createAnimation({ + transformOrigin: "top right", + duration: 3000, + timeFunction: "ease-in-out", + delay: 100, + }); + Page({ + data: { + animationInfo: {} + }, + onShow() { + const animation = my.createAnimation({ + duration: 1000, + timeFunction: 'ease-in-out', + }); + + this.animation = animation; + + animation.scale(3, 3).rotate(60).step(); + + this.setData({ + animationInfo: animation.export() + }); + + setTimeout(() => { + animation.translate(35).step(); + this.setData({ + animationInfo: animation.export(), + }); + }, 1500); + }, + rotateAndScale(this: my.Page) { + // 旋转同时放大 + this.animation.rotate(60).scale(3, 3).step(); + this.setData({ + animationInfo: this.animation.export(), + }); + }, + rotateThenScale(this: my.Page) { + // 先旋转后放大 + this.animation.rotate(60).step(); + this.animation.scale(3, 3).step(); + this.setData({ + animationInfo: this.animation.export(), + }); + }, + rotateAndScaleThenTranslate(this: my.Page) { + // 先旋转同时放大,然后平移 + this.animation.rotate(60).scale(3, 3).step(); + this.animation.translate(100, 100).step({ duration: 2000 }); + this.setData({ + animationInfo: this.animation.export() + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-canvas + const ctx = my.createCanvasContext('awesomeCanvas'); + ctx.toTempFilePath({ + success() { }, + }); + + ctx.setTextAlign("left"); + ctx.fillText("Hello world", 0, 100); + + ctx.setTextBaseline("top"); + ctx.fillText("Hello world", 0, 100); + + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 100, 175); + ctx.draw(); + + ctx.setStrokeStyle('blue'); + ctx.strokeRect(50, 50, 100, 175); + ctx.draw(); + + ctx.setFillStyle('red'); + ctx.setShadow(15, 45, 45, 'yellow'); + ctx.fillRect(20, 20, 100, 175); + ctx.draw(); + + const grd = ctx.createLinearGradient(10, 10, 150, 10); + grd.addColorStop(0, 'yellow'); + grd.addColorStop(1, 'blue'); + + ctx.setFillStyle(grd); + ctx.fillRect(20, 20, 250, 180); + ctx.draw(); + + grd.addColorStop(0, 'blue'); + grd.addColorStop(1, 'red'); + + ctx.setFillStyle(grd); + ctx.fillRect(20, 20, 250, 180); + ctx.draw(); + + grd.addColorStop(0.36, 'orange'); + grd.addColorStop(0.56, 'cyan'); + grd.addColorStop(0.63, 'yellow'); + grd.addColorStop(0.76, 'blue'); + grd.addColorStop(0.54, 'green'); + grd.addColorStop(1, 'purple'); + grd.addColorStop(0.4, 'red'); + + ctx.setFillStyle(grd); + ctx.fillRect(20, 20, 250, 180); + ctx.draw(); + + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.lineTo(250, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.moveTo(20, 35); + ctx.lineTo(250, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(20); + ctx.moveTo(20, 50); + ctx.lineTo(250, 55); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(25); + ctx.moveTo(20, 80); + ctx.lineTo(250, 85); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(150, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('round'); + ctx.setLineWidth(20); + ctx.moveTo(20, 70); + ctx.lineTo(250, 80); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('butt'); + ctx.setLineWidth(10); + ctx.moveTo(25, 80); + ctx.lineTo(250, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('square'); + ctx.setLineWidth(10); + ctx.moveTo(35, 47); + ctx.lineTo(230, 120); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.moveTo(20, 30); + ctx.lineTo(150, 70); + ctx.lineTo(20, 100); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('round'); + ctx.setLineWidth(20); + ctx.moveTo(100, 20); + ctx.lineTo(280, 80); + ctx.lineTo(100, 100); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('bevel'); + ctx.setLineWidth(20); + ctx.moveTo(60, 25); + ctx.lineTo(180, 80); + ctx.lineTo(90, 100); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('miter'); + ctx.setLineWidth(15); + ctx.moveTo(130, 70); + ctx.lineTo(250, 50); + ctx.lineTo(230, 100); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(1); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(2); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(3); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.draw(); + + ctx.rect(20, 20, 250, 80); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); + + ctx.fillRect(20, 20, 250, 80); + ctx.setFillStyle('blue'); + ctx.draw(); + + ctx.setStrokeStyle('blue'); + ctx.strokeRect(20, 20, 250, 80); + ctx.draw(); + + ctx.setFillStyle('blue'); + ctx.fillRect(250, 10, 250, 200); + ctx.setFillStyle('yellow'); + ctx.fillRect(0, 0, 150, 200); + ctx.clearRect(10, 10, 150, 75); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(200, 20); + ctx.lineTo(200, 200); + ctx.fill(); + ctx.draw(); + + ctx.rect(20, 20, 110, 40); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.rect(20, 30, 150, 40); + + ctx.setFillStyle('yellow'); + ctx.fillRect(20, 80, 150, 40); + + ctx.rect(20, 150, 150, 40); + + ctx.setFillStyle('red'); + ctx.fill(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(150, 10); + ctx.lineTo(150, 150); + ctx.stroke(); + ctx.draw(); + + ctx.rect(10, 10, 100, 30); + ctx.setStrokeStyle('blue'); + ctx.stroke(); + + ctx.beginPath(); + ctx.rect(20, 50, 150, 50); + + ctx.setStrokeStyle('yellow'); + ctx.strokeRect(15, 75, 200, 35); + + ctx.rect(20, 200, 150, 30); + + ctx.setStrokeStyle('red'); + ctx.stroke(); + ctx.draw(); + + ctx.rect(20, 20, 150, 50); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.rect(20, 50, 150, 40); + + ctx.setFillStyle('yellow'); + ctx.fillRect(20, 170, 150, 40); + + ctx.rect(10, 100, 100, 30); + + ctx.setFillStyle('red'); + ctx.fill(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(150, 20); + ctx.lineTo(150, 150); + ctx.closePath(); + ctx.stroke(); + ctx.draw(); + + ctx.rect(20, 20, 150, 50); + ctx.closePath(); + + ctx.beginPath(); + ctx.rect(20, 50, 150, 40); + + ctx.setFillStyle('red'); + ctx.fillRect(20, 80, 120, 30); + + ctx.rect(20, 150, 150, 40); + + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(150, 15); + + ctx.moveTo(20, 55); + ctx.lineTo(120, 60); + ctx.stroke(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.rect(20, 20, 80, 30); + ctx.lineTo(120, 80); + ctx.stroke(); + ctx.draw(); + + ctx.arc(200, 75, 50, 0, 2 * Math.PI); + ctx.setFillStyle('#CCCCCC'); + ctx.fill(); + + ctx.beginPath(); + ctx.moveTo(50, 65); + ctx.lineTo(170, 80); + ctx.moveTo(200, 35); + ctx.lineTo(200, 235); + ctx.setStrokeStyle('#AAAAAA'); + ctx.stroke(); + + ctx.setFontSize(12); + ctx.setFillStyle('yellow'); + ctx.fillText('0', 165, 78); + ctx.fillText('0.6*PI', 96, 148); + ctx.fillText('1*PI', 15, 57); + ctx.fillText('1.7*PI', 94, 20); + + ctx.beginPath(); + ctx.arc(200, 85, 2, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(200, 35, 2, 0, 2 * Math.PI); + ctx.setFillStyle('green'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(450, 60, 2, 0, 2 * Math.PI); + ctx.setFillStyle('red'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(150, 35, 50, 0, 1.8 * Math.PI); + ctx.setStrokeStyle('#666666'); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.arc(30, 30, 2, 0, 2 * Math.PI); + ctx.setFillStyle('red'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(250, 25, 2, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(20, 100, 2, 0, 2 * Math.PI); + ctx.arc(200, 100, 2, 0, 2 * Math.PI); + ctx.setFillStyle('green'); + ctx.fill(); + + ctx.setFillStyle('yellow'); + ctx.setFontSize(14); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.lineTo(30, 100); + ctx.lineTo(150, 75); + + ctx.moveTo(250, 30); + ctx.lineTo(250, 80); + ctx.lineTo(70, 75); + ctx.setStrokeStyle('#EEEEEE'); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.bezierCurveTo(30, 150, 250, 150, 180, 20); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.arc(30, 30, 2, 0, 2 * Math.PI); + ctx.setFillStyle('red'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(250, 20, 2, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(30, 200, 2, 0, 2 * Math.PI); + ctx.setFillStyle('green'); + ctx.fill(); + + ctx.setFillStyle('black'); + ctx.setFontSize(12); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.lineTo(30, 150); + ctx.lineTo(250, 30); + ctx.setStrokeStyle('#AAAAAA'); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.quadraticCurveTo(30, 150, 250, 25); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); + + ctx.strokeRect(15, 15, 30, 25); + ctx.scale(3, 3); + ctx.strokeRect(15, 15, 30, 25); + ctx.scale(3, 3); + ctx.strokeRect(15, 15, 30, 25); + + ctx.draw(); + + ctx.strokeRect(200, 20, 180, 150); + ctx.rotate(30 * Math.PI / 180); + ctx.strokeRect(200, 20, 180, 150); + ctx.rotate(30 * Math.PI / 180); + ctx.strokeRect(200, 20, 180, 150); + + ctx.draw(); + + ctx.strokeRect(20, 20, 250, 80); + ctx.translate(30, 30); + ctx.strokeRect(20, 20, 250, 80); + ctx.translate(30, 30); + ctx.strokeRect(20, 20, 250, 80); + + ctx.draw(); + + ctx.setFontSize(14); + ctx.fillText('14', 20, 20); + ctx.setFontSize(22); + ctx.fillText('22', 40, 40); + ctx.setFontSize(30); + ctx.fillText('30', 60, 60); + ctx.setFontSize(38); + ctx.fillText('38', 90, 90); + + ctx.draw(); + + ctx.setFontSize(42); + ctx.fillText('Hello', 30, 30); + ctx.fillText('alipay', 200, 200); + + ctx.draw(); + + ctx.drawImage('https://img.alicdn.com/tfs/TB1GvVMj2BNTKJjy0FdXXcPpVXa-520-280.jpg', 2, 2, 250, 80); + ctx.draw(); + + ctx.setFillStyle('yellow'); + ctx.fillRect(10, 10, 150, 100); + ctx.setGlobalAlpha(0.2); + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 150, 100); + ctx.setFillStyle('red'); + ctx.fillRect(100, 100, 150, 100); + + ctx.draw(); + + ctx.setLineDash([5, 15, 25]); + ctx.beginPath(); + ctx.moveTo(0, 100); + ctx.lineTo(400, 100); + ctx.stroke(); + + ctx.draw(); + + ctx.rotate(45 * Math.PI / 180); + ctx.setFillStyle('red'); + ctx.fillRect(70, 0, 100, 30); + + ctx.transform(1, 1, 0, 1, 0, 0); + ctx.setFillStyle('#000'); + ctx.fillRect(0, 0, 100, 100); + + ctx.draw(); + + ctx.rotate(45 * Math.PI / 180); + ctx.setFillStyle('red'); + ctx.fillRect(70, 0, 100, 30); + + ctx.setTransform(1, 1, 0, 1, 0, 0); + ctx.setFillStyle('#000'); + ctx.fillRect(0, 0, 100, 100); + + ctx.draw(); + + ctx.save(); + ctx.setFillStyle('red'); + ctx.fillRect(20, 20, 250, 80); + + ctx.restore(); + ctx.fillRect(60, 60, 155, 130); + + ctx.draw(); + + ctx.setFillStyle('blue'); + ctx.fillRect(20, 20, 180, 80); + ctx.draw(); + ctx.fillRect(60, 60, 250, 120); + ctx.draw(true); + + ctx.font = 'italic bold 50px cursive'; + const { width } = ctx.measureText('hello world'); + console.log(width); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-map + Page({ + onReady() { + // 使用 my.createMapContext 获取 map 上下文 + this.mapCtx = my.createMapContext('userMap'); + }, + getCenterLocation(this: my.Page) { + (this.mapCtx as my.MapContext).getCenterLocation({ + success(res) { + console.log(res.longitude); + console.log(res.latitude); + } + }); + }, + moveToLocation() { + this.mapCtx.moveToLocation(); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-hidekeyboard + my.hideKeyboard(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/scroll + my.pageScrollTo({ + scrollTop: 100 + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/selector-query + Page({ + onReady() { + my.createSelectorQuery() + .select('#non-exists').boundingClientRect() + .select('#one').boundingClientRect() + .selectAll('.all').boundingClientRect() + .select('#scroll').scrollOffset() + .selectViewport().boundingClientRect() + .selectViewport().scrollOffset().exec((ret) => { + console.log(JSON.stringify(ret, null, 2)); + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ewdxl3 + my.multiLevelSelect({ + title: 'nihao', // 级联选择标题 + list: [ + { + name: "杭州市", // 条目名称 + subList: [ + { + name: "西湖区", + subList: [ + { + name: "古翠街道" + }, + { + name: "文新街道" + } + ] + }, + { + name: "上城区", + subList: [ + { + name: "延安街道" + }, + { + name: "龙翔桥街道" + } + ] + } + ]// 级联子数据列表 + } + ]// 级联数据列表 + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/openapi-authorize + my.getAuthCode({ + scopes: 'auth_user', + success: (res) => { + my.alert({ + content: res.authCode, + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/userinfo + my.getAuthCode({ + scopes: 'auth_user', + success: (res) => { + my.getAuthUserInfo({ + success: (userInfo) => { + my.alert({ + content: userInfo.nickName + }); + my.alert({ + content: userInfo.avatar + }); + } + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/openapi-pay + my.tradePay({ + tradeNO: '201711152100110410533667792', // 调用统一收单交易创建接口(alipay.trade.create),获得返回字段支付宝交易号trade_no + success: (res) => { + my.alert({ + content: JSON.stringify(res), + }); + }, + fail: (res) => { + my.alert({ + content: JSON.stringify(res), + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/pay-sign + my.paySignCenter({ + // tslint:disable-next-line:max-line-length + signStr: 'biz_content%3D%257B%2522access_params%2522%253A%257B%2522channel%2522%253A%2522ALIPAYAPP%2522%257D%252C%2522external_agreement_no%2522%253A%2522xidong___2317%2522%252C%2522external_logon_id%2522%253A%252213852852877%2522%252C%2522personal_product_code%2522%253A%2522GENERAL_WITHHOLDING_P%2522%252C%2522product_code%2522%253A%2522GENERAL_WITHHOLDING%2522%252C%2522sign_scene%2522%253A%2522INDUSTRY%257CCARRENTAL%2522%252C%2522third_party_type%2522%253A%2522PARTNER%2522%257D%26sign%3Df3pjBDTRftOwXWnCqAMAnkBfGTFlcMmZI8hEgmV6uREZRXVDuLsSjD8WO%252FeZ1fjDG8GqVO9t1AN7q6yCUHKX%252Bw%252FE7efXwpVDWldr4iVuXDtNd3UJDJUiRJhIm6b73czWacVzm1XIery%252F2DyKI2y08tBf5NNWuQCC3d%252FITxziTl8%253D%26timestamp%3D2017-06-27%2B14%253A44%253A00%26sign_type%3DRSA%26notify_url%3Dhttp%253A%252F%252Fapi.test.alipay.net%252Fatinterface%252Freceive_notify.htm%26charset%3DUTF-8%26app_id%3D2017060101317939%26method%3Dalipay.user.agreement.page.sign%26return_url%3Dhttp%253A%252F%252Fapi.test.alipay.net%252Fatinterface%252Freceive_notify.htm%26version%3D1.0', + success: (res) => { + my.alert({ + title: 'success', // alert框的标题 + content: JSON.stringify(res) + }); + }, + fail: (res) => { + my.alert({ + title: 'fail', // alert框的标题 + content: JSON.stringify(res) + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/card-voucher-ticket + my.openCardList(); + my.openMerchantCardList({ partnerId: '2088xxxxx' }); + // 传入passId来打开 + my.openCardDetail({ passId: "11xxxxx" }); + my.openVoucherList(); + my.openMerchantVoucherList({ partnerId: '2088xxxx' }); + // 传入passId来打开 + my.openVoucherDetail({ passId: "20170921" }); + + // 传入partnerId 和 serialNumber来打开 + my.openVoucherDetail({ + partnerId: "2018xxxx", + serialNumber: "20170921" + }); + // 传入passId来打开 + my.openKBVoucherDetail({ passId: "20170921" }); + + // 传入partnerId 和 serialNumber来打开 + my.openKBVoucherDetail({ + partnerId: "2088xxxx", + serialNumber: "20170921" + }); + my.openTicketList(); + my.openMerchantTicketList({ partnerId: '2088xxxx' }); + // 传入passId来打开 + my.openTicketDetail({ passId: "20170921" }); + + // 传入partnerId 和 serialNumber来打开 + my.openTicketDetail({ + partnerId: "2088xxxx", + serialNumber: "20170921" + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/add-card-auth + my.addCardAuth({ + url: '从 openapi 接口获取到的 url', + success: (res) => { + my.alert({ content: '授权成功' }); + }, + fail: (res) => { + my.alert({ content: '授权失败' }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/zm-service + my.startZMVerify({ + bizNo: 'your-biz-no', + success: (res) => { + my.alert({ title: 'success:' + JSON.stringify(res) }); + }, + fail: (res) => { + my.alert({ title: 'fail: ' + JSON.stringify(res) }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/zmcreditborrow + my.zmCreditBorrow({ + credit_biz: "", + out_order_no: "", + borrow_shop_name: "", + goods_name: "", + product_code: "w1010100000000002858", + rent_unit: "HOUR_YUAN", + rent_amount: "0.10", + deposit_amount: "0.50", + deposit_state: "Y", + invoke_return_url: "", + invoke_type: "TINYAPP", + borrow_time: "2017-04-27 10:01:01", + expiry_time: "2017-05-27 10:01:01", + rent_info: "2hour-free", + success: (res) => { + try { + const { resultStatus, result } = res; + switch (resultStatus) { + case '9000': + const callbackData = result.callbackData; + const decodedCallbackData = decodeURIComponent(callbackData); + const json = JSON.parse(decodedCallbackData.match(/{.*}/)!.toString()); + const jsonStr = JSON.stringify(json, null, 4); + if (json.success === true || json.success === 'true') { + // 创建订单成功, 此时可以跳转到订单详情页面 + my.alert({ content: '下单成功: ' + jsonStr }); + } else { + // 创建订单失败, 请提示用户创建失败 + my.alert({ content: '下单失败: ' + jsonStr }); + } + // (this as any as my.Page).setData({ + // callbackData, + // decodedCallbackData, + // parsedJSON: jsonStr, + // }); + break; + case '6001': + // 用户点击返回, 取消此次服务, 此时可以给提示 + my.alert({ content: '取消' }); + break; + default: + break; + } + } catch (error) { + // 异常, 请在这里提示用户稍后重试 + my.alert({ + content: '异常' + JSON.stringify(error, null, 4) + }); + } + }, + fail: (error) => { + // 调用接口失败, 请在这里提示用户稍后重试 + my.alert({ + content: '调用失败' + JSON.stringify(error, null, 4) + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/templatemessage +})(); + +(() => { + // https://docs.alipay.com/mini/api/text-identification + my.textRiskIdentification({ + content: '加我支付宝', + type: ['keyword', '0', '1', '2', '3'], + success: (res) => { + my.alert({ + title: 'ok', // alert 框的标题 + content: JSON.stringify(res), + }); + }, + fail: (res) => { + my.alert({ + title: 'fail', // alert 框的标题 + content: JSON.stringify(res), + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/open-miniprogram + my.navigateToMiniProgram({ + appId: 'xxxx', + extraData: { + data1: "test" + }, + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.navigateBackMiniProgram({ + extraData: { + data1: "test" + }, + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + console.log(JSON.stringify(res)); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/webview-context + Page({ + onLoad() { + this.webViewContext = my.createWebViewContext('web-view-1'); + }, + // 接收来自H5的消息 + onMessage(e: any) { + console.log(e); // {'sendToMiniProgram': '0'} + // 向H5发送消息 + this.webViewContext.postMessage({ sendToWebView: '1' }); + } + }); + // H5的js代码中需要先定义my.onMessage 用于接收来自小程序的消息。 + my.onMessage = (e) => { + console.log(e); // {'sendToWebView': '1'} + }; + // H5想小程序发送消息 + my.postMessage({ sendToMiniProgram: '0' }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/media-image + const img = null as any as HTMLImageElement; + my.chooseImage({ + count: 2, + success: (res) => { + img.src = res.apFilePaths[0]; + }, + }); + my.previewImage({ + current: 2, + urls: [ + 'https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg', + 'https://img.alicdn.com/tps/TB1pfG4IFXXXXc6XXXXXXXXXXXX.jpg', + 'https://img.alicdn.com/tps/TB1h9xxIFXXXXbKXXXXXXXXXXXX.jpg' + ], + }); + my.saveImage({ + url: 'https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg' + }); + my.compressImage({ + apFilePaths: ['https://resource/apmlcc0ed184daffc5a0d8da86b2f518cf7b.image'], + // level: 1, + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + // 网络图片路径 + my.getImageInfo({ + src: 'https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + + // apFilePath + my.chooseImage({ + success: (res) => { + my.getImageInfo({ + src: res.apFilePaths[0], + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + }, + }); + + // 相对路径 + my.getImageInfo({ + src: 'image/api.png', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/storage + my.setStorage({ + key: 'currentCity', + data: { + cityName: '杭州', + adCode: '330100', + spell: ' hangzhou', + }, + success() { + my.alert({ content: '写入成功' }); + } + }); + my.setStorageSync({ + key: 'currentCity', + data: { + cityName: '杭州', + adCode: '330100', + spell: ' hangzhou', + } + }); + my.getStorage({ + key: 'currentCity', + success(res) { + my.alert({ content: '获取成功:' + res.data.cityName }); + }, + fail(res) { + my.alert({ content: res.errorMessage }); + } + }); + const res = my.getStorageSync({ key: 'currentCity' }); + my.alert({ + content: JSON.stringify(res.data), + }); + my.removeStorage({ + key: 'currentCity', + success() { + my.alert({ content: '删除成功' }); + } + }); + my.removeStorageSync({ + key: 'currentCity', + }); + my.clearStorage(); + my.clearStorageSync(); + my.getStorageInfo({ + success(res) { + console.log(res.keys); + console.log(res.currentSize); + console.log(res.limitSize); + } + }); + const res1 = my.getStorageInfoSync(); + console.log(res1.keys); + console.log(res1.currentSize); + console.log(res1.limitSize); +})(); + +(() => { + // https://docs.alipay.com/mini/api/file + my.chooseImage({ + success: (res) => { + my.saveFile({ + apFilePath: res.apFilePaths[0], + success: (res) => { + console.log(JSON.stringify(res)); + }, + }); + }, + }); + my.getFileInfo({ + apFilePath: 'https://resource/apml953bb093ebd2834530196f50a4413a87.video', + digestAlgorithm: 'sha1', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.getSavedFileInfo({ + apFilePath: 'https://resource/apml953bb093ebd2834530196f50a4413a87.video', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.getSavedFileList({ + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.getSavedFileList({ + success: (res) => { + my.removeSavedFile({ + apFilePath: res.fileList[0].apFilePath, + success: (res) => { + console.log('remove success'); + } + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/location + my.getLocation({ + success(res) { + my.hideLoading(); + console.log(res); + /* that对象为Page可以设置数据刷新界面 + that.setData({ + hasLocation: true, + location: formatLocation(res.longitude, res.latitude) + }) + */ + }, + fail() { + my.hideLoading(); + my.alert({ title: '定位失败' }); + }, + }); + my.openLocation({ + longitude: '121.549697', + latitude: '31.227250', + name: '支付宝', + address: '杨高路地铁站', + }); + my.chooseLocation({ + success: (res) => { + console.log(res); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/network + my.httpRequest({ + url: 'http://httpbin.org/post', + method: 'POST', + data: { + from: '支付宝', + production: 'AlipayJSAPI', + }, + dataType: 'json', + success(res) { + my.alert({ content: 'success' }); + }, + fail(res) { + my.alert({ content: 'fail' }); + }, + complete(res) { + my.hideLoading(); + my.alert({ content: 'complete' }); + } + }); + my.uploadFile({ + url: '请使用自己服务器地址', + fileType: 'image', + fileName: 'file', + filePath: '...', + success: (res) => { + my.alert({ + content: '上传成功' + }); + }, + }); + my.downloadFile({ + url: 'http://img.alicdn.com/tfs/TB1x669SXXXXXbdaFXXXXXXXXXX-520-280.jpg', + success({ apFilePath }) { + my.previewImage({ + urls: [apFilePath], + }); + }, + fail(res) { + my.alert({ + content: res.errorMessage || res.error, + }); + }, + }); + my.connectSocket({ + url: 'test.php', + data: {}, + header: { + 'content-type': 'application/json' + }, + method: 'GET' + }); + my.connectSocket({ + url: 'test.php', + }); + + my.onSocketOpen(() => { + console.log('WebSocket 连接已打开!'); + }); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onSocketOpen(this.callback); + }, + onUnload() { + my.offSocketOpen(this.callback); + }, + callback() { + }, + }); + my.connectSocket({ + url: '开发者的服务器地址' + }); + + my.onSocketOpen(() => { + console.log('WebSocket 连接已打开!'); + }); + + my.onSocketError(() => { + console.log('WebSocket 连接打开失败,请检查!'); + }); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onSocketError(this.callback); + }, + onUnload() { + my.offSocketError(this.callback); + }, + callback() { + my.sendSocketMessage({ + data: this.data.toSendMessage, // 需要发送的内容 + success: (res) => { + my.alert({ content: '数据发送!' + this.data.toSendMessage }); + }, + }); + }, + }); + my.connectSocket({ + url: '服务器地址' + }); + + my.onSocketMessage((res) => { + console.log('收到服务器内容:' + res.data); + }); + my.onSocketOpen(() => { + my.closeSocket(); + }); + + my.onSocketClose(() => { + console.log('WebSocket 已关闭!'); + }); + Page({ + // onLoad() { + onLaunch() { + // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调 + my.onSocketClose(() => { + my.alert({ content: '连接已关闭!' }); + this.setData({ + sendMessageAbility: false, + closeLinkAbility: false, + }); + }); + // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调 + my.onSocketOpen(() => { + my.alert({ content: '连接已打开!' }); + this.setData({ + sendMessageAbility: true, + closeLinkAbility: true, + }); + }); + + my.onSocketError((res) => { + my.alert({ content: 'WebSocket 连接打开失败,请检查!' + res }); + }); + + // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调 + my.onSocketMessage((res) => { + my.alert({ content: '收到数据!' + JSON.stringify(res) }); + }); + }, + connect_start() { + my.connectSocket({ + url: '服务器地址', // 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名 + success: (res) => { + my.showToast({ + content: 'success', // 文字内容 + }); + }, + fail: () => { + my.showToast({ + content: 'fail', // 文字内容 + }); + } + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/can-i-use + my.canIUse('getFileInfo'); + my.canIUse('closeSocket.object.code'); + my.canIUse('getLocation.object.type'); + my.canIUse('getSystemInfo.return.brand'); + my.canIUse('lifestyle'); + my.canIUse('button.open-type.share'); +})(); + +(() => { + // https://docs.alipay.com/mini/api/sdk-version + console.log(my.SDKVersion); +})(); + +(() => { + // https://docs.alipay.com/mini/api/system-info + Page({ + data: { + systemInfo: {} + }, + getSystemInfoPage(this: my.Page) { + my.getSystemInfo({ + success: (res) => { + this.setData({ + systemInfo: res + }); + } + }); + }, + }); + Page({ + data: { + systemInfo: {} + }, + getSystemInfoSyncPage(this: my.Page) { + this.setData({ + systemInfo: my.getSystemInfoSync() + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/network-status + Page({ + data: { + hasNetworkType: false + }, + getNetworkType(this: my.Page) { + my.getNetworkType({ + success: (res) => { + this.setData({ + hasNetworkType: true, + networkType: res.networkType + }); + } + }); + }, + clear(this: my.Page) { + this.setData({ + hasNetworkType: false, + networkType: '' + }); + }, + }); + my.onNetworkStatusChange((res) => { + console.log(JSON.stringify(res)); + }); + my.offNetworkStatusChange(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/clipboard + Page({ + data: { + text: '3.1415926', + copy: '', + }, + + handlePaste(this: my.Page) { + my.getClipboard({ + success: ({ text }) => { + this.setData({ copy: text }); + }, + }); + }, + }); + Page({ + data: { + text: '3.1415926', + copy: '', + }, + + handleCopy() { + my.setClipboard({ + text: this.data.text, + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/shake + Page({ + watchShake() { + my.watchShake({ + success() { + console.log('动起来了'); + my.alert({ title: '动起来了 o.o' }); + } + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/vibrate + Page({ + vibrate() { + my.vibrate({ + success: () => { + my.alert({ title: '震动起来了' }); + } + }); + }, + }); + Page({ + vibrateLong() { + my.vibrateLong({ + success: () => { + my.alert({ title: '震动起来了' }); + } + }); + }, + }); + Page({ + vibrateShort() { + my.vibrateShort({ + success: () => { + my.alert({ title: '震动起来了' }); + } + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/macke-call + Page({ + makePhoneCall() { + my.makePhoneCall({ number: '95888' }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/get-server-time + // getServerTime(){ + // my.getServerTime({ + // success: (res) => { + // my.alert({ + // title: res.time, + // }); + // }, + // }); + // }; +})(); + +(() => { + // https://docs.alipay.com/mini/api/user-capture-screen + my.onUserCaptureScreen(() => { + my.alert({ + content: '收到用户截屏事件' + }); + }); + my.offUserCaptureScreen(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/screen-brightness + my.setKeepScreenOn({ + keepScreenOn: true, + success: (res) => { + }, + fail: (res) => { + }, + }); + my.getScreenBrightness({ + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + }, + }); + my.setScreenBrightness({ + brightness: 0.5, + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/show-auth-guide + my.showAuthGuide({ + authType: 'LBSSERVICE' + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/scan + Page({ + scan() { + my.scan({ + type: 'qr', + success: (res) => { + my.alert({ title: res.code }); + }, + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/bluetooth-intro + // 初始化 + my.openBluetoothAdapter({ + success: (res) => { + console.log(res); + } + }); + // 注册发现事件 + my.onBluetoothDeviceFound({ + success: (res) => { + const device = res.devices[0]; + // 连接发现的设备 + my.connectBLEDevice({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + // 停止搜索 + my.stopBluetoothDevicesDiscovery({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + } + }); + const deviceId = 'test'; + const serviceId = 'test'; + const characteristicId = 'test'; + // 注册连接事件 + my.onBLEConnectionStateChanged({ + success: (res) => { + console.log(res); + if (res.connected) { + // 开始读写notify等操作 + my.notifyBLECharacteristicValueChange({ + deviceId, + serviceId, + characteristicId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + } + } + }); + // 注册接收read或notify的数据 + my.onBLECharacteristicValueChange({ + success: (res) => { + console.log(res); + } + }); + // 开始搜索 + my.startBluetoothDevicesDiscovery({ + services: ['fff0'], + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + // 断开连接 + my.disconnectBLEDevice({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + // 注销事件 + my.offBluetoothDeviceFound(); + my.offBLEConnectionStateChanged(); + my.offBLECharacteristicValueChange(); + + // 退出蓝牙模块 + my.closeBluetoothAdapter({ + success: (res) => { + }, + fail: (res) => { + }, + complete: (res) => { + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/bluetooth-api + my.openBluetoothAdapter({ + success: (res) => { + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.closeBluetoothAdapter({ + success: (res) => { + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBluetoothAdapterState({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.startBluetoothDevicesDiscovery({ + services: ['fff0'], + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.stopBluetoothDevicesDiscovery({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBluetoothDevices({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getConnectedBluetoothDevices({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + const deviceId = 'test'; + const serviceId = 'test'; + const characteristicId = 'test'; + my.connectBLEDevice({ + // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取 + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.disconnectBLEDevice({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.writeBLECharacteristicValue({ + deviceId, + serviceId, + characteristicId, + value: 'fffe', + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.readBLECharacteristicValue({ + deviceId, + serviceId, + characteristicId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.notifyBLECharacteristicValueChange({ + deviceId, + serviceId, + characteristicId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBLEDeviceServices({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBLEDeviceCharacteristics({ + deviceId, + serviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onBluetoothDeviceFound(this.callback); + }, + onUnload() { + my.offBluetoothDeviceFound(this.callback); + }, + callback(res: any) { + console.log(res); + }, + }); + my.offBluetoothDeviceFound(); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onBLECharacteristicValueChange(this.callback); + }, + onUnload() { + my.offBLECharacteristicValueChange(this.callback); + }, + callback(res: any) { + console.log(res); + }, + }); + my.offBLECharacteristicValueChange(); + my.offBLEConnectionStateChanged(); + my.offBluetoothAdapterStateChange(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/yqleyc + my.startBeaconDiscovery({ + uuids: ['uuid1', 'uuid2'], + success: (res) => { + console.log(res); + }, + fail: () => { + }, + complete: () => { + } + }); + + my.stopBeaconDiscovery({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + my.getBeacons({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + my.onBeaconUpdate({ + success: (res) => { + }, + }); + + my.onBeaconServiceChange({ + success: (res) => { + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/data-safe + Page({ + data: { + inputValue: '', + outputValue: '', + }, + onInput(this: my.Page, e: any) { + this.setData({ inputValue: e.detail.value }); + }, + onEncrypt(this: my.Page) { + my.rsa({ + action: 'encrypt', + // 设置公钥 + // tslint:disable-next-line:max-line-length + key: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKmi0dUSVQ04hL6GZGPMFK8+d6\nGzulagP27qSUBYxIJfE04KT+OHVeFFb6K+8nWDea5mkmZrIgp022zZVDgdWPNM62\n3ouBwHlsfm2ekey8PpQxfXaj8lhM9t8rJlC4FEc0s8Qp7Q5/uYrowQbT9m6t7BFK\n3egOO2xOKzLpYSqfbQIDAQAB', + text: this.data.inputValue, + success: (result) => { + this.setData({ outputValue: result.text }); + }, + fail(e) { + my.alert({ + content: e.errorMessage || e.error, + }); + }, + }); + }, + onDecrypt(this: my.Page) { + my.rsa({ + action: 'decrypt', + text: this.data.inputValue, + // 设置私钥 + // tslint:disable-next-line:prefer-template + key: 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMqaLR1RJVDTiEvo\n' + + 'ZkY8wUrz53obO6VqA/bupJQFjEgl8TTgpP44dV4UVvor7ydYN5rmaSZmsiCnTbbN\n' + + 'lUOB1Y80zrbei4HAeWx+bZ6R7Lw+lDF9dqPyWEz23ysmULgURzSzxCntDn+5iujB\n' + + 'BtP2bq3sEUrd6A47bE4rMulhKp9tAgMBAAECgYBjsfRLPdfn6v9hou1Y2KKg+F5K\n' + + 'ZsY2AnIK+6l+sTAzfIAx7e0ir7OJZObb2eyn5rAOCB1r6RL0IH+MWaN+gZANNG9g\n' + + 'pXvRgcZzFY0oqdMZDuSJjpMTj7OEUlPyoGncBfvjAg0zdt9QGAG1at9Jr3i0Xr4X\n' + + '6WrFhtfVlmQUY1VsoQJBAPK2Qj/ClkZNtrSDfoD0j083LcNICqFIIGkNQ+XeuTwl\n' + + '+Gq4USTyaTOEe68MHluiciQ+QKvRAUd4E1zeZRZ02ikCQQDVscINBPTtTJt1JfAo\n' + + 'wRfTzA0Lvgig136xLLeQXREcgq1lzgkf+tGyUGYoy9BXsV0mOuYAT9ldja4jhJeq\n' + + 'cEulAkEAuSJ5KjV9dyb0RIFAz5C8d8o5KAodwaRIxJkPv5nCZbT45j6t9qbJxDg8\n' + + 'N+vghDlHI4owvl5wwVlAO8iQBy8e8QJBAJe9CVXFV0XJR/n/XnER66FxGzJjVi0f\n' + + '185nOlFARI5CHG5VxxT2PUCo5mHBl8ctIj+rQvalvGs515VQ6YEVDCECQE3S0AU2\n' + + 'BKyFVNtTpPiTyRUWqig4EbSXwjXdr8iBBJDLsMpdWsq7DCwv/ToBoLg+cQ4Crc5/\n5DChU8P30EjOiEo=', + success: (result) => { + this.setData({ outputValue: result.text }); + }, + fail(e) { + my.alert({ + content: e.errorMessage || e.error, + }); + }, + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/share_app + Page({ + onShareAppMessage() { + return { + title: '小程序示例', + desc: '小程序官方示例Demo,展示已支持的接口能力及组件。', + path: 'page/component/component-pages/view/view?param=123' + }; + }, + }); + + my.hideShareMenu(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/report + my.reportAnalytics('purchase', { + status: 200, + reason: 'ok' + }); +})(); diff --git a/types/ali-app/index.d.ts b/types/ali-app/index.d.ts new file mode 100644 index 0000000000..82f7b2bf27 --- /dev/null +++ b/types/ali-app/index.d.ts @@ -0,0 +1,3265 @@ +// Type definitions for ali-app 1.0 +// Project: https://docs.alipay.com/mini/api/overview (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +// 公共部分 +declare namespace my { + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: any; + /** 开发者服务器返回的 HTTP 状态码 */ + status: number; + /** 开发者服务器返回的 HTTP Response Header */ + headers: object; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + apFilePath: string; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion +} + +// 界面 +declare namespace my { + //#region 导航栏 https://docs.alipay.com/mini/api/ui-navigate + interface NavigateToOptions extends BaseOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + } + /** + * 保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。 + * + * 注意:为了不让用户在使用小程序时造成困扰, + * 我们规定页面路径只能是五层,请尽量避免多层级的交互方式。 + */ + function navigateTo(options: NavigateToOptions): void; + + interface RedirectToOptions extends BaseOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + } + /** + * 关闭当前页面,跳转到应用内的某个页面。 + */ + function redirectTo(options: RedirectToOptions): void; + + interface NavigateBackOptions extends BaseOptions { + /** 返回的页面数,如果 delta 大于现有打开的页面数,则返回到首页 */ + delta: number; + } + /** + * 关闭当前页面,返回上一级或多级页面。可通过 getCurrentPages 获取当前的页面栈信息,决定需要返回几层。 + */ + function navigateBack(options?: NavigateBackOptions): void; + + interface ReLaunchOptions extends BaseOptions { + /** + * 需要跳转的应用内页面路径 , 路径后可以带参数。 + * 参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔 + * 如 'path?key=value&key2=value2',如果跳转的页面路径是 tabBar 页面则不能带参数 + */ + url: string; + } + /** + * 关闭所有页面,打开到应用内的某个页面。 + */ + function reLaunch(options?: ReLaunchOptions): void; + + interface SetNavigationBarOptions extends BaseOptions { + /** 页面标题 */ + title: string; + /** 图片连接地址,必须是https,请使用3x高清图片。若设置了image则title参数失效 */ + image: string; + /** 导航栏背景色,支持十六进制颜色值 */ + backgroundColor: string; + /** 导航栏底部边框颜色,支持十六进制颜色值。若设置了 backgroundColor,则borderBottomColor 不会生效,默认会和 backgroundColor 颜色一样 */ + borderBottomColor: string; + /** 是否重置导航栏为支付宝默认配色,默认 false */ + reset: boolean; + } + /** + * 动态设置当前页面的标题。 + */ + function setNavigationBar(options: Partial): void; + + /** + * 显示导航栏 loading + */ + function showNavigationBarLoading(): void; + + /** 隐藏导航栏 loading。 */ + function hideNavigationBarLoading(): void; + //#endregion + + //#region TabBar https://docs.alipay.com/mini/api/ui-tabbar + interface SwitchTabOptions extends BaseOptions { + /** + * 需要跳转的 tabBar 页面的路径 + * (需在 app.json 的 tabBar 字段定义的页面),路径后不能带参数 + */ + url: string; + } + /** + * 跳转到指定 tabBar 页面,并关闭其他所有非 tabBar 页面 + */ + function switchTab(options: SwitchTabOptions): void; + //#endregion + + //#region 交互反馈 https://docs.alipay.com/mini/api/ui-feedback + + interface AlertOptions extends BaseOptions { + /** alert框的标题 */ + title: string; + /** alert框的内容 */ + content: string; + /** 按钮文字,默认确定 */ + buttonText: string; + } + function alert(options: Partial): void; + + interface ConfirmOptions extends BaseOptions { + /** confirm框的标题 */ + title: string; + /** confirm框的内容 */ + content: string; + /** 确认按钮文字,默认‘确定’ */ + confirmButtonText: string; + /** 确认按钮文字,默认‘取消’ */ + cancelButtonText: string; + success(result: { confirm: boolean; }): void; + } + function confirm(options: Partial): void; + + interface PromptOptions extends BaseOptions { + /** prompt框标题 */ + title?: string; + /** prompt框文本,默认‘请输入内容’ */ + message?: string; + /** 输入框内的提示文案 */ + placeholder?: string; + /** message对齐方式,可用枚举left/center/right,iOS ‘center’, android ‘left’ */ + align?: 'left' | 'center' | 'right' | string; + /** 确认按钮文字,默认‘确定’ */ + okButtonText: string; + /** 确认按钮文字,默认‘取消’ */ + cancelButtonText: string; + success(result: { ok: boolean; inputValue: string; }): void; + } + function prompt(options: PromptOptions): void; + + interface ToastOptions extends BaseOptions { + /** + * 文字内容 + */ + content: string; + /** toast 类型,展示相应图标,默认 none,支持 success / fail / exception / none’。其中 exception 类型必须传文字信息 */ + type?: 'none' | 'success' | 'fail' | 'exception' | string; + /** + * 显示时长,单位为 ms,默认 2000 + */ + duration?: number; + } + /** + * 显示消息提示框 + */ + function showToast(options: Partial): void; + function hideToast(): void; + + interface LoadingOptions extends BaseOptions { + /** + * loading的文字内容 + */ + content?: string; + /** + * 延迟显示,单位 ms,默认 0。如果在此时间之前调用了 my.hideLoading 则不会显示 + */ + delay?: number; + } + /** + * 显示加载提示 + */ + function showLoading(options?: LoadingOptions): void; + interface HideLoadingOptions { + /** + * 体指当前page实例,某些场景下,需要指明在哪个page执行hideLoading。 + */ + page: any; + } + /** + * 隐藏消息提示框 + */ + function hideLoading(options?: HideLoadingOptions): void; + + interface Badge { + /** 需要飘红的选项的索引,从0开始 */ + index: number; + /** + * 飘红类型,支持 none(无红点)/ point(纯红点) / num(数字红点)/ text(文案红点)/ more(...) + * + */ + type: 'none' | 'point' | 'num' | 'text' | 'more' | string; + + /** + * 自定义飘红文案: + * + * 1、type为none/point/more时本文案可不填 + * 2、type为num时本文案为小数或<=0均不显示, >100 显示"..." + */ + text: string; + } + interface ActionSheetOptions extends BaseOptions { + /** 菜单标题 */ + title?: string; + /** + * 菜单按钮文字数组 + */ + items: string[]; + /** + * 取消按钮文案。默认为‘取消’。注:Android平台此字段无效,不会显示取消按钮。 + */ + cancelButtonText?: string; + /** + * (iOS特殊处理)指定按钮的索引号,从0开始,使用场景:需要删除或清除数据等类似场景,默认红色 + */ + destructiveBtnIndex?: number; + /** + * 需飘红选项的数组,数组内部对象字段见下表 + */ + badges?: Array>; + /** + * 接口调用成功的回调函数 + */ + success?(res: { + /** + * 用户点击的按钮,从上到下的顺序,从0开始 + */ + index: number; + }): void; + } + /** + * 显示操作菜单 + */ + function showActionSheet(options: ActionSheetOptions): void; + //#endregion + + //#region 下拉刷新 https://docs.alipay.com/mini/api/ui-pulldown + /** + * Page 实现的接口对象 + */ + interface PageOptions { + /** + * 下拉刷新 + * 在 Page 中定义 onPullDownRefresh 处理函数,监听该页面用户下拉刷新事件。 + * 需要在页面对应的 .json 配置文件中配置 "pullRefresh": true 选项,才能开启下拉刷新事件。 + * 当处理完数据刷新后,调用 my.stopPullDownRefresh 可以停止当前页面的下拉刷新。 + */ + onPullDownRefresh?(this: Page): void; + } + /** + * 停止当前页面的下拉刷新。 + */ + function stopPullDownRefresh(): void; + //#endregion + + //#region 联系人 https://docs.alipay.com/mini/api/ui-contact + interface ChoosePhoneContactOptions extends BaseOptions { + success(result: { + name: string; // 选中的联系人姓名 + mobile: string; // 选中的联系人手机号 + }): void; + /** + * 10 没有权限 + * 11 用户取消操作(或设备未授权使用通讯录) + */ + fail?(error: 10 | 11): void; + } + /** + * 选择本地系统通信录中某个联系人的电话。 + */ + function choosePhoneContact(options: ChoosePhoneContactOptions): void; + + interface ChooseAlipayContactOptions extends BaseOptions { + /** 单次最多选择联系人个数,默认 1,最大 10 */ + count: number; + success(result: { + realName: string; // 账号的真实姓名 + mobile: string; // 账号对应的手机号码 + email: string; // 账号的邮箱 + avatar: string; // 账号的头像链接 + userId: string; // 支付宝账号唯一 userId + }): void; + /** + * 10 没有权限 + * 11 用户取消操作(或设备未授权使用通讯录) + */ + fail?(error: 10 | 11): void; + } + /** + * 唤起支付宝通讯录,选择一个或者多个支付宝联系人。 + */ + function chooseAlipayContact(options: ChooseAlipayContactOptions): void; + + interface ContactsDic { + /** + * 支付宝账号唯一 userId + */ + userId: string; + /** + * 账号的头像链接 + */ + avatar: string; + /** + * 账号对应的手机号码 + */ + mobile: string; + /** + * 账号的真实姓名 + */ + realName: string; + /** + * 账号的显示名称:也即支付宝设置的备注名称,默认为朋友圈里面的昵称 + */ + displayName: string; // 账号的显示名称:也即支付宝设置的备注名称,默认为朋友圈里面的昵称 + } + interface ChooseContactOptions extends BaseOptions { + /** 选择类型,值为single(单选)或者 multi(多选) */ + chooseType: 'single' | 'multi' | string; + /** 包含手机通讯录联系人的模式:默认为不包含(none)、或者仅仅包含双向通讯录联系人(known)、或者包含手机通讯录联系人(all) */ + includeMobileContactMode?: 'none' | 'known' | 'all' | string; + /** 是否包含自己 */ + includeMe?: boolean; + /** 最大选择人数,仅 chooseType 为 multi 时才有效 */ + multiChooseMax?: number; + /** 多选达到上限的文案,仅 chooseType 为 multi 时才有效 */ + multiChooseMaxTips?: string; + + success(result: { + contactsDicArray: ContactsDic[]; + }): void; + } + /** + * 唤起选人组件,默认只包含支付宝联系人,可以通过修改参数包含手机通讯录联系人或者双向通讯录联系人。 + */ + function chooseContact(options: ChooseContactOptions): void; + //#endregion + + //#region 选择城市 https://docs.alipay.com/mini/api/ui-city + interface City { + city: string; // 城市名 + adCode: string; // 行政区划代码 + spell?: string; // 城市名对应拼音拼写,方便用户搜索 + } + interface ChooseCityOptions extends BaseOptions { + showLocatedCity: boolean; // 是否显示当前定位城市,默认 false + showHotCities: boolean; // 是否显示热门城市,默认 true + cities: City[]; // 自定义城市列表,列表内对象字段见下表 + hotCities: City[]; // 自定义热门城市列表,列表内对象字段见下表 + success(result: { city: string; adCode: string; }): void; + } + /** + * 打开城市选择列表 + * + * 如果用户没有选择任何城市直接点击了返回,将不会触发回调函数。 + */ + function chooseCity(options: Partial): void; + //#endregion + + //#region 选择日期 https://docs.alipay.com/mini/api/ui-date + interface DatePickerOptions extends BaseOptions { + /** + * 返回的日期格式, + * 1. yyyy-MM-dd(默认) + * 2. HH:mm + * 3. yyyy-MM-dd HH:mm + * 4. yyyy-MM (最低基础库:1.1.1, 可用 canIUse('datePicker.object.format.yyyy-MM') 判断) + * 5. yyyy (最低基础库:1.1.1,可用 canIUse('datePicker.object.format.yyyy') 判断) + */ + format: 'yyyy-MM-dd' | 'HH:mm' | 'yyyy-MM-dd HH:mm' | 'yyyy-MM' | 'yyyy'; + /** 初始选择的日期时间,默认当前时间 */ + currentDate: string; + /** 最小日期时间 */ + startDate: string; + /** 最大日期时间 */ + endDate: string; + success(result: { date: string; }): void; + /** 11 用户取消操作 */ + fail(error: 11): void; + } + /** + * 打开日期选择列表 + */ + function datePicker(optiosn: Partial): void; + //#endregion + + //#region 动画 https://docs.alipay.com/mini/api/ui-animation + type TimingFunction = + | "linear" + | "ease" + | "ease-in" + | "ease-in-out" + | "ease-out" + | "step-start" + | "step-end"; + interface CreateAnimationOptions { + /** 动画持续时间,单位ms,默认值 400 */ + duration: number; + /** 定义动画的效果,默认值"linear",有效值:"linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end" */ + timeFunction: TimingFunction; + /** 动画持续时间,单位 ms,默认值 0 */ + delay: number; + /** 设置transform-origin,默认为"50% 50% 0" */ + transformOrigin: string; + } + interface Animator { + actions: AnimationAction[]; + } + interface AnimationAction { + animates: Animate[]; + option: AnimationActionOption; + } + interface AnimationActionOption { + transformOrigin: string; + transition: AnimationTransition; + } + interface AnimationTransition { + delay: number; + duration: number; + timingFunction: TimingFunction; + } + interface Animate { + type: string; + args: any[]; + } + /** + * 创建动画实例 animation。调用实例的方法来描述动画,最后通过动画实例的export方法将动画数据导出并传递给组件的animation属性。 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + function createAnimation(options: Partial): Animation; + /** 动画实例可以调用以下方法来描述动画,调用结束后会返回自身,支持链式调用的写法。 */ + interface Animation { + /** + * 调用动画操作方法后要调用 step() 来表示一组动画完成, + * 可以在一组动画中调用任意多个动画方法, + * 一组动画中的所有动画会同时开始, + * 一组动画完成后才会进行下一组动画。 + * @param options 指定当前组动画的配置 + */ + step(options?: CreateAnimationOptions): void; + /** + * 导出动画操作 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + export(): Animator; + /** 透明度,参数范围 0~1 */ + opacity(value: number): Animation; + /** 颜色值 */ + backgroundColor(color: string): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + width(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + height(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + top(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + left(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + bottom(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + right(length: number): Animation; + /** deg的范围-180~180,从原点顺时针旋转一个deg角度 */ + rotate(deg: number): Animation; + /** deg的范围-180~180,在X轴旋转一个deg角度 */ + rotateX(deg: number): Animation; + /** deg的范围-180~180,在Y轴旋转一个deg角度 */ + rotateY(deg: number): Animation; + /** deg的范围-180~180,在Z轴旋转一个deg角度 */ + rotateZ(deg: number): Animation; + /** 同transform-function rotate3d */ + rotate3d(x: number, y: number, z: number, deg: number): Animation; + /** + * 一个参数时,表示在X轴、Y轴同时缩放sx倍数; + * 两个参数时表示在X轴缩放sx倍数,在Y轴缩放sy倍数 + */ + scale(sx: number, sy?: number): Animation; + /** 在X轴缩放sx倍数 */ + scaleX(sx: number): Animation; + /** 在Y轴缩放sy倍数 */ + scaleY(sy: number): Animation; + /** 在Z轴缩放sy倍数 */ + scaleZ(sz: number): Animation; + /** 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数 */ + scale3d(sx: number, sy: number, sz: number): Animation; + /** + * 一个参数时,表示在X轴偏移tx,单位px; + * 两个参数时,表示在X轴偏移tx,在Y轴偏移ty,单位px。 + */ + translate(tx: number, ty?: number): Animation; + /** + * 在X轴偏移tx,单位px + */ + translateX(tx: number): Animation; + /** + * 在Y轴偏移tx,单位px + */ + translateY(ty: number): Animation; + /** + * 在Z轴偏移tx,单位px + */ + translateZ(tz: number): Animation; + /** + * 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz,单位px + */ + translate3d(tx: number, ty: number, tz: number): Animation; + /** + * 参数范围-180~180; + * 一个参数时,Y轴坐标不变,X轴坐标延顺时针倾斜ax度; + * 两个参数时,分别在X轴倾斜ax度,在Y轴倾斜ay度 + */ + skew(ax: number, ay?: number): Animation; + /** 参数范围-180~180;Y轴坐标不变,X轴坐标延顺时针倾斜ax度 */ + skewX(ax: number): Animation; + /** 参数范围-180~180;X轴坐标不变,Y轴坐标延顺时针倾斜ay度 */ + skewY(ay: number): Animation; + /** + * 同transform-function matrix + */ + matrix( + a: number, + b: number, + c: number, + d: number, + tx: number, + ty: number + ): Animation; + /** 同transform-function matrix3d */ + matrix3d( + a1: number, + b1: number, + c1: number, + d1: number, + a2: number, + b2: number, + c2: number, + d2: number, + a3: number, + b3: number, + c3: number, + d3: number, + a4: number, + b4: number, + c4: number, + d4: number + ): Animation; + } + //#endregion + + //#region 画布 https://docs.alipay.com/mini/api/ui-canvas + interface ToTempFilePathOptions extends BaseOptions { + x: number; // 画布 x 轴起点,默认为 0 + y: number; // 画布 y 轴起点,默认为 0 + width: number; // 画布宽度,默认为 canvas 宽度 - x + height: number; // 画布高度,默认为 canvas 高度 - y + destWidth: number; // 输出的图片宽度,默认为 width + destHeight: number; // 输出的图片高度,默认为 height + } + type Color = string | number[] | number | CanvasAction; + + interface CanvasAction { + /** + * 创建一个颜色的渐变点。 + * 小于最小 stop 的部分会按最小 stop 的 color 来渲染,大于最大 stop 的部分会按最大 stop 的 color 来渲染。 + * + * @param stop 渐变点位置,值必须在 [0,1] 范围内 + * @param color 颜色值 + */ + addColorStop(stop: number, color: Color): void; + } + + interface TextMetrics { + width: number; + } + + interface ConvasContext { + font: string; + /** + * 把当前画布的内容导出生成图片,并返回文件路径。 + */ + toTempFilePath(options?: Partial): void; + /** + * textAlign 是 Canvas 2D API 描述绘制文本时,文本的对齐方式的属性。注意,该对齐是基于 + * CanvasRenderingContext2D.fillText 方法的x的值。所以如果 textAlign="center",那么该文本将画在 x-50%*width + */ + setTextAlign(textAlign: 'left' | 'right' | 'center' | 'start' | 'end'): void; + /** + * textBaseline 是 Canvas 2D API 描述绘制文本时,当前文本基线的属性。 + */ + setTextBaseline(textBaseline: 'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom'): void; + /** + * 设置填充色。 + * + * 如果没有设置 fillStyle,则默认颜色为 black。 + */ + setFillStyle(color: Color): void; + /** + * 设置边框颜色。 + * + * 如果没有设置 strokeStyle,则默认颜色为 black。 + */ + setStrokeStyle(color: Color): void; + /** + * 设置阴影样式。 + * 如果没有设置,offsetX 的默认值为 0, offsetY 的默认值为 0, blur 的默认值为 0,color 的默认值为 black。 + * @param offsetX 阴影相对于形状水平方向的偏移 + * @param offsetY 阴影相对于形状竖直方向的偏移 + * @param blur 0~100 阴影的模糊级别,值越大越模糊 + * @param color 阴影颜色 + */ + setShadow(offsetX: number, offsetY: number, blur: number, color: Color): void; + + /** + * 创建一个线性的渐变色。 + * + * @param x0 起点 x 坐标 + * @param y0 起点 y 坐标 + * @param x1 终点 x 坐标 + * @param y1 终点 y 坐标 + */ + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasAction; + + /** + * 创建一个圆形的渐变色。 + * 起点在圆心,终点在圆环。 + * 需要使用 addColorStop() 来指定渐变点,至少需要两个。 + * @param x 圆心 x 坐标 + * @param y 圆心 y 坐标 + * @param r 圆半径 + * @returns + */ + createCircularGradient(x: number, y: number, r: number): CanvasAction; + + /** + * 设置线条的宽度。 + * @param lineWidth 线条宽度,单位为 px + */ + setLineWidth(lineWidth: number): void; + + /** + * 设置线条的端点样式。 + * + * @param lineCap 线条的结束端点样式 + */ + setLineCap(lineCap: 'round' | 'butt' | 'square'): void; + + /** + * 设置线条的交点样式。 + * + * @param lineJoin 线条的结束交点样式 + */ + setLineJoin(lineJoin: 'round' | 'bevel' | 'miter'): void; + + /** + * 设置最大斜接长度,斜接长度指的是在两条线交汇处内角和外角之间的距离。 当 setLineJoin() 为 miter 时才有效。超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示 + * + * @param miterLimit 最大斜接长度 + */ + setMiterLimit(miterLimit: number): void; + + /** + * 创建一个矩形。 + * + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + rect(x: number, y: number, width: number, height: number): void; + + /** + * 填充矩形。 + * 用 setFillStyle() 设置矩形的填充色,如果没设置则默认是 black。 + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + fillRect(x: number, y: number, width: number, height: number): void; + + /** + * 画一个矩形(非填充)。 + * 用 setFillStroke() 设置矩形线条的颜色,如果没设置默认是 black。 + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + strokeRect(x: number, y: number, width: number, height: number): void; + + /** + * 清除画布上在该矩形区域内的内容。 + * clearRect 并非画一个白色的矩形在地址区域,而是清空,为了有直观感受,可以对 canvas 加了一层背景色。 + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + clearRect(x: number, y: number, width: number, height: number): void; + + /** + * 对当前路径中的内容进行填充。默认的填充色为黑色。 + * + */ + fill(): void; + + /** + * 画出当前路径的边框。默认 black。 + * stroke() 描绘的的路径是从 beginPath() 开始计算,但是不会将 strokeRect() 包含进去 + */ + stroke(): void; + + /** + * 关闭一个路径 + * 关闭路径会连接起点和终点。 + * 如果关闭路径后没有调用 fill() 或者 stroke() 并开启了新的路径,那之前的路径将不会被渲染。 + */ + beginPath(): void; + + /** + * 关闭一个路径 + * 关闭路径会连接起点和终点。 + * + */ + closePath(): void; + + /** + * 把路径移动到画布中的指定点,不创建线条。 + * 用 stroke() 方法来画线条 + * @param x 目标位置 x 坐标 + * @param y 目标位置 y 坐标 + */ + moveTo(x: number, y: number): void; + + /** + * lineTo 方法增加一个新点,然后创建一条从上次指定点到目标点的线。 + * 用 stroke() 方法来画线条 + * + * @param x 目标位置 x 坐标 + * @param y 目标位置 y 坐标 + */ + lineTo(x: number, y: number): void; + + /** + * 画一条弧线。 + * 创建一个圆可以用 arc() 方法指定其实弧度为0,终止弧度为 2 * Math.PI。 + * + * @param x + * @param y + * @param r + * @param sAngle + * @param eAngle + */ + arc(x: number, y: number, r: number, sAngle: number, eAngle: number): void; + + /** + * 创建三次方贝塞尔曲线路径。 + * 曲线的起始点为路径中前一个点。 + * @param cp1x + * @param cp1y + * @param cp2x + * @param cp2y + * @param x + * @param y + */ + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + + /** + * 将当前创建的路径设置为当前剪切路径。 + * + */ + clip(): void; + + /** + * 创建二次贝塞尔曲线路径。 + * 曲线的起始点为路径中前一个点。 + * @param cpx 贝塞尔控制点 x 坐标 + * @param cpy 贝塞尔控制点 y 坐标 + * @param x 结束点 x 坐标 + * @param y 结束点 y 坐标 + */ + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + + /** + * 在调用scale方法后,之后创建的路径其横纵坐标会被缩放。多次调用scale,倍数会相乘。 + * + * @param scaleWidth 横坐标缩放倍数 (1 = 100%,0.5 = 50%,2 = 200%) + * @param scaleHeight 纵坐标轴缩放倍数 (1 = 100%,0.5 = 50%,2 = 200%) + */ + scale(scaleWidth: number, scaleHeight: number): void; + + /** + * 以原点为中心,原点可以用 translate方法修改。顺时针旋转当前坐标轴。多次调用rotate,旋转的角度会叠加。 + * + * @param rotate 旋转角度,以弧度计(degrees * Math.PI/180;degrees 范围为0~360) + */ + rotate(rotate: number): void; + + /** + * 对当前坐标系的原点(0, 0)进行变换,默认的坐标系原点为页面左上角。 + * + * @param x 水平坐标平移量 + * @param y 竖直坐标平移量 + */ + translate(x: number, y: number): void; + + /** + * 设置字体大小。 + * + * @param fontSize 字号 + */ + setFontSize(fontSize: number): void; + + /** + * 在画布上绘制被填充的文本。 + * + * @param text 文本 + * @param x 绘制文本的左上角 x 坐标 + * @param y 绘制文本的左上角 y 坐标 + */ + fillText(text: string, x: number, y: number): void; + + /** + * 绘制图像,图像保持原始尺寸。 + * + * @param imageResource 图片资源, 只支持线上 cdn 地址或离线包地址,线上 cdn 需返回头 Access-Control-Allow-Origin: * + * @param x 图像左上角 x 坐标 + * @param y 图像左上角 y 坐标 + * @param width 图像宽度 + * @param height 图像高度 + */ + drawImage(imageResource: string, x: number, y: number, width: number, height: number): void; + + /** + * 设置全局画笔透明度。 + * + * @param alpha 透明度,0 表示完全透明,1 表示不透明 范围 [0, 1] + */ + setGlobalAlpha(alpha: number): void; + + /** + * 设置虚线的样式 + * + * @param segments 一组描述交替绘制线段和间距(坐标空间单位)长度的数字。 如果数组元素的数量是奇数, 数组的元素会被复制并重复。例如, [5, 15, 25] 会变成 [5, 15, 25, 5, 15, 25]。 + */ + setLineDash(segments: number[]): void; + + /** + * 使用矩阵多次叠加当前变换的方法,矩阵由方法的参数进行描述。你可以缩放、旋转、移动和倾斜上下文。 + * + * @param scaleX 水平缩放 + * @param skewX 水平倾斜 + * @param skewY 垂直倾斜 + * @param scaleY 垂直缩放 + * @param translateX 水平移动 + * @param translateY 垂直移动 + */ + transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void; + + /** + * 使用单位矩阵重新设置(覆盖)当前的变换并调用变换的方法,此变换由方法的变量进行描述。 + * + * @param scaleX 水平缩放 + * @param skewX 水平倾斜 + * @param skewY 垂直倾斜 + * @param scaleY 垂直缩放 + * @param translateX 水平移动 + * @param translateY 垂直移动 + */ + setTransform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void; + + /** + * 保存当前的绘图上下文。 + * + */ + save(): void; + + /** + * 恢复之前保存的绘图上下文。 + */ + restore(): void; + + /** + * 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。 + * 绘图上下文需要由 my.createCanvasContext(canvasId) 来创建。 + * @param [reserve] 本次绘制是否接着上一次绘制,即 reserve 参数为 false 时则在本次调用 drawCanvas绘制之前 native 层应先清空画布再继续绘制;若 reserver 参数为true 时,则保留当前画布上的内容,本次调用drawCanvas绘制的内容覆盖在上面,默认 false + */ + draw(reserve?: boolean): void; + + measureText(text: string): TextMetrics; + } + /** + * 创建 canvas 绘图上下文 + * + * 该绘图上下文只作用于对应 canvasId 的 + */ + function createCanvasContext(canvasId: string): ConvasContext; + //#endregion + + //#region 地图 https://docs.alipay.com/mini/api/ui-map + interface GetCenterLocationOptions extends BaseOptions { + success?(res: { longitude: string; latitude: string; }): void; + } + + interface MapContext extends BaseOptions { + /** + * 获取当前地图中心的经纬度,返回 gcj02 坐标系的值,可以用于 my.openLocation + * + * @param options + */ + getCenterLocation(options: GetCenterLocationOptions): void; + /** + * 将地图中心移动到当前定位点,需要配合 map 组件的 show-location 使用 + */ + moveToLocation(): void; + } + + /** + * 创建并返回一个 map 上下文对象 mapContext。 + * + * @param mapId + * @returns + */ + function createMapContext(mapId: string): MapContext; + + //#endregion + + //#region 键盘 https://docs.alipay.com/mini/api/ui-hidekeyboard + /** + * 隐藏键盘 + * + */ + function hideKeyboard(): void; + //#endregion + + //#region 滚动 https://docs.alipay.com/mini/api/scroll + interface PageScrollToOptions { + scrollTop: number; // 滚动到页面的目标位置,单位 px + } + + /** + * 滚动到页面的目标位置 + * + * @param options + */ + function pageScrollTo(options: PageScrollToOptions): void; + //#endregion + + //#region 节点查询 https://docs.alipay.com/mini/api/selector-query + interface RectArea { + /** 节点的左边界坐标 */ + left: number; + /** 节点的右边界坐标 */ + right: number; + /** 节点的上边界坐标 */ + top: number; + /** 节点的下边界坐标 */ + bottom: number; + /** 节点的宽度 */ + width: number; + /** 节点的高度 */ + height: number; + } + interface NodesRefRect extends RectArea { + /** 节点的ID */ + id: string; + /** 节点的dataset */ + dataset: any; + } + interface NodeRefOffset { + /** 节点的ID */ + id: string; + /** 节点的dataset */ + dataset: any; + /** 节点的水平滚动位置 */ + scrollLeft: number; + /** 节点的竖直滚动位置 */ + scrollTop: number; + } + interface NodesRef { + /** + * 添加节点的布局位置的查询请求,相对于显示区域,以像素为单位。 + * 其功能类似于DOM的getBoundingClientRect。 + * 返回值是nodesRef对应的selectorQuery。 + * 返回的节点信息中,每个节点的位置用 + * left、right、top、bottom、width、height字段描述。 + * 如果提供了callback回调函数,在执行selectQuery的exec方法后 + * 节点信息会在callback中返回。 + */ + boundingClientRect( + callback?: (rect: T) => void + ): SelectorQuery; + /** + * 添加节点的滚动位置查询请求,以像素为单位。 + * 节点必须是scroll-view或者viewport。 + * 返回值是nodesRef对应的selectorQuery。 + * 返回的节点信息中,每个节点的滚动位置用scrollLeft、scrollHeight字段描述。 + * 如果提供了callback回调函数,在执行selectQuery的exec方法后,节点信息会在callback中返回。 + */ + scrollOffset(callback?: (rect: NodeRefOffset) => void): SelectorQuery; + // /** + // * 获取节点的相关信息,需要获取的字段在fields中指定。 + // * 返回值是nodesRef对应的selectorQuery。 + // */ + // fields( + // fields: NodeRefFieldsOptions, + // callback?: (result: any) => void + // ): SelectorQuery; + } + /** + * SelectorQuery对象实例 + */ + interface SelectorQuery { + // /** + // * 将选择器的选取范围更改为自定义组件component内 + // * (初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点 + // * @version 1.6.0 + // */ + // in(component: Component): SelectorQuery; + /** + * 在当前页面下选择第一个匹配选择器selector的节点,返回一个NodesRef对象实例,可以用于获取节点信息。 + * selector类似于CSS的选择器,但仅支持下列语法。 + * + ID选择器:#the-id + * + class选择器(可以连续指定多个):.a-class.another-class + * + 子元素选择器:.the-parent > .the-child + * + 后代选择器:.the-ancestor .the-descendant + * + 跨自定义组件的后代选择器:.the-ancestor >>> .the-descendant + * + 多选择器的并集:#a-node, .some-other-nodes + */ + select(selector: string): NodesRef; + /** + * 在当前页面下选择匹配选择器selector的节点,返回一个NodesRef对象实例。 + * 与selectorQuery.selectNode(selector)不同的是,它选择所有匹配选择器的节点。 + */ + selectAll(selector: string): NodesRef; + /** + * 选择显示区域,可用于获取显示区域的尺寸、滚动位置等信息 + * 返回一个NodesRef对象实例。 + */ + selectViewport(): NodesRef; + /** + * 执行所有的请求 + * 请求结果按请求次序构成数组,在callback的第一个参数中返回。 + */ + exec(callback?: (result: any[]) => void): void; + } + /** + * 获取一个节点查询对象 SelectorQuery。 + * + * @param page 可以指定 page 属性,默认为当前页面 + * @returns + */ + function createSelectorQuery(page?: any): SelectorQuery; + //#endregion + + //#region 级联选择 https://docs.alipay.com/mini/api/ewdxl3 + interface MultiLevelSelectItem { + name: string; + subList?: MultiLevelSelectItem[]; + } + interface MultiLevelSelectOptions extends BaseOptions { + title?: string; // 标题 + list?: MultiLevelSelectItem[]; // 选择数据列表 + name?: string; // 条目名称 + subList?: MultiLevelSelectItem[]; // 子条目列表 + success?(res: { + success: boolean; // 是否选择完成,取消返回false + result: MultiLevelSelectItem[]; // 选择的结果,如[{“name”:”杭州市”},{“name”:”上城区”},{“name”:”古翠街道”}] + }): void; + } + + function multiLevelSelect(options?: MultiLevelSelectOptions): void; + //#endregion +} + +// 开放接口 +declare namespace my { + //#region 用户授权 https://docs.alipay.com/mini/api/openapi-authorize + interface GetAuthCodeOptions extends BaseOptions { + scopes?: string | string[]; // 授权类型,默认 auth_base。支持 auth_base(静默授权)/ auth_user(主动授权) / auth_zhima(芝麻信用) + success?(res: { + authCode: string; // 授权码 + authErrorScope: { + [scope: string]: number; + }; // 失败的授权类型,key是授权失败的 scope,value 是对应的错误码 + authSucessScope: string[]; // 成功的授权 scope + }): void; + } + /** + * 获取授权码。 + * 详细用户授权接入参考 [指引](https://docs.alipay.com/mini/introduce/auth)。 + */ + function getAuthCode(options: GetAuthCodeOptions): void; + //#endregion + + //#region 客户端获取会员信息 https://docs.alipay.com/mini/api/userinfo + interface GetAuthUserInfoOptions extends BaseOptions { + success?(res: { + nickName: string; // 用户昵称 + avatar: string; // 用户头像链接 + }): void; + } + /** + * 客户端获取会员信息 + * 获取会员信息首先需要获取用户授权,详细会员信息获取参考[指引](https://docs.alipay.com/mini/introduce/auth),采用 jsapi 调用的方式。 + */ + function getAuthUserInfo(options: GetAuthUserInfoOptions): void; + //#endregion + + //#region 小程序唤起支付 https://docs.alipay.com/mini/api/openapi-pay + interface TradePayOptions extends BaseOptions { + tradeNO?: string; // 接入小程序支付时传入此参数。此参数为支付宝交易号 + success?(res: { + // resultCode | 描述 + // -----------|------ + // 9000 | 订单支付成功 + // 8000 | 正在处理中 + // 4000 | 订单支付失败 + // 6001 | 用户中途取消 + // 6002 | 网络连接出错 + // 6004 | 支付结果未知(有可能已经支付成功),请查询商户订单列表中订单的支付状态 + // 99 | 用户点击忘记密码导致快捷界面退出(only iOS) + resultCode: string; + }): void; + } + /** + * 发起支付。 + * 详细接入支付方式参考[指引](https://docs.alipay.com/mini/introduce/pay)。 + * @param options + */ + function tradePay(options: TradePayOptions): void; + //#endregion + + //#region 支付代扣签约 https://docs.alipay.com/mini/api/pay-sign + interface PaySignCenterOptions extends BaseOptions { + signStr: string; // 签约字符串 + } + + /** + * 签约中心 + * + * 返回码 | 含义 + * ------|------ + * 7000 | 协议签约成功 + * 7001 | 签约结果未知(有可能已经签约成功),请根据外部签约号查询签约状态 + * 7002 | 协议签约失败 + * 6001 | 用户中途取消 + * 6002 | 网络连接错误 * @param options + */ + function paySignCenter(options: PaySignCenterOptions): void; + //#endregion + + //#region 小程序二维码 https://docs.alipay.com/mini/api/openapi-qrcode + // @see https://docs.alipay.com/mini/api/openapi-qrcode + // @see https://docs.alipay.com/mini/introduce/qrcode + //#endregion + + //#region 跳转支付宝卡包 https://docs.alipay.com/mini/api/card-voucher-ticket + /** + * 打开支付宝卡列表。 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openCardList(): void; + interface OpenMerchantCardList extends BaseOptions { + partnerId: string; // 商户编号 + } + + /** + * 打开支付宝卡列表。 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + * @param options + */ + function openMerchantCardList(options: OpenMerchantCardList): void; + + interface OpenCardDetailOptions extends BaseOptions { + passId: string; // 卡实例Id + } + /** + * 打开当前用户的某张卡的详情页 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + * + * passId获取方式: + * 1)通过alipass创建的卡 + * 调用alipay.pass.instance.add(支付宝pass新建卡券实例接口)接口,在出参“result”中可获取 + * 2)通过会员卡创建的卡 + * 调用alipay.marketing.card.query(会员卡查询)接口,在schema_url中可获取,具体参数为“p=xxx”,xxx即为passId。 + */ + function openCardDetail(options: OpenCardDetailOptions): void; + + /** + * 打开支付宝券列表 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + * + * @param options + */ + function openVoucherList(): void; + + interface OpenMerchantVoucherListOptions extends BaseOptions { + partnerId: string; // 商户编号 + } + /** + * 打开当前用户的某个商户的券列表 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openMerchantVoucherList(options: OpenMerchantVoucherListOptions): void; + + interface OpenVoucherDetailOptions1 extends BaseOptions { + passId: string; // 券实例Id,调用券发放接口可以获取该参数(如果传入了partnerId和serialNumber则不需传入) + } + interface OpenVoucherDetailOptions2 extends BaseOptions { + partnerId: string; // 商户编号,以 2088 为开头(如果传入了passId则不需传入) + serialNumber: string; // 序列号,调用新建卡券模板可以获取该参数(如果传入了passId则不需传入) + } + /** + * 打开当前用户的某张券的详情页(非口碑) + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openVoucherDetail(options: OpenVoucherDetailOptions1 | OpenVoucherDetailOptions2): void; + + interface OpenKBVoucherDetailOptions1 extends BaseOptions { + passId: string; // 卡实例Id(如果传入了partnerId和serialNumber则不需传入) + } + interface OpenKBVoucherDetailOptions2 extends BaseOptions { + partnerId: string; // 商户编号(如果传入了passId则不需传入) + serialNumber: string; // 序列号(如果传入了passId则不需传入) + } + /** + * 打开当前用户的某张券的详情页(口碑) + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openKBVoucherDetail(options: OpenKBVoucherDetailOptions1 | OpenKBVoucherDetailOptions2): void; + + /** + * 打开支付宝票列表。 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openTicketList(): void; + + interface OpenMerchantTicketListOptions extends BaseOptions { + partnerId: string; // 商户编号 + } + /** + * 打开某个商户的票列表 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openMerchantTicketList(options: OpenMerchantTicketListOptions): void; + + interface OpenTicketDetailOptions1 extends BaseOptions { + passId: string; // 卡实例Id(如果传入了partnerId和serialNumber则不需要传入passId) + } + interface OpenTicketDetailOptions2 extends BaseOptions { + partnerId: string; // 商户编号(如果传入了passId则不需要传入partnerId) + serialNumber: string; // 序列号(如果传入了passId则不需要传入serialNumber) + } + /** + * 打开当前用户的某张票的详情页 + * + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openTicketDetail(options: OpenTicketDetailOptions1 | OpenTicketDetailOptions2): void; + //#endregion + + //#region 会员开卡授权 https://docs.alipay.com/mini/api/add-card-auth + interface AddCardAuthResult { + success: true | boolean; // true 表示领卡成功 + resultStatus: string; // 9000 表示成功 + result: { + app_id: string; // 应用id + auth_code: string; // 授权码,用于换取authtoken + state: string; // 授权的state + scope: string; // 授权scope + template_id: string; // 会员卡模板Id + request_id: string; // 会员卡表单信息请求Id + out_string: string; // 会员卡领卡链接透传参数 + }; + } + interface AddCardAuthResult { + success: false | boolean; // false 表示领卡失败 + /** + * 失败的错误码 + * 领卡失败 code 说明 + * 名称 | 类型 | 说明 + * -----|-----|----- + * JSAPI_SERVICE_TERMINATED | String | 用户取消 + * JSAPI_PARAM_INVALID | String | url 为空或非法参数 + * JSAPI_SYSTEM_ERROR | String | 系统错误 + */ + code: string; + } + interface AddCardAuthOptions extends BaseOptions { + /** + * 开卡授权的页面地址,从alipay.marketing.card.activateurl.apply接口获取 + */ + url: string; + success?(res: AddCardAuthResult): void; + } + /** + * 小程序唤起会员开卡授权页面,小程序接入会员卡[点此查看](https://docs.alipay.com/mini/introduce/card) + */ + function addCardAuth(options: AddCardAuthOptions): void; + //#endregion + + //#region 芝麻认证 https://docs.alipay.com/mini/api/zm-service + interface StartZMVerifyOptions extends BaseOptions { + bizNo: string; // 认证标识 + success?(res: { + token: string; // 认证标识 + passed: string; // 认证是否通过 + reason?: string; // 认证不通过原因 + }): void; + } + /** + * 芝麻认证接口,调用此接口可以唤起芝麻认证页面并进行人脸身份验证。 + * 有关芝麻认证的产品和接入介绍,详见 [芝麻认证](https://docs.alipay.com/mini/introduce/zm-verify)。 + * 需要通过蚂蚁开发平台,调用certification.initialize接口进行[认证初始化](https://docs.alipay.com/zmxy/271/105914)。获得biz_no 后,方能通过以下接口激活芝麻认证小程序。 + */ + function startZMVerify(options: StartZMVerifyOptions): void; + //#endregion + + //#region 信用借还 https://docs.alipay.com/mini/api/zmcreditborrow + interface ZMCreditBorrowOptions extends BaseOptions { + /** + * 外部订单号,需要唯一,由商户传入,芝麻内部会做幂等控制,格式为:yyyyMMddHHmmss+随机数 + * + */ + out_order_no: string; + /** + * 信用借还的产品码,传入固定值:w1010100000000002858 + */ + product_code: string; + /** + * 物品名称,最长不能超过14个汉字 + */ + goods_name: string; + /** + * 租金单位,租金+租金单位组合才具备实际的租金意义。 + * 取值定义如下: + * DAY_YUAN: 元 / 天 + * HOUR_YUAN: 元 / 小时 + * YUAN: 元 + * YUAN_ONCE: 元 / 次 + */ + rent_unit: string; + /** + * 租金,租金 + 租金单位组合才具备实际的租金意义。 + * > 0.00元,代表有租金 + * = 0.00元,代表无租金,免费借用 + * 注:参数传值必须 >= 0,传入其他值会报错参数非法 + */ + rent_amount: string; + /** + * 押金,金额单位:元。 + * 注:不允许免押金的用户按此金额支付押金;当物品丢失时,赔偿金额不得高于该金额。 + */ + deposit_amount: string; + /** + * 该字段目前默认传Y; + * 是否支持当借用用户信用不够(不准入)时,可让用户支付押金借用: + * Y: 支持 + * N: 不支持 + * 注:支付押金的金额等同于deposit_amount。 + */ + deposit_state?: string; // 该字段目前默认传Y; + /** + * 回调到商户的小程序schema地址。说明:商户的回调地址可以在商户后台里进行配置,服务端回调时,首先根据参数:invoke_type 查询是否有对应的配置地址,如果有,则使用已定义的地址,否则,使用该字段定义的地址执行回调; + * 参考表格下方的说明一; + * 小程序回调地址参考表格下方的说明三; + * 说明一: + * 支付宝商户账号登录我的商家服务打开入口链接; + * 商家服务中选择“您可能需要->信用借还”或者点击链接; + * 场景ID配置->配置新ID,选择对应的业务类型、服务类目和联盟,将生成的场景ID作为credit_biz的值传入即可; + * 回调地址配置->设置小程序回调地址,注意:若设置了该回调地址,则接口my.zmCreditBorrow中的入参invoke_return_url将会失效,以该处设置为准; + * 说明三: + * 小程序回调地址示例一:alipays://platformapi/startapp?appId=1999; + * 小程序回调地址示例二:alipays://platformapi/startapp?appId=1999&page=pages/map; + */ + invoke_return_url?: string; + /** + * 商户访问蚂蚁的对接模式,默认传TINYAPP: + * TINYAPP:回跳至小程序地址; + * WINDOWS:支付宝服务窗,默认值; + */ + invoke_type?: 'TINYAPP' | 'TINYAPP' | 'WINDOWS' | string; + /** + * 信用业务服务,注意:该字段不能为空,且必须根据说明的指引配置商户专属的场景ID,商户自助接入时,登录后台可配置场景ID,将后台配置的场景ID作为该字段的输入; + * 参考说明一自助进行配置; + */ + credit_biz: string; + /** + * 商户订单创建的起始借用时间,格式:YYYY - MM - DD HH: MM: SS。如果不传入或者为空,则认为订单创建起始时间为调用此接口时的时间。 + */ + borrow_time?: string; + /** + * 到期时间,不允许为空,请根据实际业务合理设置该值,格式:YYYY - MM - DD HH: MM: SS,是指最晚归还时间,表示借用用户如果超过此时间还未完结订单(未归还物品或者未支付租金)将会进入逾期状态,芝麻会给借用用户发送催收提醒;需要晚于borrow_time。 + */ + expiry_time: string; + /** + * 借用用户的手机号码,可选字段。推荐商户传入此值,会将此手机号码与用户身份信息进行匹配验证,防范欺诈风险。 + */ + mobile_no?: string; + /** + * 物品借用地点的描述,便于用户知道物品是在哪里借的。可为空 + * + */ + borrow_shop_name?: string; + /** + * 租金的结算方式,非必填字段,默认是支付宝租金结算支付 merchant:表示商户自行结算,信用借还不提供租金支付能力; alipay:表示使用支付宝支付功能,给用户提供租金代扣及赔偿金支付能力; + * + */ + rent_settle_type?: 'merchant' | 'alipay' | string; + /** + * 商户请求状态上下文。商户发起借用服务时,需要在借用结束后返回给商户的参数,格式:json; + * 如果json的某一项值包含中文,请使用encodeURIComponent对该值进行编码; + * @example + * var ext = { + * name: encodeURIComponent('名字') + * }; + * var obj = { + * invoke_state: JSON.stringify(ext) + * } + */ + invoke_state?: string; + /** + * 租金信息描述, 长度不超过14个汉字,只用于页面展示给C端用户,除此之外无其他意义。 + */ + rent_info?: string; + /** + * 借用用户的真实姓名,非必填字段。但name和cert_no必须同时非空,或者同时为空,一旦传入会对用户身份进行校验。 + */ + name?: string; + /** + * 借用用户的真实身份证号,非必填字段。但name和cert_no必须同时非空,或者同时为空,一旦传入会对用户身份进行校验。 + */ + cert_no?: string; + /** + * 借用用户的收货地址,可选字段,最大长度128。推荐商户传入此值,会将此手机号码与用户身份信息进行匹配验证,防范欺诈风险。 + */ + address?: string; + success?(res: { + /** + * 6001 用户取消了业务流程 + * 6002 网络异常 + * 9000 成功 + * 4000 系统异常 + */ + resultStatus: '6001' | '6002' | '9000' | '4000' | string; + result: { + /** + * 商户发起借用服务时传入的参数,需要在借用结束后返回给商户的参数 + * @example + * {"user_name":"john"} + */ + invoke_state: string; + /** + * 外部订单号,需要唯一,由商户传入,芝麻内部会做幂等控制,格式为:yyyyMMddHHmmss+4位随机数 + * @example + * 201610010000283627 + */ + out_order_no: string; + /** + * 芝麻信用借还订单号 + * @example + * 10020027631 + */ + order_no: string; + /** + * 是否准入:Y:准入;N:不准入(该字段目前无实际意义) + */ + admit_state: 'Y' | 'N' | string; + /** + * 物品借用/租赁者的用户id + * @example + * 2088202924240029 + */ + user_id: string; + callbackData: any; // todo only in example + } + }): void; + } + function zmCreditBorrow(options: ZMCreditBorrowOptions): void; + //#endregion + + //#region 文本风险识别 https://docs.alipay.com/mini/api/text-identification + type TextRiskIdentificationType = 'keyword' | '0' | '1' | '2' | '3' | string; + interface TextRiskIdentificationOptions extends BaseOptions { + /** + * 需要进行风险识别的文本内容 + */ + content: string; + /** + * 识别类型:keyword 表示关键词、0 表示广告、1表示涉政、2表示涉黄、3表示低俗辱骂 + */ + type: TextRiskIdentificationType[]; + success?(res: { + result: { + /** + * 目标内容文本识别到的类型,keyword 表示关键词、0 表示广告、1表示涉政、2表示涉黄、3表示低俗辱骂 + */ + type: TextRiskIdentificationType; + /** + * 仅当识别命中了 type 为 keyword 时,才会返回该字段 + */ + hitKeywords?: string[]; + /** + * 识别命中得分,最高分100分。仅当识别没有命中 keyword ,但入参中包含了广告或涉政或涉黄时,才会返回该字段 + */ + score?: string; + }; + fail?(res: { + /** + * 识别错误码 + */ + error: string; + /** + * 识别错误消息 + */ + errorMessage: string; + }): void; + }): void; + } + /** + * 文本风险识别, **支付宝客户端10.1.10及以上版本支持。**详细接入参考[指引](https://docs.alipay.com/mini/introduce/text-identification) + */ + function textRiskIdentification(options: TextRiskIdentificationOptions): void; + //#endregion + + //#region 小程序跳转 https://docs.alipay.com/mini/api/open-miniprogram + interface NavigateToMiniProgramOptions extends BaseOptions { + /** + * 要跳转的目标小程序appId + */ + appId: string; + /** + * 打开的页面路径,如果为空则打开首页 + */ + path?: string; + /** + * 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch() ,App.onShow() 中获取到这份数据 + */ + extraData?: any; + /** + * 要打开的小程序版本,有效值 develop(开发版),trial(体验版),release(正式版) ,仅在当前小程序为开发版或体验版时此参数有效;如果当前小程序是正式版,则打开的小程序必定是正式版。默认值 release + */ + envVersion?: 'develop' | 'trial' | 'release' | string; + } + /** + * 跳转到其他小程序。详细接入参考[指引](https://docs.alipay.com/mini/introduce/open-miniprogram) + * @param options + */ + function navigateToMiniProgram(options: NavigateToMiniProgramOptions): void; + interface NavigateBackMiniProgramOptions extends BaseOptions { + /** + * 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch(),App.onShow() 中获取到这份数据 + */ + extraData?: any; + } + /** + * 跳转回上一个小程序,只有当另一个小程序跳转到当前小程序时才会能调用成功 + */ + function navigateBackMiniProgram(options: NavigateBackMiniProgramOptions): void; + //#endregion + + //#region webview组件控制 https://docs.alipay.com/mini/api/webview-context + interface WebViewContext { + postMessage(param: any): void; + } + /** + * 创建并返回 web-view 上下文 webViewContext 对象。 + * + * @param webviewId 要创建的web-view所对应的id属性 + */ + function createWebViewContext(webviewId: string): WebViewContext; + //#endregion +} + +// 多媒体 +declare namespace my { + //#region 图片 https://docs.alipay.com/mini/api/media-image + type ImageSourceType = "album" | "camera"; + interface ChooseImageOptions extends BaseOptions { + /** 最大可选照片数,默认1张 */ + count: number; + /** 相册选取或者拍照,默认 [‘camera’,‘album’] */ + sourceType: ImageSourceType[]; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success(res: { + /** + * 图片文件描述 + */ + apFilePaths: string[]; + }): void; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: Partial): void; + + interface PreviewImageOptions extends BaseOptions { + /** 当当前显示图片索引,默认 0 */ + current?: number; + /** 要预览的图片链接列表 */ + urls: string[]; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + + interface SaveImageOptions extends BaseOptions { + /** + * 要保存的图片链接 + */ + url: string; + success?(res: { errMsg: string }): void; + } + /** + * 保存在线图片到手机相册。 + */ + function saveImage(options: SaveImageOptions): void; + + interface CompressImageOptions extends BaseOptions { + /** + * 要压缩的图片地址数组 + */ + apFilePaths: string[]; + /** + * 压缩级别,支持 0 ~ 4 的整数,默认 4。详见「compressLevel表 说明表」 + * compressLevel表 + * compressLevel | 说明 + * --------------|----- + * 0 | 低质量 + * 1 | 中等质量 + * 2 | 高质量 + * 3 | 不压缩 + * 4 | 根据网络适应 + */ + compressLevel?: 0 | 1 | 2 | 3 | 4; + success?(res: { + /** + * 压缩后的路径数组 + */ + apFilePaths: string[]; + }): void; + } + /** + * 压缩图片。扫码体验: + */ + function compressImage(options: CompressImageOptions): void; + + interface GetImageInfoOptions extends BaseOptions { + /** + * 图片路径,目前支持: + * - 网络图片路径 + * - apFilePath路径 + * - 相对路径 + */ + src: string; + success?(res: { + width: number; // 图片宽度(单位px) + height: number; // 图片高度(单位px) + path: string; // 图片本地路径 + }): void; + } + /** + * 获取图片信息 + */ + function getImageInfo(options: GetImageInfoOptions): void; + //#endregion +} + +// 缓存 +declare namespace my { + //#region 缓存 https://docs.alipay.com/mini/api/storage + interface SetStorageOptions extends BaseOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 需要存储的内容 */ + data: any; + } + /** + * 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的数据。 + * 这是异步接口。 + */ + function setStorage(options: SetStorageOptions): void; + + /** + * 同步将数据存储在本地缓存中指定的 key 中。 + * 这是同步接口。 + * + * @param key 本地缓存中的指定的 key + * @param data 需要存储的内容 + */ + function setStorageSync(options: { key: string; data: any; }): void; + + interface GetStorageOptions extends BaseOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 接口调用的回调函数,res = {data: key对应的内容} */ + success(res: DataResponse): void; + } + /** + * 获取缓存数据。 + * 这是异步接口。 + */ + function getStorage(options: GetStorageOptions): void; + + /** + * 同步获取缓存数据。 + * 这是同步接口 + */ + function getStorageSync(options: { key: string; }): any; + + interface RemoveStorageOptions extends BaseOptions { + key: string; + } + /** + * 删除缓存数据。 + * 这是异步接口。 + */ + function removeStorage(options: RemoveStorageOptions): void; + + /** + * 同步删除缓存数据。 + * 这是同步接口。 + * @param key 缓存数据的key + */ + function removeStorageSync(options: { key: string; }): void; + + /** + * 清除本地数据缓存。 + * 这是异步接口。 + */ + function clearStorage(): void; + + /** + * 同步清除本地数据缓存。 + * 这是同步接口。 + */ + function clearStorageSync(): void; + + interface StorageInfo { + /** + * 当前storage中所有的key + */ + keys: string[]; + /** + * 当前占用的空间大小, 单位kb + */ + currentSize: number; + /** + * 限制的空间大小,单位kb + */ + limitSize: number; + } + interface GetStorageInfoOptions extends BaseOptions { + success(res: StorageInfo): void; + } + /** + * 异步获取当前storage的相关信息 + */ + function getStorageInfo(options: GetStorageInfoOptions): void; + + function getStorageInfoSync(): StorageInfo; + //#endregion +} + +// 文件 +declare namespace my { + //#region 文件 https://docs.alipay.com/mini/api/file + interface SavedFileData { + /** 文件保存路径 */ + apFilePath: string; + } + interface SaveFileOptions extends BaseOptions { + /** 文件路径 */ + apFilePath: string; + success?(res: SavedFileData): void; + } + /** + * 保存文件到本地(本地文件大小总容量限制:10M) + */ + function saveFile(options: SaveFileOptions): void; + + interface GetFileInfoSuccess { + /** 文件大小,单位:B */ + size: number; + /** 摘要结果 */ + digest: string; + } + interface GetFileInfoOptions extends BaseOptions { + /** 文件路径 */ + apFilePath: string; + /** 摘要算法,支持md5和sha1,默认为md5 */ + digestAlgorithm?: 'md5' | 'sha1'; + success?(options: GetFileInfoSuccess): void; + } + /** + * 获取文件信息 + * 基础库版本 1.4.0 开始支持,低版本需做兼容处理 + */ + function getFileInfo(options: GetFileInfoOptions): void; + + interface SavedFileInfoData { + /** + * 文件大小,单位B + */ + size: number; + /** + * 创建时间 + */ + createTime: number; + } + interface GetSavedFileInfoOptions extends BaseOptions { + /** 文件路径 */ + apFilePath: string; + /** 接口调用成功的回调函数 */ + success?(res: SavedFileInfoData): void; + } + /** + * 获取保存的文件信息 + */ + function getSavedFileInfo(options: GetSavedFileInfoOptions): void; + + interface GetSavedFileListOptions extends BaseOptions { + success?(res: { + fileList: Array<{ + /** 文件大小 */ + size: number; + /** 创建时间 */ + createTime: number; + /** 文件路径 */ + apFilePath: string; + }> + }): void; + } + function getSavedFileList(options: GetSavedFileListOptions): void; + + type RemoveSavedFileOptions = GetSavedFileInfoOptions; + /** + * 删除某个保存的文件 + */ + function removeSavedFile(options: RemoveSavedFileOptions): void; + //#endregion +} + +// 位置 +declare namespace my { + //#region 位置 https://docs.alipay.com/mini/api/location + interface LocationData { + /** 经度 */ + longitude: string; + /** 纬度 */ + latitude: string; + /** 精确度,单位m */ + accuracy: string; + /** + * 水平精确度,单位m + */ + horizontalAccuracy: string; + /** + * 国家(type>0生效) + */ + country?: string; + /** + * 国家编号 (type>0生效) + */ + countryCode?: string; + /** + * 省份(type>0生效) + */ + province?: string; + /** + * 城市(type>0生效) + */ + city?: string; + /** + * 城市级别的地区代码(type>0生效) + */ + cityAdcode?: string; + /** + * 区县(type>0生效) + */ + district?: string; + /** + * 区县级别的地区代码(type>0生效) + */ + districtAdcode?: string; + /** + * 需要街道级别逆地理的才会有的字段,街道门牌信息,结构是:{ street, number } (type > 1生效) + */ + streetNumber?: { + street: string; + number: string; + }; + /** + * 需要POI级别逆地理的才会有的字段, 定位点附近的 POI 信息,结构是:{ name, address } (type > 2生效) + */ + pois?: Array<{ + name: string; + address: string; + }>; + } + interface GetLocationOptions extends BaseOptions { + /** + * 支付宝客户端经纬度定位缓存过期时间,单位秒。默认 30s。使用缓存会加快定位速度,缓存过期会重新定位 + */ + cacheTimeout: number; + /** + * 0:默认,获取经纬度 + * 1:获取经纬度和详细到区县级别的逆地理编码数据 + * 2:获取经纬度和详细到街道级别的逆地理编码数据,不推荐使用 + * 3:获取经纬度和详细到POI级别的逆地理编码数据,不推荐使用 + */ + type: 0 | 1 | 2 | 3; + /** 接口调用成功的回调函数,返回内容详见返回参数说明。 */ + success(res: LocationData): void; + } + /** + * 获取用户当前的地理位置信息 + */ + function getLocation(options: Partial): void; + + interface OpenLocationOptions extends BaseOptions { + /** 经度 */ + longitude: number | string; + /** 纬度 */ + latitude: number | string; + /** 位置名称 */ + name: string; + /** 地址的详细说明 */ + address: string; + /** 缩放比例,范围 3~19,默认为 15 */ + scale?: number; + } + /** + * 使用微信内置地图查看位置 + */ + function openLocation(options: OpenLocationOptions): void; + + interface ChooseLocationData { + /** + * 位置名称 + */ + name: string; + /** + * 详细地址 + */ + address: string; + /** + * 纬度,浮点数,范围为-90~90,负数表示南纬 + */ + latitude: number; + /** + * 经度,浮点数,范围为-180~180,负数表示西经 + */ + longitude: number; + } + interface ChooseLocationOptions extends BaseOptions { + success(res: ChooseLocationData): void; + } + /** + * 使用支付宝内置地图选择地理位置。 + */ + function chooseLocation(options: ChooseLocationOptions): void; + //#endregion +} + +// 网络 +declare namespace my { + //#region 网络 https://docs.alipay.com/mini/api/network + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 目标服务器url */ + url: string; + /** 设置请求的 HTTP 头,默认 {'Content-Type': 'application/x-www-form-urlencoded'} */ + header?: RequestHeader; + /** 默认GET,目前支持GET,POST */ + method?: "GET" | "POST"; + /** 请求的参数 */ + data?: any; + /** + * 超时时间,单位ms,默认30000 + */ + timeout?: number; + /** 期望返回的数据格式,默认json,支持json,text,base64 */ + dataType?: 'json' | 'text' | 'base64'; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + } + function httpRequest(options: RequestOptions): void; + + interface UploadFileOptions extends BaseOptions { + /** 开发者服务器地址 */ + url: string; + /** 要上传文件资源的本地定位符 */ + filePath: string; + /** 文件名,即对应的 key, 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + fileName: string; + /** + * 文件类型 + */ + fileType: 'image' | 'video' | 'audio'; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form 数据 */ + formData?: any; + success?(res: { + /** 服务器返回的数据 */ + data: string; + /** HTTP 状态码 */ + statusCode: string; + header: any; + }): void; + } + /** + * 上传本地资源到开发者服务器。 + */ + function uploadFile(options: UploadFileOptions): void; + + interface DownloadFileOptions extends BaseOptions { + /** 下载文件地址 */ + url: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 下载文件资源到本地。 + */ + function downloadFile(options: DownloadFileOptions): void; + + interface ConnectSocketOptions extends BaseOptions { + /** 目标服务器url */ + url: string; + /** 请求的参数 */ + data?: any; + /** 设置请求的头部 */ + header?: RequestHeader; + method?: 'GET' | 'POST'; // todo missing in api + } + /** + * 创建一个 WebSocket 的连接; + * 一个支付宝小程序同时只能保留一个 WebSocket 连接,如果当前已存在 WebSocket 连接,会自动关闭该连接,并重新创建一个新的 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + + /** + * 监听WebSocket连接打开事件。 + */ + function onSocketOpen(callback: () => void): void; + + /** + * 监听WebSocket关闭。 + */ + function onSocketClose(callback: () => void): void; + + /** + * 取消监听WebSocket连接打开事件。 + */ + function offSocketOpen(callback: () => void): void; + + /** + * 监听WebSocket错误。 + */ + function onSocketError(callback: (error: any) => void): void; + + /** + * 取消监听WebSocket错误。 + */ + function offSocketError(callback: (error: any) => void): void; + + interface SendSocketMessageOptions extends BaseOptions { + /** + * 需要发送的内容:普通的文本内容 String 或者经 base64 编码后的 String + */ + data: string | ArrayBuffer; + /** + * 如果需要发送二进制数据,需要将入参数据经 base64 编码成 String 后赋值 data,同时将此字段设置为true,否则如果是普通的文本内容 String,不需要设置此字段 + */ + isBuffer?: boolean; + } + /** + * 通过 WebSocket 连接发送数据,需要先使用 my.connectSocket 发起建连,并在 my.onSocketOpen 回调之后再发送数据。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: (res: { + /** + * 需要发送的内容:普通的文本内容 String 或者经 base64 编码后的 String + */ + data: string | ArrayBuffer; + /** + * 如果需要发送二进制数据,需要将入参数据经 base64 编码成 String 后赋值 data,同时将此字段设置为true,否则如果是普通的文本内容 String,不需要设置此字段 + */ + isBuffer?: boolean; + }) => void): void; + function offSocketMessage(callback: (error: any) => void): void; + + interface CloseSocketOptions extends BaseOptions { + success?(res: any): void; + } + /** + * 监听WebSocket关闭。 + */ + function closeSocket(options?: CloseSocketOptions): void; + + /** + * 取消监听WebSocket关闭。 + */ + function offSocketClose(callback: (error: any) => void): void; + //#endregion +} + +// 设备 +declare namespace my { + //#region canIUse https://docs.alipay.com/mini/api/can-i-use + /** + * 判断当前小程序的 API、入参或返回值、组件、属性等在当前版本是否支持。 + * 参数使用 ${API}.${type}.${param}.${option} 或者 ${component}.${attribute}.${option} 方式来调用 + * - API 表示 api 名字 + * - type 取值 object/return/callback 表示 api 的判断类型 + * - param 表示参数的某一个属性名 + * - option 表示参数属性的具体属性值 + * - component 表示组件名称 + * - attribute 表示组件属性名 + * - option 表示组件属性值 + */ + function canIUse(api: string): boolean; + //#endregion + + //#region 获取基础库版本号 https://docs.alipay.com/mini/api/sdk-version + const SDKVersion: string; + //#endregion + //#region 系统信息 https://docs.alipay.com/mini/api/system-info + interface SystemInfo { + /** + * 手机型号 + */ + model: string; + /** + * 设备像素比 + */ + pixelRatio: number; + /** + * 窗口宽度 + */ + windowWidth: number; + /** + * 窗口高度 + */ + windowHeight: number; + /** + * 支付宝设置的语言 + */ + language: string; + /** + * 支付宝版本号 + */ + version: string; + /** + * 设备磁盘容量 + */ + storage: string; + /** + * 当前电量百分比 + */ + currentBattery: string; + /** + * 系统版本 + */ + system: string; + /** + * 系统名:Android,iOS + */ + platform: 'Android' | 'iOS' | string; + /** + * 屏幕宽度 + */ + screenWidth: number; + /** + * 屏幕高度 + */ + screenHeight: number; + /** + * 手机品牌 + */ + brand: string; + /** + * 用户设置字体大小 + */ + fontSizeSetting: number; + /** + * 当前运行的客户端,当前是支付宝则有效值是"alipay" + */ + app: 'alipay' | string; + } + interface GetSystemInfoOptions extends BaseOptions { + success?(res: SystemInfo): void; + } + function getSystemInfo(options: GetSystemInfoOptions): void; + function getSystemInfoSync(): SystemInfo; + //#endregion + + //#region 网络状态 https://docs.alipay.com/mini/api/network-status + interface GetNetworkTypeOptions extends BaseOptions { + success?(res: { + /** 网络是否可用 */ + networkAvailable: boolean; + /** 网络类型值 UNKNOWN / NOTREACHABLE / WIFI / 3G / 2G / 4G / WWAN */ + networkType: NetworkType; + }): void; + } + type NetworkType = 'UNKNOWN' | 'NOTREACHABLE' | 'WIFI' | '3G' | '2G' | '4G' | 'WWAN'; + function getNetworkType(options: GetNetworkTypeOptions): void; + + /** + * 开始网络状态变化的监听 + */ + function onNetworkStatusChange(callback: (res: { + /** 网络是否可用 */ + isConnected: boolean; + /** 网络类型值 UNKNOWN / NOTREACHABLE / WIFI / 3G / 2G / 4G / WWAN */ + networkType: NetworkType; + }) => void): void; + + /** + * 取消网络状态变化的监听 + */ + function offNetworkStatusChange(): void; + //#endregion + + //#region 剪贴板 https://docs.alipay.com/mini/api/clipboard + interface GetClipboardOptions extends BaseOptions { + success?(res: { + text: string; + }): void; + } + function getClipboard(options: GetClipboardOptions): void; + + interface SetClipboardOptions extends BaseOptions { + /** 剪贴板数据 */ + text: string; + } + function setClipboard(options: SetClipboardOptions): void; + //#endregion + + //#region 摇一摇 https://docs.alipay.com/mini/api/shake + function watchShake(options: BaseOptions): void; + //#endregion + + //#region 震动 https://docs.alipay.com/mini/api/vibrate + /** + * 调用震动功能。 + */ + function vibrate(options?: BaseOptions): void; + + /** + * 调用震动功能。 + */ + function vibrateLong(options?: BaseOptions): void; + + /** + * 调用震动功能。 + */ + function vibrateShort(options?: BaseOptions): void; + //#endregion + + //#region 拨打电话 https://docs.alipay.com/mini/api/macke-call + interface MakePhoneCallOptions extends BaseOptions { + /** + * 需要拨打的电话号码 + */ + number: string; + } + /** + * 拨打电话 + */ + function makePhoneCall(options: MakePhoneCallOptions): void; + //#endregion + + //#region 获取服务器时间 https://docs.alipay.com/mini/api/get-server-time + interface GetServerTimeOptions extends BaseOptions { + success?(res: { + /** 服务器时间的毫秒数 */ + time: number; + }): void; + } + function getServerTime(options: GetServerTimeOptions): void; + //#endregion + + //#region 用户截屏事件 https://docs.alipay.com/mini/api/user-capture-screen + /** + * 监听用户主动截屏事件,用户使用系统截屏按键截屏时触发此事件 + */ + function onUserCaptureScreen(callback?: (res: any) => void): void; + + /** + * 取消监听截屏事件。一般需要与 my.onUserCaptureScreen 成对出现。 + */ + function offUserCaptureScreen(): void; + //#endregion + + //#region 屏幕亮度 https://docs.alipay.com/mini/api/screen-brightness + interface SetKeepScreenOnOptions extends BaseOptions { + /** 是否保持屏幕常亮 */ + keepScreenOn: boolean; + success?(res: { errMsg: string }): void; + } + /** + * 设置是否保持常亮状态。 + * 仅在当前小程序生效,离开小程序后设置失效。 + */ + function setKeepScreenOn(options?: SetKeepScreenOnOptions): void; + + interface GetScreenBrightnessOptions extends BaseOptions { + /** 屏幕亮度值,范围 0~1,0 最暗,1 最亮 */ + success(value: number): void; + } + /** + * 获取屏幕亮度 + */ + function getScreenBrightness(options?: GetScreenBrightnessOptions): void; + + interface SetScreenBrightnessOptions extends BaseOptions { + /** 需要设置的屏幕亮度,取值范围0-1 */ + brightness: number; + } + /** + * 设置屏幕亮度 + */ + function setScreenBrightness(options: SetScreenBrightnessOptions): void; + //#endregion + + //#region 权限引导 https://docs.alipay.com/mini/api/show-auth-guide + interface showAuthGuideOptions extends BaseOptions { + /** + * 引导的权限标识,用于标识该权限类型(如 LBS) + * 支持的 authType 如下: + * + * 权限名称 权限码 支持平台 + * 后台保活权限 BACKGROUNDER Android + * 桌面快捷权限 SHORTCUT Android + * 麦克风权限 MICROPHONE iOS + * 通讯录权限 ADDRESSBOOK iOS + * 相机权限 CAMERA iOS + * 照片权限 PHOTO iOS + * push通知栏权限 NOTIFICATION iOS + * 自启动权限 SELFSTARTING Android + * lbs总开关 LBSSERVICE iOS + * lbs开关(app) LBS iOS + */ + authType: 'BACKGROUNDER' | 'SHORTCUT' | 'MICROPHONE' | 'ADDRESSBOOK' | 'CAMERA' | 'PHOTO' | 'NOTIFICATION' | 'SELFSTARTING' | 'LBSSERVICE' | 'LBS'; + } + function showAuthGuide(options: showAuthGuideOptions): void; + //#endregion +} + +// 扫码 +declare namespace my { + //#region 扫码 https://docs.alipay.com/mini/api/scan + type scanType = "qr" | "bar"; + interface ScanCodeData { + /** + * 扫描二维码时返回二维码数据 + */ + code: string; + /** + * 所扫码的类型 + */ + qrCode: string; + /** + * 扫描条形码时返回条形码数据 + */ + barCode: string; + } + interface ScanOptions extends BaseOptions { + /** + * 扫码样式(默认 qr): + * 1. qr,扫码框样式为二维码扫码框 + * 1. bar,扫码样式为条形码扫码框 + */ + type?: scanType; + /** + * 是否隐藏相册(不允许从相册选择图片),只能从相机扫码 + */ + hideAlbum?: boolean; + success?(res: ScanCodeData): void; + } + /** + * 调起客户端扫码界面,扫码成功后返回对应的结果 + */ + function scan(options: ScanOptions): void; + //#endregion +} + +// 蓝牙 +declare namespace my { + //#region 快速接入 https://docs.alipay.com/mini/api/bluetooth-intro + //#endregion + + //#region API https://docs.alipay.com/mini/api/bluetooth-api + interface OpenBluetoothAdapterOptions extends BaseOptions { + /** 不传的话默认是true,表示是否在离开当前页面时自动断开蓝牙(仅对android有效) */ + autoClose: boolean; + success(res: { + /** + * 是否支持 BLE + */ + isSupportBLE: boolean; + }): void; + } + /** + * 初始化小程序蓝牙模块,生效周期为调用 my.openBluetoothAdapter 至调用 my.closeBluetoothAdapter 或小程序被销毁为止。 在小程序蓝牙适配器模块生效期间,开发者可以正常调用下面的小程序API,并会收到蓝牙模块相关的 on 事件回调。 + */ + function openBluetoothAdapter(options: Partial): void; + + interface CloseBluetoothAdapterOptions extends BaseOptions { + success(res: any): void; + } + /** + * 关闭本机蓝牙模块 + */ + function closeBluetoothAdapter(options: CloseBluetoothAdapterOptions): void; + + interface BluetoothAdapterStateData extends ErrMsgResponse { + /** + * 是否正在搜索设备 + */ + discovering: boolean; + /** + * 蓝牙模块是否可用(需支持 BLE 并且蓝牙是打开状态) + */ + available: boolean; + } + interface GetBluetoothAdapterStateOptions extends BaseOptions { + success(res: BluetoothAdapterStateData): void; + } + /** + * 获取本机蓝牙适配器状态 + */ + function getBluetoothAdapterState(options: GetBluetoothAdapterStateOptions): void; + + interface StartBluetoothDevicesDiscoveryOptions extends BaseOptions { + /** + * 蓝牙设备主 service 的 uuid 列表 + * 某些蓝牙设备会广播自己的主 service 的 uuid。如果这里传入该数组,那么根据该 uuid 列表,只搜索有这个主服务的设备。 + */ + services?: string[]; + /** + * 否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同 + */ + allowDuplicatesKey?: boolean; + /** + * 上报设备的间隔,默认为0,意思是找到新设备立即上报,否则根据传入的间隔上报 + */ + interval?: number; + } + /** + * 开始搜寻附近的蓝牙外围设备。搜索结果将在 my.onBluetoothDeviceFound 事件中返回。 + */ + function startBluetoothDevicesDiscovery(options: StartBluetoothDevicesDiscoveryOptions): void; + + interface StopBluetoothDevicesDiscoveryOptions extends BaseOptions { + success(res: ErrMsgResponse): void; + } + /** + * 停止搜寻附近的蓝牙外围设备。请在确保找到需要连接的设备后调用该方法停止搜索。 + */ + function stopBluetoothDevicesDiscovery(options: StopBluetoothDevicesDiscoveryOptions): void; + + /** + * 蓝牙设备信息 + */ + interface BluetoothDevice { + /** + * 蓝牙设备名称,某些设备可能没有 + */ + name: string; + /** + * (兼容旧版本) 值与 name 一致 + */ + deviceName: string; + /** + * 广播设备名称 + */ + localName: string; + /** + * 设备的 id + */ + deviceId: string; + /** + * 设备信号强度 + */ + RSSI: number; + /** + * 设备的广播内容 + */ + advertisData: ArrayBuffer; + /** + * 设备的manufacturerData + */ + manufacturerData: ArrayBuffer; + } + interface GetBluetoothDevicesOptions extends BaseOptions { + success( + res: { + devices: BluetoothDevice[]; + } & ErrMsgResponse + ): void; + } + /** + * 获取所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备。 + */ + function getBluetoothDevices(options: GetBluetoothDevicesOptions): void; + + interface GetConnectedBluetoothDevicesOptions extends BaseOptions { + services?: string[]; + success( + res: { + devices: BluetoothDevice[]; + } & ErrMsgResponse + ): void; + } + /** + * 获取处于已连接状态的设备。 + */ + function getConnectedBluetoothDevices(options: GetConnectedBluetoothDevicesOptions): void; + + interface BLEDeviceOptions extends BaseOptions { + /** + * 蓝牙设备id + */ + deviceId: string; + } + /** + * 连接低功耗蓝牙设备。 + */ + function connectBLEDevice(options: BLEDeviceOptions): void; + + /** + * 断开与低功耗蓝牙设备的连接。 + */ + function disconnectBLEDevice(options: BLEDeviceOptions): void; + + interface WriteBLECharacteristicValueOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * 蓝牙设备特征值对应的值,16进制字符串,限制在20字节内 + */ + value: string; + } + /** + * 向低功耗蓝牙设备特征值中写入数据。 + */ + function writeBLECharacteristicValue( + options: WriteBLECharacteristicValueOptions + ): void; + + interface ReadBLECharacteristicValueOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + success( + res: { + characteristic: { + /** + * 蓝牙设备特征值的 uuid + */ + characteristicId: string; + /** + * 蓝牙设备特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙设备特征值对应的二进制值 + */ + value: ArrayBuffer; + }; + } & ErrMsgResponse + ): void; + } + + /** + * 读取低功耗蓝牙设备特征值中的数据。调用后在 my.onBLECharacteristicValueChange() 事件中接收数据返回。 + */ + function readBLECharacteristicValue(options: ReadBLECharacteristicValueOptions): void; + + interface NotifyBLECharacteristicValueChangeOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应 service 的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * notify 的 descriptor 的 uuid (只有android 会用到,非必填,默认值00002902-0000-10008000-00805f9b34fb) + */ + descriptorId?: string; + /** + * 是否启用notify或indicate + */ + state?: boolean; + } + function notifyBLECharacteristicValueChange(optons: NotifyBLECharacteristicValueChangeOptions): void; + + interface NotifyBLECharacteristicValueChangedOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * notify 的 descriptor 的 uuid (只有android 会用到,非必填,默认值00002902-0000-10008000-00805f9b34fb) + */ + descriptorId?: string; + /** + * true: 启用 notify; false: 停用 notify + */ + state: boolean; + success(res: ErrMsgResponse): void; + } + /** + * 启用低功耗蓝牙设备特征值变化时的 notify 功能。注意:设备的特征值必须支持 notify/indicate 才可以成功调用,具体参照 characteristic 的 properties 属性 另外,必须先启用 notify 才能监听到设备 characteristicValueChange 事件。 + */ + function notifyBLECharacteristicValueChanged(options: NotifyBLECharacteristicValueChangedOptions): void; + + interface GetBLEDeviceServicesOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success(res: { + services: Array<{ + /** + * 蓝牙设备服务的 uuid + */ + serviceId: string; + /** + * 该服务是否为主服务 + */ + isPrimary: boolean; + }>; + } & ErrMsgResponse): void; + } + /** + * 获取蓝牙设备所有 service(服务) + */ + function getBLEDeviceServices(options: GetBLEDeviceServicesOptions): void; + + interface GetBLEDeviceCharacteristicsOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙服务 uuid + */ + serviceId: string; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success(res: { + characteristics: Array<{ + /** + * 蓝牙设备特征值的 uuid + */ + characteristicId: string; + /** + * 蓝牙设备特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙设备特征值对应的16进制值 + */ + value: ArrayBuffer; + /** + * 该特征值支持的操作类型 + */ + properties: Array<{ + /** + * 该特征值是否支持 read 操作 + */ + read: boolean; + /** + * 该特征值是否支持 write 操作 + */ + write: boolean; + /** + * 该特征值是否支持 notify 操作 + */ + notify: boolean; + /** + * 该特征值是否支持 indicate 操作 + */ + indicate: boolean; + }>; + }>; + } & ErrMsgResponse): void; + } + /** + * 获取蓝牙设备所有 characteristic(特征值) + */ + function getBLEDeviceCharacteristics(options: GetBLEDeviceCharacteristicsOptions): void; + + interface OnBluetoothDeviceFoundOptions extends BaseOptions { + success?(res: { + devices: BluetoothDevice[]; + }): void; + } + /** + * 搜索到新的蓝牙设备时触发此事件。 + */ + function onBluetoothDeviceFound(options: OnBluetoothDeviceFoundOptions): void; + + /** + * 移除寻找到新的蓝牙设备事件的监听。 + */ + function offBluetoothDeviceFound(callback?: any): void; + + interface OnBLECharacteristicValueChangeOptions extends BaseOptions { + success?(res: { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应 service 的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * 特征值最新的16进制值 + */ + value: ArrayBuffer; + }): void; + } + /** + * 监听低功耗蓝牙设备的特征值变化的事件。 + */ + function onBLECharacteristicValueChange(options: OnBLECharacteristicValueChangeOptions): void; + + interface OnBLEConnectionStateChangedOptions extends BaseOptions { + success?(res: { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 连接目前的状态 + */ + connected: boolean; + }): void; + } + /** + * 移除低功耗蓝牙设备的特征值变化事件的监听。 + */ + function offBLECharacteristicValueChange(callback?: any): void; + + /** + * 监听低功耗蓝牙连接的错误事件,包括设备丢失,连接异常断开等。 + */ + function onBLEConnectionStateChanged(options: OnBLEConnectionStateChangedOptions): void; + + /** + * 移除低功耗蓝牙连接状态变化事件的监听。 + */ + function offBLEConnectionStateChanged(): void; + + interface BluetoothAdapterState { + /** + * 蓝牙适配器是否可用 + */ + available: boolean; + /** + * 蓝牙适配器是否处于搜索状态 + */ + discovering: boolean; + } + /** + * 监听本机蓝牙状态变化的事件。 + */ + function onBluetoothAdapterStateChange(callback: (res: BluetoothAdapterState) => void): void; + + /** + * 移除本机蓝牙状态变化的事件的监听。 + */ + function offBluetoothAdapterStateChange(): void; + //#endregion +} + +// iBeacon +declare namespace my { + //#region iBeacon https://docs.alipay.com/mini/api/yqleyc + interface StartBeaconDiscoveryOptions extends BaseOptions { + /** + * iBeacon设备广播的 uuids + */ + uuids: string[]; + success?(res: ErrMsgResponse): void; + } + /** + * 开始搜索附近的iBeacon设备 + */ + function startBeaconDiscovery(options: StartBeaconDiscoveryOptions): void; + + interface StopBeaconDiscoveryOptions extends BaseOptions { + success?(res: ErrMsgResponse): void; + } + /** + * 停止搜索附近的iBeacon设备 + */ + function stopBeaconDiscovery(options: StopBeaconDiscoveryOptions): void; + + interface Beacon { + /** iBeacon 设备广播的 uuid */ + uuid: string; + /** iBeacon 设备的主 id */ + major: string; + /** iBeacon 设备的次 id */ + minor: string; + /** 表示设备距离的枚举值(0-3分别代表:未知、极近、近、远) */ + proximity: 0 | 1 | 2 | 3; + /** iBeacon 设备的距离 */ + accuracy: number; + /** iBeacon 信号强度 */ + rssi: number; + } + interface GetBeaconsSuccess { + beacons: Beacon[]; + /** + * errorCode=0 ,接口调用成功 + */ + errCode: string; + /** + * ok + */ + errMsg: string; + } + interface GetBeaconsOptions extends BaseOptions { + success?(options: GetBeaconsSuccess): void; + } + /** + * 获取所有已搜索到的iBeacon设备 + */ + function getBeacons(options: GetBeaconsOptions): void; + + interface BeaconUpdateOptions extends BaseOptions { + success?(res: { + beacons: Beacon[]; + }): void; + } + /** + * 监听 iBeacon 设备的更新事件 + */ + function onBeaconUpdate(options: BeaconUpdateOptions): void; + + interface BeaconServiceChangeOptions extends BaseOptions { + success?(res: { + /** + * 服务目前是否可用 + */ + available: boolean; + /** + * 目前是否处于搜索状态 + */ + discovering: boolean; + }): void; + } + /** + * 监听 iBeacon 服务的状态变化 + */ + function onBeaconServiceChange(options: BeaconServiceChangeOptions): void; + //#endregion +} + +// 数据安全 +declare namespace my { + //#region 数据安全 https://docs.alipay.com/mini/api/data-safe + interface RsaOptions extends BaseOptions { + /** + * 使用rsa加密还是rsa解密,encrypt加密,decrypt解密 + */ + action: string; + /** + * 要处理的文本,加密为原始文本,解密为Base64编码格式文本 + */ + text: string; + /** + * rsa秘钥,加密使用公钥,解密使用私钥 + */ + key: string; + success?(res: { + /** + * 经过处理过后得到的文本,加密为Base64编码文本,解密为原始文本 + */ + text: string; + }): void; + } + /** + * 非对称加密。 + */ + function rsa(options: RsaOptions): void; + //#endregion +} + +// 分享 +declare namespace my { + //#region 分享 https://docs.alipay.com/mini/api/share_app + //#endregion +} + +// 自定义分析 +declare namespace my { + //#region 自定义分析 https://docs.alipay.com/mini/api/report + /** + * 自定义分析数据的上报接口。使用前需要在小程序管理后台的事件管理中新建事件,并配置好事件名和字段。 + * + * @param eventName 自定义事件名,需申请 + * @param data 上报的数据 + */ + function reportAnalytics(eventName: string, data: any): void; + + /** + * 隐藏分享按钮。 + */ + function hideShareMenu(options?: BaseOptions): void; + //#endregion +} + +declare namespace my { + interface LaunchOptions { + /** + * 打开小程序的路径 + */ + path: string; + /** + * 打开小程序的query + */ + query: object; + /** + * 打开小程序的[场景值] + */ + scene: number; + /** + * shareTicket,详见 获取更多[转发信息] + */ + shareTicket: string; + /** + * 当场景为由从另一个小程序或公众号或App打开时,返回此字段 + */ + referrerInfo: object; + /** + * 来源小程序或公众号或App的 appId,详见下方说明 + */ + "referrerInfo.appId": string; + /** + * 来源小程序传过来的数据,scene=1037或1038时支持 + */ + "referrerInfo.extraData": object; + // #endregion + } + interface AppOptions { + /** + * 监听小程序初始化。 + * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次) + * 生命周期函数 + */ + onLaunch?: (this: App, option: LaunchOptions) => void; + /** + * 监听小程序显示。 + * 当小程序启动,或从后台进入前台显示,会触发 onShow + * 生命周期函数 + */ + onShow?: (this: App, option: LaunchOptions) => void; + /** + * 监听小程序隐藏。 + * 当小程序从前台进入后台,会触发 onHide + * 生命周期函数 + */ + onHide?: (this: App) => void; + /** + * 错误监听函数 + * 当小程序发生脚本错误或者 api 调用失败时 + * 会触发 onError 并带上错误信息 + */ + onError?: (this: App, msg: string) => void; + /** + * 小程序退出时触发 + */ + onUnlaunch?: (this: App) => void; + /** + * 全局Data + */ + globalData?: object; + [key: string]: any; + } + interface CreateIntersectionObserverOption { + thresholds?: [number, number]; + initialRatio?: number; + selectAll?: boolean; + } + + interface Margins { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + interface ObserveResponse { + id: string; + dataset: any; + time: number; + intersectionRatio: number; // 相交区域占目标节点的布局区域的比例 + boundingClientRect: RectArea; + intersectionRect: RectArea; + relativeRect: RectArea; + } + interface IntersectionObserver { + relativeTo(selector?: string, margins?: Margins): IntersectionObserver; + relativeToViewport(margins?: Margins): IntersectionObserver; + observe( + selector?: string, + callback?: (response: ObserveResponse) => void + ): IntersectionObserver; + disconnect(): void; + } + interface ComponentRelation { + /** 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant */ + type: "parent" | "child" | "ancestor" | "descendant"; + /** 如果这一项被设置,则它表示关联的目标节点所应具有的behavior,所有拥有这一behavior的组件节点都会被关联 */ + target?: string; + /** 关系生命周期函数,当关系被建立在页面节点树中时触发,触发时机在组件attached生命周期之后 */ + linked?: (target: Component) => void; + /** 关系生命周期函数,当关系在页面节点树中发生改变时触发,触发时机在组件moved生命周期之后 */ + linkChanged?: (target: Component) => void; + /** 关系生命周期函数,当关系脱离页面节点树时触发,触发时机在组件detached生命周期之后 */ + unlinked?: (target: Component) => void; + } + interface Component { + /** + * 组件的文件路径 + */ + is: string; + /** + * 节点id + */ + id: string; + /** + * 节点dataset + */ + dataset: string; + /** + * 组件数据,包括内部数据和属性值 + */ + data: any; + + /** + * 组件数据,包括内部数据和属性值(与 data 一致) + */ + properties: any; + /** + * 将数据从逻辑层发送到视图层,同时改变对应的 this.data 的值 + * 1. 直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致。 + * 2. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。 + * 3. 请不要把 data 中任何一项的 value 设为 undefined ,否则这一项将不被设置并可能遗留一些潜在问题 + * @param data object 以 key,value 的形式表示将 this.data 中的 key 对应的值改变成 value + * @param [callback] callback 是一个回调函数,在这次setData对界面渲染完毕后调用 + */ + setData( + data: any, + callback?: () => void + ): void; + hasBehavior(behavior: any): boolean; + triggerEvent( + name: string, + details?: any, + options?: Partial<{ + bubbles: boolean; + composed: boolean; + capturePhase: boolean; + }> + ): void; + createSelectorQuery(): SelectorQuery; + createIntersectionObserver( + options?: CreateIntersectionObserverOption + ): IntersectionObserver; + /** + * 使用选择器选择组件实例节点 + * 返回匹配到的第一个组件实例对象 + */ + selectComponent(selector: string): Component; + /** + * selector 使用选择器选择组件实例节点,返回匹配到的全部组件实例对象组成的数组 + */ + selectAllComponents(selector: string): Component[]; + getRelationNodes(relationKey: string): ComponentRelation[]; + } + interface Page extends Component { + /** + * data + */ + data: any; + /** + * 强制更新 + */ + forceUpdate(): void; + /** + * 字段可以获取到当前页面的路径。 + */ + route(): void; + /** + * 更新 + */ + update(): void; + /** + * 将页面滚动到目标位置。 + * + * scrollTop 滚动到页面的目标位置(单位px) + * [duration] 滚动动画的时长,默认300ms,单位 ms + */ + pageScrollTo(option?: PageScrollToOptions): void; + [key: string]: any; + } + interface App { + data: any; + /** + * 获取当前页面 + */ + getCurrentPage(): Page; + [key: string]: any; + } + interface EventTarget { + id: string; + tagName: string; + dataset: { [name: string]: string }; + } + type TouchEventType = + | "tap" + | "touchstart" + | "touchmove" + | "touchcancel" + | "touchend" + | "touchforcechange"; + + type TransitionEventType = + | "transitionend" + | "animationstart" + | "animationiteration" + | "animationend"; + + type EventType = + | "input" + | "form" + | "submit" + | "scroll" + | TouchEventType + | TransitionEventType + | "tap" + | "longpress"; + interface BaseEvent { + type: T; + timeStamp: number; + currentTarget: EventTarget; + target: EventTarget; + detail: Detail; + } + interface Options { + query: any; // 当前小程序的 query + path: string; // 当前小程序的页面地址 + } + interface PageOptions { + data: any; + onLaunch(this: Page, options: Options): void; + onShow(this: Page, options: Options): void; + onHide(this: Page): void; + onError(this: Page): void; + [key: string]: any; + } + function postMessage(param: any): void; + type onMessageFun = (p: any) => void; + let onMessage: onMessageFun; +} + +declare function App(app: Partial): void; + +declare function getApp(): my.App; + +declare function Behavior(options?: any): my.Component; + +declare function Component(options?: any): my.Component; + +declare function Page(options: Partial): void; + +declare function getCurrentPages(): my.Page[]; diff --git a/types/ali-app/tsconfig.json b/types/ali-app/tsconfig.json new file mode 100644 index 0000000000..a2402fac2c --- /dev/null +++ b/types/ali-app/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "esnext", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "ali-app-tests.ts" + ], + "exclude": [ + ".prettierrc" + ] +} \ No newline at end of file diff --git a/types/ali-app/tslint.json b/types/ali-app/tslint.json new file mode 100644 index 0000000000..f491d1bed9 --- /dev/null +++ b/types/ali-app/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-mergeable-namespace": false, + "no-unnecessary-generics": false + } +} \ No newline at end of file diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 6885916e8a..e488bd6b49 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -340,6 +340,7 @@ declare module 'angular' { interface IMenuService { hide(response?: any, options?: any): IPromise; + open(event?: MouseEvent): void; } interface IColorPalette { diff --git a/types/angular-promise-tracker/angular-promise-tracker-tests.ts b/types/angular-promise-tracker/angular-promise-tracker-tests.ts index 0365709cf5..6b8b8abd31 100644 --- a/types/angular-promise-tracker/angular-promise-tracker-tests.ts +++ b/types/angular-promise-tracker/angular-promise-tracker-tests.ts @@ -1,5 +1,5 @@ -angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker', - ($q: angular.IQService, promiseTracker: angular.promisetracker.PromiseTrackerService) => { +angular.module('promise-tracker-tests', []).run(['$q', '$http', 'promiseTracker', + ($q: angular.IQService, $http: angular.IHttpService, promiseTracker: angular.promisetracker.PromiseTrackerService) => { const trackerWithoutOptions = promiseTracker(); const options = { @@ -19,4 +19,8 @@ angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker', const addedPromise: angular.IDeferred = trackerWithOptions.addPromise(promiseToAdd); const trackerWithSomeOptions = promiseTracker({activationDelay: 500}); + + $http.post('/foo', {}, { }); + $http.post('/foo', {}, { tracker: trackerWithOptions }); + $http.post('/foo', {}, { tracker: [trackerWithoutOptions, trackerWithOptions] }); }]); diff --git a/types/angular-promise-tracker/index.d.ts b/types/angular-promise-tracker/index.d.ts index 85a87bad63..78849fa3e1 100644 --- a/types/angular-promise-tracker/index.d.ts +++ b/types/angular-promise-tracker/index.d.ts @@ -28,4 +28,8 @@ declare module 'angular' { (options?: PromiseTrackerOptions): PromiseTracker; } } + + interface IRequestShortcutConfig { + tracker?: angular.promisetracker.PromiseTracker | angular.promisetracker.PromiseTracker[]; + } } diff --git a/types/angular-wizard/index.d.ts b/types/angular-wizard/index.d.ts index 33fa8b2b0a..fa14a2f2f7 100644 --- a/types/angular-wizard/index.d.ts +++ b/types/angular-wizard/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mgonto/angular-wizard // Definitions by: Marko Jurisic , Ronald Wildenberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as angular from 'angular'; diff --git a/types/animejs/index.d.ts b/types/animejs/index.d.ts index a975f59513..069187b15e 100644 --- a/types/animejs/index.d.ts +++ b/types/animejs/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -type FunctionBasedParamter = (element: HTMLElement, index: number, length: number) => number; +type FunctionBasedParameter = (element: HTMLElement, index: number, length: number) => number; type AnimeCallbackFunction = (anim: anime.AnimeInstance) => void; // Allowing null is necessary because DOM queries may not return anything. type AnimeTarget = string | object | HTMLElement | SVGElement | NodeList | null; @@ -55,10 +55,10 @@ declare namespace anime { interface AnimeAnimParams { targets: AnimeTarget | ReadonlyArray; - duration?: number | FunctionBasedParamter; - delay?: number | FunctionBasedParamter; - elasticity?: number | FunctionBasedParamter; - round?: number | boolean | FunctionBasedParamter; + duration?: number | FunctionBasedParameter; + delay?: number | FunctionBasedParameter; + elasticity?: number | FunctionBasedParameter; + round?: number | boolean | FunctionBasedParameter; easing?: EasingOptions | string | ReadonlyArray; @@ -106,7 +106,7 @@ declare namespace anime { } interface AnimeTimelineAnimParams extends AnimeAnimParams { - offset: number | string | FunctionBasedParamter; + offset: number | string | FunctionBasedParameter; } interface AnimeTimelineInstance extends AnimeInstance { diff --git a/types/ansi/ansi-tests.ts b/types/ansi/ansi-tests.ts index 5d8e73e8ec..b2625defa5 100644 --- a/types/ansi/ansi-tests.ts +++ b/types/ansi/ansi-tests.ts @@ -20,5 +20,13 @@ Object.keys({ , brightCyan: 96 , brightWhite: 97 }).forEach((color) => { - cursor[color]().bold().write(`Hello, bold ${color.replace(/([a-z])([A-Z])/g, (_: string, l: string, u: string): string => `${l} ${u.toLowerCase()}`)} world!\n`).reset(); + const cname = color.replace(/([a-z])([A-Z])/g, (_: string, l: string, u: string): string => `${l} ${u.toLowerCase()}`); + + ((<(...anything: any[]) => ansi.Cursor> cursor[color])() + .bold() + .bg)[color === 'blue' || color === 'brightBlue' ? 'black' : 'blue']() + .write( + `Hello, bold ${cname} world!\n` + ) + .reset(); }); diff --git a/types/ansi/index.d.ts b/types/ansi/index.d.ts index 976268a29a..4e486d61ef 100644 --- a/types/ansi/index.d.ts +++ b/types/ansi/index.d.ts @@ -2,6 +2,7 @@ // Project: https://www.npmjs.com/package/ansi // Definitions by: Gustavo6046 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /** * References: @@ -14,11 +15,19 @@ /// import { Stream } from "stream"; -declare function ansi(stream: Stream, options?: any): ansi.Cursor; +interface CursorOptions { + enabled: boolean; + buffering: boolean; +} + +declare function ansi(stream: Stream, options?: CursorOptions): ansi.Cursor; declare namespace ansi { class Cursor { - constructor(stream: Stream, options?: any); + bg: Colorer; + fg: Colorer; + + constructor(stream: Stream, options?: CursorOptions); /** * Helper function that calls `write()` on the underlying Stream. @@ -161,7 +170,11 @@ declare namespace ansi { } interface Cursor { - [key: string]: (...anything: any[]) => Cursor; + [key: string]: ((...anything: any[]) => Cursor) | Colorer; + } + + interface Colorer { + [key: string]: (...anything: any[]) => (Cursor | Colorer); } } diff --git a/types/aphrodite/index.d.ts b/types/aphrodite/index.d.ts index 3e7807b6b6..f41aadec46 100644 --- a/types/aphrodite/index.d.ts +++ b/types/aphrodite/index.d.ts @@ -12,7 +12,7 @@ type FontFamily = | BaseCSSProperties['fontFamily'] | CSS.FontFace; -type Omit = Pick; +type Omit = Pick>; type CSSProperties = Omit & { fontFamily?: FontFamily | FontFamily[]; diff --git a/types/apostrophe/index.d.ts b/types/apostrophe/index.d.ts index 5201453542..9c415a3931 100644 --- a/types/apostrophe/index.d.ts +++ b/types/apostrophe/index.d.ts @@ -145,6 +145,9 @@ declare namespace apostrophe { required?: boolean; options?: AposObject; choices?: SelectChoice[]; + widgetType?: string; + titleField?: string; + schema?: Field[]; } interface SelectChoice { diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index 5babc4a961..238cea2379 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -1440,6 +1440,81 @@ declare module "@arangodb/foxx/router" { export = createRouter; } +declare module "@arangodb/foxx/queues" { + interface QueueItem { + name: string; + mount: string; + backOff?: ((failureCount: number) => number) | number; + maxFailures?: number; + schema?: Foxx.Schema; + preprocess?: (data: any) => any; + } + + interface Script { + name: string; + mount: string; + } + + type JobCallback = (result: any, jobData: any, job: ArangoDB.Document) => void; + + interface Job { + status: string; + queue: string; + type: Script; + failures: object[]; + runs: number; + data: any; + created: number; + modified: number; + delayUntil: number; + maxFailures: number; + repeatDelay: number; + repeatTimes: number; + repeatUntil: number; + success?: string; + failure?: string; + runFailures: number; + abort(): void; + } + + interface JobOptions { + success?: JobCallback; + failure?: JobCallback; + delayUntil?: number | Date; + backOff?: ((failureCount: number) => number) | number; + maxFailures?: number; + repeatTimes?: number; + repeatUntil?: number | Date; + repeatDelay?: number; + } + + interface Queue { + push(item: QueueItem, data: any, opts?: JobOptions): void; + get(jobId: string): ArangoDB.Document; + delete(jobId: string): boolean; + pending(script?: Script): string[]; + progress(script?: Script): string[]; + complete(script?: Script): string[]; + failed(script?: Script): string[]; + all(script?: Script): string[]; + } + + function createQueue(name: string, maxWorkers?: number): Queue; + function deleteQueue(name: string): boolean; + function get(name: string): Queue; + + export { + createQueue as create, + deleteQueue as delete, + get, + JobOptions, + Job, + Queue, + QueueItem, + Script, + }; +} + declare module "@arangodb/foxx/graphql" { import { formatError, GraphQLSchema } from "graphql"; type GraphQLModule = object; diff --git a/types/ascii-art/ascii-art-tests.ts b/types/ascii-art/ascii-art-tests.ts new file mode 100644 index 0000000000..d5a2d567f8 --- /dev/null +++ b/types/ascii-art/ascii-art-tests.ts @@ -0,0 +1,193 @@ +import art from 'ascii-art'; + +art.font('test', 'doom').toPromise(); + +art.font('my text', 'Doom', (rendered: string) => { + rendered.big(); +}); + +art.font('my text', 'Doom', '', (rendered) => { + rendered.big(); +}); + +art.artwork({ + artwork: 'textfiles.com/art/st-char.asc' +}).lines(31, 45, (rendered: string) => { + // cleanup non-unix terminators + rendered = rendered.replace(/\r/g, ''); + art.image({ + filepath : '~/Images/earth_in_space.jpg', + alphabet : 'ultra-wide' + }).overlay(rendered, { + x: 0, + y: -1, + style: 'red+blink', + transparent: '&' + }, (_final: any) => {}); +}); + +art.font('Ghost Wire BBS', 'Doom', (logo) => { + art.font('No place like home', 'rusted', (subtext) => { + art.table({ + verticalBar : ' ', + horizontalBar : ' ', + intersection : ' ', + data: [ + {name: art.style('current users', 'red'), value: '203'}, + {name: 'operator', value: 'vince.vega'}, + {name: 'dial-in', value: '(917)555-4202'}, + ] + }).lines(2, (table: any) => { + art.image({ + filepath : '~/Images/starburst_red.jpg', + alphabet : 'ultra-wide' + }).lines(2, 30).overlay(logo, { + x: 0, + y: 0, + style: 'blue', + }).overlay(subtext, { + x: 19, + y: 8, + style: 'yellow', + }).overlay(table, { + x: -1, + y: -1, + style: 'green', + }, (_final: any) => { + }); + }); + }); +}); + +art.image({ + width : 40, + filepath : '/Images/initech.png', + alphabet : 'wide' +}).font('INITECH', 'Doom', 'cyan', (_ascii) => { +}); + +art.table({ + data: [ + {text: ' .\'ANDRE. '}, + {text: ' ..THE.GIANT\'. '}, + {text: '.With.Bobby."The.Brain"'}, + {text: '.Heenan.'} + ], + verticalBar : ' ', + horizontalBar : ' ', + intersection : ' ' +}).lines(2, (table: any) => { + art.strings([ + 'ANDRE', + 'the', + 'GIANT', + 'POSSE', + '7\'4"', + '520 LB' + ], 'rusted', (andre: any, the: any, giant: any, posse: any, height: any, weight: any) => { + art.strings([ 'has', 'a'], 'twopoint', (has: any, a: any) => { + art.image({ + filepath : '/Images/andre_has_a_posse.jpeg', + alphabet : 'ultra-wide' + }).overlay(andre, { + x: 8, y: 4, + style: 'white' + }).overlay(the, { + x: 10, y: 7, + style: 'white', + transparent : true + }).overlay(giant, { + x: 8, y: 10, + style: 'white', + transparent : true + }).overlay(has, { + x: 10, y: 14, + style: 'white' + }).overlay(a, { + x: 13, y: 17, + style: 'white' + }).overlay(posse, { + x: 5, y: 20, + style: 'bright_black', + transparent: true + }).overlay(height, { + x: 59, y: 3, + style: 'bright_black', + transparent: true + }).overlay(weight, { + x: 59, y: 8, + style: 'bright_black', + transparent: true + }).overlay(table, { + x: 6, y: -6, + style: 'bright_black', + transparent: true + }, (_final: any) => { + }); + }); + }); +}); + +art.Figlet.fontPath = 'Fonts'; + +const image = new art.Image({ + filepath: '~/Images/metropolis.jpg', + alphabet: 'variant4' +}); +image.write((_err: any, _rendered: string) => { +}); + +art.font('Prompt', 'Basic', 'red').font('v1', 'Doom', 'magenta', (_rendered) => { +}); + +art.image({ + width : 40, + filepath : '/Images/initech.png', + alphabet : 'wide' +}).font('INITECH', 'Doom', 'cyan', (_ascii) => { +}); + +art.style('my text', 'red+underline'); + +art.table({ + width : 80, + data : [ /* ... */ ], + verticalBar : ' ', + horizontalBar : ' ', + intersection : ' ', + columns : [ + { + value : 'Product', + style : 'black+gray_bg' + }, { + value : 'Maker', + style : 'white' + }, { + value : 'Location', + style : 'white' + } + ] +}, (_rendered) => { + // use rendered text +}); + +art.table({ + width : 80, + data : [ /* ... */ ], + bars : { + ul_corner: '┏', + ur_corner: '┓', + lr_corner: '┛', + ll_corner: '┗', + bottom_t: '┻', + top_t: '┳', + right_t: '┫', + left_t: '┣', + intersection: '╋', + vertical: '┃', + horizontal: '━', + }, + borderColor : 'bright_white', +}, (_rendered) => { + // use rendered text +}); diff --git a/types/ascii-art/index.d.ts b/types/ascii-art/index.d.ts new file mode 100644 index 0000000000..3a753a183b --- /dev/null +++ b/types/ascii-art/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for ascii-art 1.4 +// Project: https://github.com/khrome/ascii-art +// Definitions by: Lukas Elmer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export type StyleType = (text: string, style?: string, close?: boolean) => Art; +export type FontType = ((text: string, font?: string, styleOrCallback?: string | Cb, callback?: Cb) => Art); +export type ImageType = (options: object, callback?: Cb) => Art; +export type TableType = (options: object, callback?: Cb) => Art; +export type ArtworkType = (options: object, callback?: Cb) => Art; +export type LinesType = (...options: any[]) => Art; +export type OverlayType = (...options: any[]) => Art; +export type JoinType = (...options: any[]) => Art; +export type StringsType = (...options: any[]) => Art; + +export const style: StyleType; +export const font: FontType; +export const image: ImageType; +export const table: TableType; +export const artwork: ArtworkType; +export const lines: LinesType; +export const overlay: OverlayType; +export const join: JoinType; +export const strings: StringsType; +export const Figlet: any; +export const Image: any; + +export interface Art { + style: StyleType; + font: FontType; + image: ImageType; + table: TableType; + artwork: ArtworkType; + lines: LinesType; + overlay: OverlayType; + join: JoinType; + working: boolean; + + toPromise: (() => Promise); +} + +export type Cb = (result: string) => void; diff --git a/types/ascii-art/tsconfig.json b/types/ascii-art/tsconfig.json new file mode 100644 index 0000000000..1f9759cc1f --- /dev/null +++ b/types/ascii-art/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "allowSyntheticDefaultImports": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ascii-art-tests.ts" + ] +} diff --git a/types/ascii-art/tslint.json b/types/ascii-art/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/ascii-art/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index f4251364d2..60bbf86823 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -203,3 +203,26 @@ management.linkUsers('primaryId', { user_id: 'secondaryId' }) management.linkUsers('primaryId', { user_id: 'secondaryId' }, (err: Error, result: any) => {}); +// Get all clients (with promise) +management.getClients() + .then((clients: auth0.Client[]) => { + console.log(clients); + }) + .catch((err) => { + // Handle the error + }); + +//Get all clients (with callback) +management.getClients((err: Error, clients: auth0.Client[]) => {}); + +// Get all clients with params (with promise) +management.getClients({fields:['name','client_metadata'], include_fields:true}) + .then((clients: auth0.Client[]) => { + console.log(clients); + }) + .catch((err) => { + // Handle the error + }); + +// Get all cients with params (with callback) +management.getClients({fields:['name','client_metadata'], include_fields:true}, (err:Error, clients:auth0.Client[]) => {}); diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index e03ad5aa06..ed0e9d1f3f 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for auth0 2.9.2 // Project: https://github.com/auth0/node-auth0 -// Definitions by: Wilson Hobbs , Seth Westphal , Amiram Korach +// Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -588,7 +588,19 @@ export interface ImpersonateSettingOptions { clientId?: string; } - +export type ClientAppType = 'native' | 'spa' | 'regular_web' | 'non_interactive' | 'rms' | 'box' | + 'cloudbees' | 'concur' | 'dropbox' | 'mscrm' | 'echosign' | 'egnyte' | 'newrelic' | 'office365' | + 'salesforce' | 'sentry' | 'sharepoint' | 'slack' | 'springcm' | 'zendesk' | 'zoom'; +export interface GetClientsOptions { + fields?: string[]; + include_fields?: boolean; + page?: number; + per_page?: number; + include_totals?: boolean; + is_global?: boolean; + is_first_party?: boolean; + app_type?: ClientAppType[]; +} export class AuthenticationClient { @@ -661,8 +673,9 @@ export class ManagementClient { // Clients - getClients(): Promise; - getClients(cb: (err: Error, clients: Client[]) => void): void; + getClients(params?: GetClientsOptions): Promise; + getClients(cb: (err: Error, clients: Client[]) => void ): void; + getClients(params: GetClientsOptions, cb: (err: Error, clients: Client[]) => void ): void; getClient(params: ClientParams): Promise; getClient(params: ClientParams, cb: (err: Error, client: Client) => void): void; diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 59bb2c404d..c62f6115af 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -190,6 +190,8 @@ declare namespace autobahn { export class Connection { constructor(options?: IConnectionOptions); + isOpen: boolean; + open(): void; close(reason?: string, message?: string): void; diff --git a/types/autoprefixer/index.d.ts b/types/autoprefixer/index.d.ts index 4650f1d407..faf11371db 100644 --- a/types/autoprefixer/index.d.ts +++ b/types/autoprefixer/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/postcss/autoprefixer // Definitions by: Armando Meziat , murt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import { Plugin } from "postcss"; diff --git a/types/babylon/index.d.ts b/types/babylon/index.d.ts index 07eb74bb32..b179f6f357 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -46,6 +46,7 @@ export type PluginName = 'estree' | 'jsx' | 'flow' | + 'typescript' | 'classConstructorCall' | 'doExpressions' | 'objectRestSpread' | diff --git a/types/bootstrap-toggle/bootstrap-toggle-tests.ts b/types/bootstrap-toggle/bootstrap-toggle-tests.ts new file mode 100644 index 0000000000..764415a048 --- /dev/null +++ b/types/bootstrap-toggle/bootstrap-toggle-tests.ts @@ -0,0 +1,38 @@ +import 'bootstrap-toggle'; + +const $elem = $("#toggle"); + +// Test Initialise Cases +$elem.bootstrapToggle(); + +$elem.bootstrapToggle({}); + +$elem.bootstrapToggle({ + // Defaults from source project + on: 'On', + off: 'Off', + onstyle: 'primary', + offstyle: 'default', + size: 'normal', + style: '', + width: null, + height: null +}); + +$elem.bootstrapToggle({ + width: 100, + height: 100 +}); + +$elem.bootstrapToggle({ + width: "100%", + height: "100%" +}); + +// Methods +$elem.bootstrapToggle("destroy"); +$elem.bootstrapToggle("on"); +$elem.bootstrapToggle("off"); +$elem.bootstrapToggle("toggle"); +$elem.bootstrapToggle("enable"); +$elem.bootstrapToggle("disable"); diff --git a/types/bootstrap-toggle/index.d.ts b/types/bootstrap-toggle/index.d.ts new file mode 100644 index 0000000000..51dcec9446 --- /dev/null +++ b/types/bootstrap-toggle/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for bootstrap-toggle 2.2 +// Project: https://github.com/minhur/bootstrap-toggle +// Definitions by: Mitchell Grice +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +interface BootstrapToggleOptions { + on?: string; + off?: string; + size?: string; + onstyle?: string; + offstyle?: string; + style?: string; + width?: number | string | null; + height?: number | string | null; +} + +interface JQuery { + bootstrapToggle(options?: BootstrapToggleOptions): JQuery; + bootstrapToggle(command: "destroy" | "on" | "off" | "toggle" | "enable" | "disable"): JQuery; +} diff --git a/types/bootstrap-toggle/tsconfig.json b/types/bootstrap-toggle/tsconfig.json new file mode 100644 index 0000000000..b3d28afbde --- /dev/null +++ b/types/bootstrap-toggle/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", + "bootstrap-toggle-tests.ts" + ] +} diff --git a/types/fast-diff/tslint.json b/types/bootstrap-toggle/tslint.json similarity index 100% rename from types/fast-diff/tslint.json rename to types/bootstrap-toggle/tslint.json diff --git a/types/chai-jquery/chai-jquery-tests.ts b/types/chai-jquery/chai-jquery-tests.ts index 894acf9ca5..bd798be847 100644 --- a/types/chai-jquery/chai-jquery-tests.ts +++ b/types/chai-jquery/chai-jquery-tests.ts @@ -67,6 +67,10 @@ function test_disabled() { expect($('#foo')).to.be.disabled; } +function test_enabled() { + expect($('#foo')).to.be.enabled; +} + function test_empty() { $('.empty').should.be.empty; expect($('body')).not.to.be.empty; diff --git a/types/chai-jquery/index.d.ts b/types/chai-jquery/index.d.ts index bd6826ca08..c2827d2e05 100644 --- a/types/chai-jquery/index.d.ts +++ b/types/chai-jquery/index.d.ts @@ -25,6 +25,7 @@ declare namespace Chai { selected(): Assertion; checked(): Assertion; disabled(): Assertion; + enabled(): Assertion; (selector: string): Assertion; } diff --git a/types/chordsheetjs/chordsheetjs-tests.ts b/types/chordsheetjs/chordsheetjs-tests.ts new file mode 100644 index 0000000000..7f01828e7f --- /dev/null +++ b/types/chordsheetjs/chordsheetjs-tests.ts @@ -0,0 +1,5 @@ +import { Song, HtmlTableFormatter } from 'chordsheetjs'; + +const song = new Song({ key: 'value' }); +const formatter = new HtmlTableFormatter(); +formatter.format(song); diff --git a/types/chordsheetjs/index.d.ts b/types/chordsheetjs/index.d.ts new file mode 100644 index 0000000000..ee2e69593f --- /dev/null +++ b/types/chordsheetjs/index.d.ts @@ -0,0 +1,372 @@ +// Type definitions for chordsheetjs 2.8 +// Project: https://github.com/martijnversluis/ChordSheetJS +// Definitions by: Adam Bloom +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Represents a chord with the corresponding (partial) lyrics + */ +export class ChordLyricsPair { + /** + * Initialises a ChordLyricsPair + * @param chords The chords + * @param lyrics The lyrics + */ + constructor(chords: string, lyrics: string); + + chords: string; + lyrics: string; + + /** + * Indicates whether a ChordLyricsPair should be visible in a formatted chord sheet (except for ChordPro sheets) + */ + isRenderable: () => boolean; + + /** + * Returns a deep copy of the ChordLyricsPair, useful when programmatically transforming a song + */ + clone: () => ChordLyricsPair; + + toString: () => string; +} + +/** + * Represents a tag/directive. See https://www.chordpro.org/chordpro/ChordPro-Directives.html + */ +export class Tag { + constructor(name: string, value: string | null); + + /** + * The tag full name. When the original tag used the short name, `name` will return the full name. + */ + name: string; + + /** + * The tag value + */ + value: string | null; + + static parse(tag: string): Tag | null; + static parseWithRegex(tag: string, regex: string): Tag | null; + + /** + * The original tag name that was used to construct the tag. + */ + originalName: string; + + /** + * Checks whether the tag value is a non-empty string. + */ + hasValue(): boolean; + + /** + * Checks whether the tag is usually rendered inline. It currently only applies to comment tags. + */ + isRenderable(): boolean; + + /** + * Checks whether the tag is either a standard meta tag or a custom meta directive (`{x_some_name}`) + */ + isMetaTag(): boolean; + + /** + * Returns a clone of the tag. + */ + clone(): Tag; + + toString(): string; +} + +/** + * Represents a line in a chord sheet, consisting of items of type ChordLyricsPair or Tag + */ +export class Line { + constructor(); + + /** + * The items (ChordLyricsPair or Tag) of which the line consists + */ + items: Array; + + /** + * The line type, This is set by the ChordProParser when it read tags like {start_of_chorus} or {start_of_verse} + * Values can be 'verse', 'chorus' or 'none' + */ + type: 'verse' | 'chorus' | 'none'; + + /** + * Indicates whether the line contains any items + */ + isEmpty(): boolean; + + /** + * Adds an item to the line + * @param item The item to be added + */ + addItem(item: ChordLyricsPair | Tag): void; + + /** + * Indicates whether the line contains items that are renderable + */ + hasRenderableItems(): boolean; + + /** + * Returns a deep copy of the line and all of its items + */ + clone(): Line; + + /** + * Indicates whether the line type is 'verse' + */ + isVerse(): boolean; + + /** + * Indicates whether the line type is 'chorus' + */ + isChorus(): boolean; + + /** + * Indicates whether the line contains items that are renderable. Please use hasRenderableItems + * @deprecated + */ + hasContent(): boolean; + + addChordLyricsPair( + chords: ChordLyricsPair | string, + lyrics: string + ): ChordLyricsPair; + ensureChordLyricsPair(): void; + chords(chr: string): void; + lyrics(chr: string): void; + addTag(name: Tag | string, value: string | null): Tag; +} + +/** + * Represents a paragraph of lines in a chord sheet + */ +export class Paragraph { + constructor(); + + /** + * The Line items of which the paragraph consists + */ + lines: Line[]; + + addLine(line: Line): void; + + /** + * Tries to determine the common type for all lines. If the types for all lines are equal, it returns that type. + * If not, it returns 'indeterminate'. + */ + type: string; +} + +/** + * Represents a song in a chord sheet. Currently a chord sheet can only have one song. + */ +export class Song { + constructor(metadata: object); + + /** + * The Line items of which the song consists + */ + lines: Line[]; + + /** + * The Paragraph items of which the song consists + */ + paragraphs: Paragraph[]; + + currentLine: Line; + currentParagraph: Paragraph; + assignMetaData(metadata: object): void; + + /** + * Returns the song lines, skipping the leading empty lines (empty as in not rendering any content). This is useful + * if you want to skip the "header lines": the lines that only contain meta data. + */ + bodyLines: Line[]; + + chords(chr: string): void; + lyrics(chr: string): void; + addLine(): Line; + setCurrentLineType(type: string): void; + flushLine(): void; + finish(): void; + addChordLyricsPair(): ChordLyricsPair; + ensureLine(): void; + addParagraph(): Paragraph; + ensureParagraph(): void; + addTag(tagContents: string): Tag; + + /** + * Returns a deep clone of the song + */ + clone(): Song; + + setMetaData(name: string, value: string): void; + metaData: object; + optimizedMetaData: object; + getOptimizedMetaData(): object; + optimizeMetaDataValue( + valueSet: string[] | undefined + ): string | string[] | null; + getMetaData(name: string): string | null; +} + +/** + * Represents a parser warning, currently only used by ChordProParser. + */ +export class ParserWarning { + /** + * The warning message + */ + message: string; + + /** + * The line number on which the warning occurred + */ + lineNumber: string; + + toString(): string; +} + +/** + * Parses a ChordPro chord sheet + */ +export class ChordProParser { + /** + * Parses a ChordPro chord sheet into a song + * @param chordProChordSheet The ChordPro chord sheet + */ + parse(chordProChordSheet: string): Song; + + song: Song; + lineNumber: number; + sectionType: string; + warnings: ParserWarning[]; + + parseDocument(document: string): void; + readLyrics(chr: string): void; + readChords(chr: string): void; + readTag(chr: string): void; + readComment(chr: string): void; + finishTag(): void; + resetTag(): void; + applyTag(tag: Tag): void; + startSection(sectionType: string, tag: Tag): void; + endSection(sectionType: string, tag: Tag): void; + checkCurrentSectionType(sectionType: string, tag: Tag): void; + addWarning(message: string): void; +} + +export interface ChordSheetParserProps { + preserveWhitespace: boolean; +} + +/** + * Formats a song into a plain text chord sheet + */ +export class ChordSheetParser { + constructor(props: ChordSheetParserProps); + + song: Song; + lines: Line[]; + songLine: Line; + chordLyricsPair: ChordLyricsPair; + currentLine: number; + lineCount: number; + processingText: string; + preserveWhitespace: boolean; + + /** + * Parses a chord sheet into a song + * @param chordSheet The ChordPro chord sheet + */ + parse(chordSheet: string): Song; + + parseLine(line: string): void; + parseNonEmptyLine(line: string): void; + initialize(document: string): void; + readLine(): Line; + hasNextLine(): boolean; + parseLyricsWithChords(chordsLine: string, lyricsLine: string): void; + processCharacters(chordsLine: string, lyricsLine: string): void; + addCharacter(chr: string, nextChar: string): void; + shouldAddCharacterToChords(nextChar: string): boolean; + ensureChordLyricsPairInitialized(): void; +} + +export interface SongHeader { + title: string; + subtitle: string; +} + +export class TextFormatter { + constructor(); + /** + * Formats a song into a plain text chord sheet + * @param song The song to be formatted + */ + format(song: Song): string; + formatHeader(header: SongHeader): string; + formatParagraphs(song: Song): string; + formatParagraph(paragraph: Paragraph): string; + formatLine(line: Line): string; + formatTitle(title: string): string; + formatSubtitle(subtitle: string): string; + formatTopLine(line: Line): string | null; + chordLyricsPairLength(chordLyricsPair: ChordLyricsPair): number; + formatItemTop(item: Tag | ChordLyricsPair | Line): string; + formatLineBottom(line: Line): string; + formatLineWithFormatter( + line: Line, + formatter: (x: string) => string + ): string; + formatItemBottom(item: Tag | ChordLyricsPair | Line): string; +} + +/** + * Formats a song into HTML. It uses TABLEs to align lyrics with chords, which makes the HTML for things like + * PDF conversion. + */ +export class HtmlTableFormatter { + constructor(); + /** + * Formats a song into HTML. + * @param song The song to be formatted + */ + format(song: Song): string; +} + +/** + * Formats a song into HTML. It uses DIVs to align lyrics with chords, which makes it useful for responsive web pages. + */ +export class HtmlDivFormatter { + constructor(); + /** + * Formats a song into HTML. + * @param song The song to be formatted + */ + format(song: Song): string; +} + +/** + * Formats a song into a ChordPro chord sheet + */ +export class ChordProFormatter { + constructor(); + /** + * Formats a song into a ChordPro chord sheet. + * @param song The song to be formatted + */ + format(song: Song): string; + + formatLine(line: Line): string; + formatItem(item: Tag | ChordLyricsPair | Line): string; + formatTag(tag: Tag): string; + formatChordLyricsPair(chordLyricsPair: ChordLyricsPair): string; + formatChordLyricsPairChords(chordLyricsPair: ChordLyricsPair): string; + formatChordLyricsPairLyrics(chordLyricsPair: ChordLyricsPair): string; +} diff --git a/types/chordsheetjs/tsconfig.json b/types/chordsheetjs/tsconfig.json new file mode 100644 index 0000000000..0b2e8140ca --- /dev/null +++ b/types/chordsheetjs/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", "chordsheetjs-tests.ts"] +} diff --git a/types/mobx-cookie/tslint.json b/types/chordsheetjs/tslint.json similarity index 100% rename from types/mobx-cookie/tslint.json rename to types/chordsheetjs/tslint.json diff --git a/types/ckeditor/ckeditor-tests.ts b/types/ckeditor/ckeditor-tests.ts index a6f9c9cf5c..6a0b50a4d8 100644 --- a/types/ckeditor/ckeditor-tests.ts +++ b/types/ckeditor/ckeditor-tests.ts @@ -914,6 +914,9 @@ function test_skin() { CKEDITOR.skin.loadPart('part', () => console.log('load')); var path2: string = CKEDITOR.skin.path(); + + CKEDITOR.skin.ua_dialog = 'ie,iequirks,ie8,gecko'; + CKEDITOR.skin.ua_editor = 'ie,gecko'; } function test_style() { diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 6815d3aa98..69c23d6a99 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -2,6 +2,7 @@ // Project: https://ckeditor.com/ckeditor-4/ // Definitions by: Thomas Wittwer // Stuart Long +// Viktor Pegy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // WORK-IN-PROGRESS: Any contribution support welcomed. @@ -2168,6 +2169,8 @@ declare namespace CKEDITOR { // tslint:disable-next-line:no-duplicate-variable var name: string; var ua: { [name: string]: any }; + var ua_dialog: string; + var ua_editor: string; function addIcon(name: string, path: string, offset?: number, bgsize?: string): void; function chameleon(editor: string, part: string): void; diff --git a/types/cli-table2/cli-table2-tests.ts b/types/cli-table2/cli-table2-tests.ts index dfaed4ec33..97d8c82dbe 100644 --- a/types/cli-table2/cli-table2-tests.ts +++ b/types/cli-table2/cli-table2-tests.ts @@ -230,3 +230,24 @@ table26.push( // feel free to use colors in your content strings, column widths will be calculated correctly const table27 = new Table({ colWidths: [5], style: { head: [], border: [] } }) as Table.HorizontalTable; table27.push([/*colors.red(*/'hello'/*)*/]); + +// Header as text +const table28 = new Table({ head: ["Top Header 1", "Top Header 2"] }) as Table.HorizontalTable; +table28.push( + ['Value Row 1 Col 1', 'Value Row 1 Col 2'], + ['Value Row 2 Col 1', 'Value Row 2 Col 2'] +); + +// Header as Cells +const table29 = new Table({ head: [{content: "Top Header 1"}, {content: "Top Header 2"}] }) as Table.HorizontalTable; +table29.push( + ['Value Row 1 Col 1', 'Value Row 1 Col 2'], + ['Value Row 2 Col 1', 'Value Row 2 Col 2'] +); + +// ColSpan in header +const table30 = new Table({ head: [{content: "Top Header 1", colSpan: 2}, {content: "Top Header 3"}] }) as Table.HorizontalTable; +table30.push( + ['Value Row 1 Col 1', 'Value Row 1 Col 2', 'Value Row 1 Col 3'], + ['Value Row 2 Col 1', 'Value Row 2 Col 2', 'Value Row 2 Col 3'] +); diff --git a/types/cli-table2/index.d.ts b/types/cli-table2/index.d.ts index b216b23832..865439f000 100644 --- a/types/cli-table2/index.d.ts +++ b/types/cli-table2/index.d.ts @@ -31,7 +31,7 @@ declare namespace CliTable2 { rowHeights: Array; colAligns: HorizontalAlignment[]; rowAligns: VerticalAlignment[]; - head: string[]; + head: Cell[]; wordWrap: boolean; } diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index c1ea6c99b9..86e9067b3e 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -4,6 +4,7 @@ // nrbernard // Pr1st0n // rileymiller +// toddself // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = CodeMirror; @@ -706,8 +707,27 @@ declare namespace CodeMirror { or undefined if the marker is no longer in the document. */ find(): {from: CodeMirror.Position, to: CodeMirror.Position}; + /** Called when you've done something that might change the size of the marker and want to cheaply update the display*/ + changed(): void; + /** Returns an object representing the options for the marker. If copyWidget is given true, it will clone the value of the replacedWith option, if any. */ getOptions(copyWidget: boolean): CodeMirror.TextMarkerOptions; + + /** Fired when the cursor enters the marked range */ + on(eventName: 'beforeCursorEnter', handler: () => void) : void; + off(eventName: 'beforeCursorEnter', handler: () => void) : void; + + /** Fired when the range is cleared, either through cursor movement in combination with clearOnEnter or through a call to its clear() method */ + on(eventName: 'clear', handler: (from: Position, to: Position) => void) : void; + off(eventName: 'clear', handler: () => void) : void; + + /** Fired when the last part of the marker is removed from the document by editing operations */ + on(eventName: 'hide', handler: () => void) : void; + off(eventname: 'hide', handler: () => void) : void; + + /** Fired when, after the marker was removed by editing, a undo operation brough the marker back */ + on(eventName: 'unhide', handler: () => void) : void; + off(eventname: 'unhide', handler: () => void) : void; } interface LineWidget { diff --git a/types/commangular/commangular-mock.d.ts b/types/commangular/commangular-mock.d.ts index 134e4d0d1e..a31563bc9e 100644 --- a/types/commangular/commangular-mock.d.ts +++ b/types/commangular/commangular-mock.d.ts @@ -4,33 +4,33 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module commangular { - + /////////////////////////////////////////////////////////////////////////// // Commangular Static // see http://commangular.org/docs/#commangular-namespace /////////////////////////////////////////////////////////////////////////// interface ICommAngularStatic { - + /** * Mock dispatch function for testing commands. */ dispatch( ec: ICommandCall, callback: Function ): void; } - + interface ICommandCall { /** * Name of the command that needs to * execute */ command: string; - + /** * Data that needs to be passed to the command */ data?: any; } - - + + /** * Object type expected to be passed into the callback function * of the dispatch() function @@ -41,25 +41,25 @@ declare module commangular { * @param key The property name that is in the object that was passed */ dataPassed( key : string ) : any; - + /** * The data that was returned by the command * @param key The result key that was defined in the command. If no result * was defined use 'lastResult' as the key */ resultKey( key: string ): any; - + /** * Indicates if the command execution was cancelled. */ canceled( ): boolean; - + /** * Indicates if the command was executed???? */ commandExecuted( ): boolean; } - + } @@ -67,7 +67,6 @@ declare module commangular { * Mock dispatch function for testing commands. * @param ec an ICommandCall object * @param callback The function that will be called upon the completion of the command -* function should expecte an ICommandInfo paramter. +* function should expecte an ICommandInfo parameter. */ -declare function dispatch( ec: commangular.ICommandCall, callback: Function ): void; - +declare function dispatch( ec: commangular.ICommandCall, callback: Function ): void; diff --git a/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx b/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx new file mode 100644 index 0000000000..bceab689e7 --- /dev/null +++ b/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx @@ -0,0 +1,30 @@ +import React = require('react'); +import enzyme = require('enzyme'); +import configureExtensions = require('@commercetools/enzyme-extensions'); + +configureExtensions(enzyme.ShallowWrapper); + +function App() { + return 'Hello world'} />; +} + +interface ChildProps { + cb: () => string; +} + +function Child(props: ChildProps) { + return
{props.cb()}
; +} + +enzyme.shallow() + .find(App) + .renderProp('render'); +enzyme.shallow() + .find(Child) + .renderProp('render', 1, 2); + +enzyme.shallow() + .find(Child) + .drill(props => props.cb()); + +enzyme.shallow().until(Child); diff --git a/types/commercetools__enzyme-extensions/index.d.ts b/types/commercetools__enzyme-extensions/index.d.ts new file mode 100644 index 0000000000..7c009f8e95 --- /dev/null +++ b/types/commercetools__enzyme-extensions/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for @commercetools/enzyme-extensions 3.0 +// Project: https://github.com/commercetools/enzyme-extensions +// Definitions by: Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as enzyme from 'enzyme'; + +declare module 'enzyme' { + interface UntilOptions { + maxDepth: number; + } + interface ShallowWrapper

{ + renderProp(propName: string, ...args: any[]): ShallowWrapper

; + drill(expander: (props: any) => ShallowWrapper): ShallowWrapper

; + until(selector: EnzymeSelector, options?: UntilOptions): ShallowWrapper

; + } +} + +declare function monkeyPatchShallowWrapper(s: typeof enzyme.ShallowWrapper): void; + +export = monkeyPatchShallowWrapper; diff --git a/types/commercetools__enzyme-extensions/tsconfig.json b/types/commercetools__enzyme-extensions/tsconfig.json new file mode 100644 index 0000000000..9e6d70239e --- /dev/null +++ b/types/commercetools__enzyme-extensions/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "@commercetools/enzyme-extensions": ["commercetools__enzyme-extensions"] + } + }, + "files": [ + "index.d.ts", + "commercetools__enzyme-extensions-tests.tsx" + ] +} diff --git a/types/commercetools__enzyme-extensions/tslint.json b/types/commercetools__enzyme-extensions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/commercetools__enzyme-extensions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/consul/index.d.ts b/types/consul/index.d.ts index 3d344ae983..096a906c8b 100644 --- a/types/consul/index.d.ts +++ b/types/consul/index.d.ts @@ -625,6 +625,7 @@ declare namespace Consul { dc?: string; tag?: string; passing?: boolean; + near?: string; } interface StateOptions extends CommonOptions { diff --git a/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts b/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts new file mode 100644 index 0000000000..72925fe5ba --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts @@ -0,0 +1,63 @@ +let BluetoothClassicSerial: BluetoothClassicSerial = + window.BluetoothClassicSerial; + +BluetoothClassicSerial.connect( + "", + [""] +); +BluetoothClassicSerial.connect( + "", + [""], + results => {} +); +BluetoothClassicSerial.connect( + "", + [""], + results => {}, + error => {} +); +BluetoothClassicSerial.connectInsecure("", [""]); +BluetoothClassicSerial.connectInsecure("", [""], results => {}); +BluetoothClassicSerial.connectInsecure("", [""], results => {}, error => {}); +BluetoothClassicSerial.register(() => {}); +BluetoothClassicSerial.disconnect(results => {}); +BluetoothClassicSerial.disconnect(results => {}, error => {}); +BluetoothClassicSerial.write("", ""); +BluetoothClassicSerial.write("", "", results => {}); +BluetoothClassicSerial.write("", "", results => {}, error => {}); +BluetoothClassicSerial.available(""); +BluetoothClassicSerial.available("", results => {}); +BluetoothClassicSerial.available("", results => {}, error => {}); +BluetoothClassicSerial.read(""); +BluetoothClassicSerial.read("", results => {}); +BluetoothClassicSerial.read("", results => {}, error => {}); +BluetoothClassicSerial.readUntil("", ""); +BluetoothClassicSerial.readUntil("", "", results => {}); +BluetoothClassicSerial.readUntil("", "", results => {}, error => {}); +BluetoothClassicSerial.subscribe("", ""); +BluetoothClassicSerial.subscribe("", "", results => {}); +BluetoothClassicSerial.subscribe("", "", results => {}, error => {}); +BluetoothClassicSerial.unsubscribe(""); +BluetoothClassicSerial.unsubscribe("", results => {}); +BluetoothClassicSerial.unsubscribe("", results => {}, error => {}); +BluetoothClassicSerial.subscribeRawData(""); +BluetoothClassicSerial.subscribeRawData("", results => {}); +BluetoothClassicSerial.subscribeRawData("", results => {}, error => {}); +BluetoothClassicSerial.unsubscribeRawData(""); +BluetoothClassicSerial.unsubscribeRawData("", results => {}); +BluetoothClassicSerial.unsubscribeRawData("", results => {}, error => {}); +BluetoothClassicSerial.clear(""); +BluetoothClassicSerial.clear("", results => {}); +BluetoothClassicSerial.clear("", results => {}, error => {}); +BluetoothClassicSerial.list(results => {}); +BluetoothClassicSerial.list(results => {}, error => {}); +BluetoothClassicSerial.isConnected(results => {}); +BluetoothClassicSerial.isConnected(results => {}, error => {}); +BluetoothClassicSerial.isEnabled(results => {}); +BluetoothClassicSerial.isEnabled(results => {}, error => {}); +BluetoothClassicSerial.showBluetoothSettings(results => {}); +BluetoothClassicSerial.showBluetoothSettings(results => {}, error => {}); +BluetoothClassicSerial.enable(results => {}); +BluetoothClassicSerial.enable(results => {}, error => {}); +BluetoothClassicSerial.discoverUnpaired(results => {}); +BluetoothClassicSerial.discoverUnpaired(results => {}, error => {}); diff --git a/types/cordova-plugin-bluetoothclassic-serial/index.d.ts b/types/cordova-plugin-bluetoothclassic-serial/index.d.ts new file mode 100644 index 0000000000..2dfe8c94ae --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for cordova-plugin-bluetoothClassic-serial 0.9 +// Project: https://github.com/soltius/BluetoothClassicSerial +// Definitions by: Wouter Roosendaal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Global object bluetoothClassicSerial. + */ +interface Window { + BluetoothClassicSerial: BluetoothClassicSerial; +} + +interface BluetoothClassicSerial { + connect: ( + deviceId: string, + interfaceArray: [any], + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + connectInsecure: ( + deviceId: string, + interfaceArray: [any], + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + register: (data_cb?: () => any) => void; + disconnect: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + write: ( + interfaceId: string, + data: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + available: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + read: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + readUntil: ( + interfaceId: string, + delimiter: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + subscribe: ( + interfaceId: string, + delimiter: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + unsubscribe: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + subscribeRawData: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + unsubscribeRawData: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + clear: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + list: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + isConnected: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + isEnabled: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + showBluetoothSettings: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + enable: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + discoverUnpaired: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; +} + +declare var bluetoothClassicSerial: BluetoothClassicSerial; diff --git a/types/cordova-plugin-bluetoothclassic-serial/tsconfig.json b/types/cordova-plugin-bluetoothclassic-serial/tsconfig.json new file mode 100644 index 0000000000..5cd12b710a --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/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", + "cordova-plugin-bluetoothclassic-serial-tests.ts" + ] +} diff --git a/types/cordova-plugin-bluetoothclassic-serial/tslint.json b/types/cordova-plugin-bluetoothclassic-serial/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/crpc/crpc-tests.ts b/types/crpc/crpc-tests.ts new file mode 100644 index 0000000000..ade069cbba --- /dev/null +++ b/types/crpc/crpc-tests.ts @@ -0,0 +1,3 @@ +import crpc from 'crpc'; + +const client = crpc('https://example.com/'); diff --git a/types/crpc/index.d.ts b/types/crpc/index.d.ts new file mode 100644 index 0000000000..8947443c42 --- /dev/null +++ b/types/crpc/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for crpc 0.2 +// Project: https://github.com/billinghamj/crpc +// Definitions by: Alexander Forbes-Reed +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +export type Client = (path: string, body: any, options?: {} | null) => Promise; + +export default function crpc(baseUrl: string, options?: {}): Client; diff --git a/types/crpc/tsconfig.json b/types/crpc/tsconfig.json new file mode 100644 index 0000000000..657ccc0d04 --- /dev/null +++ b/types/crpc/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "esModuleInterop": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "crpc-tests.ts" + ] +} diff --git a/types/crpc/tslint.json b/types/crpc/tslint.json new file mode 100644 index 0000000000..8f3d5d7eec --- /dev/null +++ b/types/crpc/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/d3-contour/d3-contour-tests.ts b/types/d3-contour/d3-contour-tests.ts index 0184979be0..2d23017040 100644 --- a/types/d3-contour/d3-contour-tests.ts +++ b/types/d3-contour/d3-contour-tests.ts @@ -144,6 +144,13 @@ contDensCustom = contDensCustom.y((datum) => { // get const yAcc: (d: CustomDatum) => number = contDensCustom.y(); +// weight(...) ----------------------------------------------------------------- +contDensCustom = contDensCustom.weight((datum) => { + return 5; +}); + +// get +const weightAcc: (d: CustomDatum) => number = contDensCustom.weight(); // size(...) ------------------------------------------------------------------- // set with chainability diff --git a/types/d3-contour/index.d.ts b/types/d3-contour/index.d.ts index 8d42275ee2..bb77fb4ef8 100644 --- a/types/d3-contour/index.d.ts +++ b/types/d3-contour/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for d3-contour 1.2 +// Type definitions for d3-contour 1.3 // Project: https://d3js.org/d3-contour/ // Definitions by: Tom Wanzek , Hugues Stefanski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Last module patch version validated against: 1.2.0 +// Last module patch version validated against: 1.3.2 import { MultiPolygon } from 'geojson'; import { ThresholdNumberArrayGenerator, ThresholdCountGenerator } from 'd3-array'; @@ -169,6 +169,18 @@ export interface ContourDensity { */ y(y: (d: Datum) => number): this; + /** + * Returns the current point weight accessor. + */ + weight(): (d: Datum) => number; + + /** + * Sets the point weight accessor and returns the density contour estimator. + * + * @param weight A point weight accessor function. + */ + weight(weight: (d: Datum) => number): this; + /** * Returns the current size, which defaults to [960, 500]. */ diff --git a/types/d3-graphviz/index.d.ts b/types/d3-graphviz/index.d.ts index 9d3dc1ac61..e3a30ce4f7 100644 --- a/types/d3-graphviz/index.d.ts +++ b/types/d3-graphviz/index.d.ts @@ -407,7 +407,7 @@ export type Engine = 'circo' | 'dot' | 'fdp' | 'neato' | 'osage' | 'patchwork' | export type TypeNames = 'initEnd' | 'start' | 'layoutStart' | 'layoutEnd' | 'dataExtractEnd' | 'dataProcessPass1End' | 'dataProcessPass2End' | 'dataProcessEnd' | 'renderStart' | 'renderEnd' | 'transitionStart' | 'transitionEnd' | - 'resotreEnd' | 'end' | string; // string included to allow for optional addition of a name, e.g. initEnd.foo + 'restoreEnd' | 'end' | string; // string included to allow for optional addition of a name, e.g. initEnd.foo /** * Enum defining the valid strings that can be passed as KeyModes diff --git a/types/d3-selection/d3-selection-tests.ts b/types/d3-selection/d3-selection-tests.ts index b99c81e39a..2262a89134 100644 --- a/types/d3-selection/d3-selection-tests.ts +++ b/types/d3-selection/d3-selection-tests.ts @@ -74,7 +74,8 @@ let body: d3Selection.Selection = // with Group element of type BaseType and datum of type 'any' The parent element is of type 'null' with datum of type 'undefined' const baseTypeEl2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); -// let body2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); // fails as baseTypeEl.node() is of type cannot be assigned to HTMLElement +// $ExpectError +const body2: d3Selection.Selection = d3Selection.select(baseTypeEl.node()); // fails as baseTypeEl.node() is of type cannot be assigned to HTMLElement const body3: d3Selection.Selection = d3Selection.select(body.node()!); // element types match, but datum is of type 'any' as it cannot be inferred from .node() @@ -86,18 +87,21 @@ const body4: d3Selection.Selection // Explicitly cast body.node() to HTMLBodyElement to narrow selection definition. const body5: d3Selection.Selection = d3Selection.select(body.node()!); -// d3Selection.select(baseTypeEl.node()!); // fails as baseTypeEl.node() is not of type HTMLBodyElement +// $ExpectError +d3Selection.select(baseTypeEl.node()!); // fails as baseTypeEl.node() is not of type HTMLBodyElement // test, when it is not certain, whether an element of the type to be selected exists let maybeSVG1: d3Selection.Selection; maybeSVG1 = d3Selection.select('svg'); let maybeSVG2: d3Selection.Selection; -// maybeSVG2 = d3Selection.select(maybeSVG1.node()); // fails with strict function types +// $ExpectError +maybeSVG2 = d3Selection.select(maybeSVG1.node()); // fails with strict function types maybeSVG2 = d3Selection.select(maybeSVG1.node()); // fails, as node type mismatches selection type -// let body7: d3Selection.Selection = d3Selection.select(maybeSVG1.node()); +// $ExpectError +const body7: d3Selection.Selection = d3Selection.select(maybeSVG1.node()); // test "special case DOM objects" @@ -127,7 +131,8 @@ const divElements: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); // fails, group elements types not of compatible for baseTypeElements -// let divElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); +// $ExpectError +const divElements2: d3Selection.Selection = d3Selection.selectAll(baseTypeElements.nodes()); // element types match, but datum is of type 'any' as it cannot be inferred from .nodes() const divElements3: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); @@ -137,7 +142,8 @@ const divElements3: d3Selection.Selection const divElements4: d3Selection.Selection = d3Selection.selectAll(divElements.nodes()); -// d3Selection.selectAll(baseTypeElements.nodes()); // fails as baseTypeEl.node() is not of type HTMLBodyElement +// $ExpectError +d3Selection.selectAll(baseTypeElements.nodes()); // fails as baseTypeEl.node() is not of type HTMLBodyElement // selectAll(...) accepts NodeListOf<...> argument @@ -161,8 +167,8 @@ const documentLinks: d3Selection.Selection = d3Selection.select('svg'); let firstG: d3Selection.Selection = svgEl.select('g'); -// let firstG_2: d3Selection.Selection = svgEl.select('g'); // fails, parent element of selection does not change with .select(...) -// firstG = svgEl.select('g'); // fails, element type defaults to 'BaseType', but SVGGElement expected on left-hand side +// $ExpectError +const firstG_2: d3Selection.Selection = svgEl.select('g'); // fails, parent element of selection does not change with .select(...) // firstG = svgEl.select('svg'); // fails, element type of SVGSVGElement provided, but SVGGElement expected on left-hand side (silly test to begin with) // test, when it is not certain, whether an element of the type to be selected exists @@ -180,14 +186,16 @@ firstG = svgEl.select(svgGroupSelector); firstG = svgEl.select(function() { const that: SVGSVGElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelector('g')!; // this of type SVGSVGElement by type inference }); firstG = svgEl.select(function(d, i, g) { const that: SVGSVGElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch const datum: SVGDatum = d; const index: number = i; const group: SVGSVGElement[] | d3Selection.ArrayLike = g; @@ -199,9 +207,10 @@ firstG = svgEl.select(function(d, i, g) { return this.querySelector('g')!; // this of type SVGSVGElement by type inference }); -// firstG = svgEl.select(function() { -// return this.querySelector('a'); // fails, return type HTMLAnchorElement is not compatible with SVGGElement expected by firstG -// }); +// $ExpectError +firstG = svgEl.select(function() { + return this.querySelector('a'); // fails, return type HTMLAnchorElement is not compatible with SVGGElement expected by firstG +}); // selectAll(...) sub-selection -------------------------------------------------------------- @@ -219,7 +228,6 @@ emptySubSelection = svgEl.selectAll(undefined); let elementsUnknownData: d3Selection.Selection = svgEl.selectAll('g'); // let elementsAndDataUnknown: d3Selection.Selection = svgEl.selectAll('g'); // fails with strictFunctionTypes let gElementsOldData: d3Selection.Selection = svgEl.selectAll('g'); -// gElementsOldData = svgEl.selectAll('g'); // fails default type parameters of selectAll for group element type and datum type do not match // Using selectAll(...) sub-selection with a selector function argument. @@ -232,18 +240,21 @@ gElementsOldData = svgEl.selectAll(svgGroupSelectorAll function wrongSvgGroupSelectorAll(this: HTMLElement, d: SVGDatum, i: number, groups: HTMLElement[]): NodeListOf { return this.querySelectorAll('g'); } -// gElementsOldData = svgEl.selectAll(wrongSvgGroupSelectorAll); // fails, wrong this context +// $ExpectError +gElementsOldData = svgEl.selectAll(wrongSvgGroupSelectorAll); // fails, wrong this context gElementsOldData = svgEl.selectAll(function() { const that: SVGSVGElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference }); gElementsOldData = svgEl.selectAll(function(d, i, g) { const that: SVGSVGElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch const datum: SVGDatum = d; const index: number = i; const group: SVGSVGElement[] | d3Selection.ArrayLike = g; @@ -255,31 +266,32 @@ gElementsOldData = svgEl.selectAll(function(d, i, g) { return this.querySelectorAll('g'); }); -// gElementsOldData = svgEl.selectAll(function() { // fails, because Datum type is not compatible as selectAll defaults to 'any', but gElementsOldData expects CircleDatum -// return this.querySelectorAll('g'); -// }); - -// gElementsOldData = svgEl.selectAll(function() { // fails, return type HTMLAnchorElement is not compatible with SVGGElement expected by selectAll-typing -// return this.querySelectorAll('a'); -// }); +// $ExpectError +gElementsOldData = svgEl.selectAll(function() { // fails, return type HTMLAnchorElement is not compatible with SVGGElement expected by selectAll-typing + return this.querySelectorAll('a'); +}); elementsUnknownData = svgEl.selectAll(svgGroupSelectorAll); elementsUnknownData = svgEl.selectAll(function() { const that: SVGSVGElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch console.log('Get Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference }); -// gElementsUnknownData = svgEl.selectAll(function() { // fails, return type HTMLAnchorElement is not compatible with SVGGElement -// return this.querySelectorAll('a'); -// }); +// $ExpectError +gElementsUnknownData = svgEl.selectAll(function() { // fails, return type HTMLAnchorElement is not compatible with SVGGElement + return this.querySelectorAll('a'); +}); maybeG.selectAll(function(d, i, g) { const that: SVGGElement | null = this; - // const that2: SVGGElement = this; // fails with strictNullChecks - // const that3: HTMLElement | null = this; // fails, type mismatch + // $ExpectError + const that2: SVGGElement = this; // fails with strictNullChecks + // $ExpectError + const that3: HTMLElement | null = this; // fails, type mismatch const datum: SVGDatum = d; const index: number = i; const group: Array | d3Selection.ArrayLike = g; @@ -290,11 +302,13 @@ maybeG.selectAll(function(d, i, g) { // selector(...) and selectorAll(...) ---------------------------------------------------- -// d3Selection.select(d3Selection.selector('g')); // fails, selector as argument to top-level select not supported +// $ExpectError +d3Selection.select(d3Selection.selector('g')); // fails, selector as argument to top-level select not supported // supported on sub-selection firstG = svgEl.select(d3Selection.selector('g')); // type parameter of select(...) inferred -// firstG = svgEl.select(d3Selection.selector('div')); // fails, select and selector mismatch +// $ExpectError +firstG = svgEl.select(d3Selection.selector('div')); // fails, select and selector mismatch gElementsOldData = svgEl.selectAll(d3Selection.selectorAll('g')); @@ -308,7 +322,8 @@ filteredGElements = gElementsOldData.filter('.top-level'); filteredGElements = gElementsOldData.filter(function(d, i, g) { const that: SVGGElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch const datum: CircleDatum = d; const index: number = i; const group: SVGGElement[] | d3Selection.ArrayLike = g; @@ -325,16 +340,18 @@ filteredGElements = gElementsOldData.filter(function(d, i, g) { let filteredGElements2: d3Selection.Selection; filteredGElements2 = d3Selection.selectAll('.any-svg-type').filter('g'); -// filteredGElements2 = d3Selection.selectAll('.any-type').filter('g'); // fails without using narrowing generic on filter method +// $ExpectError +filteredGElements2 = d3Selection.selectAll('.any-type').filter('g'); // fails without using narrowing generic on filter method filteredGElements2 = d3Selection.selectAll('.any-svg-type').filter(function() { const that: SVGElement = this; return that.tagName === 'g' || that.tagName === 'G'; }); -// filteredGElements2 = d3Selection.selectAll('.any-svg-type').filter(function(){ -// const that: SVGElement = this; -// return that.tagName === 'g'|| that.tagName === 'G'; -// }); // fails without using narrowing generic on filter method +// $ExpectError +filteredGElements2 = d3Selection.selectAll('.any-svg-type').filter(function() { + const that: SVGElement = this; + return that.tagName === 'g' || that.tagName === 'G'; +}); // fails without using narrowing generic on filter method // matcher() ----------------------------------------------------------------------------- @@ -371,7 +388,8 @@ circles = d3Selection.selectAll('circl circles = circles // re-assignment test chaining return-type .attr('cx', function(d, i, g) { const that: SVGGElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch const datum: CircleDatum = d; const index: number = i; const group: SVGGElement[] | d3Selection.ArrayLike = g; @@ -395,7 +413,8 @@ divs = divs divs = divs .classed('zero-px-padding', function(d, i, g) { const that: HTMLDivElement = this; - // const that2: SVGElement = this; // fails, type mismatch + // $ExpectError + const that2: SVGElement = this; // fails, type mismatch const datum: DivDatum = d; const index: number = i; const group: HTMLDivElement[] | d3Selection.ArrayLike = g; @@ -411,13 +430,15 @@ divs = divs divs = divs .style('background-color', 'blue') // string .style('hidden', false) // boolean - // .style('color', 'green', 'test') // fails, invalid priority value + // $ExpectError + .style('color', 'green', 'test') // fails, invalid priority value .style('color', 'green', 'important'); divs = divs .style('padding', function(d, i, g) { const that: HTMLDivElement = this; - // const that2: SVGElement = this; // fails, type mismatch + // $ExpectError + const that2: SVGElement = this; // fails, type mismatch const datum: DivDatum = d; const index: number = i; const group: HTMLDivElement[] | d3Selection.ArrayLike = g; @@ -428,7 +449,8 @@ divs = divs return d.padding; // string return value }) .style('hidden', () => true, null) // boolean return + test: priority = null - // .style('color', function() { return 'green'; }, 'test') // fails, test: invalid priority value + // $ExpectError + .style('color', () => 'green', 'test') // fails, test: invalid priority value .style('color', () => 'green', 'important'); // boolean return + test: priority = 'important'; // property(...) Tests @@ -442,7 +464,8 @@ circles = circles circles = circles .property('__hitchhikersguide__', function(d, i, g) { const that: SVGCircleElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch const datum: CircleDatumAlternative = d; const index: number = i; const group: SVGCircleElement[] | d3Selection.ArrayLike = g; @@ -466,7 +489,8 @@ body = body body = body .text(function(d, i, g) { const that: HTMLBodyElement = this; - // const that2: SVGElement = this; // fails, type mismatch + // $ExpectError + const that2: SVGElement = this; // fails, type mismatch const datum: BodyDatum = d; const index: number = i; const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; @@ -482,7 +506,8 @@ body = body body = body .html(function(d, i, g) { const that: HTMLBodyElement = this; - // const that2: SVGElement = this; // fails, type mismatch + // $ExpectError + const that2: SVGElement = this; // fails, type mismatch const datum: BodyDatum = d; const index: number = i; const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; @@ -521,13 +546,15 @@ let newBodyDatum: { newFoo: string }; newBodyDatum = body.datum({ newFoo: 'new foo' }).datum(); // inferred type -// body.datum({ newFoo: 'new foo' }); // fails, data type incompatible +// $ExpectError +body.datum({ newFoo: 'new foo' }); // fails, data type incompatible // function-based newBodyDatum = body.datum(function(d, i, g) { const that: HTMLBodyElement = this; - // const that2: SVGElement = this; // fails, type mismatch + // $ExpectError + const that2: SVGElement = this; // fails, type mismatch const datum: BodyDatum = d; const index: number = i; const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; @@ -536,10 +563,11 @@ newBodyDatum = body.datum(function(d, i, g) { return { newFoo: 'new foo' }; }).datum(); // inferred type -// newBodyDatum = body.datum(function(d) { // fails, data type incompatible with return value type -// console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement -// return { newFoo: 'new foo' }; -// }).datum(); // inferred type +// $ExpectError +newBodyDatum = body.datum(function(d) { // fails, data type incompatible with return value type + console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement + return { newFoo: 'new foo' }; +}).datum(); // inferred type // SCENARIO 1: Fully type-parameterized @@ -560,7 +588,8 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la .datum(data2) // new data type inferred .classed('has-transform-property', function(d, i, g) { const that: SVGGElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch const datum: CircleDatumAlternative[] = d; const index: number = i; const group: SVGGElement[] | d3Selection.ArrayLike = g; @@ -569,14 +598,14 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la }); // below fails, as 'this' in .classed(...) will default to BaseType, which may be null and does not have 'transform' property - -// d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain -// .select('g.circles-group') // missing typing of selected DOM element for use in .classed(...) -// .datum(data2) // new data type inferred -// .classed('has-transform-property', function(d) { -// console.log('Color of first data element array', d.length > 0? d[0].color: 'Data array empty'); // CircleDatumAlternative type -// return this.transform !== undefined; -// }); +d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain + .select('g.circles-group') // missing typing of selected DOM element for use in .classed(...) + .datum(data2) // new data type inferred + .classed('has-transform-property', function(d) { + console.log('Color of first data element array', d.length > 0 ? d[0].color : 'Data array empty'); // CircleDatumAlternative type + // $ExpectError + return this.transform !== undefined; + }); // SCENARIO 3: Only inferred typing (To have datum-type in 'classed' method call, no need for DOM object access) @@ -585,7 +614,8 @@ d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in la .datum(data2) // new data type inferred .classed('has-green-first-data-element', function(d, i, g) { const that: d3Selection.BaseType = this; - // const that2: Element = this; // fails, type mismatch + // $ExpectError + const that2: Element = this; // fails, type mismatch const datum: CircleDatumAlternative[] = d; const index: number = i; const group: d3Selection.BaseType[] | d3Selection.ArrayLike = g; @@ -663,7 +693,8 @@ circles2 = d3Selection.select('#svg2') circles2 = circles2 // returned update selection has the same type parameters as original selection, if data type is unchanged .data(endCircleData, d => d.nodeId); -// circles2.data(endCircleData, function(d) { return d.nodeId; }); // fails, forced data type parameter and data argument mismatch +// $ExpectError +circles2.data(endCircleData, (d) => d.nodeId); // fails, forced data type parameter and data argument mismatch // ENTER-selection ----------------------------------------------------------------- @@ -690,7 +721,8 @@ const exitCircles = circles2.exit(); // Note: need to re exitCircles .style('opacity', function(d, i, g) { const that: SVGCircleElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch const datum: CircleDatumAlternative = d; const index: number = i; const group: SVGCircleElement[] | d3Selection.ArrayLike = g; @@ -702,12 +734,13 @@ exitCircles // Note: the alternative using only .exit() without typing, will fail, if access to datum properties is attempted. // If access to d is not required, the short-hand is acceptable e.g. circles2.exit().remove(); -// let exitCircles2 = circles2.exit(); // Note: Without explicit re-typing to the old data type, the data type default to '{}' -// exitCircles2 -// .style('opacity', function(d) { -// console.log('Circle Radius exit node: ', this.r.baseVal.value); -// return d.color === 'green' ? 1 : 0; // fails, as data type is defaulted to {}. If datum access is required, this should trigger the thought to type .exit<...> -// }); +const exitCircles2 = circles2.exit(); // Note: Without explicit re-typing to the old data type, the data type default to '{}' +exitCircles2 + .style('opacity', function(d) { + console.log('Circle Radius exit node: ', this.r.baseVal.value); + // $ExpectError + return d.color === 'green' ? 1 : 0; // fails, as data type is defaulted to {}. If datum access is required, this should trigger the thought to type .exit<...> + }); // MERGE ENTER + UPDATE ------------------------------------------------------------------ @@ -733,8 +766,8 @@ tr = d3Selection.select('body') .append('table') .selectAll() .data(matrix) - // .data([{test: 1}, {test: 2}]) // fails, using this data statement instead, would fail assignment to tr due to the data type of tr Selection - // .data([{test: 1}, {test: 2}]) // fails, using this data statement instead, would fail because of its type parameter not being met by input + // $ExpectError + .data([{test: 1}, {test: 2}]) // fails, using this data statement instead, would fail because of its type parameter not being met by input .enter().append('tr'); nMatrix = tr.data(); // i.e. matrix @@ -745,7 +778,6 @@ td = tr.selectAll() .enter().append('td') .text(function(d, i, g) { const that: HTMLTableDataCellElement = this; - // const that2: Element = this; // fails, type mismatch const datum: number = d; const index: number = i; const group: HTMLTableDataCellElement[] | d3Selection.ArrayLike = g; @@ -787,11 +819,13 @@ newDiv2 = body.append('div'); // using creator newDiv2 = body.append(d3Selection.creator('div')); -// newDiv2 = body.append(d3Selection.creator('div')); // fails, as creator returns BaseType element, but HTMLDivElement is expected. +// $ExpectError +newDiv2 = body.append(d3Selection.creator('div')); // fails, as creator returns BaseType element, but HTMLDivElement is expected. newDiv2 = body.append(function(d, i, g) { const that: HTMLBodyElement = this; - // const that2: SVGElement = this; // fails, type mismatch + // $ExpectError + const that2: SVGElement = this; // fails, type mismatch const datum: BodyDatum = d; const index: number = i; const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; @@ -799,13 +833,15 @@ newDiv2 = body.append(function(d, i, g) { return this.ownerDocument!.createElement('div'); // this-type HTMLBodyElement }); -// newDiv2 = body.append(function(d) { -// return this.ownerDocument.createElement('a'); // fails, HTMLDivElement expected by type parameter, HTMLAnchorElement returned -// }); +// $ExpectError +newDiv2 = body.append(function(d) { + return this.ownerDocument!.createElement('a'); // fails, HTMLDivElement expected by type parameter, HTMLAnchorElement returned +}); -// newDiv2 = body.append(function(d) { -// return this.ownerDocument.createElement('a'); // fails, HTMLDivElement expected by inference, HTMLAnchorElement returned -// }); +// $ExpectError +newDiv2 = body.append(function(d) { + return this.ownerDocument!.createElement('a'); // fails, HTMLDivElement expected by inference, HTMLAnchorElement returned +}); // create a detached element @@ -909,7 +945,8 @@ const size: number = gElementsOldData.size(); // returns 'this' selection circles = circles.each(function(d, i, g) { // check chaining return type by re-assigning const that: SVGCircleElement = this; - // const that2: HTMLElement = this; // fails, type mismatch + // $ExpectError + const that2: HTMLElement = this; // fails, type mismatch const datum: CircleDatum = d; const index: number = i; const group: SVGCircleElement[] | d3Selection.ArrayLike = g; @@ -931,13 +968,15 @@ function enforceMinRadius(selection: d3Selection.Selection):void { -// // fails, group element types of selection not compatible: SVGCircleElement v HTMLDivElement -// }); +// $ExpectError +circles.call((selection: d3Selection.Selection) => { + // fails, group element types of selection not compatible: SVGCircleElement v HTMLDivElement +}); -// circles.call(function(selection: d3Selection.Selection):void { -// // fails, group datum types of selection not compatible: CircleDatumAlternative v DivDatum -// }); +// $ExpectError +circles.call((selection: d3Selection.Selection) => { + // fails, group datum types of selection not compatible: CircleDatumAlternative v DivDatum +}); // --------------------------------------------------------------------------------------- // Tests of Event Handling @@ -949,7 +988,8 @@ let listener: undefined | ((this: HTMLBodyElement, datum: BodyDatum, index: numb body = body.on('click', function(d, i, g) { const that: HTMLBodyElement = this; - // const that2: SVGElement = this; // fails, type mismatch + // $ExpectError + const that2: SVGElement = this; // fails, type mismatch const datum: BodyDatum = d; const index: number = i; const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; @@ -981,7 +1021,8 @@ body = body.dispatch('fooEvent', fooEventParam); // re-assign for chaining test; body = body.dispatch('fooEvent', function(d, i, g) { // re-assign for chaining test; const that: HTMLBodyElement = this; - // const that2: SVGElement = this; // fails, type mismatch + // $ExpectError + const that2: SVGElement = this; // fails, type mismatch const datum: BodyDatum = d; const index: number = i; const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; @@ -1016,11 +1057,16 @@ function customListener(this: HTMLBodyElement | null, finalOpponent: string): st const resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); -// let result = d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in call -// let resultValue: number = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // fails, incompatible return types -// d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in type parameter and call -// d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in type parameter and call -// d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // fails, incompatible return types +// $ExpectError +const result = d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in call +// $ExpectError +const resultValue: number = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // fails, incompatible return types +// $ExpectError +d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in type parameter and call +// $ExpectError +d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in type parameter and call +// $ExpectError +d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // fails, incompatible return types // mouse() --------------------------------------------------------------------------------- diff --git a/types/d3-selection/index.d.ts b/types/d3-selection/index.d.ts index d9988636fd..9edcb4aac8 100644 --- a/types/d3-selection/index.d.ts +++ b/types/d3-selection/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for D3JS d3-selection module 1.3 // Project: https://github.com/d3/d3-selection/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Last module patch version validated against: 1.3.0 diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index 83222d0ff0..6665e39e6a 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -7,6 +7,10 @@ import { Path } from 'd3-path'; +declare global { + interface CanvasRenderingContext2D {} // tslint:disable-line no-empty-interface +} + // ----------------------------------------------------------------------------------- // Shared Types and Interfaces // ----------------------------------------------------------------------------------- diff --git a/types/dd-trace/dd-trace-tests.ts b/types/dd-trace/dd-trace-tests.ts index 8169358155..9d6936875a 100644 --- a/types/dd-trace/dd-trace-tests.ts +++ b/types/dd-trace/dd-trace-tests.ts @@ -9,6 +9,7 @@ tracer.init({ 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 90aa9afc66..311fa7675e 100644 --- a/types/dd-trace/index.d.ts +++ b/types/dd-trace/index.d.ts @@ -110,6 +110,11 @@ interface TracerOptions { debug: (message: string) => void; error: (err: Error) => void; }; + + /** + * Global tags that should be assigned to every span. + */ + tags?: { [key: string]: any }; } interface ExperimentalOptions {} diff --git a/types/deep-diff/deep-diff-tests.ts b/types/deep-diff/deep-diff-tests.ts index 42abf98ee1..6192dad9e5 100644 --- a/types/deep-diff/deep-diff-tests.ts +++ b/types/deep-diff/deep-diff-tests.ts @@ -1,9 +1,6 @@ +import { diff, observableDiff, applyChange, Diff } from 'deep-diff'; - -import _deepDiff = require('deep-diff'); -var diff = _deepDiff.diff; - -var lhs = { +let lhs = { name: 'my object', description: 'it\'s an object!', details: { @@ -13,7 +10,7 @@ var lhs = { } }; -var rhs = { +let rhs = { name: 'updated object', description: 'it\'s an object!', details: { @@ -23,17 +20,13 @@ var rhs = { } }; -var differences: deepDiff.IDiff[] = diff(lhs, rhs); +const differences: Array> = diff(lhs, rhs); console.log(differences); - // -------------------------- -var observableDiff = _deepDiff.observableDiff; -var applyChange = _deepDiff.applyChange; - -var lhs = { +lhs = { name: 'my object', description: 'it\'s an object!', details: { @@ -43,7 +36,7 @@ var lhs = { } }; -var rhs = { +rhs = { name: 'updated object', description: 'it\'s an object!', details: { @@ -53,7 +46,7 @@ var rhs = { } }; -observableDiff(lhs, rhs, function (d: deepDiff.IDiff) { +observableDiff(lhs, rhs, d => { // Apply all changes except those to the 'name' property... if (d.path.length !== 1 || d.path.join('.') !== 'name') { applyChange(lhs, rhs, d); diff --git a/types/deep-diff/index.d.ts b/types/deep-diff/index.d.ts index de17a03bc8..ac4d50b44a 100644 --- a/types/deep-diff/index.d.ts +++ b/types/deep-diff/index.d.ts @@ -1,42 +1,60 @@ -// Type definitions for deep-diff +// Type definitions for deep-diff 1.0 // Project: https://github.com/flitbit/diff/ // Definitions by: ZauberNerd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare namespace deepDiff { - interface IDiff { - kind: string; - path: string[]; - lhs: any; - rhs: any; - index?: number; - item?: IDiff; - } - - interface IAccumulator { - push(diff: IDiff): void; - length: number; - } - - interface IPrefilter { - (path: string[], key: string): boolean; - } - - interface IDeepDiff { - diff(lhs: Object, rhs: Object, prefilter?: IPrefilter, acc?: IAccumulator): IDiff[]; - diff(): IDiff; - observableDiff(lhs: Object, rhs: Object, changes: Function, prefilter?: IPrefilter, path?: string[], key?: string, stack?: Object[]): void; - applyDiff(target: Object, source: Object, filter: Function): void; - applyChange(target: Object, source: Object, change: IDiff): void; - revertChange(target: Object, source: Object, change: IDiff): void; - isConflict(): boolean; - noConflict(): IDeepDiff; - } +export interface DiffNew { + kind: 'N'; + path?: any[]; + rhs: RHS; } -declare var DeepDiff: deepDiff.IDeepDiff; - -declare module "deep-diff" { - var diff: deepDiff.IDeepDiff; - export = diff; +export interface DiffDeleted { + kind: 'D'; + path?: any[]; + lhs: LHS; } + +export interface DiffEdit { + kind: 'E'; + path?: any[]; + lhs: LHS; + rhs: RHS; +} + +export interface DiffArray { + kind: 'A'; + path?: any[]; + index: number; + item: Diff; +} + +export type Diff = DiffNew | DiffDeleted | DiffEdit | DiffArray; + +export type PreFilterFunction = (path: any[], key: any) => boolean; +export interface PreFilterObject { + prefilter?(path: any[], key: any): boolean; + normalize?(currentPath: any, key: any, lhs: LHS, rhs: RHS): [ LHS, RHS ] | undefined; +} +export type PreFilter = PreFilterFunction | PreFilterObject; + +export interface Accumulator { + push(diff: Diff): void; + length: number; +} + +export type Observer = (diff: Diff) => void; + +export type Filter = (target: LHS, source: RHS, change: Diff) => boolean; + +export function diff(lhs: LHS, rhs: RHS, prefilter?: PreFilter): Array> | undefined; +export function diff(lhs: LHS, rhs: RHS, prefilter?: PreFilter, acc?: Accumulator): Accumulator; +export function orderIndependentDiff(lhs: LHS, rhs: RHS, prefilter?: PreFilter): Array> | undefined; +export function orderIndependentDiff(lhs: LHS, rhs: RHS, prefilter?: PreFilter, acc?: Accumulator): Accumulator; +export function observableDiff(lhs: LHS, rhs: RHS, observer?: Observer, prefilter?: PreFilter, orderIndependent?: boolean): Array>; +export function orderIndependentDeepDiff(lhs: LHS, rhs: RHS, changes: Array>, prefilter: PreFilter, path: any[], key: any, stack: any[]): void; +export function orderIndepHash(object: any): number; +export function applyDiff(target: LHS, source: RHS, filter?: Filter): void; +export function applyChange(target: LHS, source: any, change: Diff): void; +export function revertChange(target: LHS, source: any, change: Diff): void; diff --git a/types/deep-diff/tslint.json b/types/deep-diff/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/deep-diff/tslint.json +++ b/types/deep-diff/tslint.json @@ -1,79 +1 @@ -{ - "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/diff/diff-tests.ts b/types/diff/diff-tests.ts index 0dea2a305e..2f640da490 100644 --- a/types/diff/diff-tests.ts +++ b/types/diff/diff-tests.ts @@ -16,6 +16,29 @@ diffArraysResult.forEach(result => { } }); +interface DiffObj { + value: number; +} +const a: DiffObj = {value: 0}; +const b: DiffObj = {value: 1}; +const c: DiffObj = {value: 2}; +const d: DiffObj = {value: 3}; +const arrayOptions: jsdiff.IArrayOptions = { + comparator: (left: DiffObj, right: DiffObj) => { + return left.value === right.value; + } +}; +const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions); +diffResult.forEach(result => { + if (result.added) { + console.log(`added ${result.value.length} line(s):`, ...result.value); + } else if (result.removed) { + console.log(`removed ${result.value.length} line(s):`, ...result.value); + } else { + console.log(`no changes`); + } +}); + // -------------------------- class LineDiffWithoutWhitespace extends jsdiff.Diff { diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts index 33d337d1b7..760aee4e61 100644 --- a/types/diff/index.d.ts +++ b/types/diff/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kpdecker/jsdiff // Definitions by: vvakame // szdc +// moc-yuto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -18,8 +19,8 @@ declare namespace JsDiff { newlineIsToken?: boolean; } - interface IArrayOptions extends IOptions { - comparator?: (left: any, right: any) => number; + interface IArrayOptions { + comparator?: (left: any, right: any) => boolean; } interface IDiffResult { diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index aa5d93858b..41707948ca 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -328,6 +328,20 @@ declare namespace Dockerode { MacAddress: string; } + // not complete definition of network inspection + // info which is returned by list / inspect + interface NetworkInspectInfo { + Id: string; + Name: string; + Driver: string; + Created: string; + Scope: string; + EnableIPv6: boolean; + Internal: boolean; + Attachable: boolean; + Ingress: boolean; + } + interface ContainerInspectInfo { Id: string; Created: string; @@ -573,6 +587,49 @@ declare namespace Dockerode { }; } + interface AuthConfig { + username: string; + password: string; + serveraddress: string; + email?: string; + } + + interface PortBinding { + HostIp?: string; + HostPort?: string; + } + + interface PortMap { + [key: string]: PortBinding[]; + } + + interface RestartPolicy { + Name: string; + MaximumRetryCount?: number; + } + + type LoggingDriverType = + | "json-file" + | "syslog" + | "journald" + | "gelf" + | "fluentd" + | "awslogs" + | "splunk" + | "etwlogs" + | "none"; + + interface LogConfig { + Type: LoggingDriverType; + Config?: { [key: string]: string }; + } + + interface DeviceMapping { + PathOnHost: string; + PathinContainer: string; + CgroupPermissions: string; + } + interface ContainerCreateOptions { name?: string; Hostname?: string; @@ -620,7 +677,7 @@ declare namespace Dockerode { OomScoreAdj?: number; PidMode?: string; PidsLimit?: number; - PortBindings?: { [portAndProtocol: string]: Array<{ [index: string]: string }> }; + PortBindings?: PortMap; PublishAllPorts?: boolean; Privileged?: boolean; ReadonlyRootfs?: boolean; @@ -632,12 +689,12 @@ declare namespace Dockerode { CapAdd?: string[]; CapDrop?: string[]; GroupAdd?: string[]; - RestartPolicy?: { [index: string]: number | string }; + RestartPolicy?: RestartPolicy; NetworkMode?: string; - Devices?: any[]; + Devices?: DeviceMapping[]; Sysctls?: { [index: string]: string }; Ulimits?: Array<{}>; - LogConfig?: { [index: string]: string | {} }; + LogConfig?: LogConfig; SecurityOpt?: { [index: string]: any }; CgroupParent?: string; VolumeDriver?: string; diff --git a/types/dojo/dijit.d.ts b/types/dojo/dijit.d.ts index b22742b85d..4b75746aed 100644 --- a/types/dojo/dijit.d.ts +++ b/types/dojo/dijit.d.ts @@ -2855,7 +2855,7 @@ declare module dijit { get(property:"ownerDocument"): Object; watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -6801,7 +6801,7 @@ declare module dijit { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -104923,7 +104923,7 @@ declare module dijit { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. diff --git a/types/dojo/dojox.widget.d.ts b/types/dojo/dojox.widget.d.ts index 9e8ce6563e..36a58aab0d 100644 --- a/types/dojo/dojox.widget.d.ts +++ b/types/dojo/dojox.widget.d.ts @@ -17225,7 +17225,7 @@ declare namespace dojox { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -18171,7 +18171,7 @@ declare namespace dojox { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -23352,7 +23352,7 @@ declare namespace dojox { get(property:"refreshOnShow"): boolean; watch(property: "refreshOnShow", callback: { (property?: string, oldValue?: boolean, newValue?: boolean): void }): { unwatch(): void } /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -24411,7 +24411,7 @@ declare namespace dojox { get(property:"ownerDocument"): Object; watch(property:"ownerDocument", callback:{(property?:string, oldValue?:Object, newValue?: Object):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. @@ -25307,7 +25307,7 @@ declare namespace dojox { get(property:"searchContainerNode"): boolean; watch(property:"searchContainerNode", callback:{(property?:string, oldValue?:boolean, newValue?: boolean):void}) :{unwatch():void} /** - * A parameter needed by RadioGroupSlide only. An optional paramter to force + * A parameter needed by RadioGroupSlide only. An optional parameter to force * the ContentPane to slide in from a set direction. Defaults * to "random", or specify one of "top", "left", "right", "bottom" * to slideFrom top, left, right, or bottom. diff --git a/types/dompurify/index.d.ts b/types/dompurify/index.d.ts index b72cc9e5e9..4c3a38d8f5 100644 --- a/types/dompurify/index.d.ts +++ b/types/dompurify/index.d.ts @@ -1,10 +1,14 @@ // Type definitions for DOM Purify // Project: https://github.com/cure53/DOMPurify -// Definitions by: Dave Taylor , Samira Bazuzi +// Definitions by: Dave Taylor , Samira Bazuzi , FlowCrypt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace DOMPurify; +export declare let version: string; +export declare let removed: any[]; +export declare let isSupported: boolean; + export declare function sanitize(source: string | Node): string; export declare function sanitize(source: string | Node, config: Config & { RETURN_DOM_FRAGMENT?: false; RETURN_DOM?: false; }): string; export declare function sanitize(source: string | Node, config: Config & { RETURN_DOM_FRAGMENT: true; }): DocumentFragment; @@ -13,6 +17,12 @@ export declare function sanitize(source: string | Node, config: Config): string export declare function addHook(hook: 'uponSanitizeElement', cb: (currentNode: Element, data: SanitizeElementHookEvent, config: Config) => void): void; export declare function addHook(hook: 'uponSanitizeAttribute', cb: (currentNode: Element, data: SanitizeAttributeHookEvent, config: Config) => void): void; export declare function addHook(hook: HookName, cb: (currentNode: Element, data: HookEvent, config: Config) => void): void; +export declare function setConfig(cfg: Config): void; +export declare function clearConfig(): void; +export declare function isValidAttribute(tag: string, attr: string, value: string): boolean; +export declare function removeHook(entryPoint: HookName): void; +export declare function removeHooks(entryPoint: HookName): void; +export declare function removeAllHooks(): void; interface Config { ADD_ATTR?: string[]; @@ -30,6 +40,11 @@ interface Config { SAFE_FOR_JQUERY?: boolean; SANITIZE_DOM?: boolean; WHOLE_DOCUMENT?: boolean; + ALLOWED_URI_REGEXP?: RegExp; + SAFE_FOR_TEMPLATES?: boolean; + ALLOW_UNKNOWN_PROTOCOLS?: boolean; + USE_PROFILES?: false | {mathMl?: boolean, svg?: boolean, svgFilters?: boolean, html?: boolean}; + IN_PLACE?: boolean; } type HookName diff --git a/types/downloadjs/downloadjs-tests.ts b/types/downloadjs/downloadjs-tests.ts index da110af46d..c33159d4ec 100644 --- a/types/downloadjs/downloadjs-tests.ts +++ b/types/downloadjs/downloadjs-tests.ts @@ -7,6 +7,7 @@ download(new Blob(['hello world']), 'dlTextBlob.txt', 'text/plain'); download('/robots.txt'); +// tslint:disable-next-line no-unnecessary-type-assertion download(document.documentElement!.outerHTML, 'dlHTML.html', 'text/html'); download(new Blob(['hello world'.bold()]), 'dlHtmlBlob.html', 'text/html'); download('/diff6.png'); diff --git a/types/duplexify/duplexify-tests.ts b/types/duplexify/duplexify-tests.ts index 11d33d7303..aeed21e8dc 100644 --- a/types/duplexify/duplexify-tests.ts +++ b/types/duplexify/duplexify-tests.ts @@ -8,9 +8,17 @@ duplexify(writable, readable); duplexify(writable); duplexify(undefined, readable); +duplexify.obj(); +duplexify.obj(writable); +duplexify.obj(writable, readable); +duplexify.obj(writable, readable, {}); + const d: duplexify.Duplexify = duplexify(); d.setReadable(readable); d.setReadable(); // $ExpectError d.setWritable(writable); d.setWritable(); // $ExpectError +d.cork(); +d.uncork(); + const f: Duplex = d; diff --git a/types/duplexify/index.d.ts b/types/duplexify/index.d.ts index 791a000f8b..7df693e93b 100644 --- a/types/duplexify/index.d.ts +++ b/types/duplexify/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for duplexify 3.5 +// Type definitions for duplexify 3.6 // Project: https://github.com/mafintosh/duplexify // Definitions by: Sami Kukkonen +// Jonathan Lui // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -11,10 +12,14 @@ export = duplexify; interface DuplexifyConstructor { (writable?: stream.Writable, readable?: stream.Readable, streamOptions?: stream.DuplexOptions): duplexify.Duplexify; new (writable?: stream.Writable, readable?: stream.Readable, streamOptions?: stream.DuplexOptions): duplexify.Duplexify; + + obj(writable?: stream.Writable, readable?: stream.Readable, streamOptions?: stream.DuplexOptions): duplexify.Duplexify; } declare var duplexify: DuplexifyConstructor; declare namespace duplexify { interface Duplexify extends stream.Duplex { + cork(): void; + uncork(): void; setWritable(writable: stream.Writable): void; setReadable(readable: stream.Readable): void; } diff --git a/types/durandal/index.d.ts b/types/durandal/index.d.ts index 85dbb86e93..77e73f2501 100644 --- a/types/durandal/index.d.ts +++ b/types/durandal/index.d.ts @@ -101,7 +101,7 @@ interface DurandalSystemModule { /** * Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise. - * @param {function} [action] The action to defer. You will be passed the deferred object as a paramter. + * @param {function} [action] The action to defer. You will be passed the deferred object as a parameter. * @returns {Deferred} The deferred object. */ defer(action?: (dfd: DurandalDeferred) => void): DurandalDeferred; diff --git a/types/dwt/index.d.ts b/types/dwt/index.d.ts index 12813a9b40..12e4ac0521 100644 --- a/types/dwt/index.d.ts +++ b/types/dwt/index.d.ts @@ -1372,7 +1372,7 @@ declare enum EnumDWT_UploadDataFormat { Base64 = 1 } -/** +/** * interface for a DWT container which basically defines a DIV on the page */ interface Container { @@ -1381,7 +1381,7 @@ interface Container { Height: string | number; } -/** +/** * interface for a base64 result */ interface Base64Result { @@ -2294,7 +2294,7 @@ interface WebTwain { */ Zoom: number; - /* ignored + /* ignored style _AutoCropMethod */ @@ -2490,7 +2490,7 @@ interface WebTwain { * @param {Array} indices indices specifies which images are to be converted to base64. * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. * @return {Base64Result} - + ConvertToBase64(indices: number[], enumImageType: EnumDWT_ImageType): Base64Result; */ @@ -3289,7 +3289,7 @@ interface WebTwain { */ MoveImage(sSourceImageIndex: number, sTargetImageIndex: number): boolean; - /*ignored + /*ignored OnRefreshUI */ @@ -3727,7 +3727,7 @@ interface WebTwain { * @param {string} InitialDir The initial directory. The algorithm for selecting the initial directory varies on different platforms. * @param {boolean} AllowMultiSelect True -- allows users to select more than one file, False -- only allows to select one file. * @param {boolean} OverwritePrompt True -- If a file already exists with the same name, the old file will be simply overwritten, False -- not allows to save and overwrite a same name file. - * @param {number} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and paramters "AllowMultiSelect" and "OverwritePrompt" will be useless. + * @param {number} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and parameters "AllowMultiSelect" and "OverwritePrompt" will be useless. * @return {boolean} */ ShowFileDialog(SaveDialog: boolean, Filter: string, FilterIndex: number, DefExtension: string, InitialDir: string, AllowMultiSelect: boolean, OverwritePrompt: boolean, Flags: number): boolean; @@ -3751,7 +3751,7 @@ interface WebTwain { */ ShowImageEditorEx(x: number, y: number, cx: number, cy: number, nCmdShow: number): boolean; - /*ingored + /*ingored SourceNameItems */ diff --git a/types/dwt/v12/index.d.ts b/types/dwt/v12/index.d.ts index 423dab8824..cc0d1f8079 100644 --- a/types/dwt/v12/index.d.ts +++ b/types/dwt/v12/index.d.ts @@ -2768,7 +2768,7 @@ interface WebTwain { * @param {string} InitialDir The initial directory. The algorithm for selecting the initial directory varies on different platforms. * @param {bool} AllowMultiSelect True -- allows users to select more than one file, False -- only allows to select one file. * @param {bool} OverwritePrompt True -- If a file already exists with the same name, the old file will be simply overwritten, False -- not allows to save and overwrite a same name file. - * @param {int} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and paramters "AllowMultiSelect" and "OverwritePrompt" will be useless. + * @param {int} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and parameters "AllowMultiSelect" and "OverwritePrompt" will be useless. * @return {bool} */ ShowFileDialog(SaveDialog: boolean, Filter: string, FilterIndex: number, DefExtension: string, InitialDir: string, AllowMultiSelect: boolean, OverwritePrompt: boolean, Flags: number): boolean; diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 60262e3d04..0818b4e5ce 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -101,7 +101,7 @@ export interface CommonWrapper

> { /** * Returns whether or not the current node exists. */ - exists(): boolean; + exists(selector?: EnzymeSelector): boolean; /** * Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector. diff --git a/types/expo-localization/expo-localization-tests.ts b/types/expo-localization/expo-localization-tests.ts new file mode 100644 index 0000000000..053c4bfe71 --- /dev/null +++ b/types/expo-localization/expo-localization-tests.ts @@ -0,0 +1,4 @@ +import { Localization } from "expo-localization"; + +Localization.getLocalizationAsync().then(localization => localization.locale); +Localization.locale; diff --git a/types/expo-localization/index.d.ts b/types/expo-localization/index.d.ts new file mode 100644 index 0000000000..21c6ca8756 --- /dev/null +++ b/types/expo-localization/index.d.ts @@ -0,0 +1,73 @@ +// Type definitions for expo-localization 1.0 +// Project: https://docs.expo.io/ +// Definitions by: Bartosz Dotryw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface LocalizationProps { + /** + * Native device language, returned in standard format. ex: `en-US`, `es-US` + */ + locale: string; + + /** + * List of all the native languages provided by the user settings. These are returned in the order the user defines in their native settings + */ + locales: string[]; + + /** + * Country code for your device + */ + country: string | undefined | null; + + /** + * A list of all the supported ISO codes + */ + isoCurrencyCodes: string[] | undefined | null; + + /** + * The current time zone in display format. ex: `America/Los_Angeles` + */ + timezone: string; + + /** + * This will return `true` if the current language is Right-to-Left + */ + isRTL: boolean; +} + +export namespace Localization { + /** + * Native device language, returned in standard format. ex: `en-US`, `es-US` + */ + const locale: string; + + /** + * List of all the native languages provided by the user settings. These are returned in the order the user defines in their native settings + */ + const locales: string[]; + + /** + * Country code for your device + */ + const country: string | undefined | null; + + /** + * A list of all the supported ISO codes + */ + const isoCurrencyCodes: string[] | undefined | null; + + /** + * The current time zone in display format. ex: `America/Los_Angeles` + */ + const timezone: string; + + /** + * This will return `true` if the current language is Right-to-Left + */ + const isRTL: boolean; + + /** + * Android only, on iOS changing the locale settings will cause all the apps to reset + */ + function getLocalizationAsync(): Promise; +} diff --git a/types/expo-localization/tsconfig.json b/types/expo-localization/tsconfig.json new file mode 100644 index 0000000000..d024122421 --- /dev/null +++ b/types/expo-localization/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", + "expo-localization-tests.ts" + ] +} diff --git a/types/expo-localization/tslint.json b/types/expo-localization/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/expo-localization/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 2ba6227012..6b04bf8f11 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -104,7 +104,7 @@ export function warn(...values: any[]): void; /////////////////////////////////////////////////////////////////////////////// // Data Object Interfaces - These intrface are not specific part of fabric, -// They are just helpful for for defining function paramters +// They are just helpful for for defining function parameters ////////////////////////////////////////////////////////////////////////////// interface IDataURLOptions { /** @@ -4682,4 +4682,3 @@ export interface WebglFilterBackend extends FilterBackend, WebglFilterBackendOpt export class WebglFilterBackend { constructor(options?: WebglFilterBackendOptions); } - diff --git a/types/fast-diff/fast-diff-tests.ts b/types/fast-diff/fast-diff-tests.ts deleted file mode 100644 index 3177bfa7fc..0000000000 --- a/types/fast-diff/fast-diff-tests.ts +++ /dev/null @@ -1,16 +0,0 @@ -import fastDiff = require('fast-diff'); - -let diffs: fastDiff.Diff[]; -diffs = fastDiff("hi there", "hi"); -diffs = fastDiff("hi there", "hi", 1); - -diffs.forEach((diff: fastDiff.Diff) => { - const operation: number = diff[0]; - const text: string = diff[1]; - - switch (diff[0]) { - case fastDiff.EQUAL: break; - case fastDiff.DELETE: break; - case fastDiff.INSERT: break; - } -}); diff --git a/types/fast-diff/index.d.ts b/types/fast-diff/index.d.ts deleted file mode 100644 index 1f306a6e9d..0000000000 --- a/types/fast-diff/index.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Type definitions for fast-diff 1.1 -// Project: https://github.com/jhchen/fast-diff#readme -// Definitions by: John Renner -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare function diff(text1: string, text2: string, cursorPos?: number): diff.Diff[]; - -declare namespace diff { - type Diff = [-1 | 0 | 1, string]; - - const DELETE: -1; - const INSERT: 1; - const EQUAL: 0; -} - -export = diff; diff --git a/types/file-saver/file-saver-tests.ts b/types/file-saver/file-saver-tests.ts index 7e704663d8..cea6d2fff5 100644 --- a/types/file-saver/file-saver-tests.ts +++ b/types/file-saver/file-saver-tests.ts @@ -22,6 +22,17 @@ function testWindowSaveAs() { window.saveAs(data, filename, disableAutoBOM); } +/** + * @summary Test for "saveAs" function with URL as first argument. + */ +function testUrlSaveAs() { + const url = 'https://example.com/test.txt'; + const filename = 'hello world.txt'; + const disableAutoBOM = true; + + window.saveAs(url, filename, disableAutoBOM); +} + /** * @summary Test for "saveAs" function with the 3rd parameter omitted */ diff --git a/types/file-saver/index.d.ts b/types/file-saver/index.d.ts index 267e49d261..524c5964bf 100644 --- a/types/file-saver/index.d.ts +++ b/types/file-saver/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for FileSaver.js 1.3 +// Type definitions for FileSaver.js 2.0 // Project: https://github.com/eligrey/FileSaver.js/ // Definitions by: Cyril Schumacher // Daniel Roth @@ -8,11 +8,11 @@ declare namespace FileSaver { /** * FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it. - * @param data - The actual file data blob. + * @param data - The actual file data blob or URL. * @param filename - The optional name of the file to be downloaded. If omitted, the name used in the file data will be used. If none is provided "download" will be used. * @param disableAutoBOM - Optional & defaults to `false`. Set to `true` if you want FileSaver.js to automatically provide Unicode text encoding hints */ - function saveAs(data: Blob, filename?: string, disableAutoBOM?: boolean): void; + function saveAs(data: Blob | string, filename?: string, disableAutoBOM?: boolean): void; } declare global { diff --git a/types/frisby/index.d.ts b/types/frisby/index.d.ts index 9057edae6d..1bcd6fdabb 100644 --- a/types/frisby/index.d.ts +++ b/types/frisby/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Christopher E. Woodland // Johnny Li // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/frisby/v0/index.d.ts b/types/frisby/v0/index.d.ts index 37ccb7c15f..bb41e93321 100644 --- a/types/frisby/v0/index.d.ts +++ b/types/frisby/v0/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/vlucas/frisby // Definitions by: Johnny Li // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/gamepad/gamepad-tests.ts b/types/gamepad/gamepad-tests.ts index af3095adb0..b71203eb7c 100644 --- a/types/gamepad/gamepad-tests.ts +++ b/types/gamepad/gamepad-tests.ts @@ -1,70 +1,69 @@ +/// +import gamepad = require('gamepad'); +// Initialize the library +gamepad.init(); +// List the state of all currently attached devices +for (let i = 0, l = gamepad.numDevices(); i < l; i++) { + console.log(i, gamepad.deviceAtIndex(i)); +} -()=>{ - function runAnimation() - { - window.requestAnimationFrame(runAnimation); +// Create a game loop and poll for events +setInterval(gamepad.processEvents, 16); +// Scan for new gamepads as a slower rate +setInterval(gamepad.detectDevices, 500); - var gamepads = navigator.getGamepads(); - - for (var i = 0; i < gamepads.length; ++i) - { - var pad = gamepads[i]; - // todo; simple demo of displaying pad.axes and pad.buttons +// Listen for new gamepads being attached +gamepad.on('attach', (deviceID, device) => { + console.log('attach', { + deviceID, + device: { + deviceID: device.deviceID, + description: device.description, + vendorID: device.vendorID, + productID: device.productID, + axisStates: device.axisStates, + buttonStates: device.buttonStates, } - } + }); +}); - window.requestAnimationFrame(runAnimation); -}; +// Listen for new gamepads being removed +gamepad.on('remove', deviceID => { + console.log('remove', { + deviceID + }); +}); -(()=>{ - var gamepadconnected = (e: Gamepad.GamepadEvent) => { - console.log('Gamepad ' + e.gamepad.index + ' connected!'); - if(e.gamepad.mapping == 'standard'){ - console.log("The Gamepad's controls have been mapped to the Standard Gamepad layout."); - } - }; - var gamepaddisconnected = (e: Gamepad.GamepadEvent) => { - console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); - }; +// Listen for button down events on all gamepads +gamepad.on('up', (deviceID, buttonID, timestamp) => { + console.log('up', { + deviceID, + buttonID, + timestamp + }); +}); - window.addEventListener('GamepadConnected', gamepadconnected, false); - window.addEventListener('GamepadDisconnected', gamepaddisconnected, false); - window.addEventListener('webkitGamepadConnected', gamepadconnected, false); - window.addEventListener('webkitGamepadDisconnected', gamepaddisconnected, false); - window.addEventListener('mozGamepadConnected', gamepadconnected, false); - window.addEventListener('mozGamepadDisconnected', gamepaddisconnected, false); +// Listen for button down events on all gamepads +gamepad.on('down', (deviceID, buttonID, timestamp) => { + console.log('down', { + deviceID, + buttonID, + timestamp + }); +}); - var requestAnimationFrame = window.requestAnimationFrame || (window).mozRequestAnimationFrame; - var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads; - if(getGamepads){ - function runAnimation() - { - requestAnimationFrame.call(window, runAnimation); +// Listen for move events on all gamepads +gamepad.on('move', (deviceID, axisID, value, lastValue, timestamp) => { + console.log('move', { + deviceID, + axisID, + value, + lastValue, + timestamp + }); +}); - var gamepads: Gamepad.Gamepad[] = getGamepads.call(navigator); - for(var i = 0; i < gamepads.length; i++){ - var pad: Gamepad.Gamepad = gamepads[i]; - if(pad && pad.connected){ - for (var k = 0; k < pad.buttons.length; k++) - { - var button: Gamepad.GamepadButton = pad.buttons[k]; - if(button.pressed){ - console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" button[' + k + '] = ' + button.value); - } - } - for (var k = 0; k < pad.axes.length; k++) - { - var axis = pad.axes[k]; - if(Math.abs(axis) > 0.1){ - console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" axis[' + k + '] = ' + axis); - } - } - } - } - } - - runAnimation(); - } -})(); \ No newline at end of file +// Shutdown the library +gamepad.shutdown(); diff --git a/types/gamepad/index.d.ts b/types/gamepad/index.d.ts index 3678190522..b66e13336b 100644 --- a/types/gamepad/index.d.ts +++ b/types/gamepad/index.d.ts @@ -1,97 +1,33 @@ -// Type definitions for Gamepad API -// Project: http://www.w3.org/TR/gamepad/ -// Definitions by: Kon +// Type definitions for gamepad 1.5 +// Project: https://github.com/creationix/node-gamepad#readme +// Definitions by: Alex Van Camp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 -declare namespace Gamepad{ - /** - * This interface defines an individual gamepad device. - */ - export interface Gamepad{ - /** - * An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID. - * @readonly - */ - id:string; +import { EventEmitter } from 'events'; - /** - * The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused. - * @readonly - */ - index:number; +declare const nodeGamepad: NodeGamepad; +export = nodeGamepad; - /** - * Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp. - * @readonly - */ - timestamp:number; +interface NodeGamepad extends EventEmitter { + init(): void; + shutdown(): void; + numDevices(): number; + deviceAtIndex(deviceIndex: number): GamepadInstance; + detectDevices(): void; + processEvents(): void; - /** - * Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick. - * @readonly - */ - axes:number[]; - - /** - * Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array. - * @readonly - */ - buttons:GamepadButton[]; - - /** - * Indicates whether the physical device represented by this object is still connected to the system. When a gamepad becomes unavailable, whether by being physically disconnected, powered off or otherwise unusable, the connected attribute must be set to false. - * @readonly - */ - connected:boolean; - - /** - * The mapping in use for this device. If the user agent has knowledge of the layout of the device, then it should indicate that a mapping is in use by setting this property to a known mapping name. Currently the only known mapping is "standard", which corresponds to the Standard Gamepad layout. If the user agent does not have knowledge of the device layout and is simply providing the controls as represented by the driver in use, then it must set the mapping property to an empty string. - * @readonly - */ - mapping:string; - } - - /** - * - */ - export interface GamepadEvent extends Event{ - /** - * The single gamepad attribute provides access to the associated gamepad data for this event. - * @readonly - */ - gamepad:Gamepad; - } - - export interface GamepadList{ - [index: number]: Gamepad; - length: number; - } - - export interface GamepadButton{ - pressed: boolean; - value: number; - } - - /* - * @event gamepadconnected - * A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis. - */ - - /* - * @event gamepaddisconnected - * When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched. - */ + on(event: 'attach', listener: (deviceID: number, device: GamepadInstance) => void): this; + on(event: 'remove', listener: (deviceID: number) => void): this; + on(event: 'down' | 'up', listener: (deviceID: number, buttonID: number, timestamp: number) => void): this; + on(event: 'move', listener: (deviceID: number, axisID: number, value: number, lastValue: number, timestamp: number) => void): this; } -interface Navigator{ - /** - * The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices. - * @readonly - */ - getGamepads(): Gamepad.Gamepad[]; - - webkitGetGamepads(): Gamepad.GamepadList; - - // Not supported yet :( - // mozGetGamepads(): Gamepad[]; +interface GamepadInstance { + deviceID: number; + description: string; + vendorID: number; + productID: number; + axisStates: number[]; + buttonStates: boolean[]; } diff --git a/types/gamepad/tsconfig.json b/types/gamepad/tsconfig.json index 4cb63f3d80..39d007a909 100644 --- a/types/gamepad/tsconfig.json +++ b/types/gamepad/tsconfig.json @@ -2,13 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": false, + "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -21,4 +20,4 @@ "index.d.ts", "gamepad-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/gamepad/tslint.json b/types/gamepad/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/gamepad/tslint.json +++ b/types/gamepad/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/gapi.client.dfareporting/index.d.ts b/types/gapi.client.dfareporting/index.d.ts index e8050193e4..8914fbb3e5 100644 --- a/types/gapi.client.dfareporting/index.d.ts +++ b/types/gapi.client.dfareporting/index.d.ts @@ -2237,7 +2237,7 @@ declare namespace gapi.client { /** Tag format type for the floodlight activity. If left blank, the tag format will default to HTML. */ tagFormat?: string; /** - * Value of the cat= paramter in the floodlight tag, which the ad servers use to identify the activity. This is optional: if empty, a new tag string will + * Value of the cat= parameter in the floodlight tag, which the ad servers use to identify the activity. This is optional: if empty, a new tag string will * be generated for you. This string must be 1 to 8 characters long, with valid characters being [a-z][A-Z][0-9][-][ _ ]. This tag string must also be * unique among activities of the same activity group. This field is read-only after insertion. */ diff --git a/types/gl-react-dom/index.d.ts b/types/gl-react-dom/index.d.ts new file mode 100644 index 0000000000..8d25b244ee --- /dev/null +++ b/types/gl-react-dom/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for gl-react-dom 3.15 +// Project: https://github.com/gre/gl-react +// Definitions by: Jussi Kinnula +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import * as glReact from 'gl-react'; + +export interface SurfaceProps extends glReact.SurfaceProps { + width: number; + height: number; +} + +export class Surface extends glReact.Surface { + props: SurfaceProps; +} diff --git a/types/gl-react-dom/tsconfig.json b/types/gl-react-dom/tsconfig.json new file mode 100644 index 0000000000..9c4d38ca44 --- /dev/null +++ b/types/gl-react-dom/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + } +} diff --git a/types/gl-react-dom/tslint.json b/types/gl-react-dom/tslint.json new file mode 100644 index 0000000000..b4b47a0378 --- /dev/null +++ b/types/gl-react-dom/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gl-react-expo/index.d.ts b/types/gl-react-expo/index.d.ts new file mode 100644 index 0000000000..20a1e19928 --- /dev/null +++ b/types/gl-react-expo/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for gl-react-expo 3.16 +// Project: https://github.com/gre/gl-react +// Definitions by: Jussi Kinnula +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Surface } from 'gl-react'; +export { Surface }; diff --git a/types/gl-react-expo/tsconfig.json b/types/gl-react-expo/tsconfig.json new file mode 100644 index 0000000000..9c4d38ca44 --- /dev/null +++ b/types/gl-react-expo/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + } +} diff --git a/types/gl-react-expo/tslint.json b/types/gl-react-expo/tslint.json new file mode 100644 index 0000000000..b4b47a0378 --- /dev/null +++ b/types/gl-react-expo/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gl-react-headless/index.d.ts b/types/gl-react-headless/index.d.ts new file mode 100644 index 0000000000..a8b0ec5212 --- /dev/null +++ b/types/gl-react-headless/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for gl-react-headless 3.15 +// Project: https://github.com/gre/gl-react +// Definitions by: Jussi Kinnula +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import * as glReact from 'gl-react'; + +export interface SurfaceProps extends glReact.SurfaceProps { + width: number; + height: number; +} + +export class Surface extends glReact.Surface { + props: SurfaceProps; +} diff --git a/types/gl-react-headless/tsconfig.json b/types/gl-react-headless/tsconfig.json new file mode 100644 index 0000000000..9c4d38ca44 --- /dev/null +++ b/types/gl-react-headless/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + } +} diff --git a/types/gl-react-headless/tslint.json b/types/gl-react-headless/tslint.json new file mode 100644 index 0000000000..b4b47a0378 --- /dev/null +++ b/types/gl-react-headless/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gl-react-native/index.d.ts b/types/gl-react-native/index.d.ts new file mode 100644 index 0000000000..b9bce2a806 --- /dev/null +++ b/types/gl-react-native/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for gl-react-native 3.15 +// Project: https://github.com/gre/gl-react +// Definitions by: Jussi Kinnula +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Surface } from 'gl-react'; +export { Surface }; diff --git a/types/gl-react-native/tsconfig.json b/types/gl-react-native/tsconfig.json new file mode 100644 index 0000000000..9c4d38ca44 --- /dev/null +++ b/types/gl-react-native/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + } +} diff --git a/types/gl-react-native/tslint.json b/types/gl-react-native/tslint.json new file mode 100644 index 0000000000..b4b47a0378 --- /dev/null +++ b/types/gl-react-native/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gl-react/index.d.ts b/types/gl-react/index.d.ts new file mode 100644 index 0000000000..e16b0d887c --- /dev/null +++ b/types/gl-react/index.d.ts @@ -0,0 +1,218 @@ +// Type definitions for gl-react 3.15 +// Project: https://github.com/gre/gl-react +// Definitions by: Jussi Kinnula +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export type Vec2 = [number, number]; +export type Vec4 = [number, number, number, number]; + +export interface BusProps { + children?: any; + uniform?: string; + index: number; +} + +export class Bus extends React.Component { + id: number; + context: { glParent: Surface | Node, glSurface: Surface }; + dependents: Array; + glNode?: Node; + glBusRootNode: any; + + static defaultProps: BusProps; + static contextTypes: { glParent: any, glSurface: any }; + static childContextTypes: { glParent: any }; + + getChildContext(): { glParent: Bus }; + getGLRenderableNode(): Node; + getGLRenderableContent(): any; + getGLName(): string; + getGLShortName(): string; + capture(x?: number, y?: number, w?: number, h?: number): any[]; + onRef: (ref: any) => void; + redraw: () => void; +} + +export type connectSize = (GLComponent: any) => any; + +export interface SurfaceProps { + children?: any; + style?: any; + preload?: any[]; + visitor?: Visitor; + + onLoad?: () => void; + onLoadError?: (e: Error) => void; + onContextLost?: () => void; + onContextRestored?: () => void; +} + +export interface SurfaceState { + ready: boolean; + rebootId: number; + debug: boolean; +} + +export class Surface extends React.Component { + props: SurfaceProps; + state: SurfaceState; + id: number; + gl: WebGLRenderingContext; + RenderLessElement: any; + root: Node; + + mapRenderableContent(inst: any): any; + getVisitors(): Visitor[]; + getGLSize(): [number, number]; + getGLName(): string; + getGLShortName(): string; + captureAsDataURL(...args: any[]): string; + captureAsBlob(...args: any[]): Promise; + capture(x?: number, y?: number, w?: number, h?: number): any[]; + redraw(): void; + flush(): void; + getEmptyTexture(): WebGLTexture; + glIsAvailable(): boolean; + rebootForDebug(): void; +} + +export type createSurface = ( + GLView: any, + RenderLessElement: any, + mapRenderableContent: any, + requestFrame: (callback: (time: number) => void) => number, + cancelFrame: (id: number) => void +) => Surface; + +export type listSurfaces = () => Surface[]; + +export function GLSL(strings: TemplateStringsArray, ...values: any[]): string; + +export interface LinearCopyProps { + children?: any; +} + +export class LinearCopy extends React.Component { + getNodeRef(): Node; +} + +export interface NearestCopyProps { + children?: any; +} + +export class NearestCopy extends React.Component { + getNodeRef(): Node; +} + +export interface SurfaceContext { + glParent: Node | Surface | Bus; + glSurface: Surface; + glSizable: { + getGLSize: () => [number, number]; + }; +} + +export interface Framebuffer { + handle: WebGLFramebuffer; + color: WebGLTexture; + bind: () => void; + dispose: () => void; + syncSize: (w: number, h: number) => void; +} + +export interface NodeProps { + shader: ShaderIdentifier | ShaderDefinition; + uniformsOptions?: any; + uniforms: { [key: string]: any }; + ignoreUnusedUniforms?: string[] | boolean; + sync?: boolean; + width?: number; + height?: number; + children?: any; + backbuffering?: boolean; + blendFunc?: { + src: () => void; + dst: () => void; + }; + clear?: { + color: Vec4; + }; + + onDraw?: () => void; +} + +export class Node extends React.Component { + drawProps: NodeProps; + context: SurfaceContext; + framebuffer?: Framebuffer; + backbuffer?: Framebuffer; + capturePixelsArray?: Uint8Array; + id: number; + uniformsBus: { + [key: string]: Array; + }; + dependencies: Array; + dependents: Array; +} + +export interface ShaderIdentifier { + type: string; + id: string; +} + +export interface ShaderDefinition { + frag: string; + vert?: string; +} + +export interface ShaderInfo { + frag: string; + vert: string; +} + +export interface ShadersSheet { + [key: string]: ShaderIdentifier; +} + +export namespace Shaders { + function create(shaders: { [key: string]: ShaderDefinition }): ShadersSheet; + function getName(shaderIdentifier: ShaderIdentifier): string; + function getShortName(shaderIdentifier: ShaderIdentifier): string; + function get(shaderIdentifier: ShaderIdentifier): ShaderInfo; +} + +export namespace Uniform { + const Backbuffer: string; + function backbufferFrom(node: Node | Bus): { type: string, node: Node | Bus }; + const Resolution: string; + function textureSize(obj: any): { type: string, obj: any }; + function textureSizeRatio(obj: any): { type: string, obj: any, ratio: boolean }; +} + +export class Visitor { + onSurfaceMount(surface: Surface): void; + onSurfaceUnmount(surface: Surface): void; + onSurfaceGLContextChange(surface: Surface, gl?: WebGLRenderingContext): void; + onSurfaceDrawSkipped(surface: Surface): void; + onSurfaceDrawStart(surface: Surface): void; + onSurfaceDrawError(e: Error): boolean; + onSurfaceDrawEnd(surface: Surface): void; + onNodeDrawSkipped(node: Node): void; + onNodeDrawStart(node: Node): void; + onNodeSyncDeps(node: Node, additions: Array, deletions: Array): void; + onNodeDraw(node: Node, preparedUniforms: any[]): void; + onNodeDrawEnd(node: Node): void; +} + +export class VisitorLogger extends Visitor { + groupNestedLvl: number; +} + +export namespace Visitors { + function add(visitor: Visitor): void; + function remove(visitor: Visitor): void; + function get(): Visitor[]; +} diff --git a/types/gl-react/package.json b/types/gl-react/package.json new file mode 100644 index 0000000000..e6696d08e7 --- /dev/null +++ b/types/gl-react/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "csstype": "^2.2.0" + } +} diff --git a/types/gl-react/tsconfig.json b/types/gl-react/tsconfig.json new file mode 100644 index 0000000000..9c4d38ca44 --- /dev/null +++ b/types/gl-react/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + } +} diff --git a/types/gl-react/tslint.json b/types/gl-react/tslint.json new file mode 100644 index 0000000000..b4b47a0378 --- /dev/null +++ b/types/gl-react/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/glue/v4/glue-tests.ts b/types/glue/v4/glue-tests.ts new file mode 100644 index 0000000000..1b67554725 --- /dev/null +++ b/types/glue/v4/glue-tests.ts @@ -0,0 +1,69 @@ +import * as glue from "glue"; +import * as hapi from "hapi"; + +const manifest: glue.Manifest = { + server: { + debug: false, + }, + connections: [ + { + port: 8000, + labels: ['web'] + }, + { + port: 8001, + labels: ['admin'] + } + ], + registrations: [ + { + plugin: { + register: './assets', + options: { + uglify: true + } + } + }, + { + plugin: './ui-user', + options: { + select: ['web'] + } + }, + { + plugin: { + register: './ui-admin', + options: { + sessiontime: 500 + } + }, + options: { + select: ['admin'], + routes: { + prefix: '/admin' + } + } + }, + { + plugin: { + register: require('./awesome-plugin.js'), + options: { + whyNot: true + } + } + }, + ] +}; + +const options: glue.Options = { + relativeTo: `${__dirname}/modules` +}; + +glue.compose(manifest, options, (err, server) => { + if (err) { + throw err; + } + server.start(() => { + console.log('hapi days!'); + }); +}); diff --git a/types/glue/v4/index.d.ts b/types/glue/v4/index.d.ts new file mode 100644 index 0000000000..69c7d56d01 --- /dev/null +++ b/types/glue/v4/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for glue 4.2 +// Project: https://github.com/hapijs/glue +// Definitions by: Greg Jednaszewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Server, ServerConnectionOptions, ServerOptions } from "hapi"; + +export interface Options { + relativeTo: string; + preConnections?: (Server: Server, next: (err: any) => void) => void; + preRegister?: (Server: Server, next: (err: any) => void) => void; +} + +export interface Plugin { + plugin: string | { + register: string; + options?: any; + }; + options?: any; +} + +export interface Manifest { + server: ServerOptions; + connections: ServerConnectionOptions[]; + registrations?: Plugin[]; +} + +export function compose(manifest: Manifest, + options?: Options, + callback?: (err?: any, server?: Server) => void): Promise; diff --git a/types/glue/v4/tsconfig.json b/types/glue/v4/tsconfig.json new file mode 100644 index 0000000000..ead9b81629 --- /dev/null +++ b/types/glue/v4/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "boom": [ "boom/v4" ], + "catbox": [ "catbox/v7" ], + "hapi": [ "hapi/v16" ], + "glue": [ "glue/v4" ] + } + }, + "files": [ + "index.d.ts", + "glue-tests.ts" + ] +} diff --git a/types/glue/v4/tslint.json b/types/glue/v4/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/glue/v4/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/graphlib-dot/index.d.ts b/types/graphlib-dot/index.d.ts new file mode 100644 index 0000000000..0a9eb1cb7a --- /dev/null +++ b/types/graphlib-dot/index.d.ts @@ -0,0 +1,56 @@ +// Type definitions for graphlib-dot 0.6 +// Project: https://github.com/dagrejs/graphlib-dot +// Definitions by: Dom Parfitt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Graph } from 'graphlib'; + +/** + * Reads a single DOT graph from the str and returns it a Graph representation. + * @param str a string in the DOT language representing a graph + */ +export function read(str: string): Graph; + +/** + * Parses one or more DOT graphs from str in a manner similar to that used by parse for individual graphs. + * @param str a string in the DOT language representing one or more graphs + */ +export function readMany(str: string): Graph[]; + +/** + * Writes a String representation of the given graph in the DOT language. + * @param g a graphlib Graph object + */ +export function write(g: Graph): string; + +/** + * Contains the version of the graphlib library used by graphlib-dot. + */ +export const graphlib: any; + +declare global { + namespace graphlibDot { + /** + * Reads a single DOT graph from the str and returns it a Graph representation. + * @param str a string in the DOT language representing a graph + */ + function read(str: string): Graph; + + /** + * Parses one or more DOT graphs from str in a manner similar to that used by parse for individual graphs. + * @param str a string in the DOT language representing one or more graphs + */ + function readMany(str: string): Graph[]; + + /** + * Writes a String representation of the given graph in the DOT language. + * @param g a graphlib Graph object + */ + function write(g: Graph): string; + + /** + * Contains the version of the graphlib library used by graphlib-dot. + */ + const graphlib: any; + } +} diff --git a/types/graphlib-dot/test/graphlib-dot-global-tests.ts b/types/graphlib-dot/test/graphlib-dot-global-tests.ts new file mode 100644 index 0000000000..7c427f21da --- /dev/null +++ b/types/graphlib-dot/test/graphlib-dot-global-tests.ts @@ -0,0 +1,6 @@ +// Global tests +const graph = graphlibDot.read('digraph {node 1}'); + +const graphs = graphlibDot.readMany('digraph { node1 }'); + +const dotStr = graphlibDot.write(graph); diff --git a/types/graphlib-dot/test/graphlib-dot-tests.ts b/types/graphlib-dot/test/graphlib-dot-tests.ts new file mode 100644 index 0000000000..138b9fdfe7 --- /dev/null +++ b/types/graphlib-dot/test/graphlib-dot-tests.ts @@ -0,0 +1,9 @@ +import { Graph } from "graphlib"; +import { read, readMany, write } from 'graphlib-dot'; + +// Module tests +const graph: Graph = read('digraph {node 1}'); + +const graphs: Graph[] = readMany('digraph { node1 }'); + +const dotStr: string = write(graph); diff --git a/types/graphlib-dot/tsconfig.json b/types/graphlib-dot/tsconfig.json new file mode 100644 index 0000000000..2e5efa560d --- /dev/null +++ b/types/graphlib-dot/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", + "test/graphlib-dot-tests.ts", + "test/graphlib-dot-global-tests.ts" + ] +} diff --git a/types/graphlib-dot/tslint.json b/types/graphlib-dot/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphlib-dot/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gulp-jasmine/index.d.ts b/types/gulp-jasmine/index.d.ts index d36896d855..e1693e38cd 100644 --- a/types/gulp-jasmine/index.d.ts +++ b/types/gulp-jasmine/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/sindresorhus/gulp-jasmine#readme // Definitions by: Andrey Lalev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// /// diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index e0bd88186d..9bd9a14f41 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -3280,7 +3280,7 @@ export type DecorateName = string | symbol; * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server) */ -export class Server extends Podium { +export class Server { /** * Creates a new server object * @param options server configuration object. diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index dcde50413d..167d6532d3 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -2976,6 +2976,21 @@ declare namespace Highcharts { * @since 3.0.1 */ printChart?: string; + /** + * The text for the label for the "from" input box in the range selector. + * @default 'From' + */ + rangeSelectorFrom?: string; + /** + * The text for the label for the "to" input box in the range selector. + * @default 'To' + */ + rangeSelectorTo?: string; + /** + * The text for the label for the range selector buttons. + * @default 'Zoom' + */ + rangeSelectorZoom?: String; /** * The text for the label appearing when a chart is zoomed. * @default 'Reset zoom' diff --git a/types/hosted-git-info/hosted-git-info-tests.ts b/types/hosted-git-info/hosted-git-info-tests.ts new file mode 100644 index 0000000000..0e4ef56cb7 --- /dev/null +++ b/types/hosted-git-info/hosted-git-info-tests.ts @@ -0,0 +1,22 @@ +import info = require("hosted-git-info"); + +info.fromUrl(''); +const result = info.fromUrl('', {}); + +result.hashformat(''); +result.hash(); +result.ssh({}); +result.sshurl({}); +result.browse('', '', {}); +result.browse('', {}); +result.browse({}); +result.docs({}); +result.bugs({}); +result.https({}); +result.git({}); +result.shortcut({}); +result.path({}); +result.tarball({}); +result.file('', {}); +result.getDefaultRepresentation(); +result.toString({}); diff --git a/types/hosted-git-info/index.d.ts b/types/hosted-git-info/index.d.ts new file mode 100644 index 0000000000..a8e5cbdeda --- /dev/null +++ b/types/hosted-git-info/index.d.ts @@ -0,0 +1,96 @@ +// Type definitions for hosted-git-info 2.7 +// Project: https://github.com/npm/hosted-git-info +// Definitions by: Jason +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class HostedGitInfo { + host: HostedGitInfo.hosts; + user: string | null; + auth: string | null; + project: string | null; + committish: string | null; + default: string; + opts: HostedGitInfo.Options; + + constructor( + host: HostedGitInfo.hosts, + user: string | null, + auth: string | null, + project: string | null, + committish: string | null, + defaultRepresentation: string, + opts?: HostedGitInfo.Options + ); + + // From git-host-info + + // defaults + sshtemplate: string; + sshurltemplate: string; + browsetemplate: string; + docstemplate: string; + filetemplate: string; + shortcuttemplate: string; + pathtemplate: string; + + pathmatch: RegExp; + protocols_re: RegExp; + hashformat(fragment: string): string; + + // special + protocols: string[]; + domain: string; + bugstemplate: string; + gittemplate: string; + browsefiletemplate: string; + httpstemplate: string; + treepath: string; + tarballtemplate: string; + + // /From git-host-info + + hash(): string; + ssh(opts?: HostedGitInfo.FillOptions): string | undefined; + sshurl(opts?: HostedGitInfo.FillOptions): string | undefined; + browse( + path: string, + fragment: string, + opts?: HostedGitInfo.FillOptions + ): string | undefined; + browse(path: string, opts?: HostedGitInfo.FillOptions): string | undefined; + browse(opts?: HostedGitInfo.FillOptions): string | undefined; + docs(opts?: HostedGitInfo.FillOptions): string | undefined; + bugs(opts?: HostedGitInfo.FillOptions): string | undefined; + https(opts?: HostedGitInfo.FillOptions): string | undefined; + git(opts?: HostedGitInfo.FillOptions): string | undefined; + shortcut(opts?: HostedGitInfo.FillOptions): string | undefined; + path(opts?: HostedGitInfo.FillOptions): string | undefined; + tarball(opts?: HostedGitInfo.FillOptions): string | undefined; + file(path: string, opts?: HostedGitInfo.FillOptions): string | undefined; + getDefaultRepresentation(): string; + toString(opts?: HostedGitInfo.FillOptions): string | undefined; + + static fromUrl( + gitUrl: string, + options?: HostedGitInfo.Options + ): HostedGitInfo; +} + +declare namespace HostedGitInfo { + interface Options { + noCommittish?: boolean; + noGitPlus?: boolean; + } + + interface FillOptions extends Options { + path?: string; + auth?: string; + fragment?: string; + committish?: string; + treepath?: string; + } + + type hosts = 'github' | 'bitbucket' | 'gitlab' | 'gist'; +} + +export = HostedGitInfo; diff --git a/types/hosted-git-info/tsconfig.json b/types/hosted-git-info/tsconfig.json new file mode 100644 index 0000000000..5736539a96 --- /dev/null +++ b/types/hosted-git-info/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", + "hosted-git-info-tests.ts" + ] +} diff --git a/types/hosted-git-info/tslint.json b/types/hosted-git-info/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hosted-git-info/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts b/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts index 174a871b9f..eadfcea369 100644 --- a/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts +++ b/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts @@ -19,7 +19,7 @@ const options: LngDetector.DetectorOptions = { cookieDomain: "myDomain", // optional htmlTag with lang attribute, the default is: - htmlTag: document.documentElement! + htmlTag: document.documentElement }; i18next.use(LngDetector).init({ diff --git a/types/i18next-browser-languagedetector/v0/index.d.ts b/types/i18next-browser-languagedetector/v0/index.d.ts index 9d8f58a52a..8b0f6b6317 100644 --- a/types/i18next-browser-languagedetector/v0/index.d.ts +++ b/types/i18next-browser-languagedetector/v0/index.d.ts @@ -28,7 +28,7 @@ declare namespace i18nextBrowserLanguageDetector { interface CustomDetector { name: string; - // todo: Checks paramters type. + // todo: Checks parameters type. cacheUserLanguage(lng: string, options: {}): void; lookup(options: {}): string; } diff --git a/types/ibm_db/ibm_db-tests.ts b/types/ibm_db/ibm_db-tests.ts index 93802c662f..cc896b8d05 100644 --- a/types/ibm_db/ibm_db-tests.ts +++ b/types/ibm_db/ibm_db-tests.ts @@ -10,3 +10,14 @@ ibmdb.open("DATABASE=;HOSTNAME=;UID=db2user;PWD=password;PORT= void): void; - _executeSync(params: any[]): ODBCResult; + _executeSync(params?: any[]): ODBCResult; _executeDirect(sql: string, cb: (err: Error, result: any[]) => void): void; @@ -170,7 +170,7 @@ export class ODBCStatement { execute(cb: (err: Error, result: any[], outparams: any) => void): void; execute(params: any[]): Promise<{result: any[], outparams: any}>; - executeSync(params: any[]): ODBCResult; + executeSync(params?: any[]): ODBCResult; executeDirect(sql: string, cb: (err: Error, result: any[]) => void): void; diff --git a/types/inquirer-npm-name/index.d.ts b/types/inquirer-npm-name/index.d.ts new file mode 100644 index 0000000000..bca64cd7ac --- /dev/null +++ b/types/inquirer-npm-name/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for inquirer-npm-name 3.0 +// Project: https://github.com/SBoudrias/inquirer-npm-name +// Definitions by: manuth +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.3 + +import { Inquirer, Answers, Question } from "inquirer"; + +declare function askName(name: string | Question, inquirer: Inquirer): Promise<{ [key: string]: string }>; +export = askName; diff --git a/types/inquirer-npm-name/inquirer-npm-name-tests.ts b/types/inquirer-npm-name/inquirer-npm-name-tests.ts new file mode 100644 index 0000000000..aee1b039d7 --- /dev/null +++ b/types/inquirer-npm-name/inquirer-npm-name-tests.ts @@ -0,0 +1,13 @@ +import inquirer = require("inquirer"); +import askName = require("inquirer-npm-name"); + +// $ExpectType Promise<{ [key: string]: string; }> +askName("moduleName", inquirer); + +// $ExpectType Promise<{ [key: string]: string; }> +askName( + { + name: "moduleName", + message: "Whar's the name of your module?" + }, + inquirer); diff --git a/types/inquirer-npm-name/tsconfig.json b/types/inquirer-npm-name/tsconfig.json new file mode 100644 index 0000000000..99dee30a17 --- /dev/null +++ b/types/inquirer-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", + "inquirer-npm-name-tests.ts" + ] +} diff --git a/types/inquirer-npm-name/tslint.json b/types/inquirer-npm-name/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/inquirer-npm-name/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ip/index.d.ts b/types/ip/index.d.ts index c51a8d37f5..ed9ba584bc 100644 --- a/types/ip/index.d.ts +++ b/types/ip/index.d.ts @@ -26,7 +26,7 @@ declare module "ip" { /** * Convert an IP string into a buffer. **/ - export function toBuffer(ip: string, buffer?: number, offset?: number): Buffer; + export function toBuffer(ip: string, buffer?: Buffer, offset?: number): Buffer; /** * Convert an IP buffer into a string. diff --git a/types/ip/ip-tests.ts b/types/ip/ip-tests.ts index 13abf1f4a6..f1fbf4726d 100644 --- a/types/ip/ip-tests.ts +++ b/types/ip/ip-tests.ts @@ -20,3 +20,7 @@ ip.toString(buff); ip.subnet('192.168.1.134', '255.255.255.192'); ip.cidrSubnet('192.168.1.134/26'); ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.134'); +var buf = new Buffer(128); +var offset = 64; +ip.toBuffer('127.0.0.1', buf, offset); +ip.toString(buf, offset, 4); diff --git a/types/jasmine-ajax/index.d.ts b/types/jasmine-ajax/index.d.ts index 2e111a19f3..ad95004612 100644 --- a/types/jasmine-ajax/index.d.ts +++ b/types/jasmine-ajax/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jasmine/jasmine-ajax // Definitions by: Louis Grignon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 interface JasmineAjaxResponse { status?: number; diff --git a/types/jasmine-data_driven_tests/index.d.ts b/types/jasmine-data_driven_tests/index.d.ts index 54a7ea0441..6e6a070eaa 100644 --- a/types/jasmine-data_driven_tests/index.d.ts +++ b/types/jasmine-data_driven_tests/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gburghardt/jasmine-data_driven_tests // Definitions by: Anthony MacKinnon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 declare var all: JasmineDataDrivenTest; declare var xall: JasmineDataDrivenTest; diff --git a/types/jasmine-es6-promise-matchers/index.d.ts b/types/jasmine-es6-promise-matchers/index.d.ts index e80b9241c7..0a1c5360be 100644 --- a/types/jasmine-es6-promise-matchers/index.d.ts +++ b/types/jasmine-es6-promise-matchers/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/bvaughn/jasmine-es6-promise-matchers // Definitions by: Stephen Lautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/jasmine-fixture/index.d.ts b/types/jasmine-fixture/index.d.ts index 82449ffc01..cb68513a79 100644 --- a/types/jasmine-fixture/index.d.ts +++ b/types/jasmine-fixture/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/searls/jasmine-fixture // Definitions by: Craig Brett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/jasmine-jquery/index.d.ts b/types/jasmine-jquery/index.d.ts index 0dc023f33a..1675992a7b 100644 --- a/types/jasmine-jquery/index.d.ts +++ b/types/jasmine-jquery/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/velesin/jasmine-jquery // Definitions by: Gregor Stamac // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// /// diff --git a/types/jasmine-matchers/index.d.ts b/types/jasmine-matchers/index.d.ts index e5167e2084..7284ffce49 100644 --- a/types/jasmine-matchers/index.d.ts +++ b/types/jasmine-matchers/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/uxebu/jasmine-matchers // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /* Typings 2013 Bart van der Schoor diff --git a/types/jasmine-node/index.d.ts b/types/jasmine-node/index.d.ts index dcb55bcd2d..3270b356bd 100644 --- a/types/jasmine-node/index.d.ts +++ b/types/jasmine-node/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mhevery/jasmine-node // Definitions by: Sven Reglitzki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/jasmine-promise-matchers/index.d.ts b/types/jasmine-promise-matchers/index.d.ts index e2b3c0116e..3c05b5304e 100644 --- a/types/jasmine-promise-matchers/index.d.ts +++ b/types/jasmine-promise-matchers/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/bvaughn/jasmine-promise-matchers // Definitions by: Matthew Hill // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index 254714ff94..a25d28a715 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -1,8 +1,14 @@ // Type definitions for Jasmine 2.8.0 // Project: http://jasmine.github.io/ -// Definitions by: Boris Yankov , Theodore Brown , David Pärsson , Gabe Moothart , Lukas Zech , Boris Breuer +// Definitions by: Boris Yankov +// Theodore Brown +// David Pärsson +// Gabe Moothart +// Lukas Zech +// Boris Breuer +// Chris Yungmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 // For ddescribe / iit use : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts /** @@ -129,7 +135,7 @@ declare function waits(timeout?: number): void; declare namespace jasmine { type Expected = T | ObjectContaining | Any | Spy; - type SpyObjMethodNames = string[] | {[methodName: string]: any} | Array; + type SpyObjMethodNames = T extends undefined ? (ReadonlyArray | {[methodName: string]: any}) : (ReadonlyArray | {[P in keyof T]?: ReturnType any ? T[P] : any>}); var clock: () => Clock; @@ -448,6 +454,12 @@ declare namespace jasmine { toThrowError(message?: string | RegExp): boolean; toThrowError(expected?: new (...args: any[]) => Error, message?: string | RegExp): boolean; + /** + * Add some context for an expect. + * @param message - Additional context to show when the matcher fails + */ + withContext(message: string): Matchers; + not: Matchers; Any: Any; diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index e96293ced4..11bfbca2b2 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -246,6 +246,12 @@ describe("A spec", () => { }); }); +describe("withContext", () => { + it("can be used after an expectation", () => { + expect(1).withContext('context message').toBe(1); + }); +}); + xdescribe("A spec", () => { var foo: number; diff --git a/types/jasmine_dom_matchers/index.d.ts b/types/jasmine_dom_matchers/index.d.ts index 5ab86cc799..b3a625f08c 100644 --- a/types/jasmine_dom_matchers/index.d.ts +++ b/types/jasmine_dom_matchers/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/charleshansen/jasmine_dom_matchers // Definitions by: Yaroslav Admin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/jasminewd2/index.d.ts b/types/jasminewd2/index.d.ts index efabeaafe0..7e75d87991 100644 --- a/types/jasminewd2/index.d.ts +++ b/types/jasminewd2/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Sammy Jelin // George Kalpakas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/jquery-formatdatetime/index.d.ts b/types/jquery-formatdatetime/index.d.ts new file mode 100644 index 0000000000..308d58fe7f --- /dev/null +++ b/types/jquery-formatdatetime/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for JQuery formatDateTime 1.1 +// Project: https://github.com/agschwender/jquery.formatDateTime +// Definitions by: Anderson Friaça +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export type Options = Partial<{ + /** + * Names of the months, e.g. January + */ + monthNames: string[]; + + /** + * Shortened names of the months, e.g. Jan + */ + monthNamesShort: string[]; + + /** + * Names of the days, e.g. Sunday + */ + dayNames: string[]; + + /** + * Shortened names of the days, e.g. Sun + */ + dayNamesShort: string[]; + + /** + * Names of the 12-hour clock periods, e.g. AM + */ + ampmNames: string[]; + + /** + * Callback to convert number to ordinal suffix, e.g. 1 to st + */ + getSuffix: ((num: number) => string); + + /** + * Attribute which contains the datetime + */ + attribute: string; + + /** + * Attribute which contains the datetime format + */ + formatAttribute: string; + + /** + * Render dates in UTC instead of local timezone + */ + utc: boolean; +}>; + +declare global { + interface JQuery { + formatDateTime(format: string, options?: Options): JQuery; + } + + interface JQueryStatic { + formatDateTime(format: string, date: Date, options?: Options): string; + } +} diff --git a/types/jquery-formatdatetime/jquery-formatdatetime-tests.ts b/types/jquery-formatdatetime/jquery-formatdatetime-tests.ts new file mode 100644 index 0000000000..fe5949f757 --- /dev/null +++ b/types/jquery-formatdatetime/jquery-formatdatetime-tests.ts @@ -0,0 +1,40 @@ +import { Options } from "jquery-formatdatetime"; + +// basic usage +$('#example').formatDateTime('mm/dd/y g:ii a'); + +const date = new Date('2012/07/05 09:55:03'); + +$.formatDateTime('mm/dd/y g:ii a', date); + +// with options +const options: Options = { + monthNames: [ + 'Janeiro', + 'Fevereiro', + 'Março', + 'Abril', + 'Maio', + 'Junho', + 'Julho', + 'Agosto', + 'Setembro', + 'Outubro', + 'Novembro', + 'Dezembro' + ], + dayNames: [ + 'Domingo', + 'Segunda-Feira', + 'Terça-Feira', + 'Quarta-Feira', + 'Quinta-Feira', + 'Sexta-Feira', + 'Sábado' + ], + ampmNames: ['AM', 'PM'] +}; + +$.formatDateTime('mm/dd/y g:ii a', date, options); + +$('#example').formatDateTime('mm/dd/y g:ii a', options); diff --git a/types/jquery-formatdatetime/tsconfig.json b/types/jquery-formatdatetime/tsconfig.json new file mode 100644 index 0000000000..a6ba781d22 --- /dev/null +++ b/types/jquery-formatdatetime/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", + "jquery-formatdatetime-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery-formatdatetime/tslint.json b/types/jquery-formatdatetime/tslint.json new file mode 100644 index 0000000000..d04fe2e1fa --- /dev/null +++ b/types/jquery-formatdatetime/tslint.json @@ -0,0 +1 @@ +{"extends": "dtslint/dt.json"} \ No newline at end of file diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 60fbd431bb..7ecb1733a7 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -2334,7 +2334,9 @@ function examples() { } function jQuery_contains_0() { + // tslint:disable-next-line no-unnecessary-type-assertion $.contains(document.documentElement!, document.body); // true + // tslint:disable-next-line no-unnecessary-type-assertion $.contains(document.body, document.documentElement!); // false } diff --git a/types/jsdom/jsdom-tests.ts b/types/jsdom/jsdom-tests.ts index 75ff0605bc..d20232e36f 100644 --- a/types/jsdom/jsdom-tests.ts +++ b/types/jsdom/jsdom-tests.ts @@ -82,6 +82,7 @@ function test_serialize() { dom.serialize() === 'hello'; // Contrast with: + // tslint:disable-next-line no-unnecessary-type-assertion dom.window.document.documentElement!.outerHTML === 'hello'; } diff --git a/types/json-rpc-random-id/index.d.ts b/types/json-rpc-random-id/index.d.ts new file mode 100644 index 0000000000..14b5ba0ff0 --- /dev/null +++ b/types/json-rpc-random-id/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for json-rpc-random-id 1.0 +// Project: https://github.com/kumavis/json-rpc-random-id#readme +// Definitions by: Micah Riggan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * Returns a function that generates a random number + * This number is to be used with web3 rpc + */ +declare function IdIterator(options?: { + max?: number; + start?: number; +}): () => number; + +export = IdIterator; diff --git a/types/json-rpc-random-id/json-rpc-random-id-tests.ts b/types/json-rpc-random-id/json-rpc-random-id-tests.ts new file mode 100644 index 0000000000..c71a7581e8 --- /dev/null +++ b/types/json-rpc-random-id/json-rpc-random-id-tests.ts @@ -0,0 +1,2 @@ +import jsonRPCRandomID = require("json-rpc-random-id"); +const generateId = jsonRPCRandomID(); diff --git a/types/json-rpc-random-id/tsconfig.json b/types/json-rpc-random-id/tsconfig.json new file mode 100644 index 0000000000..c39a0a4e2b --- /dev/null +++ b/types/json-rpc-random-id/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", + "json-rpc-random-id-tests.ts" + ] +} diff --git a/types/json-rpc-random-id/tslint.json b/types/json-rpc-random-id/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json-rpc-random-id/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jsonquery/index.d.ts b/types/jsonquery/index.d.ts new file mode 100644 index 0000000000..48afcf8d0a --- /dev/null +++ b/types/jsonquery/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for jsonquery 0.1 +// Project: https://github.com/eugeneware/jsonquery +// Definitions by: Jim Buck +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +declare function jsonquery(query: jsonquery.Query): NodeJS.ReadWriteStream; + +declare namespace jsonquery { + function match(haystack: T, predicate: Query): boolean; + + type Query = BinaryQueryCondition | QueryValue | PathQuery; + + interface OrQueryCondition { + $or: ReadonlyArray>; + } + + interface AndQueryCondition { + $and: ReadonlyArray>; + } + + type BinaryQueryCondition = OrQueryCondition | AndQueryCondition; + + interface BaseCondition

{ + $lt: P; + $lte: P; + $gt: P; + $gte: P; + $mod: [number, number]; + $ne: P; + $in: ReadonlyArray

; + $nin: ReadonlyArray

; + $all: ReadonlyArray

; + $elemMatch: Partial

; + } + + interface PathQuery { + [path: string]: any; + } + + type QueryValue = { + [P in keyof T]?: T[P] | BaseCondition; + }; +} + +export = jsonquery; diff --git a/types/jsonquery/jsonquery-tests.ts b/types/jsonquery/jsonquery-tests.ts new file mode 100644 index 0000000000..904f61d01c --- /dev/null +++ b/types/jsonquery/jsonquery-tests.ts @@ -0,0 +1,120 @@ +import jsonquery = require('jsonquery'); + +interface TestData { + name: string; + number: string; + val: number; + favorites: number[]; + awesome: boolean; + nullify: null; + tree: { + a: number; + b: number; + }; +} + +const testDataInstance: TestData = { + name: "Name 1", + number: "Number 1", + val: 10, + favorites: [10, 20], + awesome: true, + nullify: null, + tree: { + a: 1, + b: 2, + } +}; + +// $ExpectType ReadWriteStream +jsonquery({ number: 'Number 7' }); + +// $ExpectType ReadWriteStream +jsonquery({ number: 'Number 7', val: 70 }); + +// $ExpectType ReadWriteStream +jsonquery({ $or: [ { number: 'Number 7' }, { val: 50 } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ $and: [ { number: 'Number 7' }, { val: 70 } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ $or: [ { $and: [ { number: 'Number 7' }, { val: 70 } ] }, { val: 50 } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $in: [ 70, 50 ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $or: [ { $in: [ 70, 50 ] }, { $in: [ 60, 20 ] } ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $gt: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $lt: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $or: [ { $lt: 20 }, { $gt: 950 } ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $and: [ { $gt: 970 }, { $gt: 950 } ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $ne: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $lte: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $gte: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ favorites: { $all: [50, 60] } }); + +// $ExpectType ReadWriteStream +jsonquery({ tree: { $elemMatch: { a: 1, b: 2 } } }); + +// $ExpectType ReadWriteStream +jsonquery({ 'tree.a': 1 }); + +// $ExpectType ReadWriteStream +jsonquery({ 'tree.a': { $in: [1, 5] } }); + +// $ExpectType ReadWriteStream +jsonquery({ number: /er 7$/ }); + +// $ExpectType ReadWriteStream +jsonquery({ number: { $in: [ /er 7$/, /er 5$/ ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ favorites: { $all: [/^50$/, /^60$/] } }); + +// $ExpectType ReadWriteStream +jsonquery({ tree: { $elemMatch: { a: /^1$/, b: 2 } } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $nin: [ 70, 50 ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $mod: [ 7, 1 ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ favorites: { $size: 2 } }); + +// $ExpectType ReadWriteStream +jsonquery({ $and: [ { tree: { $exists: true } }, { missing: { $exists: false } } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ $not: { number: 'Number 7', val: 70 } }); + +// $ExpectType ReadWriteStream +jsonquery({ number: { $not: { $nin: ['Number 7'] } } }); + +// $ExpectType ReadWriteStream +jsonquery({ foo: { $all: ['bar'] } }); + +// $ExpectType boolean +jsonquery.match(testDataInstance, { val: 7 }); + +// $ExpectType boolean +jsonquery.match(testDataInstance, { 'tree.a': { $in: [1, 5] } }); diff --git a/types/mobx-cookie/tsconfig.json b/types/jsonquery/tsconfig.json similarity index 93% rename from types/mobx-cookie/tsconfig.json rename to types/jsonquery/tsconfig.json index 4222165feb..ffb3eb6209 100644 --- a/types/mobx-cookie/tsconfig.json +++ b/types/jsonquery/tsconfig.json @@ -6,8 +6,8 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictFunctionTypes": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "mobx-cookie-tests.ts" + "jsonquery-tests.ts" ] } diff --git a/types/jsonquery/tslint.json b/types/jsonquery/tslint.json new file mode 100644 index 0000000000..02db66c29b --- /dev/null +++ b/types/jsonquery/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules":{ + "no-unnecessary-generics": false + } +} diff --git a/types/jsonwebtoken/index.d.ts b/types/jsonwebtoken/index.d.ts index f54d3862c9..d1c3aeee5f 100644 --- a/types/jsonwebtoken/index.d.ts +++ b/types/jsonwebtoken/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for jsonwebtoken 7.2.2 +// Type definitions for jsonwebtoken 8.3 // Project: https://github.com/auth0/node-jsonwebtoken // Definitions by: Maxime LUCE , // Daniel Heim , // Brice BERNARD , -// Veli-Pekka Kestilä +// Veli-Pekka Kestilä , +// Daniel Parker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -43,9 +44,9 @@ export interface SignOptions { */ algorithm?: string; keyid?: string; - /** @member {string} - expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ expiresIn?: string | number; - /** @member {string} - expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ notBefore?: string | number; audience?: string | string[]; subject?: string; @@ -67,8 +68,8 @@ export interface VerifyOptions { jwtid?: string; subject?: string; /** - *@deprecated - *@member {string} - Max age of token + * @deprecated + * Max age of token */ maxAge?: string; } @@ -77,28 +78,45 @@ export interface DecodeOptions { complete?: boolean; json?: boolean; } -export type VerifyErrors=JsonWebTokenError | NotBeforeError | TokenExpiredError; -export interface VerifyCallback { - ( - err: VerifyErrors, - decoded: object | string, - ): void; +export type VerifyErrors= JsonWebTokenError | NotBeforeError | TokenExpiredError; +export type VerifyCallback = ( + err: VerifyErrors, + decoded: object | string, +) => void; + +export type SignCallback = ( + err: Error, encoded: string +) => void; + +export interface JwtHeader { + alg: string; + typ?: string; + kid?: string; + jku?: string; + x5u?: string; + x5t?: string; } -export interface SignCallback { - (err: Error, encoded: string): void; -} +export type SigningKeyCallback = ( + err: any, + signingKey?: Secret, +) => void; + +export type GetPublicKeyOrSecret = ( + header: JwtHeader, + callback: SigningKeyCallback +) => void; export type Secret = string | Buffer | { key: string; passphrase: string }; /** * Synchronously sign the given payload into a JSON Web Token string - * @param {String|Object|Buffer} payload - Payload to sign, could be an literal, buffer or string - * @param {String|Buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. - * @param {SignOptions} [options] - Options for the signature - * @returns {String} The JSON Web Token string + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * returns - The JSON Web Token string */ -export declare function sign( +export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, options?: SignOptions, @@ -106,17 +124,17 @@ export declare function sign( /** * Sign the given payload into a JSON Web Token string - * @param {String|Object|Buffer} payload - Payload to sign, could be an literal, buffer or string - * @param {String|Buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. - * @param {SignOptions} [options] - Options for the signature - * @param {Function} callback - Callback to get the encoded token on + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * callback - Callback to get the encoded token on */ -export declare function sign( +export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, callback: SignCallback, ): void; -export declare function sign( +export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, options: SignOptions, @@ -125,16 +143,12 @@ export declare function sign( /** * Synchronously verify given token using a secret or a public key to get a decoded token - * @param {String} token - JWT string to verify - * @param {String|Buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. - * @param {VerifyOptions} [options] - Options for the verification - * @returns The decoded token. + * token - JWT string to verify + * secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * [options] - Options for the verification + * returns - The decoded token. */ -export declare function verify( - token: string, - secretOrPublicKey: string | Buffer, -): object | string; -export declare function verify( +export function verify( token: string, secretOrPublicKey: string | Buffer, options?: VerifyOptions, @@ -142,31 +156,32 @@ export declare function verify( /** * Asynchronously verify given token using a secret or a public key to get a decoded token - * @param {String} token - JWT string to verify - * @param {String|Buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. - * @param {VerifyOptions} [options] - Options for the verification - * @param {Function} callback - Callback to get the decoded token on + * token - JWT string to verify + * secretOrPublicKey - A string or buffer containing either the secret for HMAC algorithms, + * or the PEM encoded public key for RSA and ECDSA. If jwt.verify is called asynchronous, + * secretOrPublicKey can be a function that should fetch the secret or public key + * [options] - Options for the verification + * callback - Callback to get the decoded token on */ -export declare function verify( +export function verify( token: string, - secretOrPublicKey: string | Buffer, + secretOrPublicKey: string | Buffer | GetPublicKeyOrSecret, callback?: VerifyCallback, ): void; -export declare function verify( +export function verify( token: string, - secretOrPublicKey: string | Buffer, + secretOrPublicKey: string | Buffer | GetPublicKeyOrSecret, options?: VerifyOptions, callback?: VerifyCallback, ): void; /** * Returns the decoded payload without verifying if the signature is valid. - * @param {String} token - JWT string to decode - * @param {DecodeOptions} [options] - Options for decoding - * @returns {Object} The decoded Token + * token - JWT string to decode + * [options] - Options for decoding + * returns - The decoded Token */ -export declare function decode( +export function decode( token: string, options?: DecodeOptions, ): null | { [key: string]: any } | string; - diff --git a/types/jsonwebtoken/jsonwebtoken-tests.ts b/types/jsonwebtoken/jsonwebtoken-tests.ts index f20fbba5cc..5884ff6d63 100644 --- a/types/jsonwebtoken/jsonwebtoken-tests.ts +++ b/types/jsonwebtoken/jsonwebtoken-tests.ts @@ -7,10 +7,10 @@ import jwt = require("jsonwebtoken"); import fs = require("fs"); -var token: string; -var cert: Buffer; +let token: string; +let cert: Buffer; -interface ITestObject { +interface TestObject { foo: string; } @@ -44,10 +44,10 @@ const secret = { key: privKey.toString(), passphrase: "keypwd" }; token = jwt.sign(testObject, secret, { algorithm: "RS256" }); // the algorithm option is mandatory in this case // sign asynchronously -jwt.sign(testObject, cert, { algorithm: "RS256" }, function( +jwt.sign(testObject, cert, { algorithm: "RS256" }, ( err: Error, token: string, -) { +) => { console.log(token); }); @@ -56,57 +56,70 @@ jwt.sign(testObject, cert, { algorithm: "RS256" }, function( * https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback */ // verify a token symmetric -jwt.verify(token, "shhhhh", function(err, decoded) { - const result = decoded as ITestObject; +jwt.verify(token, "shhhhh", (err, decoded) => { + const result = decoded as TestObject; console.log(result.foo); // bar }); // use external time for verifying -jwt.verify(token, 'shhhhh', { clockTimestamp: 1 }, function(err, decoded) { - const result = decoded as ITestObject +jwt.verify(token, 'shhhhh', { clockTimestamp: 1 }, (err, decoded) => { + const result = decoded as TestObject; - console.log(result.foo) // bar + console.log(result.foo); // bar }); // invalid token -jwt.verify(token, "wrong-secret", function(err, decoded) { +jwt.verify(token, "wrong-secret", (err, decoded) => { // err // decoded undefined }); // verify a token asymmetric cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, function(err, decoded) { - const result = decoded as ITestObject; +jwt.verify(token, cert, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// verify a token assymetric with async key fetch function +function getKey(header: jwt.JwtHeader, callback: jwt.SigningKeyCallback) { + cert = fs.readFileSync("public.pem"); + + callback(null, cert); +} + +jwt.verify(token, getKey, (err, decoded) => { + const result = decoded as TestObject; console.log(result.foo); // bar }); // verify audience cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { audience: "urn:foo" }, function(err, decoded) { +jwt.verify(token, cert, { audience: "urn:foo" }, (err, decoded) => { // if audience mismatch, err == invalid audience }); // verify issuer cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { audience: "urn:foo", issuer: "urn:issuer" }, function( +jwt.verify(token, cert, { audience: "urn:foo", issuer: "urn:issuer" }, ( err, decoded, -) { +) => { // if issuer mismatch, err == invalid issuer }); // verify algorithm cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { algorithms: ["RS256"] }, function(err, decoded) { +jwt.verify(token, cert, { algorithms: ["RS256"] }, (err, decoded) => { // if algorithm mismatch, err == invalid algorithm }); // verify without expiration check cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { ignoreExpiration: true }, function(err, decoded) { +jwt.verify(token, cert, { ignoreExpiration: true }, (err, decoded) => { // if ignoreExpration == false and token is expired, err == expired token }); @@ -114,7 +127,7 @@ jwt.verify(token, cert, { ignoreExpiration: true }, function(err, decoded) { * jwt.decode * https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken */ -var decoded = jwt.decode(token); +let decoded = jwt.decode(token); decoded = jwt.decode(token, { complete: false }); diff --git a/types/jsonwebtoken/tslint.json b/types/jsonwebtoken/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/jsonwebtoken/tslint.json +++ b/types/jsonwebtoken/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/jspdf/index.d.ts b/types/jspdf/index.d.ts index e393e5fba1..15b9975472 100644 --- a/types/jspdf/index.d.ts +++ b/types/jspdf/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for jsPDF v1.1.135 +// Type definitions for jsPDF 1.2 // Project: https://github.com/MrRio/jsPDF // Definitions by: Amber Schühmacher +// Kevin Gonnord // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'jspdf' { @@ -32,7 +33,9 @@ declare module 'jspdf' { 'scaleFactor':number; 'pageSize': { width:number; + getWidth: () => number; height:number; + getHeight: () => number; }; 'output'(type:any, options:any):any; 'getNumberOfPages'():number; diff --git a/types/jspdf/tslint.json b/types/jspdf/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/jspdf/tslint.json +++ b/types/jspdf/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/just-debounce-it/index.d.ts b/types/just-debounce-it/index.d.ts new file mode 100644 index 0000000000..248f6a27f8 --- /dev/null +++ b/types/just-debounce-it/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for just-debounce-it 1.1 +// Project: https://github.com/angus-c/just#readme +// Definitions by: Aziz Khambati +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +type ArgumentTypes = F extends (...args: infer A) => any ? A : never; + +/*~ This declaration specifies that the function + *~ is the exported object from the file + */ +export = debounce; + +declare function debounce( + fn: T, + wait?: 0, + callFirst?: boolean +): T; + +declare function debounce( + fn: T, + wait: number, + callFirst: true +): T; + +declare function debounce( + fn: T, + wait: number, + callFirst?: false +): (...args: ArgumentTypes) => void; diff --git a/types/just-debounce-it/just-debounce-it-tests.ts b/types/just-debounce-it/just-debounce-it-tests.ts new file mode 100644 index 0000000000..32dd33c9e7 --- /dev/null +++ b/types/just-debounce-it/just-debounce-it-tests.ts @@ -0,0 +1,23 @@ +import debounce = require("just-debounce-it"); + +const doThings = () => 1; + +const num: number = debounce(doThings)(); +const num2: number = debounce(doThings, 0)(); +const num3: number = debounce(doThings, 0, true)(); +const num4: number = debounce(doThings, 0, false)(); +const num5: number = debounce(doThings, 1000, true)(); + +// $ExpectType void +debounce(doThings, 1000)(); + +const exclaim = (a: string) => a + '!'; + +const str: string = debounce(exclaim)('hey'); +const str2: string = debounce(exclaim, 0)('hi'); +const str3: string = debounce(exclaim, 0, true)('hi'); +const str4: string = debounce(exclaim, 0, false)('hi'); +const str5: string = debounce(exclaim, 1000, true)('hooray'); + +// $ExpectType void +debounce(exclaim, 1000)('hello'); diff --git a/types/just-debounce-it/tsconfig.json b/types/just-debounce-it/tsconfig.json new file mode 100644 index 0000000000..d1a7dbd8b0 --- /dev/null +++ b/types/just-debounce-it/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", + "just-debounce-it-tests.ts" + ] +} diff --git a/types/just-debounce-it/tslint.json b/types/just-debounce-it/tslint.json new file mode 100644 index 0000000000..5bc412fb1e --- /dev/null +++ b/types/just-debounce-it/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false + } +} diff --git a/types/karma-jasmine/index.d.ts b/types/karma-jasmine/index.d.ts index ae929c6af3..73ca7a480e 100644 --- a/types/karma-jasmine/index.d.ts +++ b/types/karma-jasmine/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/karma-runner/karma-jasmine // Definitions by: Michel Salib // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/kdbush/index.d.ts b/types/kdbush/index.d.ts index 3ef758b85e..bea0366da0 100644 --- a/types/kdbush/index.d.ts +++ b/types/kdbush/index.d.ts @@ -1,14 +1,27 @@ // Type definitions for kdbush 1.0 // Project: https://github.com/mourner/kdbush // Definitions by: DenisCarriere +// Christian Scott // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped type Points = number[][]; type Get = (point: T) => number; -type ArrayType = typeof Int32Array | typeof Array; +type ArrayType = + typeof Int8Array + | typeof Int16Array + | typeof Int32Array + | typeof Float32Array + | typeof Float64Array + | typeof Array; declare function kdbush(points: Points): kdbush.KDBush; -declare function kdbush(points: T[], getX: Get, getY: Get, nodeSize?: number, ArrayType?: ArrayType): kdbush.KDBush; +declare function kdbush( + points: T[], + getX: Get, + getY: Get, + nodeSize?: number, + ArrayType?: ArrayType +): kdbush.KDBush; declare namespace kdbush { class KDBush { ids: number[]; diff --git a/types/kdbush/kdbush-tests.ts b/types/kdbush/kdbush-tests.ts index e552af4c19..5ee6165fcb 100644 --- a/types/kdbush/kdbush-tests.ts +++ b/types/kdbush/kdbush-tests.ts @@ -1,10 +1,19 @@ -import * as kdbush from 'kdbush'; -import { KDBush } from 'kdbush'; +import * as kdbush from "kdbush"; +import { KDBush } from "kdbush"; // API const points = [[110, 60], [130, 40]]; const index = kdbush(points); +// Specify array constructor +const pick = (index: number) => (point: number[]) => point[index]; +kdbush(points, pick(0), pick(1), 64, Int8Array); +kdbush(points, pick(0), pick(1), 64, Int16Array); +kdbush(points, pick(0), pick(1), 64, Int32Array); +kdbush(points, pick(0), pick(1), 64, Float32Array); +kdbush(points, pick(0), pick(1), 64, Float64Array); +kdbush(points, pick(0), pick(1), 64, Array); + // properties index.nodeSize; index.points; @@ -20,8 +29,8 @@ index.within(10, 10, 5); index.within(10, 10, 5).map(id => points[id]); // custom points (object) -const xy = [{x: 110, y: 60}, {x: 130, y: 40}]; -const index2: KDBush<{x: number, y: number}> = kdbush(xy, p => p.x, p => p.y); +const xy = [{ x: 110, y: 60 }, { x: 130, y: 40 }]; +const index2: KDBush<{ x: number; y: number }> = kdbush(xy, p => p.x, p => p.y); index2.points[0].x; index2.points[0].y; index2.points.map(p => [p.x, p.y]); diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 4d9b1b25f5..5f9f3a7d6c 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Knex.js 0.14 +// Type definitions for Knex.js 0.15 // Project: https://github.com/tgriesser/knex // Definitions by: Qubo // Pablo Rodríguez @@ -14,13 +14,13 @@ import events = require("events"); import stream = require ("stream"); import Bluebird = require("bluebird"); -type Callback = Function; -type Client = Function; -type Value = string | number | boolean | Date | Array | Array | Array | Array | Buffer | Knex.Raw; -type ValueMap = { [key: string]: Value | Knex.QueryBuilder }; +type Callback = (...args: any[]) => void; +type Client = (...args: any[]) => void; +type Value = string | number | boolean | Date | string[] | number[] | Date[] | boolean[] | Buffer | Knex.Raw; +interface ValueMap { [key: string]: Value | Knex.QueryBuilder; } type ColumnName = string | Knex.Raw | Knex.QueryBuilder | {[key: string]: string }; type TableName = string | Knex.Raw | Knex.QueryBuilder; -type Identifier = { [alias: string]: string }; +interface Identifier { [alias: string]: string; } interface Knex extends Knex.QueryInterface { (tableName?: TableName | Identifier): Knex.QueryBuilder; @@ -29,7 +29,7 @@ interface Knex extends Knex.QueryInterface { raw: Knex.RawBuilder; transaction(transactionScope: (trx: Knex.Transaction) => Promise | Bluebird | void): Bluebird; - destroy(callback: Function): void; + destroy(callback: (...args: any[]) => void): void; destroy(): Bluebird; batchInsert(tableName: TableName, data: any[], chunkSize?: number): Knex.QueryBuilder; schema: Knex.SchemaBuilder; @@ -39,7 +39,7 @@ interface Knex extends Knex.QueryInterface { migrate: Knex.Migrator; seed: any; fn: Knex.FunctionHelper; - on(eventName: string, callback: Function): Knex.QueryBuilder; + on(eventName: string, callback: (...args: any[]) => void): Knex.QueryBuilder; } declare function Knex(config: Knex.Config): Knex; @@ -138,18 +138,18 @@ declare namespace Knex { // Aggregation count(...columnNames: string[]): QueryBuilder; - count(columnName: Record | Knex.Raw): QueryBuilder; - countDistinct(columnName: string | Record | Knex.Raw): QueryBuilder; + count(columnName: Record | Raw): QueryBuilder; + countDistinct(columnName: string | Record | Raw): QueryBuilder; min(columnName: string, ...columnNames: string[]): QueryBuilder; - min(columnName: Record | Knex.Raw): QueryBuilder; + min(columnName: Record | Raw): QueryBuilder; max(columnName: string, ...columnNames: string[]): QueryBuilder; - max(columnName: Record | Knex.Raw): QueryBuilder; + max(columnName: Record | Raw): QueryBuilder; sum(columnName: string, ...columnNames: string[]): QueryBuilder; - sum(columnName: Record | Knex.Raw): QueryBuilder; - sumDistinct(columnName: string | Record | Knex.Raw): QueryBuilder; + sum(columnName: Record | Raw): QueryBuilder; + sumDistinct(columnName: string | Record | Raw): QueryBuilder; avg(columnName: string, ...columnNames: string[]): QueryBuilder; - avg(columnName: Record | Knex.Raw): QueryBuilder; - avgDistinct(columnName: string | Record | Knex.Raw): QueryBuilder; + avg(columnName: Record | Raw): QueryBuilder; + avgDistinct(columnName: string | Record | Raw): QueryBuilder; increment(columnName: string, amount?: number): QueryBuilder; decrement(columnName: string, amount?: number): QueryBuilder; @@ -180,11 +180,11 @@ declare namespace Knex { } interface Table { - (tableName: TableName | Identifier): QueryBuilder; - (callback: Function): QueryBuilder; - (raw: Raw): QueryBuilder; + // tslint:disable-next-line ban-types + (tableName: TableName | Identifier | Function | Raw): QueryBuilder; } + // tslint:disable-next-line no-empty-interface interface Distinct extends ColumnNameQueryBuilder { } @@ -258,7 +258,7 @@ declare namespace Knex { interface WithRaw { (alias: string, raw: Raw): QueryBuilder; - (alias: string, sql: string, bindings?: Value[] | Object): QueryBuilder; + (alias: string, sql: string, bindings?: Value[] | object): QueryBuilder; } interface WithSchema { @@ -273,7 +273,7 @@ declare namespace Knex { interface Where extends WhereRaw, WhereWrapped, WhereNull { (raw: Raw): QueryBuilder; (callback: QueryCallback): QueryBuilder; - (object: Object): QueryBuilder; + (object: object): QueryBuilder; (columnName: string, value: Value | null): QueryBuilder; (columnName: string, operator: string, value: Value | QueryBuilder | null): QueryBuilder; (left: Raw, operator: string, right: Value | QueryBuilder | null): QueryBuilder; @@ -318,8 +318,8 @@ declare namespace Knex { interface Union { (callback: QueryCallback | QueryBuilder | Raw, wrap?: boolean): QueryBuilder; - (callbacks: (QueryCallback | QueryBuilder | Raw)[], wrap?: boolean): QueryBuilder; - (...callbacks: (QueryCallback | QueryBuilder | Raw)[]): QueryBuilder; + (callbacks: Array, wrap?: boolean): QueryBuilder; + (...callbacks: Array): QueryBuilder; // (...callbacks: QueryCallback[], wrap?: boolean): QueryInterface; } @@ -339,8 +339,8 @@ declare namespace Knex { } interface RawQueryBuilder { - (sql: string, ...bindings: (Value | QueryBuilder)[]): QueryBuilder; - (sql: string, bindings: (Value | QueryBuilder)[] | ValueMap): QueryBuilder; + (sql: string, ...bindings: Array): QueryBuilder; + (sql: string, bindings: Array | ValueMap): QueryBuilder; (raw: Raw): QueryBuilder; } @@ -352,8 +352,8 @@ declare namespace Knex { interface RawBuilder { (value: Value): Raw; - (sql: string, ...bindings: (Value | QueryBuilder)[]): Raw; - (sql: string, bindings: (Value | QueryBuilder)[] | ValueMap): Raw; + (sql: string, ...bindings: Array): Raw; + (sql: string, bindings: Array | ValueMap): Raw; } // @@ -367,7 +367,7 @@ declare namespace Knex { or: QueryBuilder; and: QueryBuilder; - //TODO: Promise? + // TODO: Promise? columnInfo(column?: string): Bluebird; forUpdate(): QueryBuilder; @@ -375,7 +375,7 @@ declare namespace Knex { toSQL(): Sql; - on(event: string, callback: Function): QueryBuilder; + on(event: string, callback: (...args: any[]) => void): QueryBuilder; } interface Sql { @@ -398,6 +398,7 @@ declare namespace Knex { stream(handler: (readable: stream.PassThrough) => any): Bluebird; stream(options: { [key: string]: any }, handler: (readable: stream.PassThrough) => any): Bluebird; stream(options?: { [key: string]: any }): stream.PassThrough; + // tslint:disable-next-line no-unnecessary-generics pipe(writable: T, options?: { [key: string]: any }): stream.PassThrough; } @@ -444,25 +445,26 @@ declare namespace Knex { timestamp(columnName: string, standard?: boolean): ColumnBuilder; timestamps(useTimestampType?: boolean, makeDefaultNow?: boolean): ColumnBuilder; binary(columnName: string, length?: number): ColumnBuilder; - enum(columnName: string, values: Value[]): ColumnBuilder; - enu(columnName: string, values: Value[]): ColumnBuilder; + enum(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; + enu(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; json(columnName: string): ColumnBuilder; jsonb(columnName: string): ColumnBuilder; uuid(columnName: string): ColumnBuilder; comment(val: string): TableBuilder; specificType(columnName: string, type: string): ColumnBuilder; primary(columnNames: string[]): TableBuilder; - index(columnNames: (string | Raw)[], indexName?: string, indexType?: string): TableBuilder; - unique(columnNames: (string | Raw)[], indexName?: string): TableBuilder; + index(columnNames: Array, indexName?: string, indexType?: string): TableBuilder; + unique(columnNames: Array, indexName?: string): TableBuilder; foreign(column: string, foreignKeyName?: string): ForeignConstraintBuilder; foreign(columns: string[], foreignKeyName?: string): MultikeyForeignConstraintBuilder; dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; - dropUnique(columnNames: (string | Raw)[], indexName?: string): TableBuilder; + dropUnique(columnNames: Array, indexName?: string): TableBuilder; dropPrimary(constraintName?: string): TableBuilder; - dropIndex(columnNames: (string | Raw)[], indexName?: string): TableBuilder; + dropIndex(columnNames: Array, indexName?: string): TableBuilder; dropTimestamps(): ColumnBuilder; } + // tslint:disable-next-line no-empty-interface interface CreateTableBuilder extends TableBuilder { } @@ -472,9 +474,11 @@ declare namespace Knex { collate(val: string): CreateTableBuilder; } + // tslint:disable-next-line no-empty-interface interface AlterTableBuilder extends TableBuilder { } + // tslint:disable-next-line no-empty-interface interface MySqlAlterTableBuilder extends AlterTableBuilder { } @@ -509,6 +513,7 @@ declare namespace Knex { inTable(tableName: string): ColumnBuilder; } + // tslint:disable-next-line no-empty-interface interface AlterColumnBuilder extends ColumnBuilder { } @@ -517,6 +522,11 @@ declare namespace Knex { after(columnName: string): AlterColumnBuilder; } + interface EnumOptions { + useNative: boolean; + enumName: string; + } + // // Configurations // @@ -650,10 +660,10 @@ declare namespace Knex { interface PoolConfig { name?: string; - create?: Function; - afterCreate?: Function; - destroy?: Function; - beforeDestroy?: Function; + create?: (...args: any[]) => void; + afterCreate?: (...args: any[]) => void; + destroy?: (...args: any[]) => void; + beforeDestroy?: (...args: any[]) => void; min?: number; max?: number; refreshIdle?: boolean; @@ -661,7 +671,7 @@ declare namespace Knex { reapIntervalMillis?: number; returnToHead?: boolean; priorityRange?: number; - validate?: Function; + validate?: (...args: any[]) => void; log?: boolean; // generic-pool v3 configs diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 193eea8cf6..1f22e08df0 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -1,14 +1,15 @@ import Knex = require('knex'); +import { WriteStream } from 'fs'; // Initializing the Library -var knex = Knex({ +let knex = Knex({ client: 'sqlite3', connection: { filename: "./mydb.sqlite" } }); -var knex = Knex({ +knex = Knex({ debug: true, client: 'mysql', connection: { @@ -19,7 +20,7 @@ var knex = Knex({ } }); -var knex = Knex({ +knex = Knex({ debug: true, client: 'pg', version: '9.5', @@ -33,7 +34,7 @@ var knex = Knex({ } }); -var knex = Knex({ +knex = Knex({ debug: true, client: 'mssql', connection: { @@ -47,7 +48,7 @@ var knex = Knex({ }); // Mariasql configuration -var knex = Knex({ +knex = Knex({ debug: true, client: 'mariasql', connection: { @@ -59,7 +60,7 @@ var knex = Knex({ }); // Mysql configuration -var knex = Knex({ +knex = Knex({ debug: true, client: 'mysql', connection: { @@ -72,28 +73,24 @@ var knex = Knex({ }); // Pooling -var knex = Knex({ - client: 'mysql', - connection: { - host : '127.0.0.1', - user : 'your_database_user', - password : 'your_database_password', - database : 'myapp_test' - }, - pool: { - min: 0, - max: 7, - afterCreate: (connection: any, callback: Function) => { - return callback(null, connection); +knex = Knex({ + client: "mysql", + connection: { + host: "127.0.0.1", + user: "your_database_user", + password: "your_database_password", + database: "myapp_test" }, - beforeDestroy: (connection: any, callback: Function) => { - return callback(null, connection); + pool: { + min: 0, + max: 7, + afterCreate: (connection: any, callback: (...args: any[]) => void) => callback(null, connection), + beforeDestroy: (connection: any, callback: (...args: any[]) => void) => callback(null, connection) } - } }); // acquireConnectionTimeout -var knex = Knex({ +knex = Knex({ debug: true, client: 'mysql', connection: { @@ -106,41 +103,41 @@ var knex = Knex({ }); // Pure Query Builder without a connection -var knex = Knex({}); +knex = Knex({}); // Pure Query Builder without a connection, using a specific flavour of SQL -var knex = Knex({ +knex = Knex({ client: 'pg' }); // searchPath -var knex = Knex({ +knex = Knex({ client: 'pg', searchPath: 'public', }); -var knex = Knex({ +knex = Knex({ client: 'pg', searchPath: ['public', 'private'], }); // postProcessResponse -var knex = Knex({ +knex = Knex({ client: 'pg', - postProcessResponse: function(result, queryContext){ + postProcessResponse(result, queryContext) { return result; } }); // wrapIdentifier -var knex = Knex({ +knex = Knex({ client: 'pg', - wrapIdentifier: function(value, origImpl, queryContext){ + wrapIdentifier(value, origImpl, queryContext) { return origImpl(value + 'foo'); } }); // useNullAsDefault -var knex = Knex({ +knex = Knex({ client: 'sqlite', useNullAsDefault: true, }); @@ -148,14 +145,14 @@ var knex = Knex({ // Using custom client class TestClient extends Knex.Client {} -var knex = Knex({ +knex = Knex({ client: TestClient, }); knex('books').insert({title: 'Test'}).returning('*').toString(); // Migrations -var knex = Knex({ +knex = Knex({ client: 'mysql', connection: { host : '127.0.0.1', @@ -176,7 +173,7 @@ knex.select('title', 'author', 'year').from('books'); knex.select({ name: 'title', writer: 'author' }).from(knex.raw('books')); knex.select().table('books'); -knex.avg('sum_column1').from(function() { +knex.avg('sum_column1').from(() => { this.sum('column1 as sum_column1').from('t1').groupBy('column1').as('t1'); }).as('ignored_alias'); @@ -208,20 +205,20 @@ knex('users').where(knex.raw('votes + 1'), '>', 101); knex('users').where(knex.raw('votes + 1'), '>', knex.raw('100 + 1')); knex('users').where('votes', '>', knex.raw('100 + 1')); -var subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); +let subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); knex('accounts').where('id', 'in', subquery); knex.select('name').from('users') .whereIn('id', [1, 2, 3]) .orWhereIn('id', [4, 5, 6]); -var subquery = knex.select('id').from('accounts'); +subquery = knex.select('id').from('accounts'); knex.select('name').from('users') .whereIn('account_id', subquery); knex('users') .where('name', '=', 'John') - .orWhere(function() { + .orWhere(() => { this.where('votes', '>', 100).andWhere('title', '<>', 'Admin'); }); @@ -233,13 +230,13 @@ knex('users').whereNull('updated_at'); knex('users').whereNotNull('created_at'); -knex('users').whereExists(function() { +knex('users').whereExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); knex('users').whereExists(knex.select('*').from('accounts').whereRaw('users.account_id = accounts.id')); -knex('users').whereNotExists(function() { +knex('users').whereNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); @@ -324,15 +321,15 @@ knex('users') .join(knex('contacts').select('user_id', 'phone').as('contacts'), { 'users.id': 'contacts.user_id' }) .select('users.id', 'contacts.phone'); -knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), function() { +knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); -knex.select('*').from('users').join('accounts', function() { +knex.select('*').from('users').join('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); -knex.select('*').from('users').join('accounts', function(join: Knex.JoinClause) { +knex.select('*').from('users').join('accounts', (join: Knex.JoinClause) => { if (this !== join) { throw new Error("join() callback call semantics wrong"); } @@ -344,116 +341,116 @@ knex.select('*').from('user').join('contacts', () => { this.on('users.id', '=', knex.raw(7)); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNotIn('contacts.id', [7, 15, 23, 41]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNotNull('contacts.email'); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').onExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').andOnExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').orOnExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').onNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').andOnNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').orOnNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').onNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').andOnNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { +knex.select('*').from('users').join('contacts', () => { this.on('users.id', '=', 'contacts.id').orOnNotBetween('contacts.id', [5, 30]); }); -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { +knex.select('*').from('users').join('contacts', () => { + this.on('users.id', '=', 'contacts.id').onNotExists(() => { this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); }); }); @@ -478,7 +475,7 @@ knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); -knex('users').innerJoin('accounts', function() { +knex('users').innerJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -488,7 +485,7 @@ knex('users').innerJoin('accounts', (join: Knex.JoinClause) => { knex.select('*').from('users').leftJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').leftJoin('accounts', function() { +knex.select('*').from('users').leftJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -505,13 +502,13 @@ knex.select('*').from('users').leftJoin('accounts', (join) => { knex.select('*').from('users').leftOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').leftOuterJoin('accounts', function() { +knex.select('*').from('users').leftOuterJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); knex.select('*').from('users').rightJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').rightJoin('accounts', function() { +knex.select('*').from('users').rightJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -521,13 +518,13 @@ knex.select('*').from('users').rightJoin('accounts', (join: Knex.JoinClause) => knex.select('*').from('users').rightOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').rightOuterJoin('accounts', function() { +knex.select('*').from('users').rightOuterJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); knex.select('*').from('users').outerJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').outerJoin('accounts', function() { +knex.select('*').from('users').outerJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -537,7 +534,7 @@ knex.select('*').from('users').outerJoin('accounts', (join: Knex.JoinClause) => knex.select('*').from('users').fullOuterJoin('accounts', 'users.id', 'accounts.user_id'); -knex.select('*').from('users').fullOuterJoin('accounts', function() { +knex.select('*').from('users').fullOuterJoin('accounts', () => { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); }); @@ -552,43 +549,42 @@ knex.select('*').from('accounts').joinRaw('natural full join table1').where('id' knex.select('*').from('accounts').join(knex.raw('natural full join table1')).where('id', 1); knex.select('*').from('accounts') - .join(function() { + .join(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .leftJoin(function() { + .leftJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .leftOuterJoin(function() { + .leftOuterJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .rightJoin(function() { + .rightJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .rightOuterJoin(function() { + .rightOuterJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .innerJoin(function() { + .innerJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .crossJoin(function() { + .crossJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .fullOuterJoin(function() { + .fullOuterJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); knex.select('*').from('accounts') - .outerJoin(function() { + .outerJoin(() => { this.select('*').from('accounts').as('special_accounts'); }, 'special_accounts.a', '=', 'accounts.b'); - knex('customers') .distinct('first_name', 'last_name') .select(); @@ -635,7 +631,7 @@ knex('accounts').where('activated', false).delete(); knex('accounts').where('activated', false).delete('id'); knex('accounts').where('activated', false).delete(['id', 'title']); -knex.with('old_books', function(qb) { +knex.with('old_books', (qb) => { qb.select('*').from('books').where('published_date', '<', 1970); }).select('*').from('old_books'); @@ -657,30 +653,30 @@ knex.withRaw('recent_books', 'select * from books where published_date >= :year' knex.withRaw('recent_books', knex.raw('select * from books where published_date >= ?', [2013])) .select('*').from('recent_books'); -knex.withWrapped("antique_books", function (qb) { +knex.withWrapped("antique_books", (qb) => { qb.select('*').from('books').where('published_date', '<', 1899); }).select('*').from('antique_books'); knex.withWrapped('new_books', knex.select('*').from('books').where("published_date", ">=", 2016)) .select('*').from('new_books'); -var someExternalMethod: Function; +const someExternalMethod: (...args: any[]) => void = () => {}; -knex.transaction(function(trx) { +knex.transaction((trx) => { knex('books').transacting(trx).insert({name: 'Old Books'}) - .then(function(resp) { - var id = resp[0]; - return someExternalMethod(id, trx); + .then((resp) => { + const id = resp[0]; + someExternalMethod(id, trx); }) .then(trx.commit) .catch(trx.rollback); -}).then(function() { +}).then(() => { console.log('Transaction complete.'); -}).catch(function(err) { +}).catch((err) => { console.error(err); }); -knex.transaction(function(trx) { +knex.transaction((trx) => { knex('tableName') .transacting(trx) .forUpdate() @@ -692,11 +688,13 @@ knex.transaction(function(trx) { .select('*'); }); -const transactionReturnValue = knex.transaction(function(trx) { +const transactionReturnValue = knex.transaction((trx) => { return knex("table") .insert({ foo: "bar" }) .returning(["id"]) - .then(function(result) { return result[0].id as number; }); + .then((result) => { + return result[0].id as number; + }); }); // Tests that the transaction has kept the type of its return value by referencing a method of number @@ -728,31 +726,30 @@ knex('accounts').where('userid', '=', 1).decrement('balance', 5); knex('accounts').truncate(); -knex.table('users').first('id').then(function(ids) { +knex.table('users').first('id').then((ids) => { console.log(ids); }); -knex.table('users').first('id', 'name').then(function(row) { +knex.table('users').first('id', 'name').then((row) => { console.log(row); }); -knex.table('users').first(knex.raw('round(sum(products)) as p')).then(function(row) { +knex.table('users').first(knex.raw('round(sum(products)) as p')).then((row) => { console.log(row); }); -knex.table('users').select('*').clearSelect().select('id').then(function(rows) { +knex.table('users').select('*').clearSelect().select('id').then((rows) => { console.log(rows); }); -knex('accounts').where('userid', '=', 1).clearWhere().select().then(function (rows) { +knex('accounts').where('userid', '=', 1).clearWhere().select().then((rows) => { console.log(rows); }); // Using trx as a query builder: -knex.transaction(function(trx) { - - var info: any; - var books: any[] = [ +knex.transaction((trx) => { + const info: any = {}; + const books: any[] = [ {title: 'Canterbury Tales'}, {title: 'Moby Dick'}, {title: 'Hamlet'} @@ -761,42 +758,41 @@ knex.transaction(function(trx) { return trx .insert({name: 'Old Books'}, 'id') .into('catalogues') - .then(function(ids) { - return Promise.all(books.map(function (book: any) { + .then((ids) => { + return Promise.all(books.map((book: any) => { book.catalogue_id = ids[0]; // Some validation could take place here. return trx.insert(info).into('books'); })); }); }) -.then(function(inserts) { +.then((inserts) => { console.log(inserts.length + ' new books saved.'); }) -.catch(function(error) { +.catch((error) => { // If we get here, that means that neither the 'Old Books' catalogues insert, // nor any of the books inserts will have taken place. console.error(error); }); // Using trx as a transaction object: -knex.transaction<{ length: number }>(function(trx) { - +knex.transaction<{ length: number }>((trx) => { trx.raw(''); - trx.on('query-error', function(error: Error) { + trx.on('query-error', (error: Error) => { console.error(error); }); - trx.savepoint(function(nestedTrx) { + trx.savepoint((nestedTrx) => { nestedTrx.rollback(new Error('something went terribly wrong')); }); - trx.transaction(function(nestedTrx) { + trx.transaction((nestedTrx) => { nestedTrx.commit(); }); - var info: any; - var books: any[] = [ + const info: any = {}; + const books: any[] = [ {title: 'Canterbury Tales'}, {title: 'Moby Dick'}, {title: 'Hamlet'} @@ -805,8 +801,8 @@ knex.transaction<{ length: number }>(function(trx) { knex.insert({name: 'Old Books'}, 'id') .into('catalogues') .transacting(trx) - .then(function(ids) { - return Promise.all(books.map(function(book: any) { + .then((ids) => { + return Promise.all(books.map((book: any) => { book.catalogue_id = ids[0]; // Some validation could take place here. @@ -817,10 +813,10 @@ knex.transaction<{ length: number }>(function(trx) { .then(trx.commit) .catch(trx.rollback); }) -.then(function(inserts) { +.then((inserts) => { console.log(inserts.length + ' new books saved.'); }) -.catch(function(error) { +.catch((error) => { // If we get here, that means that neither the 'Old Books' catalogues insert, // nor any of the books inserts will have taken place. console.error(error); @@ -831,7 +827,7 @@ knex.insert({ name: 'Old Books'}).transacting(undefined); knex.schema.withSchema("public").hasTable("table"); // $ExpectType Bluebird -knex.schema.createTable('users', function (table) { +knex.schema.createTable('users', (table) => { table.increments(); table.string('name'); table.enu('favorite_color', ['red', 'blue', 'green']); @@ -840,7 +836,7 @@ knex.schema.createTable('users', function (table) { table.timestamps(true, true); }); -knex.schema.alterTable('users', function (table) { +knex.schema.alterTable('users', (table) => { table.string('role').nullable(); }); @@ -848,9 +844,9 @@ knex.schema.renameTable('users', 'old_users'); knex.schema.dropTable('users'); -knex.schema.hasTable('users').then(function(exists) { +knex.schema.hasTable('users').then((exists) => { if (!exists) { - return knex.schema.createTable('users', function(t) { + return knex.schema.createTable('users', (t) => { t.increments('id').primary(); t.string('first_name', 100); t.string('last_name', 100); @@ -859,20 +855,20 @@ knex.schema.hasTable('users').then(function(exists) { } }); -var tableName: string; -var columnName: string; +const tableName = ''; +const columnName = ''; knex.schema.hasColumn(tableName, columnName); knex.schema.dropTableIfExists('users'); -knex.schema.table('users', function (table) { +knex.schema.table('users', (table) => { table.dropColumn('name'); table.string('first_name'); table.string('last_name'); }); knex.schema.raw("SET sql_mode='TRADITIONAL'") -.table('users', function (table) { +.table('users', (table) => { table.dropColumn('name'); table.string('first_name'); table.string('last_name'); @@ -888,12 +884,12 @@ knex('users') .orWhere(knex.raw('status <> ?', [1])) .groupBy('status'); -knex.raw('select * from users where id = ?', [1]).then(function(resp) { +knex.raw('select * from users where id = ?', [1]).then((resp) => { // ... }); (() => { - var subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no') + const subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no') .wrap('(', ') avg_sal_dept'); knex.select('e.lastname', 'e.salary', subcolumn) @@ -902,7 +898,7 @@ knex.raw('select * from users where id = ?', [1]).then(function(resp) { })(); (() => { - var subcolumn = knex.avg('salary') + const subcolumn = knex.avg('salary') .from('employee') .whereRaw('dept_no = e.dept_no') .as('avg_sal_dept'); @@ -912,70 +908,70 @@ knex.raw('select * from users where id = ?', [1]).then(function(resp) { .whereRaw('dept_no = e.dept_no'); })(); -var x: number; +const x = 1; knex.select('name').from('users') .where('id', '>', 20) .andWhere('id', '<', 200) .limit(10) .offset(x) - .then(function(rows) { + .then((rows) => { return rows.map((r: any) => r.name); }) - .then(function(names: any) { + .then((names: any) => { return knex.select('id').from('nicknames').whereIn('nickname', names); }) - .then(function(rows) { + .then((rows) => { console.log(rows); }) - .catch(function(error) { + .catch((error) => { console.error(error); }); knex.select('*').from('users').where({name: 'Tim'}) - .then(function(rows) { + .then((rows) => { return knex.insert({user_id: rows[0].id, name: 'Test'}, 'id').into('accounts'); - }).then(function(id) { + }).then((id) => { console.log('Inserted Account ' + id); - }).catch(function(error) { + }).catch((error) => { console.error(error); }); knex.insert({id: 1, name: 'Test'}, 'id').into('accounts') - .catch(function(error) { + .catch((error) => { console.error(error); - }).then(function() { + }).then(() => { return knex.select('*').from('accounts').where('id', 1); - }).then(function(rows) { + }).then((rows) => { console.log(rows[0]); - }).catch(function(error) { + }).catch((error) => { console.error(error); }); -var query: any; -query.then(function(x: any) { +const query: any = () => {}; +query.then((x: any) => { // doSideEffectsHere(x); return x; }); -knex.select('name').from('users').limit(10).then(function (rows: any[]): string[] { - return rows.map(function (row: any): string { +knex.select('name').from('users').limit(10).then((rows: any[]): string[] => { + return rows.map((row: any): string => { return row.name; }); -}).then(function(names: string[]) { +}).then((names: string[]) => { console.log(names); -}).catch(function(e: Error) { +}).catch((e: Error) => { console.error(e); }); -knex.select('name').from('users').limit(10).then(function (rows: any[]) { - return rows.reduce(function(memo: any, row: any) { +knex.select('name').from('users').limit(10).then((rows: any[]) => { + return rows.reduce((memo: any, row: any) => { memo.names.push(row.name); memo.count++; return memo; }, {count: 0, names: []}); -}).then(function(obj: any) { +}).then((obj: any) => { console.log(obj); -}).catch(function(e: Error) { +}).catch((e: Error) => { console.error(e); }); @@ -984,10 +980,10 @@ knex.select('name').from('users') .then(console.log.bind(console)) .catch(console.error.bind(console)); -var values: any[]; +const values: any[] = []; knex.insert(values).into('users') - .then(function() { + .then(() => { return {inserted: true}; }); @@ -998,36 +994,40 @@ knex.select('name').from('users') .offset(x); // Retrieve the stream: -var stream = knex.select('*').from('users').stream(); -var writableStream: NodeJS.WritableStream; +let stream = knex.select('*').from('users').stream(); +const writableStream: NodeJS.WritableStream = new WriteStream(); stream.pipe(writableStream); // With options: -var stream = knex.select('*').from('users').stream({highWaterMark: 5}); +stream = knex.select('*').from('users').stream({highWaterMark: 5}); stream.pipe(writableStream); // Use as a promise: (() => { - -var stream = knex.select('*').from('users').where(knex.raw('id = ?', [1])).stream(function(stream: any) { - stream.pipe(writableStream); -}).then(function() { - // ... -}).catch(function(e: Error) { - console.error(e); -}); - + knex + .select("*") + .from("users") + .where(knex.raw("id = ?", [1])) + .stream((stream: any) => { + stream.pipe(writableStream); + }) + .then(() => { + // ... + }) + .catch((e: Error) => { + console.error(e); + }); })(); -var stream = knex.select('*').from('users').pipe(writableStream); -var app: any; +stream = knex.select('*').from('users').pipe(writableStream); +const app: any = () => {}; knex.select('*') .from('users') - .on('query', function(data: any) { + .on('query', (data: any) => { app.log(data); }) - .then(function() { + .then(() => { // ... }); @@ -1040,66 +1040,66 @@ knex.select('*').from('users').where(knex.raw('id = ?', [1])).toSQL(); // knex('users') .select('*') - .join('contacts', function(builder) { - this.on(function(builder) { + .join('contacts', (builder) => { + this.on((builder: any) => { let self: Knex.JoinClause = this; self = builder; - }).andOn(function(builder) { + }).andOn((builder: any) => { let self: Knex.JoinClause = this; self = builder; - }).orOn(function(builder) { + }).orOn((builder: any) => { let self: Knex.JoinClause = this; self = builder; - }).onExists(function(builder) { + }).onExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).orOnExists(function(builder) { + }).orOnExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).andOnExists(function(builder) { + }).andOnExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).onNotExists(function(builder) { + }).onNotExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).andOnNotExists(function(builder) { + }).andOnNotExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; - }).orOnNotExists(function(builder) { + }).orOnNotExists((builder: any) => { let self: Knex.QueryBuilder = this; self = builder; }); - }).where(function(builder) { + }).where((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).orWhere(function(builder) { + }).orWhere((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).andWhere(function(builder) { + }).andWhere((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).whereIn('column', function(builder) { + }).whereIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).orWhereIn('column', function(builder) { + }).orWhereIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).whereNotIn('column', function(builder) { + }).whereNotIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).orWhereNotIn('column', function(builder) { + }).orWhereNotIn('column', (builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).whereWrapped(function(builder) { + }).whereWrapped((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).union(function(builder) { + }).union((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).unionAll(function(builder) { + }).unionAll((builder) => { let self: Knex.QueryBuilder = this; self = builder; - }).modify(function(builder, aBool) { + }).modify((builder, aBool) => { let self: Knex.QueryBuilder = this; self = builder; }, true); @@ -1107,7 +1107,7 @@ knex('users') // // Migrations // -var config = { +const config = { directory: "./migrations", extension: "js", tableName: "knex_migrations", @@ -1131,7 +1131,6 @@ knex.seed.make(name); knex.seed.run(config); knex.seed.run(); - knex.schema .dropTableIfExists('A') .createTable('A', table => { @@ -1142,21 +1141,20 @@ knex.schema table.timestamp('T', false).notNullable(); }); - -//creating table in MySQL with binary primary key with known field length -knex.schema.createTable('testTable', function (table) { - table.binary('binaryKey', 16).primary(); //will make table with binaryKey type BINARY(16) +// creating table in MySQL with binary primary key with known field length +knex.schema.createTable('testTable', (table) => { + table.binary('binaryKey', 16).primary(); // will make table with binaryKey type BINARY(16) }); // allow creating decimal column that can store that can store numbers of any // precision and scale. (Only supported for Oracle, SQLite, Postgres) -var knex = Knex({ +knex = Knex({ client: 'pg' }); knex.schema .dropTableIfExists('testTable') - .createTable('testTable', function (table) { + .createTable('testTable', (table) => { table.decimal('dec', null); }) .dropTable('testTable'); @@ -1165,10 +1163,10 @@ knex.schema knex.schema .dropTableIfExists('foo') .dropTableIfExists('bar') - .createTable('foo', function (table) { + .createTable('foo', (table) => { table.uuid('id').primary(); }) - .createTable('bar', function (table) { + .createTable('bar', (table) => { table.uuid('id').primary(); }); @@ -1194,12 +1192,12 @@ knex('characters') knex('characters') .select() - .whereIn('name', function() { + .whereIn('name', () => { this.select('name').from('characters'); }); knex('characters') .select() - .whereIn(['name', 'class'], function() { + .whereIn(['name', 'class'], () => { this.select('name', 'class').from('characters'); }); diff --git a/types/knex/tslint.json b/types/knex/tslint.json index d84fe24e60..604d5950cf 100644 --- a/types/knex/tslint.json +++ b/types/knex/tslint.json @@ -1,76 +1,7 @@ { "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": 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, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "unified-signatures": false + "unified-signatures": false, + "callable-types": false } } diff --git a/types/koa-qs/index.d.ts b/types/koa-qs/index.d.ts new file mode 100644 index 0000000000..e69c131408 --- /dev/null +++ b/types/koa-qs/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for koa-qs 2.0 +// Project: https://github.com/koajs/qs#readme +// Definitions by: Rémy Jeancolas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as koa from 'koa'; + +declare namespace koaQs { + type ParseMode = 'extended'|'strict'|'first'; +} + +declare function koaQs(app: koa, mode?: koaQs.ParseMode): koa; + +export = koaQs; diff --git a/types/koa-qs/koa-qs-tests.ts b/types/koa-qs/koa-qs-tests.ts new file mode 100644 index 0000000000..c0063b757b --- /dev/null +++ b/types/koa-qs/koa-qs-tests.ts @@ -0,0 +1,6 @@ +import koaQs = require('koa-qs'); +import Koa = require('koa'); + +const app = koaQs(new Koa()); + +app.listen(80); diff --git a/types/fast-diff/tsconfig.json b/types/koa-qs/tsconfig.json similarity index 93% rename from types/fast-diff/tsconfig.json rename to types/koa-qs/tsconfig.json index 0c6f0c4ae2..b5a52f4ccd 100644 --- a/types/fast-diff/tsconfig.json +++ b/types/koa-qs/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "fast-diff-tests.ts" + "koa-qs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/koa-qs/tslint.json b/types/koa-qs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-qs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index b5dc934965..6763f8d7b8 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -4,6 +4,7 @@ // Pavel Ivanov // JounQin // Romain Faust +// Guillaume Mayer // Definitions: https://github.com/hellopao/DefinitelyTyped // TypeScript Version: 2.3 @@ -86,6 +87,10 @@ declare namespace Router { sensitive?: boolean; strict?: boolean; } + + export interface IUrlOptionsQuery { + query: object | string; + } export class ParamName { asterisk: boolean; @@ -258,9 +263,24 @@ declare class Router { /** * Generate URL for route. Takes either map of named `params` or series of * arguments (for regular expression routes) + * + * router = new Router(); + * router.get('user', "/users/:id", ... + * + * router.url('user', { id: 3 }); + * // => "/users/3" + * + * Query can be generated from third argument: + * + * router.url('user', { id: 3 }, { query: { limit: 1 } }); + * // => "/users/3?limit=1" + * + * router.url('user', { id: 3 }, { query: "limit=1" }); + * // => "/users/3?limit=1" + * */ - url(name: string, params: Object): string; - url(name: string, params: Object): Error; + url(name: string, params: any, options?: Router.IUrlOptionsQuery): string; + url(name: string, params: any, options?: Router.IUrlOptionsQuery): Error; /** * Match given `path` and return corresponding routes. diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index b2bec9ad0c..b5a4083146 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -14,11 +14,21 @@ router .get('/', function (ctx, next) { ctx.body = 'Hello World!'; }) - .get('/users/:id', function (ctx, next) { - ctx.body = ctx.router.url('user-accounts', { id: ctx.params.id }) + .get('user', '/users/:id', function (ctx, next) { + ctx.body = { + test1: ctx.router.url('user-accounts', { id: ctx.params.id }), + test2: ctx.router.url('user-accounts', ctx.params.id), + test3: ctx.router.url('user-accounts', [ctx.params.id]), + } }) .get('user-accounts', '/users/:id/accounts', function (ctx, next) { - // ... + ctx.body = { + test1: ctx.router.url('user', { id: 3 }, { query: { limit: 1 } }), + test2: ctx.router.url('user', { id: 3 }, { query: "limit=1" }), + test3: ctx.router.url('user', 3, { query: { limit: 1 } }), + test4: ctx.router.url('user', [3], { query: "limit=1" }), + test5: ctx.router.url('user', ["3"], { query: { limit: "1" } }), + } }) .post('/users', function (ctx, next) { // ... diff --git a/types/leaflet-providers/index.d.ts b/types/leaflet-providers/index.d.ts index bc9a4576de..c92eeea96f 100644 --- a/types/leaflet-providers/index.d.ts +++ b/types/leaflet-providers/index.d.ts @@ -9,7 +9,7 @@ import * as L from 'leaflet'; declare module 'leaflet' { namespace TileLayer { class Provider extends TileLayer { - constructor(provider: string, options?: TileLayerOptions) + constructor(provider: string, options?: TileLayerOptions & { [name: string]: string; }) } namespace Provider { @@ -28,6 +28,6 @@ declare module 'leaflet' { } namespace tileLayer { - function provider(provider: string, options?: TileLayerOptions): TileLayer.Provider; + function provider(provider: string, options?: TileLayerOptions & { [name: string]: string; }): TileLayer.Provider; } } diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 8402d8bc9b..8177ba1aa6 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -494,7 +494,11 @@ export interface TileLayerOptions extends GridLayerOptions { zoomReverse?: boolean; detectRetina?: boolean; crossOrigin?: boolean; - [name: string]: any; + // [name: string]: any; + // You are able add additional properties, but it makes this interface unchackable. + // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/15313 + // Example: + // tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}&{bar}&{abc}', {foo: 'bar', bar: (data: any) => 'foo', abc: () => ''}); } export class TileLayer extends GridLayer { @@ -817,7 +821,7 @@ export interface GeoJSONOptions

extends LayerOptions { pointToLayer?(geoJsonPoint: geojson.Feature, latlng: LatLng): Layer; // should import GeoJSON typings /** - * A Function defining the Path options for styling GeoJSON lines and polygons, + * PathOptions or a Function defining the Path options for styling GeoJSON lines and polygons, * called internally when data is added. * * The default value is to not override any defaults: @@ -828,7 +832,7 @@ export interface GeoJSONOptions

extends LayerOptions { * } * ``` */ - style?: StyleFunction

; + style?: PathOptions | StyleFunction

; /** * A Function that will be called once for each created Feature, after it @@ -919,6 +923,12 @@ export class GeoJSON

extends FeatureGroup

{ */ resetStyle(layer: Layer): Layer; + /** + * Same as FeatureGroup's setStyle method, but style-functions are also + * allowed here to set the style according to the feature. + */ + setStyle(style: PathOptions | StyleFunction

): this; + options: GeoJSONOptions

; } diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index d1375fa83f..6debf6b0d6 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -227,9 +227,6 @@ tileLayerOptions = { pane: '', className: '', keepBuffer: 1, - foo: 'bar', - bar: () => 'foo', - abc: (data: any) => 'foobar' }; tileLayerOptions.subdomains = 'a'; @@ -245,11 +242,9 @@ tileLayerOptions.bounds = latLngBoundsLiteral; let tileLayer: L.TileLayer; tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png'); tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', tileLayerOptions); -tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}&{bar}&{abc}', {foo: 'bar', bar: (data: any) => 'foo', abc: () => ''}); tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png'); tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', tileLayerOptions); -tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}&{bar}&{abc}', {foo: 'bar', bar: (data: any) => 'foo', abc: () => ''}); // imageOverlay let imageOverlayOptions: L.ImageOverlayOptions; @@ -414,6 +409,14 @@ let nestedTwoCoords = [ [12, 13], [13, 14], [14, 15] ]; const nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); nestedTwoCoords = L.GeoJSON.latLngsToCoords(nestedLatLngs, 1); +const geojson = new L.GeoJSON(); +const style: L.PathOptions = { + className: "string", +}; +const styler: L.StyleFunction = () => style; +geojson.setStyle(style); +geojson.setStyle(styler); + class MyMarker extends L.Marker { constructor() { super([12, 13]); diff --git a/types/lingui__core/i18n.d.ts b/types/lingui__core/i18n.d.ts index 49f663a6a8..a74ae7a7a0 100644 --- a/types/lingui__core/i18n.d.ts +++ b/types/lingui__core/i18n.d.ts @@ -27,6 +27,8 @@ export interface setupI18nProps { language?: string; catalogs?: Catalogs; development?: object; + locales?: string[]; + missing?: string | ((language: string, id: string) => string); } export class I18n { diff --git a/types/lingui__core/index.d.ts b/types/lingui__core/index.d.ts index e70f62f969..9628f85634 100644 --- a/types/lingui__core/index.d.ts +++ b/types/lingui__core/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @lingui/core 2.1 +// Type definitions for @lingui/core 2.2 // Project: https://lingui.github.io/js-lingui/ // Definitions by: Jeow Li Huan // Definitions: https://github.com/huan086/lingui-typings diff --git a/types/lingui__core/lingui__core-tests.ts b/types/lingui__core/lingui__core-tests.ts index 799bc5812b..09af3e1e4f 100644 --- a/types/lingui__core/lingui__core-tests.ts +++ b/types/lingui__core/lingui__core-tests.ts @@ -80,8 +80,17 @@ const catalog: Catalog = { } } }; + +function missingFn(language: string, id: string) { + return id; +} + const catalogs: Catalogs = { es: catalog }; const setupResult: I18n = setupI18n({ catalogs, language: 'es' }); +const setupResultLocales: I18n = setupI18n({ locales: ['en-UK', 'ar-AS'] }); +const setupResultMissingText: I18n = setupI18n({ missing: 'missing' }); +const setupResultMissingFn: I18n = setupI18n({ missing: missingFn }); +const setupResultCombined: I18n = setupI18n({ catalogs, language: 'de', locales: ['en-UK', 'ar-AS'], missing: missingFn }); const formattedDate: string = date('en', { timeZone: 'UTC' })(new Date()); const formattedNumber: string = number('en', { style: 'currency', currency: 'EUR' })(1234.56); diff --git a/types/lodash/common/common.d.ts b/types/lodash/common/common.d.ts index 864450b1bd..66dbafafb8 100644 --- a/types/lodash/common/common.d.ts +++ b/types/lodash/common/common.d.ts @@ -127,21 +127,21 @@ declare module "../index" { * @param key The key of the value to remove. * @return Returns `true` if the entry was removed successfully, else `false`. */ - delete(key: string): boolean; + delete(key: any): boolean; /** * Gets the cached value for `key`. * @param key The key of the value to get. * @return Returns the cached value. */ - get(key: string): any; + get(key: any): any; /** * Checks if a cached value for `key` exists. * @param key The key of the entry to check. * @return Returns `true` if an entry for `key` exists, else `false`. */ - has(key: string): boolean; + has(key: any): boolean; /** * Sets `value` to `key` of the cache. @@ -149,12 +149,12 @@ declare module "../index" { * @param value The value to cache. * @return Returns the cache object. */ - set(key: string, value: any): Dictionary; + set(key: any, value: any): this; /** * Removes all key-value entries from the map. */ - clear(): void; + clear?: () => void; } interface MapCacheConstructor { new (): MapCache; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 0515136714..4f7f229fe6 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -3467,7 +3467,7 @@ fp.now(); // $ExpectType number delete(key: string) { return true; }, get(key: string): any { return 1; }, has(key: string) { return true; }, - set(key: string, value: any): _.Dictionary { return {}; }, + set(key: string, value: any): _.MapCache { return this; }, clear() { }, }; @@ -3484,6 +3484,11 @@ fp.now(); // $ExpectType number // $ExpectType MapCache new _.memoize.Cache(); + _.memoize.Cache = WeakMap; + _.memoize.Cache = Map; + const memoizedFn = _.memoize(memoizeFn); + memoizedFn.cache = new WeakMap(); + memoizedFn.cache = new Map(); } // _.overArgs diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 7253dc1ce6..8d5b17d697 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Colby DeHart // Hyeonseok Yang // Jonathan Siebern +// Matt R. Wilson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -22,6 +23,11 @@ declare module 'luxon' { round?: boolean; }; + type ToSQLOptions = { + includeOffset?: boolean; + includeZone?: boolean; + }; + type ISOTimeOptions = { suppressMilliseconds?: boolean; suppressSeconds?: boolean; @@ -65,6 +71,17 @@ declare module 'luxon' { conversionAccuracy?: string; }; + type ExplainedFormat = { + input: string; + tokens: Array<{ literal: boolean, val: string }>, + regex?: RegExp; + rawMatches?: RegExpMatchArray | null; + matches?: {[k: string]: any}; + result?: {[k: string]: any} | null; + zone?: Zone | null; + invalidReason?: string; + }; + class DateTime { static readonly DATETIME_FULL: DateTimeFormatOptions; static readonly DATETIME_FULL_WITH_SECONDS: DateTimeFormatOptions; @@ -108,7 +125,7 @@ declare module 'luxon' { text: string, format: string, opts?: DateTimeOptions - ): object; + ): ExplainedFormat; /** * @deprecated since 0.3.0. Use fromFormat instead */ @@ -124,7 +141,7 @@ declare module 'luxon' { text: string, format: string, options?: DateTimeOptions - ): object; + ): ExplainedFormat; static invalid(reason: any): DateTime; static local( year?: number, @@ -213,9 +230,9 @@ declare module 'luxon' { toMillis(): number; toObject(options?: { includeConfig?: boolean }): DateObject; toRFC2822(): string; - toSQL(options?: Object): string; + toSQL(options?: ToSQLOptions): string; toSQLDate(): string; - toSQLTime(options?: Object): string; + toSQLTime(options?: ToSQLOptions): string; toString(): string; toUTC(offset?: number, options?: ZoneOptions): DateTime; until(other: DateTime): Interval; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index b7d426a2c2..587210815c 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -39,6 +39,11 @@ dt.toLocaleString(); dt.toLocaleString(DateTime.DATE_MED); dt.toISO(); dt.toISO({includeOffset: true}); +dt.toSQL(); +dt.toSQL({includeOffset: false, includeZone: true}); +dt.toSQLDate(); +dt.toSQLTime(); +dt.toSQLTime({includeOffset: false, includeZone: true}); dt.plus({ hours: 3, minutes: 2 }); dt.minus({ days: 7 }); @@ -62,6 +67,8 @@ DateTime.utc().toLocal(); DateTime.fromMillis(1527780819458).toMillis(); +const {input, result, zone} = DateTime.fromFormatExplain("Aug 6 1982", "MMMM d yyyy"); + /* Duration */ const dur = Duration.fromObject({ hours: 2, minutes: 7 }); dt.plus(dur); diff --git a/types/luxon/tslint.json b/types/luxon/tslint.json index 764ebe0c97..bc0a6d599a 100644 --- a/types/luxon/tslint.json +++ b/types/luxon/tslint.json @@ -1,7 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "ban-types": false, "no-single-declare-module": false, "interface-over-type-literal": false, "no-declare-current-package": false diff --git a/types/lzma-native/index.d.ts b/types/lzma-native/index.d.ts new file mode 100644 index 0000000000..33165885da --- /dev/null +++ b/types/lzma-native/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for lzma-native 4.0 +// Project: https://github.com/addaleax/lzma-native +// Definitions by: Evan Cameron +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +/// + +import { Stream } from "stream"; +export interface LzmaOptions { + synchronous?: boolean; + bufsize?: number; + memlimit?: number; + check?: Check; + preset?: Preset; + flags?: + | "TELL_NO_CHECK" + | "TELL_UNSUPPORTED_CHECK" + | "TELL_ANY_CHECK" + | "CONCATENATED"; + threads?: number; + blockSize?: number; + timeout?: number; +} + +export type Check = + | "CHECK_CRC32" + | "CHECK_CRC64" + | "CHECK_NONE" + | "CHECK_SHA256"; + +export type Coders = + | "easyEncoder" + | "aloneDecoder" + | "rawEncoder" + | "autoDecoder" + | "aloneEncoder" + | "streamEncoder" + | "streamDecoder"; + +export type Preset = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + +export interface FileOptions { + fileSize: number; + memlimit?: number; + read: ( + count: number, + offset: number, + cb: (err: any, buffer: Buffer) => void + ) => void; +} + +export interface StreamInfo { + streamPadding: number; + memlimit: number; + streams: number; + blocks: number; + fileSize: number; + uncompressedSize: number; + checks: number; +} + +export function createStream( + coder: Coders, + options?: LzmaOptions +): JSLzmaStream; + +export function createCompressor(options?: LzmaOptions): JSLzmaStream; +export function createDecompressor(options?: LzmaOptions): JSLzmaStream; +export function crc32( + input: string, + encoding?: string, + previous?: number +): string; +export function isXZ(buf: Buffer | string): boolean; +export function versionString(): string; +export function versionNumber(): number; +export function checkSize(check: Check): number; +export function easyDecoderMemusage(preset: Preset): number; +export function easyEncoderMemusage(preset: Preset): number; +export function rawDecoderMemusage(preset: Preset): number; +export function rawEncoderMemusage(preset: Preset): number; + +export function Compressor( + preset?: Preset, + options?: LzmaOptions +): JSLzmaStream; +export function Decompressor(options?: LzmaOptions): JSLzmaStream; + +export function parseFileIndex( + options: FileOptions, + callback?: (err: any, info?: StreamInfo) => void +): void; +export function parseFileIndexFD( + fileDescriptor: number, + callback?: (err: any, info?: StreamInfo) => void +): void; + +export function compress( + buf: Buffer | string, + options?: LzmaOptions | Preset, + on_finish?: (result: Buffer) => void +): void; +export function decompress( + buf: Buffer | string, + options?: LzmaOptions | Preset, + on_finish?: (result: Buffer) => void +): void; +export function LZMA(): { + compress( + buf: Buffer | string, + mode: Preset, + on_finish: (result: Buffer) => void, + on_progress?: (progress: number) => void + ): void; + decompress( + buf: Buffer | string, + on_finish: (result: Buffer) => void, + on_progress?: (progress: number) => void + ): void; +}; + +export class JSLzmaStream extends Stream.Transform { + constructor(nativeStream: Stream, options: LzmaOptions); + bufsize(): number; + bufsize(size: number): void; + totalInt(): number; + totalOut(): number; + cleanUp(): void; +} diff --git a/types/lzma-native/lzma-native-tests.ts b/types/lzma-native/lzma-native-tests.ts new file mode 100644 index 0000000000..44a5eab221 --- /dev/null +++ b/types/lzma-native/lzma-native-tests.ts @@ -0,0 +1,55 @@ +import * as lzma from "lzma-native"; +import * as fs from "fs"; + +const compressor = lzma.createCompressor(); +const input = fs.createReadStream("tsconfig.json"); +const output = fs.createWriteStream("tsconfig.json.xz"); + +input.pipe(compressor).pipe(output); + +lzma.compress("Banana", undefined, result => { + console.log(result); // +}); + +lzma.compress("Bananas", 6, result => { + lzma.decompress(result, undefined, decompressedResult => { + console.log(decompressedResult.toString() === "Bananas"); + }); +}); + +lzma.LZMA().compress("Bananas", 4, result => { + lzma.LZMA().decompress(result, decompressedResult => { + console.log("Bananas" === decompressedResult.toString()); + }); +}); + +const comp = lzma.Compressor(); + +process.stdin.pipe(comp).pipe(process.stdout); +lzma.crc32("Banana"); // => 69690105 +lzma.checkSize("CHECK_SHA256"); // => 16 +lzma.checkSize("CHECK_CRC32"); // => 4 +lzma.easyDecoderMemusage(6); // => 8454192 +lzma.easyEncoderMemusage(6); // => 97620499 +lzma.versionString(); // => '5.2.3' +lzma.versionNumber(); // => 50020012 +lzma.isXZ("Banana"); // => false + +fs.open("test/hamlet.txt.xz", "r", (err: any, fd: number) => { + if (err) return; + // handle error + lzma.parseFileIndexFD(fd, (err, info) => { + // handle error + if (err) { + console.log(err); + } + // do something with e.g. info.uncompressedSize + + fs.close(fd, (err: any) => { + /* handle error */ + if (err) { + console.log(err); + } + }); + }); +}); diff --git a/types/lzma-native/tsconfig.json b/types/lzma-native/tsconfig.json new file mode 100644 index 0000000000..fa7667f123 --- /dev/null +++ b/types/lzma-native/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noImplicitThis": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "lzma-native-tests.ts"] +} diff --git a/types/lzma-native/tslint.json b/types/lzma-native/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lzma-native/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-keyboard-trap/index.d.ts b/types/makeup-keyboard-trap/index.d.ts new file mode 100644 index 0000000000..4645d57e2c --- /dev/null +++ b/types/makeup-keyboard-trap/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for makeup-keyboard-trap 0.1 +// Project: https://github.com/makeup-js/makeup-keyboard-trap#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export function refresh(): any; + +export function trap(el: any): any; + +export function untrap(): any; diff --git a/types/makeup-keyboard-trap/makeup-keyboard-trap-tests.ts b/types/makeup-keyboard-trap/makeup-keyboard-trap-tests.ts new file mode 100644 index 0000000000..0f7687d750 --- /dev/null +++ b/types/makeup-keyboard-trap/makeup-keyboard-trap-tests.ts @@ -0,0 +1,7 @@ +import { trap, untrap } from 'makeup-keyboard-trap'; + +const widgetEl: HTMLElement | null = document.querySelector('.expander'); + +trap(widgetEl); + +untrap(); diff --git a/types/makeup-keyboard-trap/tsconfig.json b/types/makeup-keyboard-trap/tsconfig.json new file mode 100644 index 0000000000..0e4c00274f --- /dev/null +++ b/types/makeup-keyboard-trap/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", + "makeup-keyboard-trap-tests.ts" + ] +} diff --git a/types/makeup-keyboard-trap/tslint.json b/types/makeup-keyboard-trap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-keyboard-trap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-prevent-scroll-keys/index.d.ts b/types/makeup-prevent-scroll-keys/index.d.ts new file mode 100644 index 0000000000..bb59ece615 --- /dev/null +++ b/types/makeup-prevent-scroll-keys/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for makeup-prevent-scroll-keys 0.0 +// Project: https://github.com/makeup-js/makeup-prevent-scroll-keys#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export function add(el: any): void; + +export function remove(el: any): void; diff --git a/types/makeup-prevent-scroll-keys/makeup-prevent-scroll-keys-tests.ts b/types/makeup-prevent-scroll-keys/makeup-prevent-scroll-keys-tests.ts new file mode 100644 index 0000000000..c889c6299a --- /dev/null +++ b/types/makeup-prevent-scroll-keys/makeup-prevent-scroll-keys-tests.ts @@ -0,0 +1,9 @@ +import * as scrollKeyPreventer from 'makeup-prevent-scroll-keys'; + +const widgetEl: HTMLElement | null = document.querySelector('.widget'); + +if (widgetEl) { + scrollKeyPreventer.add(widgetEl); + + scrollKeyPreventer.remove(widgetEl); +} diff --git a/types/makeup-prevent-scroll-keys/tsconfig.json b/types/makeup-prevent-scroll-keys/tsconfig.json new file mode 100644 index 0000000000..d48ada0be6 --- /dev/null +++ b/types/makeup-prevent-scroll-keys/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", + "makeup-prevent-scroll-keys-tests.ts" + ] +} diff --git a/types/makeup-prevent-scroll-keys/tslint.json b/types/makeup-prevent-scroll-keys/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-prevent-scroll-keys/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-screenreader-trap/index.d.ts b/types/makeup-screenreader-trap/index.d.ts new file mode 100644 index 0000000000..0995b62a3c --- /dev/null +++ b/types/makeup-screenreader-trap/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for makeup-screenreader-trap 0.0 +// Project: https://github.com/makeup-js/makeup-screenreader-trap#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export function trap(el: HTMLElement): void; + +export function untrap(): void; diff --git a/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts b/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts new file mode 100644 index 0000000000..48b198ab2d --- /dev/null +++ b/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts @@ -0,0 +1,9 @@ +import { trap, untrap } from 'makeup-screenreader-trap'; + +const widgetEl: HTMLElement | null = document.querySelector('.expander'); + +if (widgetEl) { + trap(widgetEl); +} + +untrap(); diff --git a/types/makeup-screenreader-trap/tsconfig.json b/types/makeup-screenreader-trap/tsconfig.json new file mode 100644 index 0000000000..08df420e11 --- /dev/null +++ b/types/makeup-screenreader-trap/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", + "makeup-screenreader-trap-tests.ts" + ] +} diff --git a/types/makeup-screenreader-trap/tslint.json b/types/makeup-screenreader-trap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-screenreader-trap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 1aad087460..33a619b9ae 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -692,6 +692,8 @@ declare namespace mapboxgl { clusterMaxZoom?: number; lineMetrics?: boolean; + + generateId?: boolean; } /** diff --git a/types/markdown-it-anchor/index.d.ts b/types/markdown-it-anchor/index.d.ts index fc4cead6d4..39cb91be45 100644 --- a/types/markdown-it-anchor/index.d.ts +++ b/types/markdown-it-anchor/index.d.ts @@ -4,7 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt, Core, Token } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); +import Core = require('markdown-it/lib/parser_core'); +import Token = require('markdown-it/lib/token'); declare namespace anchor { interface AnchorInfo { diff --git a/types/markdown-it-anchor/markdown-it-anchor-tests.ts b/types/markdown-it-anchor/markdown-it-anchor-tests.ts index 3570ba764b..a9a865a469 100644 --- a/types/markdown-it-anchor/markdown-it-anchor-tests.ts +++ b/types/markdown-it-anchor/markdown-it-anchor-tests.ts @@ -1,4 +1,4 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); import anchor = require("markdown-it-anchor"); const md = new MarkdownIt(); diff --git a/types/markdown-it-container/index.d.ts b/types/markdown-it-container/index.d.ts index b0913972fa..2920f38f91 100644 --- a/types/markdown-it-container/index.d.ts +++ b/types/markdown-it-container/index.d.ts @@ -4,7 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt, Token, Renderer } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); +import Renderer = require('markdown-it/lib/renderer'); +import Token = require('markdown-it/lib/token'); declare namespace markdownItContainer { interface ContainerOpts { diff --git a/types/markdown-it-container/markdown-it-container-tests.ts b/types/markdown-it-container/markdown-it-container-tests.ts index 3c8f3bf980..e6754f82f3 100644 --- a/types/markdown-it-container/markdown-it-container-tests.ts +++ b/types/markdown-it-container/markdown-it-container-tests.ts @@ -1,11 +1,13 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); +import Token = require("markdown-it/lib/token"); + import MarkdownItContainer = require("markdown-it-container"); const md = new MarkdownIt(); md.use(MarkdownItContainer, 'spoiler', { validate: (params: any) => params.trim().match(/^spoiler\s+(.*)$/), - render: (tokens: MarkdownIt.Token[], index: number) => { + render: (tokens: Token[], index: number) => { const match = tokens[index].info.trim().match(/^spoiler\s+(.*)$/); const onClick = "this.parentNode.classList.toggle('_expanded');" + diff --git a/types/markdown-it-lazy-headers/index.d.ts b/types/markdown-it-lazy-headers/index.d.ts index 0579118f80..43ac828764 100644 --- a/types/markdown-it-lazy-headers/index.d.ts +++ b/types/markdown-it-lazy-headers/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); declare function lazyheaders(md: MarkdownIt): void; diff --git a/types/markdown-it/index.d.ts b/types/markdown-it/index.d.ts index 0948a6d353..e7d0ffa6e7 100644 --- a/types/markdown-it/index.d.ts +++ b/types/markdown-it/index.d.ts @@ -4,235 +4,5 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -interface MarkdownItStatic { - new (): MarkdownIt.MarkdownIt; - new (presetName: "commonmark" | "zero" | "default", options?: MarkdownIt.Options): MarkdownIt.MarkdownIt; - new (options: MarkdownIt.Options): MarkdownIt.MarkdownIt; - (): MarkdownIt.MarkdownIt; - (presetName: "commonmark" | "zero" | "default", options ?: MarkdownIt.Options): MarkdownIt.MarkdownIt; - (options: MarkdownIt.Options): MarkdownIt.MarkdownIt; -} - -declare var MarkdownIt: MarkdownItStatic; +import MarkdownIt = require("./lib"); export = MarkdownIt; -export as namespace markdownit; - -declare module MarkdownIt { - interface MarkdownIt { - render(md: string, env?: any): string; - renderInline(md: string, env?: any): string; - parse(src: string, env: any): Token[]; - parseInline(src: string, env: any): Token[]; - - /* - // The following only works in 3.0 - // Since it's still not allowed to target 3.0, i'll leave the code commented out - - use = any[]>( - plugin: (md: MarkdownIt, ...params: T) => void, - ...params: T - ): MarkdownIt; - */ - - use(plugin: (md: MarkdownIt, ...params: any[]) => void, ...params: any[]): MarkdownIt; - - utils: { - assign(obj: any): any; - isString(obj: any): boolean; - has(object: any, key: string): boolean; - unescapeMd(str: string): string; - unescapeAll(str: string): string; - isValidEntityCode(str: any): boolean; - fromCodePoint(str: string): string; - escapeHtml(str: string): string; - arrayReplaceAt(src: any[], pos: number, newElements: any[]): any[] - isSpace(str: any): boolean; - isWhiteSpace(str: any): boolean - isMdAsciiPunct(str: any): boolean; - isPunctChar(str: any): boolean; - escapeRE(str: string): string; - normalizeReference(str: string): string; - } - - disable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; - enable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; - set(options: Options): MarkdownIt; - normalizeLink(url: string): string; - normalizeLinkText(url: string): string; - validateLink(url: string): boolean; - block: ParserBlock; - core: Core; - helpers: any; - inline: ParserInline; - linkify: LinkifyIt; - renderer: Renderer; - } - interface Options { - html?: boolean; - xhtmlOut?: boolean; - breaks?: boolean; - langPrefix?: string; - linkify?: boolean; - typographer?: boolean; - quotes?: string; - highlight?: (str: string, lang: string) => void; - } - interface LinkifyIt { - tlds(lang: string, linkified: boolean): void; - } - interface Renderer { - rules: { [name: string]: TokenRender }; - render(tokens: Token[], options: any, env: any): string; - renderAttrs(token: Token): string; - renderInline(tokens: Token[], options: any, env: any): string; - renderToken(tokens: Token[], idx: number, options: any): string; - } - interface Token { - new (type: string, tag: string, nesting: number): Token; - attrGet: (name: string) => string | null; - attrIndex: (name: string) => number; - attrJoin: (name: string, value: string) => void; - attrPush: (attrData: string[]) => void; - attrSet: (name: string, value: string) => void; - attrs: string[][]; - block: boolean; - children: Token[]; - content: string; - hidden: boolean; - info: string; - level: number; - map: number[]; - markup: string; - meta: any; - nesting: number; - tag: string; - type: string; - } - - type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; - - interface Rule { - (state: S, silent?: boolean): boolean | void; - } - - interface RuleInline extends Rule {} - interface RuleBlock extends Rule {} - - interface Ruler { - after(afterName: string, ruleName: string, rule: Rule, options?: any): void; - at(name: string, rule: Rule, options?: any): void; - before(beforeName: string, ruleName: string, rule: Rule, options?: any): void; - disable(rules: string | string[], ignoreInvalid?: boolean): string[]; - enable(rules: string | string[], ignoreInvalid?: boolean): string[]; - enableOnly(rule: string, ignoreInvalid?: boolean): void; - getRules(chain: string): Rule[]; - push(ruleName: string, rule: Rule, options?: any): void; - } - - interface RulerInline extends Ruler {} - interface RulerBlock extends Ruler {} - - interface ParserBlock { - parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; - ruler: RulerBlock; - } - - interface Core { - process(state: any): void; - ruler: Ruler; - } - - interface ParserInline { - parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; - tokenize(state: State): void; - skipToken(state: State): void; - ruler: RulerInline; - ruler2: RulerInline; - } - - interface Delimiter { - close: boolean; - end: number; - jump: number; - length: number; - level: number; - marker: number; - open: boolean; - token: number; - } - - interface State { - env: any; - level: number; - - /** Link to parser instance */ - md: MarkdownIt; - - /** The markdown source code that is being parsed. */ - src: string; - - tokens: Token[]; - - /** Return any for a yet untyped property */ - [undocumented: string]: any; - } - - interface StateInline extends State { - /** - * Stores `{ start: end }` pairs. Useful for backtrack - * optimization of pairs parse (emphasis, strikes). - */ - cache: { [start: number]: number }; - - /** Emphasis-like delimiters */ - delimiters: Delimiter[]; - - pending: string; - pendingLevel: number; - - /** Index of the first character of this token. */ - pos: number; - - /** Index of the last character that can be used (for example the one before the end of this line). */ - posMax: number; - - /** - * Push new token to "stream". - * If pending text exists, flush it as text token. - */ - push(type: string, tag: string, nesting: number): Token; - - /** Flush pending text */ - pushPending(): Token; - - /** - * Scan a sequence of emphasis-like markers and determine whether - * it can start an emphasis sequence or end an emphasis sequence. - * @param start - position to scan from (it should point to a valid marker) - * @param canSplitWord - determine if these markers can be found inside a word - */ - scanDelims(start: number, canSplitWord: boolean): { - can_open: boolean, - can_close: boolean, - length: number - }; - } - - interface StateBlock extends State { - /** Used in lists to determine if they interrupt a paragraph */ - parentType: 'blockquote' | 'list' | 'root' | 'paragraph' | 'reference'; - - eMarks: number[]; - bMarks: number[]; - bsCount: number[]; - sCount: number[]; - tShift: number[]; - - blkIndent: number; - ddIndent: number; - - line: number; - lineMax: number; - tight: boolean; - } -} diff --git a/types/markdown-it/lib/index.d.ts b/types/markdown-it/lib/index.d.ts new file mode 100644 index 0000000000..9a9caf37b6 --- /dev/null +++ b/types/markdown-it/lib/index.d.ts @@ -0,0 +1,113 @@ +import { LinkifyIt } from 'linkify-it' + +import State = require('./rules_core/state_core'); +import StateBlock = require('./rules_block/state_block'); +import StateInline = require('./rules_inline/state_inline'); + +import Core = require('./parser_core'); +import ParserBlock = require('./parser_block'); +import ParserInline = require('./parser_inline'); + +import Renderer = require('./renderer'); +import Ruler = require('./ruler'); +import Token = require('./token'); + +export = MarkdownIt; +export as namespace markdownit; + +declare const MarkdownIt: MarkdownItConstructor; + +interface MarkdownItConstructor { + new (): MarkdownIt; + new (presetName: "commonmark" | "zero" | "default", options?: MarkdownIt.Options): MarkdownIt; + new (options: MarkdownIt.Options): MarkdownIt; + (): MarkdownIt; + (presetName: "commonmark" | "zero" | "default", options ?: MarkdownIt.Options): MarkdownIt; + (options: MarkdownIt.Options): MarkdownIt; +} + +interface MarkdownIt { + render(md: string, env?: any): string; + renderInline(md: string, env?: any): string; + parse(src: string, env: any): Token[]; + parseInline(src: string, env: any): Token[]; + + /* + // The following only works in 3.0 + // Since it's still not allowed to target 3.0, i'll leave the code commented out + + use = any[]>( + plugin: (md: MarkdownIt, ...params: T) => void, + ...params: T + ): MarkdownIt; + */ + + use(plugin: (md: MarkdownIt, ...params: any[]) => void, ...params: any[]): MarkdownIt; + + utils: { + assign(obj: any): any; + isString(obj: any): boolean; + has(object: any, key: string): boolean; + unescapeMd(str: string): string; + unescapeAll(str: string): string; + isValidEntityCode(str: any): boolean; + fromCodePoint(str: string): string; + escapeHtml(str: string): string; + arrayReplaceAt(src: any[], pos: number, newElements: any[]): any[] + isSpace(str: any): boolean; + isWhiteSpace(str: any): boolean + isMdAsciiPunct(str: any): boolean; + isPunctChar(str: any): boolean; + escapeRE(str: string): string; + normalizeReference(str: string): string; + } + + disable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; + enable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; + set(options: MarkdownIt.Options): MarkdownIt; + normalizeLink(url: string): string; + normalizeLinkText(url: string): string; + validateLink(url: string): boolean; + block: ParserBlock; + core: Core; + helpers: any; + inline: ParserInline; + linkify: LinkifyIt; + renderer: Renderer; +} + +declare module MarkdownIt { + interface Options { + html?: boolean; + xhtmlOut?: boolean; + breaks?: boolean; + langPrefix?: string; + linkify?: boolean; + typographer?: boolean; + quotes?: string; + highlight?: (str: string, lang: string) => void; + } + + interface Rule { + (state: S, silent?: boolean): boolean | void; + } + + interface RuleInline extends Rule {} + interface RuleBlock extends Rule {} + + interface RulerInline extends Ruler {} + interface RulerBlock extends Ruler {} + + type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; + + interface Delimiter { + close: boolean; + end: number; + jump: number; + length: number; + level: number; + marker: number; + open: boolean; + token: number; + } +} diff --git a/types/markdown-it/lib/parser_block.d.ts b/types/markdown-it/lib/parser_block.d.ts new file mode 100644 index 0000000000..2efc76b858 --- /dev/null +++ b/types/markdown-it/lib/parser_block.d.ts @@ -0,0 +1,9 @@ +import MarkdownIt = require("."); +import Token = require("./token"); + +export = ParserBlock; + +declare class ParserBlock { + parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; + ruler: MarkdownIt.RulerBlock; +} diff --git a/types/markdown-it/lib/parser_core.d.ts b/types/markdown-it/lib/parser_core.d.ts new file mode 100644 index 0000000000..a6559bdfef --- /dev/null +++ b/types/markdown-it/lib/parser_core.d.ts @@ -0,0 +1,10 @@ +import MarkdownIt = require("."); +import Ruler = require("./ruler"); +import Token = require("./token"); + +export = ParserCore; + +declare class ParserCore { + process(state: any): void; + ruler: Ruler; +} diff --git a/types/markdown-it/lib/parser_inline.d.ts b/types/markdown-it/lib/parser_inline.d.ts new file mode 100644 index 0000000000..ad7aa26d93 --- /dev/null +++ b/types/markdown-it/lib/parser_inline.d.ts @@ -0,0 +1,13 @@ +import MarkdownIt = require("."); +import State = require("./rules_core/state_core"); +import Token = require("./token"); + +export = ParserInline; + +declare class ParserInline { + parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; + tokenize(state: State): void; + skipToken(state: State): void; + ruler: MarkdownIt.RulerInline; + ruler2: MarkdownIt.RulerInline; +} diff --git a/types/markdown-it/lib/renderer.d.ts b/types/markdown-it/lib/renderer.d.ts new file mode 100644 index 0000000000..0231dad0f9 --- /dev/null +++ b/types/markdown-it/lib/renderer.d.ts @@ -0,0 +1,12 @@ +import MarkdownIt = require("."); +import Token = require("./token"); + +export = Renderer; + +declare class Renderer { + rules: { [name: string]: MarkdownIt.TokenRender }; + render(tokens: Token[], options: any, env: any): string; + renderAttrs(token: Token): string; + renderInline(tokens: Token[], options: any, env: any): string; + renderToken(tokens: Token[], idx: number, options: any): string; +} diff --git a/types/markdown-it/lib/ruler.d.ts b/types/markdown-it/lib/ruler.d.ts new file mode 100644 index 0000000000..62ab55e3de --- /dev/null +++ b/types/markdown-it/lib/ruler.d.ts @@ -0,0 +1,15 @@ +import MarkdownIt = require("."); +import State = require("./rules_core/state_core"); + +export = Ruler; + +declare class Ruler { + after(afterName: string, ruleName: string, rule: MarkdownIt.Rule, options?: any): void; + at(name: string, rule: MarkdownIt.Rule, options?: any): void; + before(beforeName: string, ruleName: string, rule: MarkdownIt.Rule, options?: any): void; + disable(rules: string | string[], ignoreInvalid?: boolean): string[]; + enable(rules: string | string[], ignoreInvalid?: boolean): string[]; + enableOnly(rule: string, ignoreInvalid?: boolean): void; + getRules(chain: string): MarkdownIt.Rule[]; + push(ruleName: string, rule: MarkdownIt.Rule, options?: any): void; +} diff --git a/types/markdown-it/lib/rules_block/state_block.d.ts b/types/markdown-it/lib/rules_block/state_block.d.ts new file mode 100644 index 0000000000..6eebab4202 --- /dev/null +++ b/types/markdown-it/lib/rules_block/state_block.d.ts @@ -0,0 +1,23 @@ +import MarkdownIt = require(".."); +import State = require("../rules_core/state_core"); +import Token = require("../token"); + +export = StateBlock; + +declare class StateBlock extends State { + /** Used in lists to determine if they interrupt a paragraph */ + parentType: 'blockquote' | 'list' | 'root' | 'paragraph' | 'reference'; + + eMarks: number[]; + bMarks: number[]; + bsCount: number[]; + sCount: number[]; + tShift: number[]; + + blkIndent: number; + ddIndent: number; + + line: number; + lineMax: number; + tight: boolean; +} diff --git a/types/markdown-it/lib/rules_core/state_core.d.ts b/types/markdown-it/lib/rules_core/state_core.d.ts new file mode 100644 index 0000000000..7cf73134aa --- /dev/null +++ b/types/markdown-it/lib/rules_core/state_core.d.ts @@ -0,0 +1,20 @@ +import MarkdownIt = require(".."); +import Token = require("../token"); + +export = StateCore; + +declare class StateCore { + env: any; + level: number; + + /** Link to parser instance */ + md: MarkdownIt; + + /** The markdown source code that is being parsed. */ + src: string; + + tokens: Token[]; + + /** Return any for a yet untyped property */ + [undocumented: string]: any; +} diff --git a/types/markdown-it/lib/rules_inline/state_inline.d.ts b/types/markdown-it/lib/rules_inline/state_inline.d.ts new file mode 100644 index 0000000000..27938d99da --- /dev/null +++ b/types/markdown-it/lib/rules_inline/state_inline.d.ts @@ -0,0 +1,46 @@ +import MarkdownIt = require(".."); +import State = require("../rules_core/state_core"); +import Token = require("../token"); + +export = StateInline; + +declare class StateInline extends State { + /** + * Stores `{ start: end }` pairs. Useful for backtrack + * optimization of pairs parse (emphasis, strikes). + */ + cache: { [start: number]: number }; + + /** Emphasis-like delimiters */ + delimiters: MarkdownIt.Delimiter[]; + + pending: string; + pendingLevel: number; + + /** Index of the first character of this token. */ + pos: number; + + /** Index of the last character that can be used (for example the one before the end of this line). */ + posMax: number; + + /** + * Push new token to "stream". + * If pending text exists, flush it as text token. + */ + push(type: string, tag: string, nesting: number): Token; + + /** Flush pending text */ + pushPending(): Token; + + /** + * Scan a sequence of emphasis-like markers and determine whether + * it can start an emphasis sequence or end an emphasis sequence. + * @param start - position to scan from (it should point to a valid marker) + * @param canSplitWord - determine if these markers can be found inside a word + */ + scanDelims(start: number, canSplitWord: boolean): { + can_open: boolean, + can_close: boolean, + length: number + }; +} diff --git a/types/markdown-it/lib/token.d.ts b/types/markdown-it/lib/token.d.ts new file mode 100644 index 0000000000..1f71d54bfd --- /dev/null +++ b/types/markdown-it/lib/token.d.ts @@ -0,0 +1,23 @@ +export = Token; + +declare class Token { + constructor(type: string, tag: string, nesting: number); + attrGet: (name: string) => string | null; + attrIndex: (name: string) => number; + attrJoin: (name: string, value: string) => void; + attrPush: (attrData: string[]) => void; + attrSet: (name: string, value: string) => void; + attrs: string[][]; + block: boolean; + children: Token[]; + content: string; + hidden: boolean; + info: string; + level: number; + map: number[]; + markup: string; + meta: any; + nesting: number; + tag: string; + type: string; +} diff --git a/types/markdown-it/markdown-it-tests.ts b/types/markdown-it/markdown-it-tests.ts index f22fc5cb2d..343661ad87 100644 --- a/types/markdown-it/markdown-it-tests.ts +++ b/types/markdown-it/markdown-it-tests.ts @@ -1,4 +1,6 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); +import Renderer = require("markdown-it/lib/renderer"); +import Token = require("markdown-it/lib/token"); { const md = new MarkdownIt(); @@ -141,7 +143,7 @@ function myToken(tokens: any, idx: number, options: any, env: any, self: any) { return ""; }, }); - md.renderer.rules["image"] = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + md.renderer.rules["image"] = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { const token = tokens[index]; const aIndex = token.attrIndex("src"); token.attrs[aIndex][1]; @@ -154,11 +156,11 @@ function myToken(tokens: any, idx: number, options: any, env: any, self: any) { if (md.renderer.rules["link_open"]) { defaultLinkRender = md.renderer.rules["link_open"]; } else { - defaultLinkRender = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + defaultLinkRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { return self.renderToken(tokens, index, options); }; } - md.renderer.rules["link_open"] = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + md.renderer.rules["link_open"] = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { tokens[index].attrPush(["target", "_blank"]); tokens[index].attrPush(["rel", "nofollow"]); return defaultLinkRender(tokens, index, options, env, self); diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index 71f89b3e1a..6cb49323fa 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -1345,7 +1345,7 @@ declare namespace math { * the Matrix/array being traversed. * @returns Transformed map of x */ - map(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)): Matrix | MathArray; + map(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => MathType | string)): Matrix | MathArray; /** * Create a matrix filled with ones. The created matrix can have one or @@ -2876,6 +2876,7 @@ declare namespace math { interface Parser { eval(expr: string): any; get(variable: string): any; + getAll(): { [key: string]: any; }; set: (variable: string, value: any) => void; clear: () => void; } diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index 7c3dfaec35..babfa3ff37 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -179,6 +179,7 @@ Expressions examples const x = parser.get('x'); const f = parser.get('f'); + const y = parser.getAll(); const g = f(3, 3); parser.set('h', 500); @@ -270,6 +271,13 @@ Matrices examples math.range('2:-1:-3'); math.factorial(math.range('1:6')); } + + // map matrix + { + math.map([1, 2, 3], function(value) { + return value * value; + }); // returns [1, 4, 9] + } } /* diff --git a/types/meteor-astronomy/index.d.ts b/types/meteor-astronomy/index.d.ts new file mode 100644 index 0000000000..c17c1d1498 --- /dev/null +++ b/types/meteor-astronomy/index.d.ts @@ -0,0 +1,118 @@ +// Type definitions for meteor-astronomy 2.6 +// Project: https://github.com/jagi/meteor-astronomy/ +// Definitions by: Igor Golovin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +declare namespace MeteorAstronomy { + type NonFunctionPropertyNames = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T]; // tslint:disable-line:ban-types + type NonFunctionProperties = Pick>; + type FunctionPropertyNames = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T]; // tslint:disable-line:ban-types + type FunctionProperties = Pick>; + + type TypeOptionsPrimitives = typeof String | typeof Date | typeof Boolean | typeof Object | typeof Number; + type TypeOptions = TypeOptionsPrimitives | TypeOptionsPrimitives[] | Class | Enum; + type MongoQuery = object | string; + + interface SaveAndValidateOptions { + fields?: K[]; + stopOnFirstError?: boolean; + simulation?: boolean; + cast?: boolean; + } + + type SaveAndValidateCallback = (err: any, id: any) => void; + type RemoveCallback = (err: any, result: any) => void; + + interface Validator { + type: string; + param: any; + } + + interface ModelFullField { + type: TypeOptions; + optional?: boolean; + transient?: boolean; + immutable?: boolean; + default?: () => Field | Field; + index?: string | number; + validators?: Validator[]; + resolve?: (doc: Doc) => Field; + } + + type ModelField = ModelFullField | TypeOptions; + + type Fields = { + [P in keyof NonFunctionProperties]: ModelField; + }; + + type Helpers = { + [P in keyof FunctionProperties]: (this: T, ...args: any[]) => any; + }; + + interface ClassModel { + name: string; + collection?: Mongo.Collection; + fields: Fields; + behaviors?: object; + secured?: { + insert: boolean, + update: boolean, + remove: boolean, + } | boolean; + helpers?: Helpers; + events?: object; + meteorMethods?: object; + indexes?: object; + } + + interface EnumModel { + name: string; + identifiers: string[] | T; + } + + type Model = T & { + set(fields: Partial, options?: {cast?: boolean; clone?: boolean; merge?: boolean}): void; + set(field: string, value: any): void; + get(field: string): any; + get(fields: string[]): any[]; + isModified(field?: string): boolean; + getModified(): any; + getModifiedValues(options?: {old?: boolean, raw?: boolean}): Partial; + getModifier(): any; + raw(): T; + raw(field: string): any; + raw(fields: string[]): any[]; + save(options?: SaveAndValidateOptions, callback?: SaveAndValidateCallback): void; + save(callback?: SaveAndValidateCallback): void; + copy(save: boolean): any; + validate(options?: SaveAndValidateOptions, callback?: SaveAndValidateCallback): void; + validate(callback?: SaveAndValidateCallback): void; + remove(callback?: RemoveCallback): void; + }; + + interface Class { + new(data?: Partial): Model; + + findOne(query?: MongoQuery): Model; + find(query?: MongoQuery): Array>; + update(search: object | string, query: object, callback?: () => void): void; + } + + type Enum = T & { + getValues(): any[]; + getIdentifier(identifier: any): string; + }; +} + +declare module 'meteor/jagi:astronomy' { // tslint:disable-line:no-single-declare-module + namespace Class { + function create(model: MeteorAstronomy.ClassModel): MeteorAstronomy.Class; + } + + namespace Enum { + function create(model: MeteorAstronomy.EnumModel): MeteorAstronomy.Enum; + } +} diff --git a/types/meteor-astronomy/meteor-astronomy-tests.ts b/types/meteor-astronomy/meteor-astronomy-tests.ts new file mode 100644 index 0000000000..59f0f99644 --- /dev/null +++ b/types/meteor-astronomy/meteor-astronomy-tests.ts @@ -0,0 +1,176 @@ +import { Class, Enum } from 'meteor/jagi:astronomy'; +import { Meteor } from 'meteor/meteor'; +import { Mongo } from 'meteor/mongo'; + +interface PostInterface { + title: string; + userId: string; + publishedAt: Date; +} + +const Posts = new Mongo.Collection('posts'); + +const Post = Class.create({ + name: 'Post', + collection: Posts, + fields: { + title: { + type: String, + validators: [{ + type: 'minLength', + param: 3 + }] + }, + userId: String, + publishedAt: Date + }, + behaviors: { + timestamp: {} + }, +}); + +let post = new Post({ + title: 'text', +}); + +// Validate length of the "title" field. +post.save(); + +// Notice that we call the "findOne" method +// from the "Post" class not from the "Posts" collection. +post = Post.findOne('id'); +// Auto convert a string input value to a number. +post.title = 'input[name=title]'; +post.publishedAt = new Date(); +// Check if all fields are valid and update document +// with only the fields that have changed. +post.save({fields: ['title']}); + +interface UserProfileInterface { + nickname: string; + firstName: string; + createdAt: Date; + age: number; +} + +const UserProfile = Class.create({ + name: 'UserProfile', + fields: { + nickname: String, + firstName: String, + createdAt: Date, + age: Number, + } +}); + +interface UserInterface extends Meteor.User { + address: object; + firstName: string; + lastName: string; + phone: string; + phoneNumber: string; + fullName: (param: string) => string; +} + +const User = Class.create({ + name: 'User', + collection: Meteor.users as Mongo.Collection, + fields: { + createdAt: Number, + firstName: String, + lastName: String, + emails: { + type: [Object], + default: (): Meteor.UserEmail[] => [], + }, + profile: { + type: UserProfile, + default: () => {}, + }, + address: { + type: Object, + optional: true + }, + phoneNumber: { + type: String, + }, + phone: { + type: String, + resolve(doc: UserInterface) { + return doc.phoneNumber; + }, + }, + }, + helpers: { + fullName(param: string): string { + const fullName = `${this.firstName} ${this.lastName}`; + + if (param === 'lower') { + return fullName.toLowerCase(); + } else if (param === 'upper') { + return fullName.toUpperCase(); + } + + return fullName; + }, + }, + indexes: { + fullName: { // Index name. + fields: { // List of fields. + phoneNumber: 1, + createdAt: 1 + }, + options: {} + } + } +}); + +const user = User.findOne(); +user.set({username: 'user1'}); +user.save(); + +interface StatusInterface { + OPENED: number; + CLOSED: number; + DONE: number; + CANCELED: number; +} + +const Status = Enum.create({ + name: 'Status', + identifiers: ['OPENED', 'CLOSED', 'DONE', 'CANCELED'], +}); + +const Issue = Class.create({ + name: 'Issue', + fields: { + status: { + type: Status + } + } +}); + +Status.getValues(); // [0, 1, 2, 3] + +interface StatusBisInterface { + OPENED: string; + CLOSED: string; + DONE: string; + CANCELED: string; +} + +const StatusBis = Enum.create({ + name: 'Status', + identifiers: { + OPENED: 'OPENED', + CLOSED: 'CLOSED', + DONE: 'DONE', + CANCELED: 'CANCELED', + } +}); + +StatusBis.getValues(); // [5, 6, 15, 16] + +const statusNumber = Status.OPENED; + +Status.getIdentifier(statusNumber); // "OPENED" diff --git a/types/meteor-astronomy/tsconfig.json b/types/meteor-astronomy/tsconfig.json new file mode 100644 index 0000000000..90412b0069 --- /dev/null +++ b/types/meteor-astronomy/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", + "meteor-astronomy-tests.ts" + ] +} diff --git a/types/meteor-astronomy/tslint.json b/types/meteor-astronomy/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/meteor-astronomy/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/minio/index.d.ts b/types/minio/index.d.ts index 1bb407529d..e81661c506 100644 --- a/types/minio/index.d.ts +++ b/types/minio/index.d.ts @@ -61,6 +61,7 @@ export interface IncompleteUploadedBucketItem { export interface BucketStream extends Stream { on(event: 'data', listener: (item: T) => void): this; + on(event: 'error', listener: (error: Error) => void): this; } export interface PostPolicyResult { diff --git a/types/mjml-react/index.d.ts b/types/mjml-react/index.d.ts new file mode 100644 index 0000000000..decb895010 --- /dev/null +++ b/types/mjml-react/index.d.ts @@ -0,0 +1,413 @@ +// Type definitions for mjml-react 1.0 +// Project: https://github.com/wix-incubator/mjml-react +// Definitions by: Henri Normak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export namespace extensions { + class MjmlComment extends React.Component<{ children: string }> { } + class MjmlConditionalComment extends React.Component<{ children: string; condition: string }> { } + class MjmlTrackingPixel extends React.Component<{ src: string }> { } + class MjmlYahooStyle extends React.Component<{ children: string }> { } +} + +export namespace utils { + function namedEntityToHexCode(html: string): string; + function fixConditionalComment(html: string, havingContent: string, newCondition: string): string; + function useHttps(url?: string): string | undefined; + function toMobileFontSize(sizeWithUnit: string): number; + function addQueryParams(url: string, params: { [key: string]: any }): string; + + type TextAlignment = 'left' | 'right' | 'center' | 'justify' | 'inherit'; + function getTextAlign(value: string, fallback?: TextAlignment): TextAlignment; +} + +export function renderToMjml(email: React.ReactElement): string; + +export interface Mjml2HtmlOptions { + fonts?: { [key: string]: string }; + keepComments?: boolean; + beautify?: boolean; + minify?: boolean; + validationLevel?: 'strict' | 'soft' | 'skip'; + filePath?: string; +} + +export function render(email: React.ReactElement, options?: Mjml2HtmlOptions): { html: string; errors: Error[] }; + +// Components + +export interface RequiredChildrenProps { + children: React.ReactNode; +} + +export interface PaddingProps { + padding?: string | number; + paddingTop?: string | number; + paddingRight?: string | number; + paddingBottom?: string | number; + paddingLeft?: string | number; +} + +export interface BorderProps { + border?: string; + borderBottom?: string; + borderLeft?: string; + borderTop?: string; + borderRight?: string; + borderRadius?: string | number; +} + +export interface ClassNameProps { + cssClass?: string; +} + +export interface HrefProps { + href?: string; + target?: string; + rel?: string; +} + +// mjml +export interface MjmlProps { + lang?: string; + owa?: string; +} + +export class Mjml extends React.Component { } + +// mj-head +export class MjmlHead extends React.Component { } + +// mj-attributes +export class MjmlAttributes extends React.Component { } +export class MjmlAll extends React.Component<{ [key: string]: any; children?: React.ReactNode }> { } +export class MjmlClass extends React.Component<{ [key: string]: any; children?: React.ReactNode; name: string }> { } + +// mj-breakpoint +export interface MjmlBreakpointProps { + width?: string | number; +} + +export class MjmlBreakpoint extends React.Component { } + +// mj-body +export interface MjmlBodyProps { + width ?: number; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlBody extends React.Component { } + +// mj-font +export interface MjmlFontProps { + href?: string; + name?: string; +} + +export class MjmlFont extends React.Component { } + +// mj-preview +export class MjmlPreview extends React.Component<{ children: string }> { } + +// mj-style +export class MjmlStyle extends React.Component<{ children: string, inline?: boolean }> { } + +// mj-title +export class MjmlTitle extends React.Component<{ children: string }> { } + +// mj-accordion +export class MjmlAccordion extends React.Component { } + +export interface MjmlAccordionElementProps { + fontFamily?: string; + iconAlign?: string; + iconWrappedUrl?: string; + iconWrappedAlt?: string; + iconUnwrappedAlt?: string; + iconUnwrappedUrl?: string; + iconPosition?: 'left' | 'right'; + iconHeight?: string; + iconWidth?: string; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlAccordionElement extends React.Component { } + +export interface MjmlAccordionTextProps { + color?: React.CSSProperties['color']; + fontFamily?: string; + fontSize?: string | number; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlAccordionText extends React.Component { } + +export interface MjmlAccordionTitleProps { + color?: React.CSSProperties['color']; + backgroundColor?: React.CSSProperties['backgroundColor']; + fontFamily?: string; + fontSize?: string | number; +} + +export class MjmlAccordionTitle extends React.Component { } + +// mj-button +export interface MjmlButtonProps { + backgroundColor?: React.CSSProperties['backgroundColor']; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; + fontStyle?: string; + fontSize?: string | number; + fontWeight?: number; + fontFamily?: string; + color?: React.CSSProperties['color']; + textAlign?: React.CSSProperties['textAlign']; + textDecoration?: string; + textTransform?: string; + align?: string; + verticalAlign?: React.CSSProperties['verticalAlign']; + lineHeight?: string | number; + innerPadding?: string; + width?: string | number; + height?: string | number; +} + +export class MjmlButton extends React.Component { } + +// mj-carousel +export interface MjmlCarouselProps { + backgroundColor?: React.CSSProperties['backgroundColor']; + align?: string; + borderRadius?: string | number; + thumbnails?: 'hidden' | 'visible'; + tbBorder?: React.CSSProperties['border']; + tbBorderRadius?: React.CSSProperties['borderRadius']; + tbHoverBorderColor?: string; + tbSelectedBorderColor?: string; + tbWidth?: string; + leftIcon?: string; + rightIcon?: string; + iconWidth?: string; +} + +export class MjmlCarousel extends React.Component {} + +export interface MjmlCarouselImageProps { + src?: string; + thumbnailsSrc?: string; + alt?: string; + title?: string; +} + +export class MjmlCarouselImage extends React.Component { } + +// mj-carousel +export interface MjmlColumnProps { + width?: string | number; + verticalAlign?: React.CSSProperties['verticalAlign']; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlColumn extends React.Component { } + +// mj-divider +export interface MjmlDividerProps { + borderColor?: React.CSSProperties['borderColor']; + borderStyle?: React.CSSProperties['borderStyle']; + borderWidth?: string | number; + width?: string | number; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlDivider extends React.Component { } + +// mj-group +export interface MjmlGroupProps { + width?: string | number; + verticalAlign?: React.CSSProperties['verticalAlign']; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlGroup extends React.Component { } + +// mj-hero +export interface MjmlHeroProps { + width?: string | number; + height?: string | number; + mode?: 'fluid-height' | 'fixed-height'; + backgroundWidth?: string; + backgroundHeight?: string; + backgroundUrl?: string; + backgroundPosition?: React.CSSProperties['backgroundPosition']; + verticalAlign?: React.CSSProperties['verticalAlign']; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlHero extends React.Component { } + +// mj-image +export interface MjmlImageProps { + containerBackgroundColor?: React.CSSProperties['backgroundColor']; + border?: React.CSSProperties['border']; + borderRadius?: string | number; + width?: string | number; + height?: string | number; + src?: string; + srcset?: string; + alt?: string; + align?: string; + title?: string; + fluidOnMobile?: string; +} + +export class MjmlImage extends React.Component { } + +// mj-navbar +export interface MjmlNavbarProps { + baseUrl?: string; + hamburger?: 'hamburger'; + align?: string; + icoOpen?: string; + icoClose?: string; + icoPadding?: string; + icoPaddingTop?: string; + icoPaddingRight?: string; + icoPaddingBottom?: string; + icoPaddingLeft?: string; + icoAlign?: string; + icoColor?: React.CSSProperties['color']; + icoFontSize?: string; + icoTextTransform?: string; + icoTextDecoration?: string; + icoLineHeight?: string; +} + +export class MjmlNavbar extends React.Component { } + +export interface MjmlNavbarLinkProps { + color?: React.CSSProperties['color']; + fontFamily?: string; + fontSize?: string | number; + fontStyle?: string; + fontWeight?: number; + lineHeight?: string | number; + textDecoration?: string; + textTransform?: string; +} + +export class MjmlNavbarLink extends React.Component { } + +// mj-raw +export class MjmlRaw extends React.Component { } + +// mj-section +export interface MjmlSectionProps { + fullWidth?: boolean; + backgroundColor?: React.CSSProperties['backgroundColor']; + backgroundUrl?: string; + backgroundRepeat?: React.CSSProperties['backgroundRepeat']; + backgroundSize?: React.CSSProperties['backgroundSize']; + verticalAlign?: React.CSSProperties['verticalAlign']; + textAlign?: React.CSSProperties['textAlign']; + direction?: 'ltr' | 'rtl'; +} + +export class MjmlSection extends React.Component { } + +// mj-social +export interface MjmlSocialProps { + borderRadius?: string | number; + fontFamily?: string; + fontSize?: string | number; + iconSize?: string; + iconHeight?: string; + lineHeight?: string | number; + mode?: 'vertical' | 'horizontal'; + textDecoration?: string; + align?: string; + color?: React.CSSProperties['color']; + innerPadding?: string; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlSocial extends React.Component { } + +export interface MjmlSocialElementProps { + borderRadius?: string | number; + backgroundColor?: React.CSSProperties['backgroundColor']; + fontFamily?: string; + fontSize?: string | number; + iconSize?: string; + iconHeight?: string; + lineHeight?: string | number; + mode?: 'vertical' | 'horizontal'; + textDecoration?: string; + align?: string; + color?: React.CSSProperties['color']; + name?: 'facebook' | 'facebook-noshare' | 'twitter' | 'twitter-noshare' | 'google' | 'google-noshare' | 'pinterest' | 'pinterest-noshare' | + 'linkedin' | 'linkedin-noshare' | 'tumblr' | 'tumblr-noshare' | 'xing' | 'xing-noshare' | + 'github' | 'instagram' | 'web' | 'snapchat' | 'youtube' | 'vimeo' | 'medium' | 'soundcloud' | 'dribbble'; + src?: string; + alt?: string; +} + +export class MjmlSocialElement extends React.Component { } + +// mj-spacer +export interface MjmlSpacerProps { + height?: string | number; + width?: string | number; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; + verticalAlign?: React.CSSProperties['verticalAlign']; +} + +export class MjmlSpacer extends React.Component { } + +// mj-table +export interface MjmlTableProps { + color?: React.CSSProperties['color']; + cellpadding?: string; + cellspacing?: string; + fontFamily?: string; + fontSize?: string | number; + fontStyle?: string; + lineHeight?: string | number; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; + width?: string | number; + tableLayout?: 'auto' | 'fixed' | 'initial' | 'inherit'; +} + +export class MjmlTable extends React.Component { } + +// mj-text +export interface MjmlTextProps { + color?: React.CSSProperties['color']; + fontFamily?: string; + fontSize?: string | number; + fontStyle?: string; + fontWeight?: number; + lineHeight?: string; + letterSpacing?: string; + height?: string | number; + textDecoration?: string; + textTransform?: string; + align?: string; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlText extends React.Component { } + +// mj-wrapper +export interface MjmlWrapperProps { + fullWidth?: boolean; + backgroundColor?: React.CSSProperties['backgroundColor']; + backgroundUrl?: string; + backgroundRepeat?: React.CSSProperties['backgroundRepeat']; + backgroundSize?: React.CSSProperties['backgroundSize']; + verticalAlign?: React.CSSProperties['verticalAlign']; + textAlign?: React.CSSProperties['textAlign']; +} + +export class MjmlWrapper extends React.Component { } diff --git a/types/mjml-react/mjml-react-tests.tsx b/types/mjml-react/mjml-react-tests.tsx new file mode 100644 index 0000000000..7ff38e21f8 --- /dev/null +++ b/types/mjml-react/mjml-react-tests.tsx @@ -0,0 +1,40 @@ +import * as React from 'react'; +import { + render, + Mjml, + MjmlHead, + MjmlTitle, + MjmlPreview, + MjmlBody, + MjmlSection, + MjmlColumn, + MjmlButton, + MjmlImage +} from 'mjml-react'; + +function renderOutTestEmail() { + // $ExpectType { html: string; errors: Error[]; } + const result = render(( + + + Last Minute Offer + Last Minute Offer... + + + + + + + + + + + + I like it! + + + + + + ), { validationLevel: 'soft' }); +} diff --git a/types/mjml-react/tsconfig.json b/types/mjml-react/tsconfig.json new file mode 100644 index 0000000000..11cabc646f --- /dev/null +++ b/types/mjml-react/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "mjml-react-tests.tsx" + ] +} diff --git a/types/mjml-react/tslint.json b/types/mjml-react/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mjml-react/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mobx-cookie/index.d.ts b/types/mobx-cookie/index.d.ts deleted file mode 100644 index fbf3cc58fd..0000000000 --- a/types/mobx-cookie/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Type definitions for mobx-cookie 1.1 -// Project: https://github.com/will-stone/mobx-cookie#readme -// Definitions by: Duong Tran -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import { CookieAttributes } from 'js-cookie'; - -declare class MobxCookie { - constructor(name: string, options?: CookieAttributes); - - get(): any; - set(value: any, options?: CookieAttributes): void; - remove(): void; -} - -export default MobxCookie; diff --git a/types/mobx-cookie/mobx-cookie-tests.ts b/types/mobx-cookie/mobx-cookie-tests.ts deleted file mode 100644 index 66965a9f31..0000000000 --- a/types/mobx-cookie/mobx-cookie-tests.ts +++ /dev/null @@ -1,11 +0,0 @@ -import MobxCookie from 'mobx-cookie'; - -// Declare a reactive mobx cookie that last for 20 days -const mobxCookie = new MobxCookie('TEST_MOBX_COOKIE', {expires: 20}); - -// Set a new value for the cookie that last for 10 days -mobxCookie.set('MY_VALUE', {expires: 10}); - -const cookieValue = mobxCookie.get(); - -mobxCookie.remove(); diff --git a/types/module-deps/index.d.ts b/types/module-deps/index.d.ts new file mode 100644 index 0000000000..94706542a1 --- /dev/null +++ b/types/module-deps/index.d.ts @@ -0,0 +1,181 @@ +// Type definitions for module-deps 6.1 +// Project: https://github.com/browserify/module-deps +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as browserResolve from "browser-resolve"; + +/** + * Return an object transform stream 'd' that expects entry filenames or '{ id: ..., file: ... }' objects + * as input and produces objects for every dependency from a recursive module traversal as output. + */ +declare function moduleDeps(opts?: moduleDeps.Options): moduleDeps.ModuleDepsObject; + +/** + * Walk the dependency graph to generate json output that can be fed into browser-pack + */ +declare namespace moduleDeps { + /** + * module-deps constructor options + */ + interface Options { + /** + * A string or array of string transforms + */ + transform?: string | string[]; + + /** + * An array path of strings showing where to look in the package.json + * for source transformations. If falsy, don't look at the package.json at all + */ + transformKey?: string[]; + + /** + * Custom resolve function using the opts.resolve(id, parent, cb) signature that browser-resolve has + */ + resolve?: (id: string, opts: browserResolve.SyncOpts, cb: (err?: Error | null, file?: string, pkg?: PackageObject, fakePath?: any) => void) => void; + + /** + * A custom dependency detection function. opts.detect(source) should return an array of dependency module names. By default detective is used + */ + detect?: (source: string) => string[]; + + /** + * A function (id) to skip resolution of some module id strings. If defined, + * opts.filter(id) should return truthy for all the ids to include and falsey for all the ids to skip. + */ + filter?: (id: string) => boolean; + + /** + * A function (id, file, pkg) that gets called after id has been resolved. + * Return false to skip this file + */ + postFilter?: (id: string, file: string, pkg: PackageObject) => (void | boolean); // tslint:disable-line:void-return + + /** + * Transform the parsed package.json contents before using the values. + * opts.packageFilter(pkg, dir) should return the new pkg object to use. + */ + packageFilter?: (pkg: PackageObject, dir: string) => PackageObject; + + /** + * An array of absolute paths to not parse for dependencies. + * Use this for large dependencies like jquery or threejs which take forever to parse. + */ + noParse?: boolean | string[]; + + /** + * An object mapping filenames to file objects to skip costly io + */ + cache?: { [fileName: string]: any }; + + /** + * An object mapping filenames to their parent package.json contents + * for browser fields, main entries, and transforms + */ + packageCache?: { [fileName: string]: any }; + + /** + * An object mapping filenames to raw source to avoid reading from disk. + */ + fileCache?: { [fileName: string]: string }; + + /** + * A complex cache handler that allows async and persistent caching of data. + */ + persistentCache?: (file: string, id: string, pkg: PackageObject, fallback: (dataAsString: string, cb: CacheCallback) => void, cb: CacheCallback) => void; + + /** + * Array of global paths to search. Defaults to splitting on ':' in process.env.NODE_PATH + */ + paths?: string[]; + + /** + * Ignore files that failed to resolve + */ + ignoreMissing?: boolean; + + // un-documented options used by module-deps + basedir?: string; + globalTransform?: any[]; + extensions?: string[]; + modules?: { [name: string]: any }; + expose?: { [name: string]: string }; + + [prop: string]: any; + } + + interface ModuleDepsObject extends NodeJS.ReadWriteStream { + resolve(id: string, parent: { id: string }, cb: (err: Error | null, file?: string, pkg?: PackageObject, fakePath?: any) => any): any; + + readFile(file: string, id?: any, pkg?: PackageObject): NodeJS.ReadableStream; + + getTransforms(file: string, pkg: PackageObject, opts?: { builtin?: boolean; inNodeModules?: boolean }): NodeJS.ReadWriteStream; + + walk(id: string | { file: string; id: string; entry?: boolean; expose?: string; noparse?: boolean; source?: string }, + parent: { modules: any }, + cb: (err: Error | null, file?: string) => void): void; + + parseDeps(file: string, src: string, cb: any): any[]; + + lookupPackage(file: string, cb: (a: any, b: any, c?: any) => any): void; + + _isTopLevel(file: string): boolean; + _transform(row: string | InputRow | InputTransform, enc: string, next: () => void): void; + _flush(): void; + + /** + * Every time a transform is applied to a file, a 'transform' event fires with the instantiated transform stream tr. + */ + on(event: "transform", listener: (tr: any, file: string) => any): this; + /** + * Every time a file is read, this event fires with the file path. + */ + on(event: "file", listener: (file: string, id: string) => any): this; + /** + * When opts.ignoreMissing is enabled, this event fires for each missing package. + */ + on(event: "missing", listener: (id: string, parent: { id: string; filename: string; [prop: string]: any }) => any): this; + /** + * Every time a package is read, this event fires. The directory name of the package is available in pkg.__dirname. + */ + on(event: "package", listener: (package: PackageObject) => any): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + } + + type CacheCallback = (err: Error | null, res?: { source: string; package: any; deps: { [dep: string]: boolean } }) => void; + + interface InputRow { + file: string; + id: string; + entry?: boolean; + expose: string; + noparse?: boolean; + } + + interface InputTransform { + transform: string | (() => any); + options: any; + global?: boolean; + } + + interface TransformObject { + id: string; + file: string; + entry: boolean; + expose: string; + source: string; + deps: { [requireName: string]: any }; + } + + /** + * Placeholder, feel free to redefine or put in a pull request to improve + */ + interface PackageObject { + [prop: string]: any; + } +} + +export = moduleDeps; diff --git a/types/module-deps/module-deps-tests.ts b/types/module-deps/module-deps-tests.ts new file mode 100644 index 0000000000..e0930f8f88 --- /dev/null +++ b/types/module-deps/module-deps-tests.ts @@ -0,0 +1,95 @@ +import moduleDeps = require("module-deps"); + +function coreDepsTest() { + const coreDeps: { [prop: string]: any } = {}; + const coreModules = { + assert: "./assert.js", + buffer: "./buffer.js", + path: "./path.js" + }; + + const opts = { + resolve: () => { }, + modules: coreModules, + extensions: [".js", ".json"] + }; + + const s = moduleDeps(opts); + + s.on("data", (obj) => { + for (const dep of Object.keys(obj.deps)) { + if (dep in coreModules) { + coreDeps[dep] = true; + } + } + }); +} + +function rifiTest() { + const md = moduleDeps({ + resolve: (id, parent, cb) => { + const dependency = id.substr(1); + }, + transform: [], + globalTransform: [], + cache: {} + }); + + md.once("error", (err) => { + console.error(err); + }); +} + +function browserifyTest(opts: moduleDeps.Options) { + const packOpts: moduleDeps.Options = { + basedir: opts.basedir || "./", + externalRequireName: opts["externalRequireName"] || "require", + hasExports: opts["hasExports"] || false, + prelude: opts["prelude"] || undefined, + preludePath: opts["preludePath"] || undefined, + raw: opts["raw"] || false, + sourceMapPrefix: opts["sourceMapPrefix"] || "//#", + standalone: opts["standalone"] || undefined, + standaloneModule: opts["standaloneModule"] || undefined, + }; + + const res = moduleDeps(); // 'opts' are optional + const res2 = moduleDeps(packOpts); + + // ensure return value is a stream + const res3 = res.pipe(res2); + + res.on("error", (err: any) => { + console.error("module-deps error: ", err); + }); + + const inst: moduleDeps.ModuleDepsObject = moduleDeps({ + expose: { id: "file.txt" }, + extensions: [ ".js", ".json" ], + transform: [], + transformKey: ["browserify", "transform"], + filter: (id) => { + if (opts.filter && !opts.filter(id)) return false; + if (["name"].indexOf(id) >= 0) return false; + return true; + }, + postFilter: (id, file, pkg) => { + console.log("postFilter", id, file, pkg); + }, + globalTransform: [], + modules: {}, + resolve: (id, parent, cb) => { + cb(null, "", {}); + } + }); + + inst.on("file", (file, id) => { + console.log("file", file, id); + }); + inst.on("package", (pkg) => { + console.log("package", pkg); + }); + inst.on("transform", (tr, file) => { + console.log("transform", tr, file); + }); +} diff --git a/types/module-deps/tsconfig.json b/types/module-deps/tsconfig.json new file mode 100644 index 0000000000..5dd4af3cc1 --- /dev/null +++ b/types/module-deps/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", + "module-deps-tests.ts" + ] +} \ No newline at end of file diff --git a/types/module-deps/tslint.json b/types/module-deps/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/module-deps/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 79b5c553fb..5963be87ed 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mongoose 5.2.13 +// Type definitions for Mongoose 5.3.4 // Project: http://mongoosejs.com/ // Definitions by: horiuchi // sindrenm @@ -13,7 +13,9 @@ // Idan Dardikman // Dominik Heigl // Fazendaaa +// Norman Perrin // Dan Manastireanu +// stablio // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -391,6 +393,8 @@ declare module "mongoose" { useNewUrlParser?: boolean; /** Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify(). */ useFindAndModify?: boolean; + /** If true, this connection will use createIndex() instead of ensureIndex() for automatic index builds via Model.init(). */ + useCreateIndex?: boolean; // TODO safe?: any; @@ -409,11 +413,6 @@ declare module "mongoose" { * models associated with this connection. */ autoIndex?: boolean; - - /** - * If true, this connection will use createIndex() instead of ensureIndex() for automatic index builds via Model.init(). - */ - useCreateIndex?: boolean; }; } @@ -480,15 +479,6 @@ declare module "mongoose" { static STATES: any; } - /* - * section error/validation.js - * http://mongoosejs.com/docs/api.html#error-validation-js - */ - class ValidationError extends Error { - /** Console.log helper */ - toString(): string; - } - /* * section error.js * http://mongoosejs.com/docs/api.html#error-js @@ -513,6 +503,143 @@ declare module "mongoose" { /** For backwards compatibility. Same as mongoose.Error.messages */ static Messages: any; + + } + + module Error { + + /** + * 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 + * conditions that mongoose passed to `update()` when trying to update + * the document. + */ + export class DocumentNotFoundError extends Error { + } + + /** + * 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. + */ + export class CastError extends Error { + stringValue: string; + kind: string; + path: string; + value: any; + reason?: any; + model?: any; + + constructor(type: string, value: any, path: string, reason?: NativeError); + + setModel(model: any): void; + } + + /** + * 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 { + errors: any; + + constructor(instance: MongooseDocument); + + /** Console.log helper */ + toString(): string; + + inspect(): object; + + toJSON(): object; + + addError(path: string, error: any): void; + } + + /** + * 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 { + properties: any; + kind: string; + path: string; + value: any; + reason: any; + + constructor(properties: any); + + formatMessage(msg: string | Function, properties: any): string; + + toString(): string; + } + + /** + * 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. + */ + export class VersionError extends Error { + version: any; + modifiedPaths: Array; + + constructor(doc: MongooseDocument, currentVersion: any, modifiedPaths: any); + } + + /** + * 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. + */ + export class ParallelSaveError extends Error { + constructor(doc: MongooseDocument); + } + + /** + * 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). + */ + export class OverwriteModelError extends Error { + constructor(name: string); + } + + /** + * 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 { + constructor(name: string); + } + + /** + * 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. + */ + export class DivergentArrayError extends Error { + constructor(paths: Array); + } } interface EachAsyncOptions { @@ -1168,7 +1295,7 @@ declare module "mongoose" { * @param kind optional kind property for the error * @returns the current ValidationError, with all currently invalidated paths */ - invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): ValidationError | boolean; + invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): Error.ValidationError | boolean; /** Returns true if path was directly set and modified, else false. */ isDirectModified(path: string): boolean; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index a57d3d085a..c8873f85b3 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -22,12 +22,12 @@ const connection2: Promise = mongoose.connect(connectUri, { pass: 'housan', config: { autoIndex: true, - useCreateIndex: true, }, mongos: true, bufferCommands: false, useNewUrlParser: true, useFindAndModify: true, + useCreateIndex: true }); const connection3: null = mongoose.connect(connectUri, function (error) { error.stack; @@ -166,17 +166,6 @@ const getDB = async (tenant: string)=> { return conn1.useDb(tenant); }; - -/* - * section error/validation.js - * http://mongoosejs.com/docs/api.html#error-validation-js - */ -var validationError = {}; -validationError.toString().toLowerCase(); -/* inherited properties */ -validationError.stack; -validationError.message; - /* * section error.js * http://mongoosejs.com/docs/api.html#error-js @@ -190,6 +179,93 @@ mongooseError.stack; mongoose.Error.messages.hasOwnProperty(''); mongoose.Error.Messages.hasOwnProperty(''); +/* + * section error/cast.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError + */ +var castError: mongoose.Error.CastError = new mongoose.Error.CastError('', '', ''); +castError.setModel('foo'); +castError.stringValue; +castError.kind; +castError.path; +castError.value; +/* inherited properties */ +castError.name; +castError.stack; +castError.message; + +/* + * section error/validator.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidatorError + */ +var validatorError: mongoose.Error.ValidatorError = new mongoose.Error.ValidatorError({ foo: 'bar' }) +validatorError.properties; +validatorError.kind; +validatorError.path; +validatorError.value; +validatorError.toString().toLowerCase(); +validatorError.formatMessage('foo', {}); +validatorError.formatMessage('foo', (bar: any)=>{ return bar; }); +/* inherited properties */ +validatorError.name; +validatorError.stack; +validatorError.message; + +/* + * section error/validation.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidationError + */ +var doc = {}; +var validationError: mongoose.Error.ValidationError = new mongoose.Error.ValidationError(doc); +validationError.toString().toLowerCase(); +validationError.inspect(); +validationError.toJSON().hasOwnProperty(''); +validationError.addError('foo', validatorError) +/* inherited properties */ +validationError.name; +validationError.stack; +validationError.message; + +/* + * section error/parallelSave.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ParallelSaveError + */ +var parallelSaveError: mongoose.Error.ParallelSaveError = new mongoose.Error.ParallelSaveError(doc); +/* inherited properties */ +parallelSaveError.name; +parallelSaveError.stack; +parallelSaveError.message; + +/* + * section error/overwriteModel.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.OverwriteModelError + */ +var overwriteModelError: mongoose.Error.OverwriteModelError = new mongoose.Error.OverwriteModelError('foo'); +/* inherited properties */ +overwriteModelError.name; +overwriteModelError.stack; +overwriteModelError.message; + +/* + * section error/missingSchema.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError + */ +var missingSchemaError: mongoose.Error.MissingSchemaError = new mongoose.Error.MissingSchemaError('foo'); +/* inherited properties */ +missingSchemaError.name; +missingSchemaError.stack; +missingSchemaError.message; + +/* + * section error/divergentArray.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError + */ +var missingSchemaError: mongoose.Error.DivergentArrayError = new mongoose.Error.DivergentArrayError(['foo','bar']); +/* inherited properties */ +missingSchemaError.name; +missingSchemaError.stack; +missingSchemaError.message; + const pluralize = mongoose.pluralize(); const plural: string = pluralize('foo'); diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 99d3f5b45d..88d44b169a 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -73,7 +73,9 @@ declare module "node-forge" { prng?: any; algorithm?: string; } - + + function setPublicKey(n: any, e: any): any; + function generateKeyPair(bits?: number, e?: number, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; function generateKeyPair(options?: GenerateKeyPairOptions, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; } @@ -141,7 +143,8 @@ declare module "node-forge" { hash: any; }; extensions: any[]; - publicKey: any; + privateKey: Key; + publicKey: Key; md: any; /** * Sets the subject of this certificate. @@ -198,6 +201,16 @@ declare module "node-forge" { function decryptRsaPrivateKey(pem: PEM, passphrase?: string): Key; function createCertificate(): Certificate; + + function certificationRequestToPem(cert: Certificate, maxline?: number): PEM; + + function certificationRequestFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; + + function createCertificationRequest(): Certificate; + + function publicKeyToAsn1(publicKey: Key): any; + + function publicKeyToRSAPublicKey(publicKey: Key): any; } namespace ssh { @@ -411,6 +424,7 @@ declare module "node-forge" { function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string): Pkcs12Pfx; function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx; } + namespace pkcs7 { interface PkcsSignedData { content?: string | util.ByteBuffer; @@ -446,6 +460,10 @@ declare module "node-forge" { namespace sha256 { function create(): MessageDigest; } + + namespace sha512 { + function create(): MessageDigest; + } namespace md5 { function create(): MessageDigest; @@ -470,4 +488,14 @@ declare module "node-forge" { output: util.ByteStringBuffer; } } + + namespace pss { + function create(any: any): any; + } + + namespace mgf { + namespace mgf1 { + function create(any: any): any; + } + } } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index e24fdb4438..ee3fdad616 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -5666,7 +5666,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, * until an absolute path is found. If after using all {from} paths still no absolute path is found, diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index 2e91826cc8..1f29bbcc10 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -1483,7 +1483,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index a241b8b87e..26210a1857 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -2055,7 +2055,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 98b3f503c6..250a7b6640 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -3040,7 +3040,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index b834d238d4..55cea44126 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -3065,7 +3065,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index e0f904b1b0..d0497223dc 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -4770,7 +4770,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 1ea05db2b0..e7a6c41b10 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -4856,7 +4856,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/nodegit/repository.d.ts b/types/nodegit/repository.d.ts index 20da9ce052..710c0531cd 100644 --- a/types/nodegit/repository.d.ts +++ b/types/nodegit/repository.d.ts @@ -78,7 +78,7 @@ export class Repository { /** * Creates a branch with the passed in name pointing to the commit */ - createBranch(name: string, commit: Commit | string | Oid, force: boolean): Promise; + createBranch(name: string, commit: Commit | string | Oid, force?: boolean): Promise; /** * Look up a refs's commit. */ @@ -175,7 +175,7 @@ export class Repository { * Fetches from all remotes. This is done in series due to deadlocking issues with fetching from many remotes that can happen. */ fetchAll(fetchOptions?: FetchOptions, callback?: Function): Promise; - mergeBranches(to: string | Reference, from: string | Reference, signature: Signature, mergePreference: Merge.PREFERENCE, mergeOptions?: MergeOptions): Promise; + mergeBranches(to: string | Reference, from: string | Reference, signature?: Signature, mergePreference?: Merge.PREFERENCE, mergeOptions?: MergeOptions): Promise; /** * Rebases a branch onto another branch */ diff --git a/types/normalize-url/index.d.ts b/types/normalize-url/index.d.ts index ec70be130b..fd76c4f72a 100644 --- a/types/normalize-url/index.d.ts +++ b/types/normalize-url/index.d.ts @@ -1,14 +1,20 @@ -// Type definitions for normalize-url 1.9 +// Type definitions for normalize-url 3.3 // Project: https://github.com/sindresorhus/normalize-url // Definitions by: odin3 // BendingBender +// Mathieu M-Gosselin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace normalizeUrl { interface Options { + defaultProtocol?: string; + forceHttp?: boolean; + forceHttps?: boolean; normalizeProtocol?: boolean; normalizeHttps?: boolean; + sortQueryParameters?: boolean; stripFragment?: boolean; + stripHash?: boolean; stripWWW?: boolean; removeQueryParameters?: Array; removeTrailingSlash?: boolean; diff --git a/types/npm-package-arg/index.d.ts b/types/npm-package-arg/index.d.ts index bb1a0d8550..d83c95a6a7 100644 --- a/types/npm-package-arg/index.d.ts +++ b/types/npm-package-arg/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for npm-package-arg 5.1 +// Type definitions for npm-package-arg 6.1 // Project: https://github.com/npm/npm-package-arg // Definitions by: Melvin Groenhoff +// Jason // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /** * Throws if the package name is invalid, a dist-tag is invalid or a URL's protocol is not supported. @@ -20,7 +22,12 @@ declare namespace npa { * Something like: 1.2, ^1.7.17, http://x.com/foo.tgz, git+https://github.com/user/foo, bitbucket:user/foo, file:foo.tar.gz or file:../foo/bar/. If not included then the default is latest. * @param where Optionally the path to resolve file paths relative to. Defaults to process.cwd() */ - function resolve(name: string, spec: string, where?: string): Result; + function resolve(name: string, spec: string, where?: string): + FileResult | + HostedGitResult | + URLResult | + AliasResult | + RegistryResult; class Result { /** @@ -33,52 +40,95 @@ declare namespace npa { * * directory - A local directory. * * remote - An http url (presumably to a tgz) */ - type: "git" | "tag" | "version" | "range" | "file" | "directory" | "remote"; - /** - * If true this specifier refers to a resource hosted on a registry. This is true for tag, version and range types. - */ + type: + | "git" + | "tag" + | "version" + | "range" + | "file" + | "directory" + | "remote" + | "alias"; + + /** If true this specifier refers to a resource hosted on a registry. This is true for tag, version and range types. */ registry: boolean; - /** - * If known, the name field expected in the resulting pkg. - */ + + /** If known, the name field expected in the resulting pkg. */ name: string | null; - /** - * If a name is something like @org/module then the scope field will be set to @org. If it doesn't have a scoped name, then scope is null. - */ + + /** If a name is something like @org/module then the scope field will be set to @org. If it doesn't have a scoped name, then scope is null. */ scope: string | null; - /** - * A version of name escaped to match the npm scoped packages specification. Mostly used when making requests against a registry. When name is null, escapedName will also be null. - */ + + /** A version of name escaped to match the npm scoped packages specification. Mostly used when making requests against a registry. When name is null, escapedName will also be null. */ escapedName: string | null; - /** - * The specifier part that was parsed out in calls to npa(arg), or the value of spec in calls to `npa.resolve(name, spec). - */ + + /** The specifier part that was parsed out in calls to npa(arg), or the value of spec in calls to `npa.resolve(name, spec). */ rawSpec: string; - /** - * The normalized specifier, for saving to package.json files. null for registry dependencies. - */ + + /** The normalized specifier, for saving to package.json files. null for registry dependencies. */ saveSpec: string | null; - /** - * The version of the specifier to be used to fetch this resource. null for shortcuts to hosted git dependencies as there isn't just one URL to try with them. - */ + + /** The version of the specifier to be used to fetch this resource. null for shortcuts to hosted git dependencies as there isn't just one URL to try with them. */ fetchSpec: string | null; - /** - * If set, this is a semver specifier to match against git tags with - */ + + /** If set, this is a semver specifier to match against git tags with */ gitRange?: string; - /** - * If set, this is the specific committish to use with a git dependency. - */ + + /** If set, this is the specific committish to use with a git dependency. */ gitCommittish?: string; - /** - * If from === 'hosted' then this will be a hosted-git-info object. This property is not included when serializing the object as JSON. - */ - hosted?: any; - /** - * The original un-modified string that was provided. If called as npa.resolve(name, spec) then this will be name + '@' + spec. - */ + + /** If from === 'hosted' then this will be a hosted-git-info object. This property is not included when serializing the object as JSON. */ + hosted?: HostedGit; + + /** The original un-modified string that was provided. If called as npa.resolve(name, spec) then this will be name + '@' + spec. */ raw: string; } + + interface FileResult extends Result { + type: "file" | "directory"; + where: string; + saveSpec: string; + fetchSpec: null | string; + } + + interface HostedGitResult extends Result { + type: "git"; + hosted: HostedGit; + saveSpec: string; + fetchSpec: null | string; + gitRange: undefined | string; + gitCommittish: undefined | string; + } + + interface URLResult extends Result { + saveSpec: string; + type: "git" | "remote"; + fetchSpec: string; + gitCommittish: string | undefined; + gitRange: string | undefined; + } + + interface AliasResult extends Result { + subSpec: Result; + registry: true; + type: "alias"; + saveSpec: null; + fetchSpec: null; + } + + interface RegistryResult extends Result { + registry: true; + type: "version" | "range" | "tag"; + saveSpec: null; + fetchSpec: string; + } + + interface HostedGit { + type: string; + domain: string; + user: string; + project: string; + } } export = npa; diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 98e296cfd9..d6dd662105 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1035,6 +1035,10 @@ declare namespace Office { * 12007 * A dialog box is already opened from the task pane. A task pane add-in can only have one dialog box open at a time. * + * + * 12009 + * The user chose to ignore the dialog box. This error can occur in online versions of Office, where users may choose not to allow an add-in to present a dialog. + * * * * In the callback function passed to the displayDialogAsync method, you can use the properties of the AsyncResult object to return the @@ -1212,7 +1216,7 @@ declare namespace Office { * * Example: `[{cells: Office.Table.Data, format: {fontColor: "yellow"}}, {cells: {row: 3, column: 4}, format: {borderColor: "white", fontStyle: "bold"}}]` */ - cellFormat?: Array + cellFormat?: RangeFormatConfiguration[] /** * Explicitly sets the shape of the data object. If not supplied is inferred from the data type. */ @@ -1220,7 +1224,7 @@ declare namespace Office { /** * Only for table bindings in content add-ins for Access. Array of strings. Specifies the column names. */ - columns?: Array + columns?: string[] /** * Only for table bindings in content add-ins for Access. Specifies the pre-defined string "thisRow" to get data in the currently selected row. */ @@ -1334,7 +1338,7 @@ declare namespace Office { /** * The names of the columns involved in the binding. */ - columns?: Array + columns?: string[] /** * A user-defined item of any type that is returned, unchanged, in the asyncContext property of the AsyncResult object that is passed to a callback. */ @@ -1407,7 +1411,7 @@ declare namespace Office { * * Example: `[\{cells: Office.Table.Data, format: \{fontColor: "yellow"\}\}, \{cells: \{row: 3, column: 4\}, format: \{borderColor: "white", fontStyle: "bold"\}\}]` */ - cellFormat?: Array + cellFormat?: RangeFormatConfiguration[] /** * Explicitly sets the shape of the data object. If not supplied is inferred from the data type. */ @@ -7376,7 +7380,12 @@ declare namespace Office { /** * The content of the attachment is returned as a string representing an .eml formatted file. */ - Eml = "eml" + Eml = "eml", + + /** + * The content of the attachment is returned as a string representing an .icalendar formatted file. + */ + ICalendar = "iCalendar" } /** * Specifies whether an attachment was added to or removed from an item. @@ -8574,8 +8583,13 @@ declare namespace Office { content: string; /** * The string format to use for an attachment's content. - * For file attachments, the formatting is a base64-encoded string. - * For item attachments that represent messages, the formatting is a string representing an .eml formatted file. + * + * For file attachments, the formatting is a base64-encoded string. + * + * For item attachments that represent messages, the formatting is a string representing an .eml formatted file. + * + * For item attachments that represent calendar items, the formatting is a string representing an .icalendar file. + * * For cloud attachments, the formatting is a URL string. */ format: Office.MailboxEnums.AttachmentContentFormat; @@ -8701,7 +8715,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8735,7 +8749,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8759,7 +8773,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8780,7 +8794,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8800,7 +8814,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8835,7 +8849,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8860,7 +8874,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8884,7 +8898,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8907,7 +8921,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8942,7 +8956,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8967,7 +8981,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8991,7 +9005,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -9024,7 +9038,7 @@ declare namespace Office { /** * An array of strings containing the mailing and street addresses associated with the contact. Nullable. */ - addresses: Array; + addresses: string[]; /** * A string containing the name of the business associated with the contact. Nullable. */ @@ -9032,7 +9046,7 @@ declare namespace Office { /** * An array of strings containing the SMTP email addresses associated with the contact. Nullable, */ - emailAddresses: Array; + emailAddresses: string[]; /** * A string containing the name of the person associated with the contact. Nullable. */ @@ -9040,11 +9054,11 @@ declare namespace Office { /** * An array containing a PhoneNumber object for each phone number associated with the contact. Nullable. */ - phoneNumbers: Array; + phoneNumbers: PhoneNumber[]; /** * An array of strings containing the Internet URLs associated with the contact. Nullable. */ - urls: Array; + urls: string[]; } /** * The CustomProperties object represents custom properties that are specific to a particular item and specific to a mail add-in for Outlook. @@ -15086,7 +15100,7 @@ declare namespace Office { */ restUrl: string; /** - * Information about the user associated with the mailbox. This includes their account type, display name, email adddress, and time zone. + * Information about the user associated with the mailbox. This includes their account type, display name, email address, and time zone. * * More information is under {@link Office.UserProfile} */ @@ -17150,7 +17164,7 @@ declare namespace Office { } /** - * Information about the user associated with the mailbox. This includes their account type, display name, email adddress, and time zone. + * Information about the user associated with the mailbox. This includes their account type, display name, email address, and time zone. * * [Api set: Mailbox 1.0] * @@ -17486,7 +17500,7 @@ declare namespace OfficeExtension { * If there was an error, this contains all trace messages that were executed before the error occurred. * These messages can help you monitor the program execution sequence and detect the case of the error. */ - traceMessages: Array; + traceMessages: string[]; /** Debug info (useful for detailed logging of the error, i.e., via `JSON.stringify(...)`). */ debugInfo: DebugInfo; /** Inner error, if applicable. */ @@ -20273,7 +20287,7 @@ declare namespace Excel { * @param key The Key of the new setting. * @param value The Value for the new setting. */ - add(key: string, value: string | number | boolean | Date | Array | any): Excel.Setting; + add(key: string, value: string | number | boolean | Date | any[] | any): Excel.Setting; /** * * Gets the number of Settings in the collection. diff --git a/types/on-wake-up/index.d.ts b/types/on-wake-up/index.d.ts new file mode 100644 index 0000000000..c9568404b8 --- /dev/null +++ b/types/on-wake-up/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for on-wake-up 1.0 +// Project: https://github.com/mafintosh/on-wake-up +// Definitions by: Klaus Meinhardt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Register a callback when the device presumably wakes up from sleep. + * @param cb The callback to execute + * @returns Function to unregister the callback + */ +declare function onWakeUp(cb: () => void): () => void; + +export = onWakeUp; diff --git a/types/on-wake-up/on-wake-up-tests.ts b/types/on-wake-up/on-wake-up-tests.ts new file mode 100644 index 0000000000..985d415063 --- /dev/null +++ b/types/on-wake-up/on-wake-up-tests.ts @@ -0,0 +1,4 @@ +import onWakeUp = require('on-wake-up'); + +const unregister = onWakeUp(() => void 0); +unregister(); diff --git a/types/on-wake-up/tsconfig.json b/types/on-wake-up/tsconfig.json new file mode 100644 index 0000000000..691fba15c1 --- /dev/null +++ b/types/on-wake-up/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", + "on-wake-up-tests.ts" + ] +} diff --git a/types/on-wake-up/tslint.json b/types/on-wake-up/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/on-wake-up/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/onoff/index.d.ts b/types/onoff/index.d.ts index 55701976a9..f4eba3ffb6 100644 --- a/types/onoff/index.d.ts +++ b/types/onoff/index.d.ts @@ -28,6 +28,8 @@ declare namespace __ONOFF { options?: GpioOptions ); + static accessible: boolean; + gpio: number; gpioPath: string; opts: GpioOptions; diff --git a/types/onoff/onoff-tests.ts b/types/onoff/onoff-tests.ts index 21b47e7f99..776b577348 100644 --- a/types/onoff/onoff-tests.ts +++ b/types/onoff/onoff-tests.ts @@ -14,3 +14,5 @@ setTimeout(function() { led.writeSync(0); led.unexport(); }, 2000); + +var accessible:boolean = onoff.Gpio.accessible; diff --git a/types/opossum/index.d.ts b/types/opossum/index.d.ts index f1e14a939b..b955f940e3 100644 --- a/types/opossum/index.d.ts +++ b/types/opossum/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for opossum 1.8 -// Project: https://github.com/bucharest-gold/opossum +// Type definitions for opossum 1.9 +// Project: https://github.com/nodeshift/opossum // Definitions by: Quinn Langille +// Lance Ball // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -31,6 +32,7 @@ export class CircuitBreaker { static readonly hystrixStats: symbol; static readonly enabled: symbol; static readonly warmUp: symbol; + static readonly volumeThreshold: symbol; } export interface CircuitBreakerOptions { @@ -45,6 +47,7 @@ export interface CircuitBreakerOptions { errorThresholdPercentage?: number; enabled?: boolean; allowWarmUp?: boolean; + volumeThreshold?: number; } export default function circuitBreaker( diff --git a/types/opossum/opossum-tests.ts b/types/opossum/opossum-tests.ts index 3f020eff52..9ec5425416 100644 --- a/types/opossum/opossum-tests.ts +++ b/types/opossum/opossum-tests.ts @@ -17,7 +17,8 @@ const options: CircuitBreakerOptions = { capacity: 1, errorThresholdPercentage: 1, enabled: true, - allowWarmUp: true + allowWarmUp: true, + volumeThreshold: 1 }; const testWithOptions: CircuitBreaker = circuitBreaker(_blank, options); @@ -44,3 +45,4 @@ const shouldBeSymbol7: symbol = CircuitBreaker.hystrixStats; const shouldBeSymbol8: symbol = CircuitBreaker.status; const shouldBeSymbol9: symbol = CircuitBreaker.enabled; const shouldBeSymbol10: symbol = CircuitBreaker.warmUp; +const shouldBeSymbol11: symbol = CircuitBreaker.volumeThreshold; diff --git a/types/p-wait-for/index.d.ts b/types/p-wait-for/index.d.ts index 5e8f88d413..d7fa76e016 100644 --- a/types/p-wait-for/index.d.ts +++ b/types/p-wait-for/index.d.ts @@ -1,8 +1,15 @@ -// Type definitions for p-wait-for 1.0 +// Type definitions for p-wait-for 2.0 // Project: https://github.com/sindresorhus/p-wait-for#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = pWaitFor; -declare function pWaitFor(condition: () => PromiseLike | boolean, interval?: number): Promise; +declare function pWaitFor(condition: () => PromiseLike | boolean, options?: pWaitFor.Options): Promise; + +declare namespace pWaitFor { + interface Options { + interval?: number; + timeout?: number; + } +} diff --git a/types/p-wait-for/p-wait-for-tests.ts b/types/p-wait-for/p-wait-for-tests.ts index 587d08d5a5..ef23ef6526 100644 --- a/types/p-wait-for/p-wait-for-tests.ts +++ b/types/p-wait-for/p-wait-for-tests.ts @@ -1,6 +1,8 @@ import pWaitFor = require('p-wait-for'); pWaitFor(() => Promise.resolve(false)).then(() => {}); -pWaitFor(() => Promise.resolve(true), 1).then(() => {}); +pWaitFor(() => Promise.resolve(true), { interval: 1 }).then(() => {}); +pWaitFor(() => Promise.resolve(true), { timeout: 1 }).then(() => {}); pWaitFor(() => false).then(() => {}); -pWaitFor(() => true, 1).then(() => {}); +pWaitFor(() => true, { interval: 1 }).then(() => {}); +pWaitFor(() => true, { timeout: 1 }).then(() => {}); diff --git a/types/p5/lib/addons/p5.sound.d.ts b/types/p5/lib/addons/p5.sound.d.ts index 6a057b6289..faa16f7e1b 100644 --- a/types/p5/lib/addons/p5.sound.d.ts +++ b/types/p5/lib/addons/p5.sound.d.ts @@ -1990,7 +1990,7 @@ declare module "../../index" { * Reverb adds depth to a sound through a large * number of decaying echoes. It creates the * perception that sound is occurring in a physical - * space. The p5.Reverb has paramters for Time (how + * space. The p5.Reverb has parameters for Time (how * long does the reverb last) and decayRate (how much * the sound decays with each echo) that can be set * with the .set() or .process() methods. The @@ -2511,7 +2511,7 @@ declare module "../../index" { maxIterations: number; /** - * Getters and Setters, setting any paramter will + * Getters and Setters, setting any parameter will * result in a change in the clock's frequency, that * will be reflected after the next callback beats * per minute (defaults to 60) @@ -2588,7 +2588,7 @@ declare module "../../index" { ): void; /** - * Set the paramters of a compressor. + * Set the parameters of a compressor. * @param attack The amount of time (in seconds) to * reduce the gain by 10dB, default = .003, range 0 - * 1 diff --git a/types/paho-mqtt/index.d.ts b/types/paho-mqtt/index.d.ts index fed67ff262..b1fac43793 100644 --- a/types/paho-mqtt/index.d.ts +++ b/types/paho-mqtt/index.d.ts @@ -4,9 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// +export = Paho.MQTT; -declare namespace Paho { +declare global { /** * Send and receive messages using web browsers. *

@@ -40,7 +40,7 @@ declare namespace Paho { * an error with any parameter. *

*/ - namespace MQTT { + namespace Paho.MQTT { /** * The Quality of Service used to deliver a message. *

diff --git a/types/paho-mqtt/module.d.ts b/types/paho-mqtt/module.d.ts deleted file mode 100644 index 8ab421779f..0000000000 --- a/types/paho-mqtt/module.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for paho-mqtt 1.0 -// Project: https://github.com/eclipse/paho.mqtt.javascript#readme -// Definitions by: Alex Mikhalev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'paho-mqtt' { - export = Paho.MQTT; -} diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index 4e52dd66a4..c7246ecb1f 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -7,6 +7,7 @@ // Alberto Restifo // Behind The Math // 3af +// Janne Liuhtonen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -23,7 +24,7 @@ export function parse(file: File, config?: ParseConfig): ParseResult; export function parse(stream: NodeJS.ReadableStream, config?: ParseConfig): ParseResult; -export function parse(stream: typeof NODE_STREAM_INPUT, config?: ParseConfig): NodeJS.ReadableStream; +export function parse(stream: typeof NODE_STREAM_INPUT, config?: ParseConfig): NodeJS.ReadWriteStream; /** * Unparses javascript data objects and returns a csv string diff --git a/types/papaparse/papaparse-tests.ts b/types/papaparse/papaparse-tests.ts index 5db22091ca..57115dc0d5 100644 --- a/types/papaparse/papaparse-tests.ts +++ b/types/papaparse/papaparse-tests.ts @@ -9,6 +9,7 @@ import { ParseMeta, ParseResult } from "papaparse"; +import { Readable } from "stream"; /** * Parsing @@ -40,8 +41,19 @@ Papa.parse(file, { } }); +const readable = new Readable() +const rows = [ + "1,2,3", + "4,5,6" +] -Papa.parse(Papa.NODE_STREAM_INPUT); +rows.forEach(r => { + readable.push(r); +}); + +const papaStream: NodeJS.ReadWriteStream = Papa.parse(Papa.NODE_STREAM_INPUT); + +readable.pipe(papaStream); /** * Unparsing diff --git a/types/passport-github2/index.d.ts b/types/passport-github2/index.d.ts index 91adbb6567..0b2c1f6a5d 100644 --- a/types/passport-github2/index.d.ts +++ b/types/passport-github2/index.d.ts @@ -21,7 +21,6 @@ export interface StrategyOption extends passport.AuthenticateOptions { scope?: string[]; userAgent?: string; - state?: boolean; authorizationURL?: string; tokenURL?: string; @@ -42,7 +41,7 @@ export interface _StrategyOptionsBase extends OAuth2StrategyOptionsWithoutRequir scope?: string[]; userAgent?: string; - state?: boolean; + state?: string; authorizationURL?: string; tokenURL?: string; diff --git a/types/passport/index.d.ts b/types/passport/index.d.ts index fe0c26c775..1a8afed691 100644 --- a/types/passport/index.d.ts +++ b/types/passport/index.d.ts @@ -45,6 +45,7 @@ declare namespace passport { successMessage?: boolean | string; successRedirect?: string; successReturnToOrRedirect?: string; + state?: string; pauseStream?: boolean; userProperty?: string; passReqToCallback?: boolean; diff --git a/types/paypal-rest-sdk/index.d.ts b/types/paypal-rest-sdk/index.d.ts index 414c3fa0f5..d6457fc981 100644 --- a/types/paypal-rest-sdk/index.d.ts +++ b/types/paypal-rest-sdk/index.d.ts @@ -162,7 +162,7 @@ export interface Transaction { }; notify_url?: string; order_url?: string; - readonly related_resources?: RelatedResources; + readonly related_resources?: RelatedResources[]; } export interface Payee { diff --git a/types/pdfmake/index.d.ts b/types/pdfmake/index.d.ts index fdc0a9de05..a812611400 100644 --- a/types/pdfmake/index.d.ts +++ b/types/pdfmake/index.d.ts @@ -2,7 +2,9 @@ // Project: http://pdfmake.org // Definitions by: Milen Stefanov // Rajab Shakirov +// Enzo Volkmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 declare module 'pdfmake/build/vfs_fonts' { let pdfMake: { @@ -16,15 +18,61 @@ declare module 'pdfmake/build/pdfmake' { let fonts: { [name: string]: TFontFamilyTypes }; function createPdf(documentDefinitions: TDocumentDefinitions): TCreatedPdf; - type pageSizeType = - '4A0' | '2A0' | 'A0' | 'A1' | 'A2' | 'A3' | 'A4' | 'A5' | 'A6' | 'A7' | 'A8' | 'A9' | 'A10' | - 'B0' | 'B1' | 'B2' | 'B3' | 'B4' | 'B5' | 'B6' | 'B7' | 'B8' | 'B9' | 'B10' | - 'C0' | 'C1' | 'C2' | 'C3' | 'C4' | 'C5' | 'C6' | 'C7' | 'C8' | 'C9' | 'C10' | - 'RA0' | 'RA1' | 'RA2' | 'RA3' | 'RA4' | - 'SRA0' | 'SRA1' | 'SRA2' | 'SRA3' | 'SRA4' | - 'EXECUTIVE' | 'FOLIO' | 'LEGAL' | 'LETTER' | 'TABLOID'; + enum PageSize { + A0_x_4 = '4A0', + A0_x_2 = '2A0', + AO = 'A0', + A1 = 'A1', + A2 = 'A2', + A3 = 'A3', + A4 = 'A4', + A5 = 'A5', + A6 = 'A6', + A7 = 'A7', + A8 = 'A8', + A9 = 'A9', + A1O = 'A10', + BO = 'B0', + B1 = 'B1', + B2 = 'B2', + B3 = 'B3', + B4 = 'B4', + B5 = 'B5', + B6 = 'B6', + B7 = 'B7', + B8 = 'B8', + B9 = 'B9', + B1O = 'B10', + CO = 'C0', + C1 = 'C1', + C2 = 'C2', + C3 = 'C3', + C4 = 'C4', + C5 = 'C5', + C6 = 'C6', + C7 = 'C7', + C8 = 'C8', + C9 = 'C9', + C1O = 'C10', + RA1 = 'RA1', + RA2 = 'RA2', + RA3 = 'RA3', + RA4 = 'RA4', + SRA1 = 'SRA1', + SRA2 = 'SRA2', + SRA3 = 'SRA3', + SRA4 = 'SRA4', + EXECUTIVE = 'EXECUTIVE', + FOLIO = 'FOLIO', + LEGAL = 'LEGAL', + LETTER = 'LETTER', + TABLOID = 'TABLOID' + } - type pageOrientationType = "portrait" | "landscape"; + enum PageOrientation { + PORTRAIT = 'PORTRAIT', + LANDSCAPE = 'LANDSCAPE' + } let pdfMake: pdfMakeStatic; @@ -48,18 +96,90 @@ declare module 'pdfmake/build/pdfmake' { type TDocumentHeaderFooterFunction = (currentPage: number, pageCount: number) => any; + type Margins = number | [number, number] | [number, number, number, number]; + + type Alignment = 'left' | 'right' | 'justify' | 'center' | string; + + interface Style { + font?: any; + fontSize?: number; + fontFeatures?: any; + bold?: boolean; + italics?: boolean; + alignment?: Alignment; + color?: string; + columnGap?: any; + fillColor?: string; + decoration?: any; + decorationany?: any; + decorationColor?: string; + background?: any; + lineHeight?: number; + characterSpacing?: number; + noWrap?: boolean; + markerColor?: string; + leadingIndent?: any; + [additionalProperty: string]: any; + } + + type TableRowFunction = (row: number) => number; + + interface TableLayoutFunctions { + hLineWidth?: (i: number, node: any) => number; + vLineWidth?: (i: number, node: any) => number; + hLineColor?: (i: number, node: any) => string; + vLineColor?: (i: number, node: any) => string; + fillColor?: (i: number, node: any) => string; + paddingLeft?: (i: number, node: any) => number; + paddingRight?: (i: number, node: any) => number; + paddingTop?: (i: number, node: any) => number; + paddingBottom?: (i: number, node: any) => number; + } + + interface TableCell { + text: string; + rowSpan?: number; + colSpan?: number; + fillColor?: string; + border?: [boolean, boolean, boolean, boolean]; + } + + interface Table { + widths?: Array<(string | number)>; + heights?: Array<(string | number)> | TableRowFunction; + headerRows?: number; + body: Content[][] | TableCell[][]; + layout?: string | TableLayoutFunctions; + } + + interface Content { + style?: 'string'; + margin?: Margins; + text?: string | string[] | Content[]; + columns?: Content[]; + stack?: Content[]; + image?: string; + width?: string | number; + height?: string | number; + fit?: [number, number]; + pageBreak?: 'before' | 'after'; + alignment?: Alignment; + table?: Table; + ul?: Content[]; + ol?: Content[]; + [additionalProperty: string]: any; + } + interface TDocumentDefinitions { info?: TDocumentInformation; - header?: any; - footer?: any; - content: any; - styles?: any; - pageSize?: pageSizeType; - pageOrientation?: pageOrientationType; - pageMargins?: [number, number, number, number]; - defaultStyle?: { - font?: string; - }; + header?: TDocumentHeaderFooterFunction; + footer?: TDocumentHeaderFooterFunction; + content: string | Content; + styles?: Style; + pageSize?: PageSize; + pageOrientation?: PageOrientation; + pageMargins?: Margins; + defaultStyle?: Style; } type CreatedPdfParams = ( diff --git a/types/pdfmake/pdfmake-tests.ts b/types/pdfmake/pdfmake-tests.ts index 0f23e5c5d5..1913e3fe8a 100644 --- a/types/pdfmake/pdfmake-tests.ts +++ b/types/pdfmake/pdfmake-tests.ts @@ -1,10 +1,1330 @@ import * as pdfMake from 'pdfmake/build/pdfmake'; import * as pdfFonts from 'pdfmake/build/vfs_fonts'; -const docDefinition = { content: 'This is an sample PDF printed with pdfMake' }; +const definitions = [ + { + content: [ + 'First paragraph', + 'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines' + ] + }, + { + content: [ + { + text: 'This is a header, using header style', + style: 'header' + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n', + { + text: 'Subheader 1 - using subheader style', + style: 'subheader' + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n', + { + text: 'Subheader 2 - using subheader style', + style: 'subheader' + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n', + { + text: 'It is possible to apply multiple styles, ', + style: ['quote', 'small'] + } + ], + styles: { + header: { + fontSize: 18, + bold: true + }, + subheader: { + fontSize: 15, + bold: true + }, + quote: { + italics: true + }, + small: { + fontSize: 8 + } + } + }, + { + content: [ + { + text: 'This is a header (whole paragraph uses the same header style)\n\n', + style: 'header' + }, + { + text: [ + 'It is however possible to provide an array of texts ', + 'to the paragraph (instead of a single string) and have ', + { text: 'a better ', fontSize: 15, bold: true }, + 'control over it. \nEach inline can be ', + { text: 'styled ', fontSize: 20 }, + { text: 'independently ', italics: true, fontSize: 40 }, + 'then.\n\n' + ] + }, + { text: 'Mixing named styles and style-overrides', style: 'header' }, + { + style: 'bigger', + italics: false, + text: [ + 'We can also mix named-styles and style-overrides at both paragraph and inline level. ', + 'For example, this paragraph uses the "bigger" style, which changes fontSize to 15 and sets italics to true. ', + 'Texts are not italics though. It\'s because we\'ve overriden italics back to false at ', + 'the paragraph level. \n\n', + 'We can also change the style of a single inline. Let\'s use a named style called header: ', + { text: 'like here.\n', style: 'header' }, + 'It got bigger and bold.\n\n', + 'OK, now we\'re going to mix named styles and style-overrides at the inline level. ', + 'We\'ll use header style (it makes texts bigger and bold), but we\'ll override ', + 'bold back to false: ', + { text: 'wow! it works!', style: 'header', bold: false }, + '\n\nMake sure to take a look into the sources to understand what\'s going on here.' + ] + } + ], + styles: { + header: { + fontSize: 18, + bold: true + }, + bigger: { + fontSize: 15, + italics: true + } + } + }, + { + content: [ + { + text: 'This paragraph uses header style and extends the alignment property', + style: 'header', + alignment: 'center' + }, + { + text: [ + 'This paragraph uses header style and overrides bold value setting it back to false.\n', + 'Header style in this example sets alignment to justify, so this paragraph should be rendered \n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Malit profecta versatur nomine ocurreret ' + ], + style: 'header', + bold: false + } + ], + styles: { + header: { + fontSize: 18, + bold: true, + alignment: 'justify' + } + } + }, + { + content: [ + 'By default paragraphs are stacked one on top of (or actually - below) another. ', + 'It\'s possible however to split any paragraph (or even the whole document) into columns.\n\n', + 'Here we go with 2 star-sized columns, with justified text and gap set to 20:\n\n', + { + alignment: 'justify', + columns: [ + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + } + ] + }, + '\nStar-sized columns have always equal widths, so if we define 3 of those, ', + 'it\'ll look like this (make sure to scroll to the next page, as we have a couple of more examples):\n\n', + { + columns: [ + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + } + ] + }, + '\nYou can also specify accurate widths for some (or all columns)', + { + columns: [ + { + width: 90, + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + width: '*', + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + width: '*', + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + width: 90, + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + } + ] + }, + '\nWe also support auto columns. They set their widths based on the content:\n\n', + { + columns: [ + { + width: 'auto', + text: 'auto column' + }, + { + width: '*', + text: 'This is a star-sized column. It should get the remaining' + + ' space divided by the number of all star-sized columns.' + }, + { + width: 50, + text: 'this one has specific width set to 50' + }, + { + width: 'auto', + text: 'another auto column' + }, + { + width: '*', + text: 'This is a star-sized column. It should get the remaining space ' + + 'divided by the number of all star-sized columns.' + }, + ] + }, + '\nIf all auto columns fit within available width, the table does not occupy whole space:\n\n', + { + columns: [ + { + width: 'auto', + text: 'val1' + }, + { + width: 'auto', + text: 'val2' + }, + { + width: 'auto', + text: 'value3' + }, + { + width: 'auto', + text: 'value 4' + }, + ] + }, + '\nAnother cool feature of pdfmake is the ability to have nested elements.', + { + columns: [ + { + width: 100, + fontSize: 9, + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ' + }, + [ + 'As you can see in the document definition - this column is not defined with ', + 'an object, but an array, which means it\'s treated as an array of paragraphs rendered one below another.', + 'Just like on the top-level of the document. Let\'s try to divide the remaing space into 3 star-sized columns:\n\n', + { + columns: [ + { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' }, + { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' }, + { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' }, + ] + } + ] + ] + }, + '\n\nOh, don\'t forget, we can use everything from styling examples (named styles, custom overrides) here as well.\n\n', + 'For instance - our next paragraph will use the \'bigger\' style (with fontSize set to 15 and italics - true).', + ' We\'ll split it into three columns and make sure they inherit the style:\n\n', + { + style: 'bigger', + columns: [ + 'First column (BTW - it\'s defined as a single string value. pdfmake will turn it into appropriate structure ', + 'automatically and make sure it inherits the styles', + { + fontSize: 20, + text: 'In this column, we\'ve overriden fontSize to 20. It means the content should have italics=true' + + ' (inherited from the style) and be a little bit bigger' + }, + { + style: 'header', + text: 'Last column does not override any styling properties, but applies a new style (header) to itself.' + + ' Eventually - texts here have italics=true (from bigger) and derive fontSize from the style.' + + ' OK, but which one? Both styles define it. As we already know from our styling examples, multiple' + + ' styles can be applied to the element and their order is important. Because \'header\' style has been' + + ' set after \'bigger\' its fontSize takes precedence over the fontSize from \'bigger\'. This is how it works. ' + + 'You will find more examples in the unit tests.' + } + ] + }, + '\n\nWow, you\'ve read the whole document! Congratulations :D' + ], + styles: { + header: { + fontSize: 18, + bold: true + }, + bigger: { + fontSize: 15, + italics: true + } + }, + defaultStyle: { + columnGap: 20 + } + }, + { + content: [ + { text: 'Tables', style: 'header' }, + 'Official documentation is in progress, this document is just', + ' a glimpse of what is possible with pdfmake and its layout engine.', + { text: 'A simple table (no headers, no width specified, no spans, no styling)', + style: 'subheader' }, + 'The following table has nothing more than a body array', + { + style: 'tableExample', + table: { + body: [ + ['Column 1', 'Column 2', 'Column 3'], + ['One value goes here', 'Another one here', 'OK?'] + ] + } + }, + { text: 'A simple table with nested elements', style: 'subheader' }, + 'It is of course possible to nest any other type of nodes available in ', + 'pdfmake inside table cells', + { + style: 'tableExample', + table: { + body: [ + ['Column 1', 'Column 2', 'Column 3'], + [ + { + stack: [ + 'Let\'s try an unordered list', + { + ul: [ + 'item 1', + 'item 2' + ] + } + ] + }, + [ + 'or a nested table', + { + table: { + body: [ + ['Col1', 'Col2', 'Col3'], + ['1', '2', '3'], + ['1', '2', '3'] + ] + }, + } + ], + { + text: [ + 'Inlines can be ', + { text: 'styled\n', italics: true }, + { text: 'easily as everywhere else', fontSize: 10 }] + } + ] + ] + } + }, + { text: 'Defining column widths', style: 'subheader' }, + 'Tables support the same width definitions as standard columns:', + { + bold: true, + ul: [ + 'auto', + 'star', + 'fixed value' + ] + }, + { + style: 'tableExample', + table: { + widths: [100, '*', 200, '*'], + body: [ + ['width=100', 'star-sized', 'width=200', 'star-sized'], + ['fixed-width cells have exactly the specified width', + { text: 'nothing interesting here', italics: true, color: 'gray' }, + { text: 'nothing interesting here', italics: true, color: 'gray' }, + { text: 'nothing interesting here', italics: true, color: 'gray' }] + ] + } + }, + { + style: 'tableExample', + table: { + widths: ['*', 'auto'], + body: [ + ['This is a star-sized column. The next column over, an auto-sized column, will wrap to accomodate all the text in this cell.', 'I am auto sized.'], + ] + } + }, + { + style: 'tableExample', + table: { + widths: ['*', 'auto'], + body: [ + ['This is a star-sized column. The next column over, an auto-sized column', + { text: 'I am auto sized.', noWrap: true }], + ] + } + }, + { text: 'Defining row heights', style: 'subheader' }, + { + style: 'tableExample', + table: { + heights: [20, 50, 70], + body: [ + ['row 1 with height 20', 'column B'], + ['row 2 with height 50', 'column B'], + ['row 3 with height 70', 'column B'] + ] + } + }, + 'With same height:', + { + style: 'tableExample', + table: { + heights: 40, + body: [ + ['row 1', 'column B'], + ['row 2', 'column B'], + ['row 3', 'column B'] + ] + } + }, + 'With height from function:', + { + style: 'tableExample', + table: { + heights: (row: number) => { + return (row + 1) * 25; + }, + body: [ + ['row 1', 'column B'], + ['row 2', 'column B'], + ['row 3', 'column B'] + ] + } + }, + { text: 'Column/row spans', pageBreak: 'before', style: 'subheader' }, + 'Each cell-element can set a rowSpan or colSpan', + { + style: 'tableExample', + color: '#444', + table: { + widths: [200, 'auto', 'auto'], + headerRows: 2, + // keepWithHeaderRows: 1, + body: [ + [{ text: 'Header with Colspan = 2', style: 'tableHeader', colSpan: 2, alignment: 'center' }, + {}, { text: 'Header 3', style: 'tableHeader', alignment: 'center' }], + [{ text: 'Header 1', style: 'tableHeader', alignment: 'center' }, + { text: 'Header 2', style: 'tableHeader', alignment: 'center' }, + { text: 'Header 3', style: 'tableHeader', alignment: 'center' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + [{ rowSpan: 3, text: 'rowSpan set to 3\nLorem ipsum dolor sit amet' }, + 'Sample value 2', 'Sample value 3'], + ['', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', { colSpan: 2, rowSpan: 2, text: 'Both:\nrowSpan and colSpan\ncan be defined at the same time' }, ''], + ['Sample value 1', '', ''], + ] + } + }, + { text: 'Headers', pageBreak: 'before', style: 'subheader' }, + 'You can declare how many rows should be treated as a header. Headers are', + ' automatically repeated on the following pages', + { text: ['It is also possible to set keepWithHeaderRows to make sure there will be no page-break' + + 'between the header and these rows. Take a look at the document-definition and play with it. ' + + 'If you set it to one, the following table will automatically start on the next page, ' + + 'since there\'s not enough space for the first row to be rendered here'], color: 'gray', italics: true }, + { + style: 'tableExample', + table: { + headerRows: 1, + // dontBreakRows: true, + // keepWithHeaderRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, + { text: 'Header 3', style: 'tableHeader' }], + [ + 'Lorem ipsum dolor sit amet, ', + 'Lorem ipsum dolor sit amet, ', + 'Lorem ipsum dolor sit amet, ', + ] + ] + } + }, + { text: 'Styling tables', style: 'subheader' }, + 'You can provide a custom styler for the table. Currently it supports:', + { + ul: [ + 'line widths', + 'line colors', + 'cell paddings', + ] + }, + 'with more options coming soon...\n\npdfmake currently has a few predefined styles (see them on the next page)', + { text: 'noBorders:', fontSize: 14, bold: true, pageBreak: 'before', margin: [0, 0, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, + { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: 'noBorders' + }, + { text: 'headerLineOnly:', fontSize: 14, bold: true, margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, + { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: 'headerLineOnly' + }, + { text: 'lightHorizontalLines:', fontSize: 14, bold: true, margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: 'lightHorizontalLines' + }, + { text: 'but you can provide a custom styler as well', margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: { + hLineWidth: (i: number, node: any) => { + return (i === 0 || i === node.table.body.length) ? 2 : 1; + }, + vLineWidth: (i: number, node: any) => { + return (i === 0 || i === node.table.widths.length) ? 2 : 1; + }, + hLineColor: (i: number, node: any) => { + return (i === 0 || i === node.table.body.length) ? 'black' : 'gray'; + }, + vLineColor: (i: number, node: any) => { + return (i === 0 || i === node.table.widths.length) ? 'black' : 'gray'; + }, + // paddingLeft: function(i, node) { return 4; }, + // paddingRight: function(i, node) { return 4; }, + // paddingTop: function(i, node) { return 2; }, + // paddingBottom: function(i, node) { return 2; }, + // fillColor: (i: number, node: any) => { return null; } + } + }, + { text: 'zebra style', margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + body: [ + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: { + fillColor: (i: number, node: any) => { + return (i % 2 === 0) ? '#CCCCCC' : null; + } + } + }, + { text: 'Optional border', fontSize: 14, bold: true, pageBreak: 'before', margin: [0, 0, 0, 8] }, + 'Each cell contains an optional border property: an array of 4 booleans for left border, top border, right border, bottom border.', + { + style: 'tableExample', + table: { + body: [ + [ + { + border: [false, true, false, false], + fillColor: '#eeeeee', + text: 'border:\n[false, true, false, false]' + }, + { + border: [false, false, false, false], + fillColor: '#dddddd', + text: 'border:\n[false, false, false, false]' + }, + { + border: [true, true, true, true], + fillColor: '#eeeeee', + text: 'border:\n[true, true, true, true]' + } + ], + [ + { + rowSpan: 3, + border: [true, true, true, true], + fillColor: '#eeeeff', + text: 'rowSpan: 3\n\nborder:\n[true, true, true, true]' + }, + { + border: undefined, + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + { + border: [true, false, false, false], + fillColor: '#dddddd', + text: 'border:\n[true, false, false, false]' + } + ], + [ + '', + { + colSpan: 2, + border: [true, true, true, true], + fillColor: '#eeffee', + text: 'colSpan: 2\n\nborder:\n[true, true, true, true]' + }, + '' + ], + [ + '', + { + border: undefined, + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + { + border: [false, false, true, true], + fillColor: '#dddddd', + text: 'border:\n[false, false, true, true]' + } + ] + ] + }, + layout: { + defaultBorder: false, + } + }, + 'For every cell without a border property, whether it has all borders or not is determined by ', + 'layout.defaultBorder, which is false in the table above and true (by default) in the table below.', + { + style: 'tableExample', + table: { + body: [ + [ + { + border: [false, false, false, false], + fillColor: '#eeeeee', + text: 'border:\n[false, false, false, false]' + }, + { + fillColor: '#dddddd', + text: 'border:\nundefined' + }, + { + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + ], + [ + { + fillColor: '#dddddd', + text: 'border:\nundefined' + }, + { + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + { + border: [true, true, false, false], + fillColor: '#dddddd', + text: 'border:\n[true, true, false, false]' + }, + ] + ] + } + }, + 'And some other examples with rowSpan/colSpan...', + { + style: 'tableExample', + table: { + body: [ + [ + '', + 'column 1', + 'column 2', + 'column 3' + ], + [ + 'row 1', + { + rowSpan: 3, + colSpan: 3, + border: [true, true, true, true], + fillColor: '#cccccc', + text: 'rowSpan: 3\ncolSpan: 3\n\nborder:\n[true, true, true, true]' + }, + '', + '' + ], + [ + 'row 2', + '', + '', + '' + ], + [ + 'row 3', + '', + '', + '' + ] + ] + }, + layout: { + defaultBorder: false, + } + }, + { + style: 'tableExample', + table: { + body: [ + [ + { + colSpan: 3, + text: 'colSpan: 3\n\nborder:\n[false, false, false, false]', + fillColor: '#eeeeee', + border: [false, false, false, false] + }, + '', + '' + ], + [ + 'border:\nundefined', + 'border:\nundefined', + 'border:\nundefined' + ] + ] + } + }, + { + style: 'tableExample', + table: { + body: [ + [ + { rowSpan: 3, text: 'rowSpan: 3\n\nborder:\n[false, false, false, false]', fillColor: '#eeeeee', border: [false, false, false, false] }, + 'border:\nundefined', + 'border:\nundefined' + ], + [ + '', + 'border:\nundefined', + 'border:\nundefined' + ], + [ + '', + 'border:\nundefined', + 'border:\nundefined' + ] + ] + } + } + ], + styles: { + header: { + fontSize: 18, + bold: true, + margin: [0, 0, 0, 10] + }, + subheader: { + fontSize: 16, + bold: true, + margin: [0, 10, 0, 5] + }, + tableExample: { + margin: [0, 5, 0, 15] + }, + tableHeader: { + bold: true, + fontSize: 13, + color: 'black' + } + }, + defaultStyle: { + // alignment: 'justify' + } + }, + { + content: [ + { text: 'Unordered list', style: 'header' }, + { + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nUnordered list with longer lines', style: 'header' }, + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', + 'item 3' + ] + }, + { text: '\n\nOrdered list', style: 'header' }, + { + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with longer lines', style: 'header' }, + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', + 'item 3' + ] + }, + { text: '\n\nOrdered list should be descending', style: 'header' }, + { + reversed: true, + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with start value', style: 'header' }, + { + start: 50, + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own values', style: 'header' }, + { + ol: [ + { text: 'item 1', counter: 10 }, + { text: 'item 2', counter: 20 }, + { text: 'item 3', counter: 30 }, + { text: 'item 4 without own value' } + ] + }, + { text: '\n\nNested lists (ordered)', style: 'header' }, + { + ol: [ + 'item 1', + [ + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', + { + ol: [ + 'subitem 1', + 'subitem 2', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + { + text: [ + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + ] + }, + + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 4', + 'subitem 5', + ] + } + ], + 'item 3\nsecond line of item3' + ] + }, + { text: '\n\nNested lists (unordered)', style: 'header' }, + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + { + ul: [ + 'subitem 1', + 'subitem 2', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + { + text: [ + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + ] + }, + + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 4', + 'subitem 5', + ] + }, + 'item 3\nsecond line of item3', + ] + }, + { text: '\n\nUnordered lists inside columns', style: 'header' }, + { + columns: [ + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + }, + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + } + ] + }, + { text: '\n\nOrdered lists inside columns', style: 'header' }, + { + columns: [ + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + }, + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + } + ] + }, + { text: '\n\nNested lists width columns', style: 'header' }, + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + { + ol: [ + [ + { + columns: [ + 'column 1', + { + stack: [ + 'column 2', + { + ul: [ + 'item 1', + 'item 2', + { + ul: [ + 'item', + 'item', + 'item', + ] + }, + 'item 4', + ] + } + ] + }, + 'column 3', + 'column 4', + ] + }, + 'subitem 1 in a vertical container', + 'subitem 2 in a vertical container', + ], + 'subitem 2', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + { + text: [ + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + ] + }, + + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 4', + 'subitem 5', + ] + }, + 'item 3\nsecond line of item3', + ] + }, + { text: '\n\nUnordered list with square marker type', style: 'header' }, + { + type: 'square', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nUnordered list with circle marker type', style: 'header' }, + { + type: 'circle', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored unordered list', style: 'header' }, + { + color: 'blue', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored unordered list with own marker color', style: 'header' }, + { + color: 'blue', + markerColor: 'red', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored ordered list', style: 'header' }, + { + color: 'blue', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored ordered list with own marker color', style: 'header' }, + { + color: 'blue', + markerColor: 'red', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list - type: lower-alpha', style: 'header' }, + { + type: 'lower-alpha', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list - type: upper-alpha', style: 'header' }, + { + type: 'upper-alpha', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + + { text: '\n\nOrdered list - type: upper-roman', style: 'header' }, + { + type: 'upper-roman', + ol: [ + 'item 1', + 'item 2', + 'item 3', + 'item 4', + 'item 5' + ] + }, + { text: '\n\nOrdered list - type: lower-roman', style: 'header' }, + { + type: 'lower-roman', + ol: [ + 'item 1', + 'item 2', + 'item 3', + 'item 4', + 'item 5' + ] + }, + { text: '\n\nOrdered list - type: none', style: 'header' }, + { + type: 'none', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nUnordered list - type: none', style: 'header' }, + { + type: 'none', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own separator', style: 'header' }, + { + separator: ')', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own complex separator', style: 'header' }, + { + separator: ['(', ')'], + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own items type', style: 'header' }, + { + ol: [ + 'item 1', + { text: 'item 2', listType: 'none' }, + { text: 'item 3', listType: 'upper-roman' } + ] + }, + { text: '\n\nUnordered list with own items type', style: 'header' }, + { + ul: [ + 'item 1', + { text: 'item 2', listType: 'none' }, + { text: 'item 3', listType: 'circle' } + ] + }, + ], + styles: { + header: { + bold: true, + fontSize: 15 + } + }, + defaultStyle: { + fontSize: 12 + } + }, + { + content: [ + { + stack: [ + 'This header has both top and bottom margins defined', + { text: 'This is a subheader', style: 'subheader' }, + ], + style: 'header' + }, + { + text: [ + 'Margins have slightly different behavior than other layout properties. ', + 'They are not inherited, unlike anything else. They\'re applied only to those nodes which explicitly ', + 'set margin or style property.\n', + ] + }, + { + text: 'This paragraph (consisting of a single line) directly sets top and bottom margin to 20', + margin: [0, 20], + }, + { + stack: [ + { + text: [ + 'This line begins a stack of paragraphs. The whole stack uses a ', + { text: 'superMargin', italics: true }, + ' style (with margin and fontSize properties).', + ] + }, + { text: ['When you look at the', { text: ' document definition', italics: true }, + ', you will notice that fontSize is inherited by all paragraphs inside the stack.'] }, + 'Margin however is only applied once (to the whole stack).' + ], + style: 'superMargin' + }, + { + stack: [ + 'I\'m not sure yet if this is the desired behavior. I find it a better approach however.', + ' One thing to be considered in the future is an explicit layout property called inheritMargin which could opt-in the inheritance.\n\n', + { + fontSize: 15, + text: [ + 'Currently margins for ', + /* the following margin definition doesn't change anything */ + { text: 'inlines', margin: 20 }, + ' are ignored\n\n' + ], + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + ], + margin: [0, 20, 0, 0], + alignment: 'justify' + } + ], + styles: { + header: { + fontSize: 18, + bold: true, + alignment: 'right', + margin: [0, 190, 0, 80] + }, + subheader: { + fontSize: 14 + }, + superMargin: { + margin: [20, 0, 40, 0], + fontSize: 15 + } + } + }, + { + content: [ + 'pdfmake (since it\'s based on pdfkit) supports JPEG and PNG format', + 'If no width/height/fit is provided, image original size will be used', + { + image: 'sampleImage.jpg', + }, + 'If you specify width, image will scale proportionally', + { + image: 'sampleImage.jpg', + width: 150 + }, + 'If you specify both width and height - image will be stretched', + { + image: 'sampleImage.jpg', + width: 150, + height: 150, + }, + 'You can also fit the image inside a rectangle', + { + image: 'sampleImage.jpg', + fit: [100, 100], + pageBreak: 'after' + }, + // Warning! Make sure to copy this definition and paste it to an + // external text editor, as the online AceEditor has some troubles + // with long dataUrl lines and the following image values look like + // they're empty. + 'Images can be also provided in dataURL format...', + { + image: 'data:image/gif;base64,...', + width: 200 + }, + 'or be declared in an "images" dictionary and referenced by name', + { + image: 'building', + width: 200 + }, + ], + images: { + building: 'data:image/gif;base64,...' + } + } +]; const createPdf = () => { const pdf = pdfMake; pdf.vfs = pdfFonts.pdfMake.vfs; - pdfMake.createPdf(docDefinition).download(); + + for (const definition of definitions) { + const typedDefinition: pdfMake.TDocumentDefinitions = definition; + pdfMake.createPdf(typedDefinition).download(); + } }; diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 4392d09ae9..fed6c45253 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -10,9 +10,9 @@ /// -import * as stream from 'stream'; -import * as http from 'http'; -import { EventEmitter } from 'events'; +import stream = require('stream'); +import http = require('http'); +import EventEmitter = require('events'); import SonicBoom = require('sonic-boom'); export = P; @@ -98,6 +98,23 @@ declare namespace P { */ function extreme(fileDescriptor?: string | number): SonicBoom; + /** + * The pino.final method can be used to create an exit listener function. + * This listener function can be supplied to process exit events. + * The exit listener function will cal the handler with + * @param [logger]: pino logger that serves as reference for the final logger + * @param [handler]: Function that will be called by the handler returned from this function + * @returns Exit listener function that can be supplied to process exit events and will call the supplied handler function + */ + function final(logger: Logger, handler: (error: Error, finalLogger: Logger, ...args: any[]) => void): (error: Error | null, ...args: any[]) => void; + + /** + * The pino.final method can be used to acquire a final logger instance that synchronously flushes on every write. + * @param [logger]: pino logger that serves as reference for the final logger + * @returns Final, synchronous logger + */ + function final(logger: Logger): Logger; + interface LevelMapping { /** * Returns the mappings of level names to their respective internal number representation. diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 609cac121f..c85f2f6873 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -7,9 +7,9 @@ const error = log.error; info('hello world'); error('this is at error level'); info('the answer is %d', 42); -info({obj: 42}, 'hello world'); -info({obj: 42, b: 2}, 'hello world'); -info({obj: {aa: 'bbb'}}, 'another'); +info({ obj: 42 }, 'hello world'); +info({ obj: 42, b: 2 }, 'hello world'); +info({ obj: { aa: 'bbb' } }, 'another'); setImmediate(info, 'after setImmediate'); error(new Error('an error')); @@ -41,27 +41,27 @@ pino({ }); pino({ base: null }); -pino({ base: { foo: 'bar' } , changeLevelName: 'severity' }); +pino({ base: { foo: 'bar' }, changeLevelName: 'severity' }); if ('pino' in log) console.log(`pino version: ${log.pino}`); -log.child({a: 'property'}).info('hello child!'); +log.child({ a: 'property' }).info('hello child!'); log.level = 'error'; log.info('nope'); -const child = log.child({foo: 'bar'}); +const child = log.child({ foo: 'bar' }); child.info('nope again'); child.level = 'info'; child.info('hooray'); log.info('nope nope nope'); -log.child({foo: 'bar', level: 'debug'}).debug('debug!'); +log.child({ foo: 'bar', level: 'debug' }).debug('debug!'); const customSerializers = { test() { return 'this is my serializer'; } }; -pino().child({serializers: customSerializers}).info({test: 'should not show up'}); -const child2 = log.child({father: true}); -const childChild = child2.child({baby: true}); +pino().child({ serializers: customSerializers }).info({ test: 'should not show up' }); +const child2 = log.child({ father: true }); +const childChild = child2.child({ baby: true }); log.level = 'info'; if (log.levelVal === 30) { @@ -91,3 +91,14 @@ logstderr.error('on stderr instead of stdout'); log.useLevelLabels = true; log.info('lol'); log.level === 'info'; + +const extremeDest = pino.extreme(); +const logExtreme = pino(extremeDest); + +const handler = pino.final(logExtreme, (err: Error, finalLogger: pino.BaseLogger) => { + if (err) { + finalLogger.error(err, 'error caused exit'); + } +}); + +handler(new Error('error')); diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index 985e1a77c0..7c05701e75 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -377,9 +377,7 @@ declare namespace PIXI { | PIXI.HitArea; buttonMode: boolean; cursor: string; - trackedPointers(): { - [key: number]: interaction.InteractionTrackingData; - }; + trackedPointers: { [key: number]: interaction.InteractionTrackingData; }; // Deprecated defaultCursor: string; // end interactive target @@ -2811,7 +2809,7 @@ declare namespace PIXI { | PIXI.HitArea; buttonMode: boolean; cursor: string; - trackedPointers(): { [key: number]: InteractionTrackingData }; + trackedPointers: { [key: number]: InteractionTrackingData }; // Deprecated defaultCursor: string; diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index adf853af72..d0d3fb1be7 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -479,7 +479,7 @@ export type DataTransform = Partial; export type ScatterData = PlotData; // Bar Scatter export interface PlotData { - type: 'bar' | 'histogram' | 'pointcloud' | 'scatter' | 'scattergl' | 'scatter3d' | 'surface'; + type: 'bar' | 'box' | 'heatmap' | 'histogram' | 'pointcloud' | 'scatter' | 'scattergl' | 'scatter3d' | 'surface'; x: Datum[] | Datum[][] | TypedArray; y: Datum[] | Datum[][] | TypedArray; z: Datum[] | Datum[][] | Datum[][][] | TypedArray; @@ -530,6 +530,18 @@ export interface PlotData { visible: boolean | 'legendonly'; transforms: DataTransform[]; orientation: 'v' | 'h'; + boxmean: boolean | 'sd'; + colorscale: string | Array<[number, string]>; + zsmooth: 'fast' | 'best' | false; + ygap: number; + xgap: number; + transpose: boolean; + autobinx: boolean; + xbins: { + start: number | string; + end: number | string; + size: number | string; + }; } /** diff --git a/types/postcss-calc/index.d.ts b/types/postcss-calc/index.d.ts new file mode 100644 index 0000000000..c9ac8e30bb --- /dev/null +++ b/types/postcss-calc/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for postcss-calc 7.0 +// Project: https://github.com/postcss/postcss-calc +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare namespace calc { + interface Options { + precision?: number; + preserve?: boolean; + warnWhenCannotResolve?: boolean; + mediaQueries?: boolean; + selectors?: boolean; + } + + type Calc = Plugin; +} + +declare const calc: calc.Calc; +export = calc; diff --git a/types/postcss-calc/package.json b/types/postcss-calc/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-calc/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-calc/postcss-calc-tests.ts b/types/postcss-calc/postcss-calc-tests.ts new file mode 100644 index 0000000000..937741a1f3 --- /dev/null +++ b/types/postcss-calc/postcss-calc-tests.ts @@ -0,0 +1,12 @@ +import calc = require("postcss-calc"); +import { Transformer } from 'postcss'; + +const ap1: Transformer = calc(); + +const ap2: Transformer = calc({ + precision: 5, + preserve: false, + warnWhenCannotResolve: false, + mediaQueries: false, + selectors: false +}); diff --git a/types/postcss-calc/tsconfig.json b/types/postcss-calc/tsconfig.json new file mode 100644 index 0000000000..d21d8b4969 --- /dev/null +++ b/types/postcss-calc/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-calc-tests.ts" + ] +} diff --git a/types/postcss-calc/tslint.json b/types/postcss-calc/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-calc/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-icss-values/index.d.ts b/types/postcss-icss-values/index.d.ts new file mode 100644 index 0000000000..f7133420e8 --- /dev/null +++ b/types/postcss-icss-values/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for postcss-icss-values 2.0 +// Project: https://github.com/css-modules/postcss-icss-values +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare const values: Plugin<{}>; +export = values; diff --git a/types/postcss-icss-values/package.json b/types/postcss-icss-values/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-icss-values/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-icss-values/postcss-icss-values-tests.ts b/types/postcss-icss-values/postcss-icss-values-tests.ts new file mode 100644 index 0000000000..ac63f19aa0 --- /dev/null +++ b/types/postcss-icss-values/postcss-icss-values-tests.ts @@ -0,0 +1,4 @@ +import values = require("postcss-icss-values"); +import { Transformer } from "postcss"; + +const ap1: Transformer = values(); diff --git a/types/postcss-icss-values/tsconfig.json b/types/postcss-icss-values/tsconfig.json new file mode 100644 index 0000000000..354ce66470 --- /dev/null +++ b/types/postcss-icss-values/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-icss-values-tests.ts" + ] +} diff --git a/types/postcss-icss-values/tslint.json b/types/postcss-icss-values/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-icss-values/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-modules-resolve-imports/index.d.ts b/types/postcss-modules-resolve-imports/index.d.ts new file mode 100644 index 0000000000..698ce430ff --- /dev/null +++ b/types/postcss-modules-resolve-imports/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for postcss-modules-resolve-imports 1.3 +// Project: https://github.com/css-modules/postcss-modules-resolve-imports +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare namespace resolveImports { + interface Resolve { + alias?: { [alias: string]: string }; + extensions?: string[]; + modules?: string[]; + mainFile?: string; + preserveSymlinks?: boolean; + } + + interface Options { + icssExports?: boolean; + resolve?: Resolve; + } + + type ResolveImports = Plugin; +} + +declare const resolveImports: resolveImports.ResolveImports; +export = resolveImports; diff --git a/types/postcss-modules-resolve-imports/package.json b/types/postcss-modules-resolve-imports/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-modules-resolve-imports/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-modules-resolve-imports/postcss-modules-resolve-imports-tests.ts b/types/postcss-modules-resolve-imports/postcss-modules-resolve-imports-tests.ts new file mode 100644 index 0000000000..cb46a28ddc --- /dev/null +++ b/types/postcss-modules-resolve-imports/postcss-modules-resolve-imports-tests.ts @@ -0,0 +1,20 @@ +/// + +import path = require("path"); +import resolveImports = require("postcss-modules-resolve-imports"); +import { Transformer } from "postcss"; + +const ap1: Transformer = resolveImports(); + +const ap2: Transformer = resolveImports({ + icssExports: false, + resolve: { + alias: { + lib: path.resolve(__dirname, "lib"), + }, + extensions: [".css"], + modules: [path.resolve(__dirname, "lib")], + mainFile: "index.css", + preserveSymlinks: false + } +}); diff --git a/types/postcss-modules-resolve-imports/tsconfig.json b/types/postcss-modules-resolve-imports/tsconfig.json new file mode 100644 index 0000000000..a1b942ae1c --- /dev/null +++ b/types/postcss-modules-resolve-imports/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-modules-resolve-imports-tests.ts" + ] +} diff --git a/types/postcss-modules-resolve-imports/tslint.json b/types/postcss-modules-resolve-imports/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-modules-resolve-imports/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pouchdb-core/index.d.ts b/types/pouchdb-core/index.d.ts index 63f03a6832..221b5984b6 100644 --- a/types/pouchdb-core/index.d.ts +++ b/types/pouchdb-core/index.d.ts @@ -1,13 +1,15 @@ -// Type definitions for pouchdb-core 6.4 +// Type definitions for pouchdb-core 7.0 // Project: https://pouchdb.com/ // Definitions by: Simon Paulger , Jakub Navratil , // Brian Geppert , Frederico Galvão , -// Tobias Bales , Sebastián Ramírez +// Tobias Bales , Sebastián Ramírez , +// Katy Moe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// /// +/// interface Blob { readonly size: number; @@ -87,6 +89,11 @@ interface EventEmitter { eventNames(): Array; } +type Fetch = ( + url: string | Request, + opts?: RequestInit +) => Promise; + declare namespace PouchDB { namespace Core { interface Error { @@ -110,7 +117,7 @@ declare namespace PouchDB { type AttachmentData = string | Blob | Buffer; interface Options { - ajax?: Configuration.RemoteRequesterConfiguration; + fetch?: Fetch; } interface BasicResponse { @@ -568,33 +575,8 @@ declare namespace PouchDB { size?: number; } - interface RemoteRequesterConfiguration { - /** - * Time before HTTP requests time out (in ms). - */ - timeout?: number; - /** - * Appends a random string to the end of all HTTP GET requests to avoid - * them being cached on IE. Set this to true to prevent this happening. - */ - cache?: boolean; - /** - * HTTP headers to add to requests. - */ - headers?: { - [name: string]: string; - }; - - /** - * Enables transferring cookies and HTTP Authorization information. - * - * Defaults to true. - */ - withCredentials?: boolean; - } - interface RemoteDatabaseConfiguration extends CommonDatabaseConfiguration { - ajax?: RemoteRequesterConfiguration; + fetch?: Fetch; auth?: { username?: string; @@ -615,6 +597,8 @@ declare namespace PouchDB { version: string; + fetch: Fetch; + on(event: 'created' | 'destroyed', listener: (dbName: string) => any): this; debug: debug.IDebug; diff --git a/types/pouchdb-core/pouchdb-core-tests.ts b/types/pouchdb-core/pouchdb-core-tests.ts index f8accd1c3a..c4c1e0e408 100644 --- a/types/pouchdb-core/pouchdb-core-tests.ts +++ b/types/pouchdb-core/pouchdb-core-tests.ts @@ -233,12 +233,8 @@ function testChanges() { function testRemoteOptions() { const db = new PouchDB('http://example.com/dbname', { - ajax: { - cache: false, - timeout: 10000, - headers: { - 'X-Some-Special-Header': 'foo' - }, + fetch(url, opts) { + return PouchDB.fetch(url, opts); }, auth: { username: 'mysecretusername', diff --git a/types/prosemirror-markdown/index.d.ts b/types/prosemirror-markdown/index.d.ts index 7af366c04e..91b37ea51e 100644 --- a/types/prosemirror-markdown/index.d.ts +++ b/types/prosemirror-markdown/index.d.ts @@ -7,7 +7,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); import { Node as ProsemirrorNode, Schema } from 'prosemirror-model'; /** diff --git a/types/protractor-helpers/index.d.ts b/types/protractor-helpers/index.d.ts index bc52455d6e..686c2442be 100644 --- a/types/protractor-helpers/index.d.ts +++ b/types/protractor-helpers/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/wix/protractor-helpers // Definitions by: John Cant // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as webdriver from "selenium-webdriver"; diff --git a/types/puppeteer/v0/puppeteer-tests.ts b/types/puppeteer/v0/puppeteer-tests.ts index 963fb1c8c1..76717da98f 100644 --- a/types/puppeteer/v0/puppeteer-tests.ts +++ b/types/puppeteer/v0/puppeteer-tests.ts @@ -27,8 +27,8 @@ import * as puppeteer from "puppeteer"; // Get the "viewport" of the page, as reported by the page. const dimensions = await page.evaluate(() => { return { - width: document.documentElement!.clientWidth, - height: document.documentElement!.clientHeight, + width: document.documentElement!.clientWidth, // tslint:disable-line no-unnecessary-type-assertion + height: document.documentElement!.clientHeight, // tslint:disable-line no-unnecessary-type-assertion deviceScaleFactor: window.devicePixelRatio }; }); diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 9375c3107b..851a778827 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -23,6 +23,7 @@ // Marcin Biernat // Rayhaneh Banyassady // Ryan McCuaig +// Drew Wyatt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -430,12 +431,20 @@ declare namespace R { (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; } + interface Placeholder { __isRamdaPlaceholder__: true; } + interface Reduced { '@@transducer/value': T; '@@transducer/reduced': true; } interface Static { + /** + * Placeholder. When used with functions like curry, or op, the second argument is applied to the second + * position, and it returns a function waiting for its first argument. + */ + __: Placeholder; /* This is used in examples throughout the docs, but I it only seems to be directly explained here: https://ramdajs.com/0.9/docs/#op */ + /** * Adds two numbers (or strings). Equivalent to a + b but curried. */ @@ -754,6 +763,8 @@ declare namespace R { * Returns a new list consisting of the elements of the first list followed by the elements * of the second. */ + concat(placeholder: Placeholder): (list2: ReadonlyArray, list1: ReadonlyArray) => T[]; + concat(placeholder: Placeholder, list2: ReadonlyArray): (list1: ReadonlyArray) => T[]; concat(list1: ReadonlyArray, list2: ReadonlyArray): T[]; concat(list1: ReadonlyArray): (list2: ReadonlyArray) => T[]; concat(list1: string, list2: string): string; @@ -782,6 +793,10 @@ declare namespace R { * Returns `true` if the specified item is somewhere in the list, `false` otherwise. * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. */ + contains(__: Placeholder, list: string): (a: string) => boolean; + contains(__: Placeholder, list: T[]): (a: T) => boolean; + contains(__: Placeholder): (list: string, a: string) => boolean; + contains(__: Placeholder): (list: T[], a: T) => boolean; contains(a: string, list: string): boolean; contains(a: T, list: ReadonlyArray): boolean; contains(a: string): (list: string) => boolean; @@ -876,6 +891,8 @@ declare namespace R { /** * Divides two numbers. Equivalent to a / b. */ + divide(__: Placeholder, b: number): (a: number) => number; + divide(__: Placeholder): (b: number, a: number) => number; divide(a: number, b: number): number; divide(a: number): (b: number) => number; @@ -1053,18 +1070,24 @@ declare namespace R { /** * Returns true if the first parameter is greater than the second. */ + gt(__: Placeholder, b: number): (a: number) => boolean; + gt(__: Placeholder): (b: number, a: number) => boolean; gt(a: number, b: number): boolean; gt(a: number): (b: number) => boolean; /** * Returns true if the first parameter is greater than or equal to the second. */ + gte(__: Placeholder, b: number): (a: number) => boolean; + gte(__: Placeholder): (b: number, a: number) => boolean; gte(a: number, b: number): boolean; gte(a: number): (b: number) => boolean; /** * Returns whether or not an object has an own property with the specified name. */ + has(__: Placeholder, obj: T): (s: string) => boolean; + has(__: Placeholder): (obj: T, s: string) => boolean; has(s: string, obj: T): boolean; has(s: string): (obj: T) => boolean; @@ -1300,12 +1323,16 @@ declare namespace R { /** * Returns true if the first parameter is less than the second. */ + lt(__: Placeholder, b: number): (a: number) => boolean; + lt(__: Placeholder): (b: number, a: number) => boolean; lt(a: number, b: number): boolean; lt(a: number): (b: number) => boolean; /** * Returns true if the first parameter is less than or equal to the second. */ + lte(__: Placeholder, b: number): (a: number) => boolean; + lte(__: Placeholder): (b: number, a: number) => boolean; lte(a: number, b: number): boolean; lte(a: number): (b: number) => boolean; @@ -1361,6 +1388,8 @@ declare namespace R { * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN * when the modulus is zero or negative. */ + mathMod(__: Placeholder, b: number): (a: number) => number; + mathMod(__: Placeholder): (b: number, a: number) => number; mathMod(a: number, b: number): number; mathMod(a: number): (b: number) => number; @@ -1409,6 +1438,8 @@ declare namespace R { * merged with the own properties of object b. * This function will *not* mutate passed-in objects. */ + merge(__: Placeholder, b: T2): (a: T1) => T1 & T2; + merge(__: Placeholder): (b: T2, a: T1) => T1 & T2; merge(a: T1, b: T2): T1 & T2; merge(a: T1): (b: T2) => T1 & T2; @@ -1496,6 +1527,8 @@ declare namespace R { * Note that this functions preserves the JavaScript-style behavior for * modulo. For mathematical modulo see `mathMod` */ + modulo(__: Placeholder, b: number): (a: number) => number; + modulo(__: Placeholder): (b: number, a: number) => number; modulo(a: number, b: number): number; modulo(a: number): (b: number) => number; @@ -2282,6 +2315,8 @@ declare namespace R { /** * Subtracts two numbers. Equivalent to `a - b` but curried. */ + subtract(__: Placeholder, b: number): (a: number) => number; + subtract(__: Placeholder): (b: number, a: number) => number; subtract(a: number, b: number): number; subtract(a: number): (b: number) => number; diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 951c11ba02..749ebdaf8b 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -124,6 +124,45 @@ class F2 { } }; +/** R.__ */ +() => { + R.concat(R.__, [4, 5, 6])([1, 2, 3]); // [1, 2, 3, 4, 5, 6] + R.concat(R.__)([4, 5, 6], [1, 2, 3]); // [1, 2, 3, 4, 5, 6] + + R.contains(R.__, [1, 2, 3])(3); // true + R.contains(R.__)([1, 2, 3], 3); // true + + R.divide(R.__)(2, 42); // 21 + R.divide(R.__, 2)(42); // 21 + + R.gt(R.__, 2)(10); // true + R.gt(R.__)(2, 10); // true + + R.gte(R.__, 6)(2); // false + R.gte(R.__)(6, 2); // false + + R.has(R.__, {x: 0, y: 0})('x'); // true; + R.has(R.__)({x: 0, y: 0}, 'x'); // true; + + R.lt(R.__, 5)(10); // false + R.lt(R.__)(5, 10); // false + + R.lte(R.__, 2)(1); // true + R.lte(R.__)(2, 1); // true + + R.mathMod(R.__, 12)(15); // 3 + R.mathMod(R.__)(12, 15); // 3 + + R.modulo(R.__, 2)(42); // 0 + R.modulo(R.__)(2, 42); // 0 + + R.merge(R.__, {x: 0})({x: 5, y: 2}); // {x: 0, y: 2} + R.merge(R.__)({x: 0}, {x: 5, y: 2}); // {x: 0, y: 2} + + R.subtract(R.__, 5)(17); // 12 + R.subtract(R.__)(5, 17); // 12 +}; + () => { const addFour = (a: number) => (b: number) => (c: number) => (d: number) => a + b + c + d; const uncurriedAddFour = R.uncurryN(4, addFour); diff --git a/types/raygun/index.d.ts b/types/raygun/index.d.ts new file mode 100644 index 0000000000..9315161a33 --- /dev/null +++ b/types/raygun/index.d.ts @@ -0,0 +1,146 @@ +// Type definitions for raygun 0.10 +// Project: https://github.com/MindscapeHQ/raygun4node +// Definitions by: Taylor Lodge +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare namespace raygun { + interface KeyValueObject { + [key: string]: string | number | boolean | KeyValueObject; + } + interface StackFrame { + lineNumber: number; + className: string; + fileName: string; + methodName: string; + columnNumber?: number; + } + interface RaygunErrorObject { + message: string; + className: string; + stackTrace: StackFrame[]; + innerError?: RaygunErrorObject; + } + interface RaygunRequest { + hostname?: string; + host?: string; + path?: string; + method?: string; + ip?: string; + queryString?: KeyValueObject; + headers?: KeyValueObject; + form?: KeyValueObject; + } + interface RaygunUser { + identifier: string; + email?: string; + fullName?: string; + firstName?: string; + uuid?: string; + } + interface RaygunPayload { + occurredOn: Date; + details: { + client: { + name: "raygun-node"; + version: string; + }; + groupingKey?: string; + error: RaygunErrorObject; + environment: { + osVersion: string; + architecture: string; + totalPhysicalMemory: number; + availablePhysicalMemory: number; + utcOffset: number; + processorCount?: number; + cpu: { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + }; + }; + machineName: string; + userCustomData?: KeyValueObject; + tags: string[]; + request?: RaygunRequest; + user?: RaygunUser | { identifier: string }; + version?: string; + }; + } + + interface RaygunOfflineStorageProvider< + TTransportItem = RaygunPayload, + TStorageItem = string + > { + init(options: any): RaygunOfflineStorageProvider; + save(item: TTransportItem, callback: (error?: Error) => void): void; + retrieve( + callback: ( + error: Error, + storageItems: ReadonlyArray + ) => void + ): void; + send( + callback: ( + error: Error, + sendItems: ReadonlyArray + ) => void + ): void; + } + + type OnBeforeSend = ( + payload: RaygunPayload, + exception: Error, + customData: KeyValueObject, + request: RaygunRequest, + tags: ReadonlyArray + ) => boolean | RaygunPayload; + interface RaygunOptions { + apiKey: string; + filters?: ReadonlyArray; + port?: number; + host?: string; + useSSL?: boolean; + onBeforeSend?: OnBeforeSend; + offlineStorage?: RaygunOfflineStorageProvider; + offlineStorageOptions?: any; + isOffline?: boolean; + groupingKey?: string; + tags?: ReadonlyArray; + userHumanStringForObject?: boolean; + reportColumnNumbers?: boolean; + innerErrorFieldName?: string; + } +} + +declare class Client { + init(options: raygun.RaygunOptions): Client; + setUser(user: raygun.RaygunUser): Client; + setVersion(version: string): Client; + onBeforeSend(callback: raygun.OnBeforeSend): Client; + groupingKey(groupingKey: string): Client; + offline(): Client; + online(): Client; + send( + exception: Error | string | object, + customData?: raygun.KeyValueObject, + offlineStorageCallback?: (error?: Error) => void, + request?: raygun.RaygunRequest, + tags?: ReadonlyArray + ): raygun.RaygunPayload; + expressHandler( + error: Error, + request: raygun.RaygunRequest, + res: any, + next: any + ): void; +} + +export = Client; diff --git a/types/raygun/raygun-tests.ts b/types/raygun/raygun-tests.ts new file mode 100644 index 0000000000..76328b01c5 --- /dev/null +++ b/types/raygun/raygun-tests.ts @@ -0,0 +1,59 @@ +import Client = require('raygun'); + +const client = new Client(); // $ExpectType Client +client.init({apiKey: '1'}); // $ExpectType Client + +client.init(); // $ExpectError +client.init({}); // $ExpectError +client.init({apiKey: 123}); // $ExpectError +// +// $ExpectType Client +client.setUser({ + identifier: '123' +}); +// $ExpectType Client +client.setUser({ + identifier: '123', + email: '123', + fullName: '123', + firstName: '123', + uuid: '123' +}); + +client.setUser(); // $ExpectError +client.setUser({}); // $ExpectError +client.setUser({identifier: 1}); // $ExpectError + +client.setVersion('123'); // $ExpectType Client + +client.setVersion(); // $ExpectError +client.setVersion({}); // $ExpectError + +client.onBeforeSend(payload => payload); // $ExpectType Client +// $ExpectType Client +client.onBeforeSend(payload => { + payload.details; + + return payload; +}); + +client.onBeforeSend(); // $ExpectError + +client.groupingKey('123'); // $ExpectType Client + +client.groupingKey(); // $ExpectError +client.groupingKey({}); // $ExpectError + +client.offline(); // $ExpectType Client + +client.online(); // $ExpectType Client + +client.send(new Error()); // $ExpectType RaygunPayload +client.send({foo: 'bar'}); // $ExpectType RaygunPayload +client.send('error message'); // $ExpectType RaygunPayload +client.send(new Error(), {foo: 'bar'}); // $ExpectType RaygunPayload +client.send(new Error(), {}, undefined, undefined, ['1', '2']); // $ExpectType RaygunPayload + +client.send(); // $ExpectError +client.send(null); // $ExpectError +client.send(undefined); // $ExpectError diff --git a/types/raygun/tsconfig.json b/types/raygun/tsconfig.json new file mode 100644 index 0000000000..f85de6fb88 --- /dev/null +++ b/types/raygun/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", + "raygun-tests.ts" + ] +} diff --git a/types/raygun/tslint.json b/types/raygun/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/raygun/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/raygun4js/index.d.ts b/types/raygun4js/index.d.ts index 66a7ce8ee9..d5faa0028b 100644 --- a/types/raygun4js/index.d.ts +++ b/types/raygun4js/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for raygun4js 2.6.0 +// Type definitions for raygun4js 2.13 // Project: https://github.com/MindscapeHQ/raygun4js -// Definitions by: Brian Surowiec , Benjamin Harding +// Definitions by: Brian Surowiec , Benjamin Harding , Taylor Lodge // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 interface TracekitStackTrace { message: string; @@ -20,7 +21,6 @@ interface TracekitStack { url: string; } - interface RaygunStackTrace { LineNumber: number; ColumnNumber: number; @@ -61,14 +61,17 @@ interface RaygunOptions { disablePulse?: boolean; /** - * Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested. + * Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). + * Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested. */ - excludedHostnames?: (string|RegExp)[]; + excludedHostnames?: ReadonlyArray; /** - * Prevents errors from being sent from certain user agents by providing an array of strings. This is very helpful to exclude errors reported by certain browsers or test automation with CasperJS, PhantomJS or any other testing utility that sends a custom user agent. If a part of the client's navigator.userAgent matches one of the given strings in the array, then the client will be excluded from error reporting. + * Prevents errors from being sent from certain user agents by providing an array of strings. + * This is very helpful to exclude errors reported by certain browsers or test automation with CasperJS, PhantomJS or any other testing utility that sends a custom user agent. + * If a part of the client's navigator.userAgent matches one of the given strings in the array, then the client will be excluded from error reporting. */ - excludedUserAgents?: (string|RegExp)[]; + excludedUserAgents?: ReadonlyArray; /** * The maximum time a virtual page can be considered viewed, in milliseconds (defaults to 30 minutes). @@ -80,11 +83,6 @@ interface RaygunOptions { */ pulseIgnoreUrlCasing?: boolean; - /** - * A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this. - */ - apiUrl?: string; - /** * If false, async callback functions triggered by setTimeout/setInterval will not be wrapped when attach() is called. Defaults to true */ @@ -95,20 +93,25 @@ interface RaygunOptions { */ debugMode?: boolean; + captureUnhandledRejections?: boolean; + setCookieAsSecure?: boolean; + /** - * Ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. + * Ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - + * if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. */ ignore3rdPartyErrors?: boolean; /** - * A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this. + * A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. + * This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this. */ apiEndpoint?: string; /** * String which can be optionally set "onLoad" which will then boot the RealUserMonitoring side instead of waiting for the `load` event. */ - from?: string|"onLoad"; + from?: string | "onLoad"; } interface RaygunPayload { @@ -121,16 +124,16 @@ interface RaygunPayload { }; Environment: { UtcOffset: number; - 'User-Language': string; - 'Document-Mode': number; - 'Browser-Width': number; - 'Browser-Height': number; - 'Screen-Width': number; - 'Screen-Height': number; - 'Color-Depth': number; + "User-Language": string; + "Document-Mode": number; + "Browser-Width": number; + "Browser-Height": number; + "Screen-Width": number; + "Screen-Height": number; + "Color-Depth": number; Browser: string; - 'Browser-Name': string; - 'Browser-Version': string; + "Browser-Name": string; + "Browser-Version": string; Platform: string; }; Client: { @@ -143,7 +146,7 @@ interface RaygunPayload { Url: string; QueryString: string; Headers: { - 'User-Agent': string; + "User-Agent": string; Referer: string; Host: string; }; @@ -162,7 +165,6 @@ interface RaygunPayload { } interface RaygunStatic { - /** * Prevents Raygun from overwriting anything bound to `window.Raygun`. */ @@ -176,7 +178,11 @@ interface RaygunStatic { /** * Configures the Raygun provider. */ - init(apiKey: string, options?: RaygunOptions, customdata?: any): RaygunStatic; + init( + apiKey: string, + options?: RaygunOptions, + customdata?: any + ): RaygunStatic; /** * Attaches custom data to any errors sent to Raygun. @@ -206,7 +212,14 @@ interface RaygunStatic { /** * Provides additional information about the current user. */ - setUser(user: string, isAnonymous?: boolean, email?: string, fullName?: string, firstName?: string, uuid?: string): RaygunStatic; + setUser( + user: string, + isAnonymous?: boolean, + email?: string, + fullName?: string, + firstName?: string, + uuid?: string + ): RaygunStatic; /** * Resets the information about the current user. @@ -226,12 +239,14 @@ interface RaygunStatic { /** * Blacklist keys to prevent their values from being sent to Raygun. */ - filterSensitiveData(filteredKeys: (string|RegExp)[]): RaygunStatic; + filterSensitiveData( + filteredKeys: ReadonlyArray + ): RaygunStatic; /** * Change the scope at which filters are applied. Defaults to `customData` by default. */ - setFilterScope(scope: "all"|"customData"): RaygunStatic; + setFilterScope(scope: "all" | "customData"): RaygunStatic; /** * Whitelist damains which should transmit errors to Raygun. @@ -241,12 +256,20 @@ interface RaygunStatic { /** * Executed before the payload is sent. If a truthy object is returned, Raygun will attempt to use that as the payload. Raygun will abort the send if `false` is returned. */ - onBeforeSend(callback: (payload: RaygunPayload) => RaygunPayload|boolean): RaygunStatic; + onBeforeSend( + callback: (payload: RaygunPayload) => RaygunPayload | boolean + ): RaygunStatic; /** * Overrides the default automatic grouping and instead group errors together by the string returned by the callback. */ - groupingKey(callback: (payload: RaygunPayload, stackTrace: TracekitStackTrace, options: any) => string|void): RaygunStatic; + groupingKey( + callback: ( + payload: RaygunPayload, + stackTrace: TracekitStackTrace, + options: any + ) => string | void + ): RaygunStatic; onBeforeXHR(callback: (xhr: XMLHttpRequest) => void): RaygunStatic; onAfterSend(callback: (response: XMLHttpRequest) => void): RaygunStatic; endSession(): void; @@ -259,22 +282,29 @@ interface RaygunStatic { /** * Records a manual breadcrumb with the given message and metadata passed. */ - recordBreadcrumb(message:string,metadata?:any): void; + recordBreadcrumb(message: string, metadata?: any): void; /** * Enables all breadcrumbs level or a type can be passed which will enable only that passed one. */ - enableAutoBreadcrumbs(type?:"XHR"|"Clicks"|"Console"|"Navigation"): void; + enableAutoBreadcrumbs( + type?: "XHR" | "Clicks" | "Console" | "Navigation" + ): void; /** * Disables all breadcrumbs or a type can be passed to disable only that one. */ - disableAutoBreadcrumbs(type?:"XHR"|"Clicks"|"Console"|"Navigation"): void; + disableAutoBreadcrumbs( + type?: "XHR" | "Clicks" | "Console" | "Navigation" + ): void; /** * Pass "breadcrumbsLevel" alongside a valid breadcrumbs level to set the current level. Passing options other than "breadcrumbsLevel" will set xhr hosts to ignore being */ - setBreadcrumbOption(option?:string|"breadcrumbsLevel", value?:string|"debug"|"info"|"warning"|"error"): void; + setBreadcrumbOption( + option?: string | "breadcrumbsLevel", + value?: string | "debug" | "info" | "warning" | "error" + ): void; } interface RaygunV2UserDetails { @@ -286,7 +316,7 @@ interface RaygunV2UserDetails { /** * Indicates whether the user is anonymous or has a user account. Even if this is set to true, you should still give the user a unique identifier of some kind. */ - isAnonymous?: string; + isAnonymous?: boolean; /** * The user's email address. @@ -309,42 +339,79 @@ interface RaygunV2UserDetails { uuid?: string; } - +type BreadcrumbLevel = "debug" | "error" | "warning" | "info"; interface RaygunV2 { - (key: "options", value:RaygunOptions):void; - (key: "setUser", value: RaygunV2UserDetails):void; - (key: "onBeforeSend", callback: (payload: RaygunPayload) => RaygunPayload|boolean):void; - (key: "onBeforeXHR"|"onAfterSend", callback: (xhr: XMLHttpRequest) => void): void; - (key: "groupingKey", value:(payload: RaygunPayload, stackTrace: TracekitStackTrace, options: any) => string|void):void; - (key: "trackEvent", value: { type: string, path: string }): void; - (key: "apiKey"|"setVersion"|"setFilterScope", value:string):void; - (key: "attach"|"enableCrashReporting"|"enablePulse"|"noConflict"|"saveIfOffline", value: boolean):void; - (key: "filterSensitiveData"|"whitelistCrossOriginDomains"|"withTags", values: string[]): void; - (key: "send"|"withCustomData", value: any): void; - (key: "getRaygunInstance"):RaygunStatic; - (key: "detach"): void; - (key: "disableAutoBreadcrumbs"): void; - (key: "enableAutoBreadcrumbs"): void; - (key: "disableAutoBreadcrumbsConsole"): void; - (key: "enableAutoBreadcrumbsConsole"): void; - (key: "disableAutoBreadcrumbsNavigation"): void; - (key: "enableAutoBreadcrumbsNavigation"): void; - (key: "disableAutoBreadcrumbsClicks"): void; - (key: "enableAutoBreadcrumbsClicks"): void; - (key: "disableAutoBreadcrumbsXHR"): void; - (key: "enableAutoBreadcrumbsXHR"): void; - (key: "setAutoBreadcrumbsXHRIgnoredHosts"): void; - (key: "setBreadcrumbLevel"): void; - (key: "recordBreadcrumb", message:string|{message:string,metadata:any,level:string|"debug"|"info"|"warning"|"error",location:string}, metadata:any): void; - (key: string):void; + (key: "options", value: RaygunOptions): void; + (key: "setUser", value: RaygunV2UserDetails): void; + ( + key: "onBeforeSend", + callback: (payload: RaygunPayload) => RaygunPayload | boolean + ): void; + ( + key: "onBeforeXHR" | "onAfterSend", + callback: (xhr: XMLHttpRequest) => void + ): void; + ( + key: "groupingKey", + value: ( + payload: RaygunPayload, + stackTrace: TracekitStackTrace, + options: any + ) => string | void + ): void; + (key: "trackEvent", value: { type: string; path: string }): void; + (key: "apiKey" | "setVersion" | "setFilterScope", value: string): void; + ( + key: + | "attach" + | "enableCrashReporting" + | "enablePulse" + | "noConflict" + | "saveIfOffline", + value: boolean + ): void; + ( + key: "filterSensitiveData" | "whitelistCrossOriginDomains" | "withTags", + values: string[] + ): void; + (key: "send" | "withCustomData", value: any): void; + (key: "getRaygunInstance"): RaygunStatic; + ( + key: + | "detach" + | "disableAutoBreadcrumbs" + | "enableAutoBreadcrumbs" + | "disableAutoBreadcrumbsConsole" + | "enableAutoBreadcrumbsConsole" + | "disableAutoBreadcrumbsNavigation" + | "enableAutoBreadcrumbsNavigation" + | "disableAutoBreadcrumbsClicks" + | "enableAutoBreadcrumbsClicks" + | "disableAutoBreadcrumbsXHR" + | "enableAutoBreadcrumbsXHR" + | "setAutoBreadcrumbsXHRIgnoredHosts" + ): void; + (key: "setBreadcrumbLevel", level: BreadcrumbLevel): void; + ( + key: "recordBreadcrumb", + message: + | string + | { + message: string; + metadata: any; + level: BreadcrumbLevel; + location: string; + }, + metadata: object + ): void; } +declare const rg4js: RaygunV2; + interface Window { Raygun: RaygunStatic; } -declare var Raygun: RaygunStatic; +export { RaygunStatic, RaygunV2 }; -declare module 'raygun4js' { - export = Raygun; -} +export default rg4js; diff --git a/types/raygun4js/raygun4js-tests.ts b/types/raygun4js/raygun4js-tests.ts index 7fe6fc6496..388c960276 100644 --- a/types/raygun4js/raygun4js-tests.ts +++ b/types/raygun4js/raygun4js-tests.ts @@ -1,8 +1,7 @@ // V2 Api +// Used in CommonJS-like environments -// To use the V2 api you will need to declare a `rg4js` variable -// This is because `rg4js` name is configurable by users -declare var rg4js: RaygunV2; +import rg4js, { RaygunStatic } from 'raygun4js'; rg4js("apiKey", "api-key"); rg4js("enableCrashReporting", true); @@ -13,16 +12,25 @@ rg4js('setUser', { fullName: "Robert Raygun" }); +try { + throw new Error('oops'); +} catch (e) { + rg4js('send', e); +} + // V1 Api -var client: RaygunStatic = Raygun.noConflict(); -var newClient: RaygunStatic = client.constructNewRaygun(); +// Used in non CommonJS enviroments +declare const Raygun: RaygunStatic; + +const client: RaygunStatic = Raygun.noConflict(); +const newClient: RaygunStatic = client.constructNewRaygun(); client.init('api-key'); client.init('api-key', { allowInsecureSubmissions: true, disablePulse: false }); client.init('api-key', { allowInsecureSubmissions: true, disablePulse: false }, { some: 'data' }); client.withCustomData({ some: 'data' }); -client.withCustomData(function() { +client.withCustomData(() => { return { some: 'data' }; }); @@ -36,8 +44,7 @@ client.send(new Error('a error'), { some: 'data' }, ['tag1', 'tag2']); try { throw new Error('oops'); -} -catch (e) { +} catch (e) { client.send(e); } @@ -57,7 +64,7 @@ client.setFilterScope('all'); client.whitelistCrossOriginDomains(['domain1', 'domain2']); -client.onBeforeSend(payload=> { +client.onBeforeSend(payload => { payload.OccurredOn = new Date(); return payload; }); diff --git a/types/raygun4js/tslint.json b/types/raygun4js/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/raygun4js/tslint.json +++ b/types/raygun4js/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/rc-time-picker/index.d.ts b/types/rc-time-picker/index.d.ts new file mode 100644 index 0000000000..62f6a7711a --- /dev/null +++ b/types/rc-time-picker/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for rc-time-picker 3.4 +// Project: http://github.com/react-component/time-picker +// Definitions by: Frithjof Winkelmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as moment from "moment"; +import * as React from 'react'; + +interface TimePickerProps { + prefixCls: string; + clearText: string; + disabled: boolean; + allowEmpty: boolean; + open: boolean; + defaultValue: moment.Moment; + defaultOpenValue: moment.Moment; + value: moment.Moment; + placeholder: string; + className: string; + id: string; + popupClassName: string; + showHour: boolean; + showMinute: boolean; + showSecond: boolean; + format: string; + disabledHours: () => number[]; + disabledMinutes: (hour: number) => number[]; + disabledSeconds: (hour: number, minute: number) => number[]; + use12Hours: boolean; + hideDisabledOptions: boolean; + onChange: (value: moment.Moment) => void; + addon: (timepicker: TimePicker) => JSX.Element; + placement: string; + transitionName: string; + onOpen: (state: { open: boolean }) => void; + onClose: (state: { open: boolean }) => void; + hourStep: number; + minuteStep: number; + secondStep: number; + focusOnOpen: boolean; + inputReadOnly: boolean; + inputIcon: React.ReactNode; + clearIcon: React.ReactNode; +} + +declare class TimePicker extends React.Component> { + constructor(props: Readonly>) + + close(): void; + isAM(): boolean; +} + +export = TimePicker; diff --git a/types/rc-time-picker/rc-time-picker-tests.tsx b/types/rc-time-picker/rc-time-picker-tests.tsx new file mode 100644 index 0000000000..7f0ea63e9c --- /dev/null +++ b/types/rc-time-picker/rc-time-picker-tests.tsx @@ -0,0 +1,10 @@ +import TimePicker from 'rc-time-picker'; +import * as React from 'react'; +import moment from 'moment'; + + {}} + placeholder={'Input time'} + showSecond={false} + onOpen={({open}: { open: boolean }) => {}}/>; diff --git a/types/rc-time-picker/tsconfig.json b/types/rc-time-picker/tsconfig.json new file mode 100644 index 0000000000..adda4c82bb --- /dev/null +++ b/types/rc-time-picker/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, + "jsx": "react", + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "rc-time-picker-tests.tsx" + ] +} diff --git a/types/rc-time-picker/tslint.json b/types/rc-time-picker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rc-time-picker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rdf-js/index.d.ts b/types/rdf-js/index.d.ts index 41491d8d09..964f042134 100644 --- a/types/rdf-js/index.d.ts +++ b/types/rdf-js/index.d.ts @@ -297,7 +297,7 @@ export interface DataFactory { * @see Triple * @see DefaultGraph */ - triple(subject: Q_In['subject'], predicate: Q_In['predicate'], object: Q_In['object']): Q_Out; + triple(subject: Q['subject'], predicate: Q['predicate'], object: Q['object']): Q; /** * @param subject The quad subject term. @@ -307,7 +307,7 @@ export interface DataFactory { * @return A new instance of Quad. * @see Quad */ - quad(subject: Q_In['subject'], predicate: Q_In['predicate'], object: Q_In['object'], graph?: Q_In['graph']): Q_Out; + quad(subject: Q['subject'], predicate: Q['predicate'], object: Q['object'], graph?: Q['graph']): Q; } /* Stream Interfaces */ diff --git a/types/rdf-js/rdf-js-tests.ts b/types/rdf-js/rdf-js-tests.ts index eb55002149..12b92b952d 100644 --- a/types/rdf-js/rdf-js-tests.ts +++ b/types/rdf-js/rdf-js-tests.ts @@ -77,7 +77,7 @@ function test_datafactory() { object: Term; graph: Term; } - const quad = dataFactory.quad(literal1, blankNode1, term, term); + const quad = dataFactory.quad(literal1, blankNode1, term, term); const hasBnode = quad.predicate.termType === "BlankNode"; } diff --git a/types/rdf-js/tslint.json b/types/rdf-js/tslint.json index e27ad90359..724f3870ca 100644 --- a/types/rdf-js/tslint.json +++ b/types/rdf-js/tslint.json @@ -1,6 +1,5 @@ { "extends": "dtslint/dt.json", "rules": { - "no-unnecessary-generics": false } } diff --git a/types/reach__router/index.d.ts b/types/reach__router/index.d.ts index 60b1c6253e..ed3a6ff649 100644 --- a/types/reach__router/index.d.ts +++ b/types/reach__router/index.d.ts @@ -24,7 +24,9 @@ export interface History { navigate: NavigateFn; } -export class Router extends React.Component { } +export class Router extends React.Component< + RouterProps & React.HTMLProps +> {} export interface RouterProps { basepath?: string; diff --git a/types/reach__router/reach__router-tests.tsx b/types/reach__router/reach__router-tests.tsx index d279547fd2..a64e1ae70d 100644 --- a/types/reach__router/reach__router-tests.tsx +++ b/types/reach__router/reach__router-tests.tsx @@ -4,9 +4,9 @@ import { RouteComponentProps, Router, Redirect -} from "@reach/router"; -import * as React from "react"; -import { render } from "react-dom"; +} from '@reach/router'; +import * as React from 'react'; +import { render } from 'react-dom'; interface DashParams { id: string; @@ -21,7 +21,7 @@ const Dash = (props: RouteComponentProps) => ( const NotFound = (props: RouteComponentProps) =>
Route not found
; render( - + @@ -33,18 +33,18 @@ render( - + {context => ( <>
hostname is {context.location.hostname}
- )}
, - document.getElementById("app-root") + document.getElementById('app-root') ); diff --git a/types/react-alert/index.d.ts b/types/react-alert/index.d.ts index 3814b7f29f..6c94da77b0 100644 --- a/types/react-alert/index.d.ts +++ b/types/react-alert/index.d.ts @@ -1,110 +1,97 @@ -// Type definitions for react-alert 2.4 +// Type definitions for react-alert 4.0 // Project: https://github.com/schiehll/react-alert -// Definitions by: Steve Syrell +// Definitions by: Yue Yang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from "react"; +import * as React from 'react'; -export interface AlertContainerProps { - /** - * The offset of the alert from the page border, can be any number. - * - * Default: 14. - */ - offset: number; +export type AlertPosition = + | 'top left' + | 'top right' + | 'top center' + | 'bottom left' + | 'bottom right' + | 'bottom center'; - /** - * The position of the alert. Can be [bottom left, bottom right, top left, top right]. - * - * Default: 'bottom left' - */ - position: string; +export type AlertType = 'info' | 'success' | 'error'; +export type AlertTransition = 'fade' | 'scale'; +export interface ProviderOptions { /** - * The color theme of the alert. Can be [dark, light]. + * The margin of each alert * - * Default: 'dark' + * Default value: '10px' */ - theme: string; - + offset?: string; /** - * The time in milliseconds the alert is displayed. After this - * time ellapses, the alert will close itself. Use 0 to prevent self-closure - * (applies to all alerts). + * The position of the alerts in the page * - * Default: 5000 + * Default value: 'top center' */ - time: number; - + position?: AlertPosition; /** - * The transition animation. Can be [scale, fade]. + * Timeout to alert remove itself, if set to 0 it never removes itself * - * Default: 'scale' + * Default value: 0 */ - transition: string; + timeout?: number; + /** + * The default alert type used when calling this.props.alert.show + * + * Default value: 'info' + */ + type?: AlertType; + /** + * The transition animation + * + * Default value: 'fade' + */ + transition?: AlertTransition; + /** + * The z-index of alerts + * + * Default value: 100 + */ + zIndex?: number; } -export interface AlertShowOptions { - /** - * The time in milliseconds the alert is displayed. After this - * time ellapses, the alert will close itself. Use 0 to prevent self-closure. - */ - time?: number; +export class Provider extends React.Component {} - /** - * The icon to show in the alert. - * - * Default: the icon which matches the type of alert to be shown. - */ - icon?: React.ReactNode; +export const Alert: React.Consumer; +export interface AlertCustomOptions { /** - * A callback function that will be called when the alert is closed. + * Custom timeout just for this one alert */ - onClose?: () => void; - + timeout?: number; /** - * The type of alert to show. This will only be used when calling show(). - * Can be [info, success, error]. - * - * Default: 'info' + * Callback that will be executed after this alert open */ - type?: string; + onOpen?(): undefined; + /** + * Callback that will be executed after this alert is removed + */ + onClose?(): undefined; } -export default class AlertContainer extends React.Component { - /** - * Show a success alert. - * @returns The id of the created alert. - */ - success(message: string, options?: AlertShowOptions): string; - - /** - * Show an error alert. - * @returns The id of the created alert. - */ - error(message: string, options?: AlertShowOptions): string; - - /** - * Show an info alert. - * @returns The id of the created alert. - */ - info(message: string, options?: AlertShowOptions): string; - - /** - * Show an alert. - * @returns The id of the created alert. - */ - show(message: string, options?: AlertShowOptions): string; - - /** - * Remove all alerts from the page. - */ - removeAll(): void; - - /** - * Removes the alert with the specified id from the page. - */ - remove(id: string): void; +export interface AlertCustomOptionsWithType extends AlertCustomOptions { + type?: AlertType; } + +export interface InjectedAlertProp { + show( + message?: string, + options?: AlertCustomOptionsWithType + ): InjectedAlertProp; + remove(alert: InjectedAlertProp): undefined; + success(message?: string, options?: AlertCustomOptions): InjectedAlertProp; + error(message?: string, options?: AlertCustomOptions): InjectedAlertProp; + info(message?: string, options?: AlertCustomOptions): InjectedAlertProp; +} + +export function withAlert

( + c: React.ComponentType

+): React.ComponentType>>; diff --git a/types/react-alert/react-alert-tests.tsx b/types/react-alert/react-alert-tests.tsx index 84686ea73d..c6088a52a8 100644 --- a/types/react-alert/react-alert-tests.tsx +++ b/types/react-alert/react-alert-tests.tsx @@ -1,48 +1,91 @@ -import * as React from "react"; -import AlertContainer, { AlertContainerProps, AlertShowOptions } from "react-alert"; +import * as React from 'react'; +import { + Provider as AlertProvider, + Alert, + withAlert, + AlertPosition, + AlertTransition, + ProviderOptions, + InjectedAlertProp +} from 'react-alert'; -export class ReactAlertTest extends React.Component { - private _alert: AlertContainer; +class AppWithoutAlert extends React.Component<{ alert: InjectedAlertProp }> { render() { - const props: AlertContainerProps = { - offset: 14, - position: "bottom left", - theme: "dark", - time: 5000, - transition: "scale" - }; + return ( + + ); + } +} + +const App = withAlert(AppWithoutAlert); + +class AppAlert extends React.Component { + render() { + return ( + + {alert => ( + + )} + + ); + } +} + +class AlertTemplate extends React.Component { + render() { + // the style contains only the margin given as offset + // options contains all alert given options + // message is the alert message... + // close is a function that closes the alert + const { style, options, message, close } = this.props; return ( -

- this._alert = a as AlertContainer} {...props} /> +
+ {options.type === 'info' && '!'} + {options.type === 'success' && ':)'} + {options.type === 'error' && ':('} + {message} +
); } +} - private _testMethods(): void { - const options: AlertShowOptions = { - time: 5000, - type: "info", - onClose: this._onAlertClosed, - icon: - }; +const options: ProviderOptions = { + position: 'bottom center' as AlertPosition, + timeout: 5000, + offset: '30px', + transition: 'scale' as AlertTransition +}; - let alertId: string; - alertId = this._alert.show("show without options"); - alertId = this._alert.show("show with options", options); - - alertId = this._alert.error("error without options"); - alertId = this._alert.error("error with options", options); - - alertId = this._alert.info("info without options"); - alertId = this._alert.info("info with options", options); +class Root extends React.Component { + render() { + return ( + + + + ); + } +} - alertId = this._alert.success("success without options"); - alertId = this._alert.success("success with options", options); - - this._alert.remove(alertId); - this._alert.removeAll(); +class RootAlert extends React.Component { + render() { + return ( + + + + ); } - - private _onAlertClosed(): void { } } diff --git a/types/react-alert/v2/index.d.ts b/types/react-alert/v2/index.d.ts new file mode 100644 index 0000000000..3814b7f29f --- /dev/null +++ b/types/react-alert/v2/index.d.ts @@ -0,0 +1,110 @@ +// Type definitions for react-alert 2.4 +// Project: https://github.com/schiehll/react-alert +// Definitions by: Steve Syrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export interface AlertContainerProps { + /** + * The offset of the alert from the page border, can be any number. + * + * Default: 14. + */ + offset: number; + + /** + * The position of the alert. Can be [bottom left, bottom right, top left, top right]. + * + * Default: 'bottom left' + */ + position: string; + + /** + * The color theme of the alert. Can be [dark, light]. + * + * Default: 'dark' + */ + theme: string; + + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure + * (applies to all alerts). + * + * Default: 5000 + */ + time: number; + + /** + * The transition animation. Can be [scale, fade]. + * + * Default: 'scale' + */ + transition: string; +} + +export interface AlertShowOptions { + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure. + */ + time?: number; + + /** + * The icon to show in the alert. + * + * Default: the icon which matches the type of alert to be shown. + */ + icon?: React.ReactNode; + + /** + * A callback function that will be called when the alert is closed. + */ + onClose?: () => void; + + /** + * The type of alert to show. This will only be used when calling show(). + * Can be [info, success, error]. + * + * Default: 'info' + */ + type?: string; +} + +export default class AlertContainer extends React.Component { + /** + * Show a success alert. + * @returns The id of the created alert. + */ + success(message: string, options?: AlertShowOptions): string; + + /** + * Show an error alert. + * @returns The id of the created alert. + */ + error(message: string, options?: AlertShowOptions): string; + + /** + * Show an info alert. + * @returns The id of the created alert. + */ + info(message: string, options?: AlertShowOptions): string; + + /** + * Show an alert. + * @returns The id of the created alert. + */ + show(message: string, options?: AlertShowOptions): string; + + /** + * Remove all alerts from the page. + */ + removeAll(): void; + + /** + * Removes the alert with the specified id from the page. + */ + remove(id: string): void; +} diff --git a/types/react-alert/v2/react-alert-tests.tsx b/types/react-alert/v2/react-alert-tests.tsx new file mode 100644 index 0000000000..84686ea73d --- /dev/null +++ b/types/react-alert/v2/react-alert-tests.tsx @@ -0,0 +1,48 @@ +import * as React from "react"; +import AlertContainer, { AlertContainerProps, AlertShowOptions } from "react-alert"; + +export class ReactAlertTest extends React.Component { + private _alert: AlertContainer; + render() { + const props: AlertContainerProps = { + offset: 14, + position: "bottom left", + theme: "dark", + time: 5000, + transition: "scale" + }; + + return ( +
+ this._alert = a as AlertContainer} {...props} /> +
+ ); + } + + private _testMethods(): void { + const options: AlertShowOptions = { + time: 5000, + type: "info", + onClose: this._onAlertClosed, + icon: + }; + + let alertId: string; + alertId = this._alert.show("show without options"); + alertId = this._alert.show("show with options", options); + + alertId = this._alert.error("error without options"); + alertId = this._alert.error("error with options", options); + + alertId = this._alert.info("info without options"); + alertId = this._alert.info("info with options", options); + + alertId = this._alert.success("success without options"); + alertId = this._alert.success("success with options", options); + + this._alert.remove(alertId); + this._alert.removeAll(); + } + + private _onAlertClosed(): void { } +} diff --git a/types/react-alert/v2/tsconfig.json b/types/react-alert/v2/tsconfig.json new file mode 100644 index 0000000000..47de249c7e --- /dev/null +++ b/types/react-alert/v2/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "react-alert": ["react-alert/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-alert-tests.tsx" + ] +} diff --git a/types/react-alert/v2/tslint.json b/types/react-alert/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-alert/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-infinite-scroller/index.d.ts b/types/react-infinite-scroller/index.d.ts index 12388231ce..f0af24ac5e 100644 --- a/types/react-infinite-scroller/index.d.ts +++ b/types/react-infinite-scroller/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for react-infinite-scroller 1.0 +// Type definitions for react-infinite-scroller 1.2 // Project: https://github.com/CassetteRocks/react-infinite-scroller // Definitions by: Lauri Lavanti , // Piotr Srebniak // Brett Miller +// Yipeng Zhao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -62,6 +63,10 @@ declare namespace InfiniteScroll { * Loader component for indicating "loading more". */ loader?: React.ReactElement; + /** + * Override method to return a different scroll listener if it's not the immediate parent of InfiniteScroll. + */ + getScrollParent?(): HTMLElement | null; } class InfiniteScroll extends React.Component { getParentElement(elem?: HTMLElement | null): HTMLElement | undefined | null; diff --git a/types/react-infinite-scroller/react-infinite-scroller-tests.tsx b/types/react-infinite-scroller/react-infinite-scroller-tests.tsx index 8f08d576e6..eeb2214826 100644 --- a/types/react-infinite-scroller/react-infinite-scroller-tests.tsx +++ b/types/react-infinite-scroller/react-infinite-scroller-tests.tsx @@ -27,12 +27,29 @@ class Test2 extends React.Component { useCapture useWindow={false} > -
Test 1
+
Test 2
); } } +class Test3 extends React.Component { + inputRef = React.createRef(); + + render() { + return ( +
+ {}} + getScrollParent={() => this.inputRef.current} + > +
Test 3
+
+
+ ); + } +} + class InfiniteScrollOverride extends InfiniteScroll { getParentElement(el: HTMLElement) { if (document.getElementById("scroll-header")) { diff --git a/types/react-instantsearch-core/index.d.ts b/types/react-instantsearch-core/index.d.ts new file mode 100644 index 0000000000..e428cc6432 --- /dev/null +++ b/types/react-instantsearch-core/index.d.ts @@ -0,0 +1,468 @@ +// Type definitions for react-instantsearch-core 5.2 +// Project: https://community.algolia.com/react-instantsearch/ +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as React from 'react'; + +// Core +/** + * Creates a specialized root InstantSearch component. It accepts + * an algolia client and a specification of the root Element. + * @param defaultAlgoliaClient - a function that builds an Algolia client + * @param root - the defininition of the root of an InstantSearch sub tree. + * @returns an InstantSearch root + */ +export function createInstantSearch( + defaultAlgoliaClient: (appId: string, apiKey: string, options: { _useRequestCache: boolean }) => object, + root: object +): React.ComponentClass; + +/** + * Creates a specialized root Index component. It accepts + * a specification of the root Element. + * @param defaultRoot - the defininition of the root of an Index sub tree. + * @return a Index root + */ +export function createIndex(defaultRoot: object): React.ComponentClass; + +export interface ConnectorDescription { + displayName: string; + propTypes?: any; + defaultProps?: any; + + /** + * This method should return the props to forward to the composed component. + * props are the props that were provided to the higher-order component. + * searchState holds the search state of all widgets. You can find the shape of all widgets search state in the corresponding guide. + * searchResults holds the search results, search errors and search loading state, with the shape + * {results: ?SearchResults, error: ?Error, searching: boolean, searchingForFacetValues: boolean}. The SearchResults type is described in the Helper’s documentation. + * meta is the list of metadata from all widgets whose connector defines a getMetadata method. + * searchForFacetValuesResults holds the search for facet values results. + */ + getProvidedProps?(...args: any[]): any; + + /** + * This method defines exactly how the refine prop of widgets affects the search state. + * It takes in the current props of the higher-order component, the search state of all widgets, as well as all arguments passed + * to the refine and createURL props of stateful widgets, and returns a new state. + */ + refine?(...args: any[]): any; + + /** + * This method applies the current props and state to the provided SearchParameters, and returns a new SearchParameters. The SearchParameters + * type is described in the Helper’s documentation. + * Every time the props or state of a widget change, all the getSearchParameters methods of all the registered widgets are called in a chain + * to produce a new SearchParameters. Then, if the output SearchParameters differs from the previous one, a new search is triggered. + * As such, the getSearchParameters method allows you to describe how the state and props of a widget should affect the search parameters. + */ + getSearchParameters?(...args: any[]): any; + + /** + * This method allows the widget to register a custom metadata object for any props and state combination. + * If your widget is stateful, the corresponding URL key should be declared on the metadata object as the id property, so that the InstantSearch + * component can determine which URL keys it controls and which are foreign and should be left intact. + * The metadata object also allows you to declare any data that you would like to pass down to all other widgets. The list of metadata objects of + * all components is available as the fourth argument to the getProvidedProps method. + * The CurrentRefinements widget leverages this mechanism in order to allow any widget to declare the filters it has applied. If you want to add + * your own filter, declare a filters property on your widget’s metadata + */ + getMetadata?(...args: any[]): any; + + /** + * This method needs to be implemented if you want to have the ability to perform a search for facet values inside your widget. + * It takes in the current props of the higher-order component, the search state of all widgets, as well as all arguments passed to the searchForFacetValues + * props of stateful widgets, and returns an object of the shape: {facetName: string, query: string, maxFacetHits?: number}. The default value for the + * maxFacetHits is the one set by the API which is 10. + */ + searchForFacetValues?(...args: any[]): any; + + /** + * This method is called when a widget is about to unmount in order to clean the searchState. + * It takes in the current props of the higher-order component and the searchState of all widgets and expect a new searchState in return. + * props are the props that were provided to the higher-order component. + * searchState holds the searchState of all widgets, with the shape {[widgetId]: widgetState}. Stateful widgets describe the format of their searchState + * in their respective documentation entry. + */ + cleanUp?(...args: any[]): any; +} + +/** + * Connectors are the HOC used to transform React components + * into InstantSearch widgets. + * In order to simplify the construction of such connectors + * `createConnector` takes a description and transform it into + * a connector. + * @param connectorDesc the description of the connector + * @return a function that wraps a component into + * an instantsearch connected one. + */ +export function createConnector(connectorDesc: ConnectorDescription): (Composed: React.ComponentType) => React.ComponentClass; + +// Utils +export const HIGHLIGHT_TAGS: { + highlightPreTag: string, + highlightPostTag: string, +}; +export const version: string; +export function translatable(defaultTranslations: any): (Composed: React.ComponentType) => React.ComponentClass; + +// Widgets +/** + * Configure is a widget that lets you provide raw search parameters + * to the Algolia API. + * + * Any of the props added to this widget will be forwarded to Algolia. For more information + * on the different parameters that can be set, have a look at the + * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). + * + * This widget can be used either with react-dom and react-native. It will not render anything + * on screen, only configure some parameters. + */ +export class Configure extends React.Component {} + +// Connectors +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 interface NESW { + northEast: { lat: number, lng: number }; + southWest: { lat: number, lng: number }; +} + +export interface GeoSearchExposed { + defaultRefinement?: NESW; +} +export interface GeoSearchProvided { + /** a function to toggle the refinement */ + refine: (refinement: NESW) => void; + /** a function to generate a URL for the corresponding search state */ + createURL: (...args: any[]) => any; + /** the records that matched the search */ + hits: THit[]; + /** true if the current refinement is set with the map bounds */ + isRefinedWithMap: boolean; + /** the refinement currently applied */ + currentRefinement: NESW; + /** the position of the search */ + position: { lat: number, lng: number }; +} +/** + * The GeoSearch connector provides the logic to build a widget that will display the results on a map. + * It also provides a way to search for results based on their position. The connector provides function to manage the + * search experience (search on map interaction). + * + * https://community.algolia.com/react-instantsearch/connectors/connectGeoSearch.html + */ +export function connectGeoSearch(stateless: React.StatelessComponent): React.ComponentClass; +export function connectGeoSearch>, THit>(ctor: React.ComponentType): ConnectedComponentClass, GeoSearchExposed>; + +export function connectHierarchicalMenu(Composed: React.ComponentType): React.ComponentClass; +export function connectHighlight(Composed: React.ComponentType): React.ComponentClass; + +/** + * connectHits connector provides the logic to create connected components that will render the results retrieved from Algolia. + * To configure the number of hits retrieved, use HitsPerPage widget, connectHitsPerPage connector or pass the hitsPerPage prop to a Configure widget. + * Warning: you will need to use the objectID property available on every hit as a key when iterating over them. This will ensure you have the best possible UI experience especially on slow networks. + * + * https://community.algolia.com/react-instantsearch/connectors/connectHits.html + */ +export function connectHits(ctor: React.ComponentType): ConnectedComponentClass; + +export function connectHitsPerPage(Composed: React.ComponentType): React.ComponentClass; +export function connectInfiniteHits(Composed: React.ComponentType): React.ComponentClass; + +export interface MenuProvided { + items: Array<{count: number, isRefined: boolean, label: string, value: string}>; + currentRefinement: string; + refine: (...args: any[]) => any; + createURL: (...args: any[]) => any; + searchForItems: (...args: any[]) => any; + isFromSearch: boolean; +} +export interface MenuExposed { + attribute: string; + showMore?: boolean; + limit?: number; + showMoreLimit?: number; + defaultRefinement?: string; + transformItems?: (...args: any[]) => any; + searchable?: boolean; +} +/** + * connectMenu connector provides the logic to build a widget that will give the user the ability to choose a single value for a specific facet. + * + * https://community.algolia.com/react-instantsearch/connectors/connectMenu.html + */ +export function connectMenu(stateless: React.StatelessComponent): React.ComponentClass; +export function connectMenu>(ctor: React.ComponentType): ConnectedComponentClass; + +export interface NumericMenuProvided { + /** the list of ranges the NumericMenu can display. */ + items: Array<{isRefined: boolean, label: string, value: string, noRefinement: boolean}>; + /** + * the refinement currently applied. follow the shape of a string with a pattern of '{start}:{end}' which corresponds to the current selected item. + * For instance, when the selected item is {start: 10, end: 20}, the searchState of the widget is '10:20'. When start isn’t defined, the searchState + * of the widget is ':{end}', and the same way around when end isn’t defined. However, when neither start nor end are defined, the searchState is an empty string. + */ + currentRefinement: string; + /** a function to select a range. */ + refine: (...args: any[]) => any; + /** a function to generate a URL for the corresponding search state */ + createURL: (...args: any[]) => any; +} +export interface NumericMenuExposed { + id?: string; + /** the name of the attribute in the records */ + attribute: string; + /** List of options. With a text label, and upper and lower bounds. */ + items: Array<{ + label: string | JSX.Element; + start?: number; + end?: number; + }>; + /** the value of the item selected by default, follow the shape of a string with a pattern of '{start}:{end}'. */ + defaultRefinement?: string; + /** (...args: any[]) => any 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; +} +/** + * connectNumericMenu connector provides the logic to build a widget that will give the user the ability to select a range value for a numeric attribute. + * Ranges are defined statically. + * + * https://community.algolia.com/react-instantsearch/connectors/connectNumericMenu.html + */ +export function connectNumericMenu(stateless: React.StatelessComponent): React.ComponentClass; +export function connectNumericMenu>(ctor: React.ComponentType): ConnectedComponentClass; + +export function connectPagination(Composed: React.ComponentType): React.ComponentClass; +export function connectPoweredBy(Composed: React.ComponentType): React.ComponentClass; +export function connectRange(Composed: React.ComponentType): React.ComponentClass; + +export interface RefinementListProvided { + /** a function to toggle a refinement */ + refine: (...args: any[]) => 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>; + /** 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. */ + isFromSearch: boolean; +} +export interface RefinementListExposed { + /** the name of the attribute in the record */ + attribute: string; + /** allow search inside values */ + searchable?: boolean; + /** How to apply the refinements. Possible values: ‘or’ or ‘and’. */ + operator?: 'or' | 'and'; + /** true if the component should display a button that will expand the number of items */ + showMore?: boolean; + /** the minimum number of displayed items */ + limit?: number; + /** the maximun number of displayed items. Only used when showMore is set to true */ + showMoreLimit?: number; + /** + * the values of the items selected by default. The searchState of this widget takes the form of a list of strings, + * which correspond to the values of all selected refinements. However, when there are no refinements selected, + * the value of the searchState is an empty string. + */ + defaultRefinement?: string[]; + /** (...args: any[]) => any 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; +} + +/** + * connectRefinementList connector provides the logic to build a widget that will give the user the ability to choose multiple values for a specific facet. + * + * https://community.algolia.com/react-instantsearch/connectors/connectRefinementList.html + */ +export function connectRefinementList(stateless: React.StatelessComponent): React.ComponentClass; +export function connectRefinementList>(ctor: React.ComponentType): + ConnectedComponentClass; + +export function connectScrollTo(Composed: React.ComponentType): React.ComponentClass; + +export interface SearchBoxProvided { + /** a function to change the current query */ + refine: (...args: any[]) => any; + /** the current query used */ + currentRefinement: string; + /** a flag that indicates if InstantSearch has detected that searches are stalled */ + isSearchStalled: boolean; +} +export interface SearchBoxExposed { + /** Provide a default value for the query */ + defaultRefinement?: string; +} +export function connectSearchBox(stateless: React.StatelessComponent): React.ComponentClass; +export function connectSearchBox>(ctor: React.ComponentType): ConnectedComponentClass; + +export function connectSortBy(Composed: React.ComponentType): React.ComponentClass; + +export interface StateResultsProvided { + /** The search state of the instant search component. */ + searchState: SearchState; + /** + * The search results. + * In case of multiple indices: if used under , results will be those of the corresponding index + * otherwise it’ll be those of the root index + */ + searchResults: SearchResults; + /** In case of multiple indices you can retrieve all the results */ + allSearchResults: { [index: string]: SearchResults }; + /** If there is a search in progress. */ + searching: boolean; + /** Flag that indicates if React InstantSearch has detected that searches are stalled. */ + isSearchStalled: any; + /** If the search failed, the error will be logged here. */ + error: AlgoliaError; + /** If there is a search in a list in progress. */ + searchingForFacetValues: any; +} +/** + * The connectStateResults connector provides a way to access the `searchState` and the `searchResults` of InstantSearch. + * For instance this connector allows you to create results/noResults or query/noQuery pages. + * + * https://community.algolia.com/react-instantsearch/connectors/connectStateResults.html + */ +export function connectStateResults(stateless: React.StatelessComponent): React.ComponentClass; +export function connectStateResults>, TDoc>(ctor: React.ComponentType): ConnectedComponentClass>; + +export function connectStats(Composed: React.ComponentType): React.ComponentClass; +export function connectToggleRefinement(Composed: React.ComponentType): React.ComponentClass; + +export interface AlgoliaError { + stack: string; + name: string; + message: string; + debugData: any[]; + statusCode: number; +} + +type Omit = Pick>; + +export type ConnectedComponentClass + = React.ComponentClass & TExposedProps>; + +/** + * The searchState contains all widgets states. If a widget uses an attribute, + * we store it under its widget category to prevent collision. + * + * https://community.algolia.com/react-instantsearch/guide/Search_state.html + */ +export interface SearchState { + range?: { + [key: string]: { + min: number; + max: number; + } + }; + configure?: { + aroundLatLng: boolean; + [key: string]: any; + }; + refinementList?: { + [key: string]: string[] + }; + hierarchicalMenu?: { + [key: string]: string + }; + menu?: { + [key: string]: string + }; + multiRange?: { + [key: string]: string + }; + toggle?: { + [key: string]: boolean + }; + hitsPerPage?: number; + sortBy?: string; + query?: string; + page?: number; + + indices?: { + [index: string]: { + configure: { + hitsPerPage: number, + }, + } + }; +} + +/** + * The most basic possible document in an Algolia index: + * a set of string-value pairs. + */ +export interface BasicDoc { [k: string]: string; } + +/** + * The shape of the searchResults object provided + * via connectors + * https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults + */ +export interface SearchResults { + query: string; + hits: Array>; + index: string; + hitsPerPage: number; + nbHits: number; + nbPages: number; + page: number; + processingTimeMS: number; + exhaustiveNbHits: true; + disjunctiveFacets: any[]; + hierarchicalFacets: any[]; + facets: any[]; + aroundLatLng?: string; + automaticRadius?: string; +} + +/** + * All the records that match the search parameters. + * Each record is augmented with a new attribute `_highlightResult` which is an + * object keyed by attribute and contains additional properties + * https://community.algolia.com/algoliasearch-helper-js/reference.html#SearchResults#hits + */ +export type Hit = TDoc & { + objectID: string; + '_highlightResult': HighlightResult; +}; + +export type HighlightResult = + TDoc extends { [k: string]: any } ? + { [K in keyof TDoc]: HighlightResultField } : + never; + +type HighlightResultField = + TField extends Array ? + HighlightResultArray : + TField extends string ? + HighlightResultPrimitive : + HighlightResult; + +type HighlightResultArray = + TItem extends string ? + HighlightResultPrimitive[] : + Array>; + +interface HighlightResultPrimitive { + /** the value of the facet highlighted (html) */ + value: string; + /** full, partial or none depending on how the query terms match */ + matchLevel: 'none' | 'partial' | 'full'; + matchedWords: string[]; + fullyHighlighted?: boolean; +} + +// Turn off automatic exports - so we don't export internal types like Omit<> +export {}; diff --git a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx new file mode 100644 index 0000000000..62bf99e3d4 --- /dev/null +++ b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx @@ -0,0 +1,155 @@ +import * as React from 'react'; +import { + createInstantSearch, + createIndex, + createConnector, + SearchResults, + connectStateResults, + SearchBoxProvided, + connectSearchBox, + connectRefinementList +} from 'react-instantsearch-core'; + +() => { + const InstantSearch = createInstantSearch(() => ({}), {Root: 'div', props: {className: `widget`}}); + + +
+
; +}; + +() => { + const Index = createIndex({Root: 'div', props: {className: `widget`}}); + + +
+
; +}; + +// https://community.algolia.com/react-instantsearch/guide/Custom_connectors.html +() => { + const CoolWidget = createConnector({ + displayName: 'CoolWidget', + + getProvidedProps(props, searchState) { + // Since the `queryAndPage` searchState entry isn't necessarily defined, we need + // to default its value. + const [query, page] = searchState.queryAndPage || ['', 0]; + + // Connect the underlying component to the `queryAndPage` searchState entry. + return { + query, + page, + }; + }, + + refine(props, searchState, newQuery, newPage) { + // When the underlying component calls its `refine` prop, update the searchState + // with the new query and page. + return { + // `searchState` represents the search state of *all* widgets. We need to extend it + // instead of replacing it, otherwise other widgets will lose their + // respective state. + ...searchState, + queryAndPage: [newQuery, newPage], + }; + }, + })(props => +
+ The query is {props.query}, the page is {props.page}. + {/* + Clicking on this button will update the searchState to: + { + ...otherSearchState, + query: 'algolia', + page: 20, + } + */} +
+ ); + + +
+
; +}; + +() => { + interface StateResultsProps { + searchResults: SearchResults<{ + field1: string + field2: number + field3: { compound: string } + }>; + // partial of StateResultsProvided + + additionalProp: string; + } + + const Stateless = ({ additionalProp, searchResults }: StateResultsProps) => +
+

{additionalProp}

+ {searchResults.hits.map((h) => { + // $ExpectType string + const compound = h._highlightResult.field3.compound.value; + // $ExpectType never + const field2 = h._highlightResult.field2; + return {compound}; + })} +
; + const ComposedStateless = connectStateResults(Stateless); + + ; // $ExpectError + + ; + + class MyComponent extends React.Component { + render() { + const { additionalProp, searchResults } = this.props; + return
+

{additionalProp}

+ {searchResults.hits.map((h) => { + // $ExpectType string[] + const words = h._highlightResult.field3.compound.matchedWords; + return {h.field2}: {words.join(',')}; + })} +
; + } + } + const ComposedMyComponent = connectStateResults(MyComponent); + + ; // $ExpectError + + ; +}; + +() => { + const InstantSearch = createInstantSearch( + () => null, // $ExpectError + {} + ); +}; + +// https://community.algolia.com/react-instantsearch/guide/Connectors.html +() => { + const MySearchBox = ({currentRefinement, refine}: SearchBoxProvided) => + refine(e.target.value)} + />; + + // `ConnectedSearchBox` renders a `` widget that is connected to + // the state, providing it with `currentRefinement` and `refine` props for + // reading and manipulating the current query of the search. + const ConnectedSearchBox = connectSearchBox(MySearchBox); +}; diff --git a/types/react-instantsearch-core/tsconfig.json b/types/react-instantsearch-core/tsconfig.json new file mode 100644 index 0000000000..44fe46a735 --- /dev/null +++ b/types/react-instantsearch-core/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "jsx": "react", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-instantsearch-core-tests.tsx" + ] +} diff --git a/types/react-instantsearch-core/tslint.json b/types/react-instantsearch-core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-instantsearch-core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-instantsearch-dom/index.d.ts b/types/react-instantsearch-dom/index.d.ts new file mode 100644 index 0000000000..f1dec59118 --- /dev/null +++ b/types/react-instantsearch-dom/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for react-instantsearch 5.2 +// Project: https://community.algolia.com/react-instantsearch/ +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as React from 'react'; + +import { Hit, BasicDoc } from 'react-instantsearch-core'; + +// Core +export { createConnector } from 'react-instantsearch-core'; +export { HIGHLIGHT_TAGS } from 'react-instantsearch-core'; +export { translatable } from 'react-instantsearch-core'; + +// Widget +export { Configure } from 'react-instantsearch-core'; + +// Connectors +export { connectAutoComplete } from 'react-instantsearch-core'; +export { connectBreadcrumb } from 'react-instantsearch-core'; +export { connectConfigure } from 'react-instantsearch-core'; +export { connectCurrentRefinements } from 'react-instantsearch-core'; +export { connectGeoSearch } from 'react-instantsearch-core'; +export { connectHierarchicalMenu } from 'react-instantsearch-core'; +export { connectHighlight } from 'react-instantsearch-core'; +export { connectHits } from 'react-instantsearch-core'; +export { connectHitsPerPage } from 'react-instantsearch-core'; +export { connectInfiniteHits } from 'react-instantsearch-core'; +export { connectMenu } from 'react-instantsearch-core'; +export { connectNumericMenu } from 'react-instantsearch-core'; +export { connectPagination } from 'react-instantsearch-core'; +export { connectPoweredBy } from 'react-instantsearch-core'; +export { connectRange } from 'react-instantsearch-core'; +export { connectRefinementList } from 'react-instantsearch-core'; +export { connectScrollTo } from 'react-instantsearch-core'; +export { connectSearchBox } from 'react-instantsearch-core'; +export { connectSortBy } from 'react-instantsearch-core'; +export { connectStateResults } from 'react-instantsearch-core'; +export { connectStats } from 'react-instantsearch-core'; +export { connectToggleRefinement } from 'react-instantsearch-core'; + +// DOM +interface CommonWidgetProps { + /** + * All static text rendered by widgets, such as “Load more”, “Show more” are translatable using the translations prop on relevant widgets. + * This prop is a mapping of keys to translation values. Translation values can be either a String or a (...args: any[]) => any, as some take parameters. + * + * https://community.algolia.com/react-instantsearch/guide/i18n.html + */ + translations?: { [key: string]: string | ((...args: any[]) => any) }; +} + +export interface InstantSearchProps { + apiKey: string; + appId: string; + indexName: string; + + algoliaClient?: any; + searchClient?: any; + createURL?: (...args: any[]) => any; + searchState?: any; + refresh?: boolean; + onSearchStateChange?: (...args: any[]) => any; + onSearchParameters?: (...args: any[]) => any; + resultsState?: any; + root?: { + Root: string | ((...args: any[]) => any); + props: any; + }; +} +/** + * is the root component of all React InstantSearch implementations. It provides all the connected components (aka widgets) a means to interact with the searchState. + * + * https://community.algolia.com/react-instantsearch/widgets/%3CInstantSearch%3E.html + */ +export class InstantSearch extends React.Component {} +export class Index extends React.Component {} +export class Breadcrumb extends React.Component {} +export class ClearRefinements extends React.Component {} +export class CurrentRefinements extends React.Component {} +export class HierarchicalMenu extends React.Component {} +export class Highlight extends React.Component {} + +export interface HitsProps { + hitComponent?: React.ComponentType<{ hit: Hit }>; +} +/** + * Displays a list of hits. + * To configure the number of hits being shown, use the HitsPerPage widget, connectHitsPerPage connector or the Configure widget. + * + * https://community.algolia.com/react-instantsearch/widgets/Hits.html + */ +export class Hits extends React.Component> {} +export class HitsPerPage extends React.Component {} +export class InfiniteHits extends React.Component {} +export class Menu extends React.Component {} +export class MenuSelect extends React.Component {} +export class NumericMenu extends React.Component {} +export class Pagination extends React.Component {} +export class Panel extends React.Component {} +export class PoweredBy extends React.Component {} +export class RangeInput extends React.Component {} +export class RangeSlider extends React.Component {} +export class RatingMenu extends React.Component {} +export class RefinementList extends React.Component {} +export class ScrollTo extends React.Component {} + +export interface SearchBoxProps extends CommonWidgetProps { + focusShortcuts?: string[]; + autoFocus?: boolean; + defaultRefinement?: string; + searchAsYouType?: boolean; + showLoadingIndicator?: boolean; + + submit?: JSX.Element; + reset?: JSX.Element; + loadingIndicator?: JSX.Element; + + onSubmit?: (...args: any[]) => any; + onReset?: (...args: any[]) => any; +} +/** + * The SearchBox component displays a search box that lets the user search for a specific query. + * + * https://community.algolia.com/react-instantsearch/widgets/SearchBox.html + */ +export class SearchBox extends React.Component {} +export class Snippet extends React.Component {} +export class SortBy extends React.Component {} +/** + * The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server). + */ +export class Stats extends React.Component<{translations?: { [key: string]: (n: number, ms: number) => string }}> {} +export class ToggleRefinement extends React.Component {} diff --git a/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx new file mode 100644 index 0000000000..6d9b7b55f8 --- /dev/null +++ b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx @@ -0,0 +1,265 @@ +import * as React from 'react'; +import { InstantSearch, Hits, Highlight, SearchBox, RefinementList, CurrentRefinements, ClearRefinements, Pagination, Menu, Configure, Index } from 'react-instantsearch/dom'; +import { Hit, connectRefinementList, connectMenu } from 'react-instantsearch-core'; + +// DOM +// https://community.algolia.com/react-instantsearch/Getting_started.html +() => { + const App = () => ( + + + + ); + + function Search() { + return ( +
+ +
+ ); + } + + function Product({ hit }: { hit: Hit }) { + return
{hit.name}
; + } + + function Search2() { + return ( +
+ +
+ ); + } + + function Product2({ hit }: { hit: Hit }) { + return ( +
+ + + +
+ ); + } + + function Search3() { + return ( +
+ + + +
+ ); + } + + function Search4() { + return ( +
+ + + + + + +
+ ); + } +}; + +// https://community.algolia.com/react-instantsearch/guide//Highlighting_results.html +() => { + const Hit = ({ hit }: { hit: Hit }) => ( +

+ +

+ ); + + function App() { + return ( + + + + ); + } +}; + +// TODO +// () => { +// const CustomHighlight = connectHighlight( +// ({ highlight, attribute, hit, highlightProperty }) => { +// const parsedHit = highlight({ +// attribute, +// hit, +// highlightProperty: '_highlightResult' +// }); +// const highlightedHits = parsedHit.map(part => { +// if (part.isHighlighted) return {part.value}; +// return part.value; +// }); +// return
{highlightedHits}
; +// } +// ); + +// const Hit = ({ hit }: { hit: Hit }) => ( +//

+// +//

+// ); + +// function App() { +// return ( +// +// +// +// ); +// } +// }; + +// https://community.algolia.com/react-instantsearch/guide/i18n.html +() => { + const App = () => ( + + + + ); +}; + +// https://community.algolia.com/react-instantsearch/guide/Sorting_and_filtering.html +// TODO +// () => { +// const App = () => ( +// +// +// +// orderBy(items, ['label', 'count'], ['asc', 'desc']) +// } +// /> +// +// ); +// }; + +// https://community.algolia.com/react-instantsearch/guide/Default_refinements.html +() => { + const App = () => ( + + + + + ); +}; + +// TODO +// () => { +// const VirtualMenu = connectMenu(() => null); + +// const App = () => ( +// +//
+// +// items.filter(item => item.currentRefinement !== 'Orange') +// } +// /> +// +// +// +//
+//
+// ); +// }; + +// https://community.algolia.com/react-instantsearch/guide/Searching_in_Lists.html + +; + +() => { + // https://community.algolia.com/react-instantsearch/guide/Search_parameters.html + + + // widgets + ; +}; + +import { createInstantSearch } from 'react-instantsearch-dom/server'; +// import { createServer } from 'http'; +declare function createServer(handler: (req: any, res: any) => any): any; +import { renderToString } from 'react-dom/server'; + +() => { + // https://community.algolia.com/react-instantsearch/guide/Server-side_rendering.html + + // Now we create a dedicated `InstantSearch` component + const { InstantSearch, findResultsState } = createInstantSearch(); + + class App extends React.Component { + render() { + return ( + + + + + ); + } + } + + const server = createServer(async (req, res) => { + const searchState = {query: 'chair'}; + const resultsState = await findResultsState(App, {searchState}); + const appInitialState = {searchState, resultsState}; + const appAsString = renderToString(); + res.send( + ` + + + +

Awesome server-side rendered search

+ ${appAsString}
+ + + + ` + ); + }); +}; diff --git a/types/react-instantsearch-dom/server.d.ts b/types/react-instantsearch-dom/server.d.ts new file mode 100644 index 0000000000..b1ba930ace --- /dev/null +++ b/types/react-instantsearch-dom/server.d.ts @@ -0,0 +1,14 @@ +import * as React from 'react'; + +/** + * Creates a specialized root InstantSearch component. It accepts + * an algolia client and a specification of the root Element. + * @param defaultAlgoliaClient - a function that builds an Algolia client + * @returns an InstantSearch root + */ +export function createInstantSearch( + defaultAlgoliaClient?: (appId: string, apiKey: string, options: { _useRequestCache: boolean }) => object +): { + InstantSearch: React.ComponentClass; + findResultsState(App: React.ComponentType, props: any): Promise +}; diff --git a/types/react-instantsearch-dom/tsconfig.json b/types/react-instantsearch-dom/tsconfig.json new file mode 100644 index 0000000000..15ec605c21 --- /dev/null +++ b/types/react-instantsearch-dom/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "server.d.ts", + "react-instantsearch-dom-tests.tsx" + ] +} diff --git a/types/react-instantsearch-dom/tslint.json b/types/react-instantsearch-dom/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-instantsearch-dom/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-instantsearch-native/index.d.ts b/types/react-instantsearch-native/index.d.ts new file mode 100644 index 0000000000..6b328de132 --- /dev/null +++ b/types/react-instantsearch-native/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for react-instantsearch-native 5.3 +// Project: https://community.algolia.com/react-instantsearch +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as React from 'react'; + +// Core +export { createConnector } from 'react-instantsearch-core'; +export { HIGHLIGHT_TAGS } from 'react-instantsearch-core'; +export { translatable } from 'react-instantsearch-core'; + +// Widget +export { Configure } from 'react-instantsearch-core'; + +// Connectors +export { connectAutoComplete } from 'react-instantsearch-core'; +export { connectBreadcrumb } from 'react-instantsearch-core'; +export { connectConfigure } from 'react-instantsearch-core'; +export { connectCurrentRefinements } from 'react-instantsearch-core'; +export { connectGeoSearch } from 'react-instantsearch-core'; +export { connectHierarchicalMenu } from 'react-instantsearch-core'; +export { connectHighlight } from 'react-instantsearch-core'; +export { connectHits } from 'react-instantsearch-core'; +export { connectHitsPerPage } from 'react-instantsearch-core'; +export { connectInfiniteHits } from 'react-instantsearch-core'; +export { connectMenu } from 'react-instantsearch-core'; +export { connectNumericMenu } from 'react-instantsearch-core'; +export { connectPagination } from 'react-instantsearch-core'; +export { connectPoweredBy } from 'react-instantsearch-core'; +export { connectRange } from 'react-instantsearch-core'; +export { connectRefinementList } from 'react-instantsearch-core'; +export { connectScrollTo } from 'react-instantsearch-core'; +export { connectSearchBox } from 'react-instantsearch-core'; +export { connectSortBy } from 'react-instantsearch-core'; +export { connectStateResults } from 'react-instantsearch-core'; +export { connectStats } from 'react-instantsearch-core'; +export { connectToggleRefinement } from 'react-instantsearch-core'; + +// Native +export interface InstantSearchProps { + apiKey: string; + appId: string; + indexName: string; + + algoliaClient?: any; + searchClient?: any; + createURL?: (...args: any[]) => any; + searchState?: any; + refresh?: boolean; + onSearchStateChange?: (...args: any[]) => any; + onSearchParameters?: (...args: any[]) => any; + resultsState?: any; + root?: { + Root: string | ((...args: any[]) => any); + props: any; + }; +} +/** + * is the root component of all React InstantSearch implementations. It provides all the connected components (aka widgets) a means to interact with the searchState. + * + * https://community.algolia.com/react-instantsearch/widgets/%3CInstantSearch%3E.html + */ +export class InstantSearch extends React.Component {} + +export class Index extends React.Component {} diff --git a/types/react-instantsearch-native/react-instantsearch-native-tests.tsx b/types/react-instantsearch-native/react-instantsearch-native-tests.tsx new file mode 100644 index 0000000000..7a369b0487 --- /dev/null +++ b/types/react-instantsearch-native/react-instantsearch-native-tests.tsx @@ -0,0 +1,69 @@ +import * as React from "react"; + +import { SearchBox, Hits, Highlight, Menu } from "react-instantsearch-dom"; +import { InstantSearch, Index, connectStateResults } from 'react-instantsearch-native'; +import { values } from 'lodash'; + +// https://community.algolia.com/react-instantsearch/guide/Conditional_display.html +const App = () => ( + + + +
+ + +
+
first:
+ +
+
+
+ + +
+
second:
+ +
+
+
+ + +
+
third:
+ +
+
+
+
+
+
+); + +const IndexResults = connectStateResults( + ({ searchState, searchResults, children }) => + searchResults && searchResults.nbHits !== 0 ? ( + children as React.ReactElement + ) : ( +
+ No results has been found for {searchState.query} and index{' '} + {searchResults ? searchResults.index : ''} +
+ ) +); + +const AllResults = connectStateResults(({ allSearchResults, children }) => { + const hasResults = + allSearchResults && + values(allSearchResults).some(results => results.nbHits > 0); + + return !hasResults ? ( +
+
No results in category, products or brand
+ + + +
+ ) : ( + children as React.ReactElement + ); +}); diff --git a/types/react-instantsearch-native/tsconfig.json b/types/react-instantsearch-native/tsconfig.json new file mode 100644 index 0000000000..d4fb7501c4 --- /dev/null +++ b/types/react-instantsearch-native/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-instantsearch-native-tests.tsx" + ] +} diff --git a/types/react-instantsearch-native/tslint.json b/types/react-instantsearch-native/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-instantsearch-native/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-instantsearch/connectors.d.ts b/types/react-instantsearch/connectors.d.ts new file mode 100644 index 0000000000..e926f79e0a --- /dev/null +++ b/types/react-instantsearch/connectors.d.ts @@ -0,0 +1,22 @@ +export { connectAutoComplete } from 'react-instantsearch-core'; +export { connectBreadcrumb } from 'react-instantsearch-core'; +export { connectConfigure } from 'react-instantsearch-core'; +export { connectCurrentRefinements } from 'react-instantsearch-core'; +export { connectGeoSearch, GeoSearchExposed, GeoSearchProvided, NESW } from 'react-instantsearch-core'; +export { connectHierarchicalMenu } from 'react-instantsearch-core'; +export { connectHighlight } from 'react-instantsearch-core'; +export { connectHits, Hit } from 'react-instantsearch-core'; +export { connectHitsPerPage } from 'react-instantsearch-core'; +export { connectInfiniteHits } from 'react-instantsearch-core'; +export { connectMenu, MenuExposed, MenuProvided } from 'react-instantsearch-core'; +export { connectNumericMenu, NumericMenuExposed, NumericMenuProvided } from 'react-instantsearch-core'; +export { connectPagination } from 'react-instantsearch-core'; +export { connectPoweredBy } from 'react-instantsearch-core'; +export { connectRange } from 'react-instantsearch-core'; +export { connectRefinementList, RefinementListExposed, RefinementListProvided } from 'react-instantsearch-core'; +export { connectScrollTo } from 'react-instantsearch-core'; +export { connectSearchBox, SearchBoxExposed, SearchBoxProvided } from 'react-instantsearch-core'; +export { connectSortBy } from 'react-instantsearch-core'; +export { connectStateResults, StateResultsProvided, SearchState, SearchResults } from 'react-instantsearch-core'; +export { connectStats } from 'react-instantsearch-core'; +export { connectToggleRefinement } from 'react-instantsearch-core'; diff --git a/types/react-instantsearch/dom.d.ts b/types/react-instantsearch/dom.d.ts new file mode 100644 index 0000000000..ad857eaa58 --- /dev/null +++ b/types/react-instantsearch/dom.d.ts @@ -0,0 +1,27 @@ +export { InstantSearch, InstantSearchProps } from 'react-instantsearch-dom'; +export { Index } from 'react-instantsearch-dom'; +export { Breadcrumb } from 'react-instantsearch-dom'; +export { ClearRefinements } from 'react-instantsearch-dom'; +export { Configure } from 'react-instantsearch-dom'; +export { CurrentRefinements } from 'react-instantsearch-dom'; +export { HierarchicalMenu } from 'react-instantsearch-dom'; +export { Highlight } from 'react-instantsearch-dom'; +export { Hits, HitsProps } from 'react-instantsearch-dom'; +export { HitsPerPage } from 'react-instantsearch-dom'; +export { InfiniteHits } from 'react-instantsearch-dom'; +export { Menu } from 'react-instantsearch-dom'; +export { MenuSelect } from 'react-instantsearch-dom'; +export { NumericMenu } from 'react-instantsearch-dom'; +export { Pagination } from 'react-instantsearch-dom'; +export { Panel } from 'react-instantsearch-dom'; +export { PoweredBy } from 'react-instantsearch-dom'; +export { RangeInput } from 'react-instantsearch-dom'; +export { RangeSlider } from 'react-instantsearch-dom'; +export { RatingMenu } from 'react-instantsearch-dom'; +export { RefinementList } from 'react-instantsearch-dom'; +export { ScrollTo } from 'react-instantsearch-dom'; +export { SearchBox, SearchBoxProps } from 'react-instantsearch-dom'; +export { Snippet } from 'react-instantsearch-dom'; +export { SortBy } from 'react-instantsearch-dom'; +export { Stats } from 'react-instantsearch-dom'; +export { ToggleRefinement } from 'react-instantsearch-dom'; diff --git a/types/react-instantsearch/index.d.ts b/types/react-instantsearch/index.d.ts new file mode 100644 index 0000000000..3f80cf4aa3 --- /dev/null +++ b/types/react-instantsearch/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for react-instantsearch 5.2 +// Project: https://community.algolia.com/react-instantsearch/ +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +export { createConnector } from 'react-instantsearch-core'; diff --git a/types/react-instantsearch/native.d.ts b/types/react-instantsearch/native.d.ts new file mode 100644 index 0000000000..ff6ff89a3f --- /dev/null +++ b/types/react-instantsearch/native.d.ts @@ -0,0 +1,3 @@ +export { InstantSearch } from 'react-instantsearch-native'; +export { Index } from 'react-instantsearch-native'; +export { Configure } from 'react-instantsearch-native'; diff --git a/types/react-instantsearch/react-instantsearch-tests.tsx b/types/react-instantsearch/react-instantsearch-tests.tsx new file mode 100644 index 0000000000..82672b7a60 --- /dev/null +++ b/types/react-instantsearch/react-instantsearch-tests.tsx @@ -0,0 +1,386 @@ +import * as React from "react"; + +import { connectMenu, connectRefinementList, connectStateResults, SearchState } from "react-instantsearch/connectors"; +import { InstantSearch, SearchBox, Index, Hits, Highlight, Menu } from "react-instantsearch/dom"; +import { orderBy, omit, values } from 'lodash'; +import { createInstantSearch } from "react-instantsearch-core"; + +// https://community.algolia.com/react-instantsearch/guide/Search_state.html +() => { + const searchState: SearchState = { + range: { + price: { + min: 20, + max: 3000 + } + }, + configure: { + aroundLatLng: true, + }, + refinementList: { + fruits: ['lemon', 'orange'] + }, + hierarchicalMenu: { + products: 'Laptops > Surface' + }, + menu: { + brands: 'Sony' + }, + multiRange: { + rank: '2:5' + }, + toggle: { + freeShipping: true + }, + hitsPerPage: 10, + sortBy: 'mostPopular', + query: 'ora', + page: 2 + }; +}; + +() => { + const searchState: SearchState = { + query: 'ora', // shared state between all indices + page: 2, // shared state between all indices + indices: { + index1: { + configure: { + hitsPerPage: 3, + }, + }, + index2: { + configure: { + hitsPerPage: 10, + }, + }, + }, + }; +}; + +// https://community.algolia.com/react-instantsearch/guide/Custom_connectors.html +// TODO +// () => { +// const CoolWidget = createConnector({ +// displayName: 'CoolWidget', + +// getProvidedProps(props, searchState) { +// // Since the `queryAndPage` searchState entry isn't necessarily defined, we need +// // to default its value. +// const [query, page] = searchState.queryAndPage || ['', 0]; + +// // Connect the underlying component to the `queryAndPage` searchState entry. +// return { +// query, +// page, +// }; +// }, + +// refine(props, searchState, newQuery, newPage) { +// // When the underlying component calls its `refine` prop, update the searchState +// // with the new query and page. +// return { +// // `searchState` represents the search state of *all* widgets. We need to extend it +// // instead of replacing it, otherwise other widgets will lose their +// // respective state. +// ...searchState, +// queryAndPage: [newQuery, newPage], +// }; +// }, +// })(props => +//
+// The query is {props.query}, the page is {props.page}. +// {/* +// Clicking on this button will update the searchState to: +// { +// ...otherSearchState, +// query: 'algolia', +// page: 20, +// } +// */} +//
+// ); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine + +// getSearchParameters(searchParameters, props, searchState) { +// // Since the `queryAndPage` state entry isn't necessarily defined, we need +// // to default its value. +// const [query, page] = searchState.queryAndPage || ['', 0]; + +// // When the `queryAndPage` state entry changes, update the query and page of +// // search. +// return searchParameters +// .setQuery(query) +// .setPage(page); +// }, +// })(Widget); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine, getSearchParameters + +// getMetadata(props, searchState) { +// // Since the `queryAndPage` searchState entry isn't necessarily defined, we need +// // to default its value. +// const [query, page] = searchState.queryAndPage || ['', 0]; + +// const filters = []; +// if (query !== '') { +// filters.push({ +// // Unique identifier for this filter. +// key: `queryAndPage.query`, +// // String label (or node) that should appear in the CurrentRefinements +// // component. +// label: `Query: ${query}`, +// // Describes how clearing this filter affects the InstantSearch searchState. +// // In our case, clearing the query just resets it to an empty string +// // without affecting the page. +// clear: nextSearchState => { +// return { +// ...nextSearchState, +// // Do not depend on the current `searchState` here. Since filters can be +// // cleared in batches, the `searchState` parameter is not up-to-date when +// // this method is called. +// queryAndPage: ['', nextSearchState.queryAndPage[1]], +// }; +// }, +// }); +// } + +// if (page !== 0) { +// filters.push({ +// key: `queryAndPage.page`, +// label: `Page: ${page}`, +// clear: nextSearchState => { +// return { +// ...nextSearchState, +// queryAndPage: [nextSearchState.queryAndPage[0], 0], +// }; +// }, +// }); +// } + +// return { +// // This widget manipulates the `queryAndPage` state entry. +// id: 'queryAndPage', +// filters, +// }; +// }, +// })(Widget); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine, getSearchParameters, getMetadata + +// searchForFacetValues(props, searchState, nextRefinement) { +// return {facetName: props.attribute, query: nextRefinement}; +// }, +// })(Widget); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine, getSearchParameters, getMetadata + +// cleanUp(props, searchState) { +// return omit('queryAndPage', searchState); +// }, +// })(Widget); +// }; + +// https://community.algolia.com/react-instantsearch/guide/Conditional_display.html +() => { + const Content = connectStateResults( + ({ searchState }) => + searchState && searchState.query + ?
+ The query {searchState.query} exists +
+ :
No query
+ ); +}; + +() => { + const Content = connectStateResults( + ({ searchState, searchResults }) => + searchResults && searchResults.nbHits !== 0 + ?
Some results
+ :
+ No results has been found for {searchState.query} +
+ ); +}; + +() => { + const Content = connectStateResults( + ({ error }) => + error ?
Some error
:
No error
+ ); +}; + +() => { + const Content = connectStateResults( + ({ searching }) => + searching ?
We are searching
:
Search finished
+ ); +}; + +() => { + const Content = connectStateResults( + ({ searchingForFacetValues }) => + searchingForFacetValues ?
We are searching
:
Search finished
+ ); +}; + +() => { + const App = () => ( + + + +
+ + +
+
first:
+ +
+
+
+ + +
+
second:
+ +
+
+
+ + +
+
third:
+ +
+
+
+
+
+
+ ); + + const IndexResults = connectStateResults( + ({ searchState, searchResults, children }) => + searchResults && searchResults.nbHits !== 0 ? ( + children as React.ReactElement + ) : ( +
+ No results has been found for {searchState.query} and index{' '} + {searchResults ? searchResults.index : ''} +
+ ) + ); + + const AllResults = connectStateResults(({ allSearchResults, children }) => { + const hasResults = + allSearchResults && + values(allSearchResults).some(results => results.nbHits > 0); + + return !hasResults ? ( +
+
No results in category, products or brand
+ + + +
+ ) : ( + children as React.ReactElement + ); + }); +}; + +// https://github.com/algolia/react-instantsearch/blob/master/packages/react-instantsearch-dom/src/widgets/InstantSearch.js +() => { + const InstantSearch = createInstantSearch( + () => ({}), + { + Root: 'div', + props: { + className: 'ais-InstantSearch__root', + }, + } + ); + + ; +}; + +() => { + const RefinementListWithSearchBox = connectRefinementList(props => { + const values = props.items.map(item => { + const label = item._highlightResult + ? + : item.label; + + return ( +
  • + props.refine(item.value)}> + {label} {item.isRefined ? '- selected' : ''} + +
  • + ); + }); + + return ( +
    + props.searchForItems((e.target as HTMLInputElement).value)}/> +
      {values}
    +
    + ); + }); + + return ; +}; + +// https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html +() => { + const VirtualMenu = connectMenu(() => null); + const Hoodies = () => ; + + const App = () => ( + + + +
    + + ); +}; diff --git a/types/react-instantsearch/server.d.ts b/types/react-instantsearch/server.d.ts new file mode 100644 index 0000000000..d8fb0d1a46 --- /dev/null +++ b/types/react-instantsearch/server.d.ts @@ -0,0 +1 @@ +export { createInstantSearch } from 'react-instantsearch-dom/server'; diff --git a/types/react-instantsearch/tsconfig.json b/types/react-instantsearch/tsconfig.json new file mode 100644 index 0000000000..79afa53442 --- /dev/null +++ b/types/react-instantsearch/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "experimentalDecorators": true, + "jsx": "react", + "lib": ["es6", "dom"], + "module": "commonjs", + "noEmit": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "forceConsistentCasingInFileNames": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "connectors.d.ts", + "dom.d.ts", + "native.d.ts", + "server.d.ts", + "react-instantsearch-tests.tsx" + ] +} diff --git a/types/react-instantsearch/tslint.json b/types/react-instantsearch/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/react-instantsearch/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/react-mailchimp-subscribe/index.d.ts b/types/react-mailchimp-subscribe/index.d.ts index 55b5c487ed..ed0165ed00 100644 --- a/types/react-mailchimp-subscribe/index.d.ts +++ b/types/react-mailchimp-subscribe/index.d.ts @@ -2,7 +2,7 @@ // Project: https://revolunet.github.io/react-mailchimp-subscribe/ // Definitions by: Omar Diab // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 import { Component, ReactNode } from "react"; diff --git a/types/react-mailchimp-subscribe/react-mailchimp-subscribe-tests.tsx b/types/react-mailchimp-subscribe/react-mailchimp-subscribe-tests.tsx index 0507d7657a..d09ef6cc9a 100644 --- a/types/react-mailchimp-subscribe/react-mailchimp-subscribe-tests.tsx +++ b/types/react-mailchimp-subscribe/react-mailchimp-subscribe-tests.tsx @@ -25,9 +25,7 @@ const Example: React.StatelessComponent = () => ( )} url="spam.biz/subscribe" /> - { /* once Typescript 2.9 is out, generics in components will be allowed, at that point uncomment these. */ } - { /* https://github.com/Microsoft/TypeScript/pull/22415 */ } - {/* + render={(hooks) => (
    { @@ -52,6 +50,6 @@ const Example: React.StatelessComponent = () => ( /> )} url="spam.biz/subscribe" - /> */} + /> ); diff --git a/types/react-native-flip-card/index.d.ts b/types/react-native-flip-card/index.d.ts new file mode 100644 index 0000000000..6fc1156a1a --- /dev/null +++ b/types/react-native-flip-card/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for react-native-flip-card 3.5 +// Project: https://github.com/moschan/react-native-flip-card +// Definitions by: Jake Chapman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Component, ReactNode, ComponentClass } from "react"; +import { + ViewProps, + TextProps, + StyleProp, + TextInputProps, + ViewStyle +} from "react-native"; + +// FlipCard +export interface FlipCardProps { + style?: StyleProp; + flip?: boolean; + friction?: number; + perspective?: number; + flipHorizontal?: boolean; + flipVertical?: boolean; + clickable?: boolean; + onFlipEnd?: () => void; + onFlipStart?: () => void; + alignHeight?: boolean; + alignWidth?: boolean; + useNativeDriver?: boolean; +} +// Face +export interface FaceProps { + chilren: JSX.Element[]; +} + +// Back +export interface BackProps { + flipHorizontal: boolean; + flipVertical: boolean; + perspective: number; + chilren: JSX.Element[]; +} + +export const Face: ComponentClass; +export const Back: ComponentClass; +export default class FlipCard extends Component {} diff --git a/types/react-native-flip-card/react-native-flip-card-tests.tsx b/types/react-native-flip-card/react-native-flip-card-tests.tsx new file mode 100644 index 0000000000..e741589be4 --- /dev/null +++ b/types/react-native-flip-card/react-native-flip-card-tests.tsx @@ -0,0 +1,33 @@ +import * as React from "react"; +import { View, Text, StyleSheet } from "react-native"; + +// Component +import FlipCard from "react-native-flip-card"; + +export default class FlipCardTest extends React.Component { + render() { + return ( + {}} + onFlipEnd={() => {}} + alignHeight={false} + alignWidth={false} + useNativeDriver={true} + > + + Front + + + Back + + + ); + } +} diff --git a/types/react-native-flip-card/tsconfig.json b/types/react-native-flip-card/tsconfig.json new file mode 100644 index 0000000000..92f1878d71 --- /dev/null +++ b/types/react-native-flip-card/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" + }, + "files": [ + "index.d.ts", + "react-native-flip-card-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-native-flip-card/tslint.json b/types/react-native-flip-card/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/react-native-flip-card/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/react-native-google-signin/index.d.ts b/types/react-native-google-signin/index.d.ts index a114a06882..54e19715e1 100644 --- a/types/react-native-google-signin/index.d.ts +++ b/types/react-native-google-signin/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Jacob Froman // Michele Bombardi // Christian Chown +// Eric Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -53,6 +54,11 @@ export interface ConfigureParams { */ webClientId?: string; + /** + * If you want to specify the client ID of type iOS + */ + iosClientId?: string; + /** * Must be true if you wish to access user APIs on behalf of the user from * your own server diff --git a/types/react-native-modalbox/react-native-modalbox-tests.tsx b/types/react-native-modalbox/react-native-modalbox-tests.tsx index a2e54a7653..31f104161f 100644 --- a/types/react-native-modalbox/react-native-modalbox-tests.tsx +++ b/types/react-native-modalbox/react-native-modalbox-tests.tsx @@ -16,6 +16,8 @@ interface State { sliderValue: number; } +const screen = Dimensions.get('window'); + class Example extends React.Component<{}, State> { modal1: Modal; modal2: Modal; diff --git a/types/react-native-popup-dialog/index.d.ts b/types/react-native-popup-dialog/index.d.ts index 3ff12802f4..dcf6e5cb1c 100644 --- a/types/react-native-popup-dialog/index.d.ts +++ b/types/react-native-popup-dialog/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native-popup-dialog 1.0 +// Type definitions for react-native-popup-dialog 0.16 // Project: https://github.com/jacklam718/react-native-popup-dialog/blob/master/README.md // Definitions by: Paito Anderson // connectdotz @@ -55,7 +55,7 @@ export interface PopupDialogProps { dismissOnTouchOutside?: boolean; dismissOnHardwareBackPress?: boolean; haveOverlay?: boolean; - show?: boolean; + visible?: boolean; onShown?: () => void; onDismissed?: () => void; actions?: any[]; diff --git a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx index 379d4fd788..95bfa66f4e 100644 --- a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx +++ b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx @@ -72,7 +72,7 @@ class Test extends React.Component { dismissOnTouchOutside={false} dismissOnHardwareBackPress={false} haveOverlay={true} - show={true} + visible={true} onShown={() => { console.log('onShown'); }} onDismissed={() => { console.log('onDismissed'); }} /> diff --git a/types/react-native-svg-charts/tslint.json b/types/react-native-svg-charts/tslint.json index c040aa7670..ca872cae09 100644 --- a/types/react-native-svg-charts/tslint.json +++ b/types/react-native-svg-charts/tslint.json @@ -1,6 +1,6 @@ { - "extends": "dtslint/dt.json", - "rules": { - "strict-export-declare-modifiers": false - } + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false + } } diff --git a/types/react-native-uuid-generator/index.d.ts b/types/react-native-uuid-generator/index.d.ts new file mode 100644 index 0000000000..ad5cb96bec --- /dev/null +++ b/types/react-native-uuid-generator/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for react-native-uuid-generator 4.0 +// Project: https://github.com/Traviskn/react-native-uuid-generator#readme +// Definitions by: burtek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace UUIDGenerator { + function getRandomUUID(): Promise; + function getRandomUUID(callback: (uuid: string) => void): void; +} + +export default UUIDGenerator; diff --git a/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts b/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts new file mode 100644 index 0000000000..b65f0ef410 --- /dev/null +++ b/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts @@ -0,0 +1,5 @@ +import UUIDGenerator from 'react-native-uuid-generator'; + +UUIDGenerator.getRandomUUID().then((uuid: string) => { }).catch((error: any) => { }); + +UUIDGenerator.getRandomUUID((uuid: string) => { }); diff --git a/types/react-native-uuid-generator/tsconfig.json b/types/react-native-uuid-generator/tsconfig.json new file mode 100644 index 0000000000..30c1f52249 --- /dev/null +++ b/types/react-native-uuid-generator/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-uuid-generator-tests.ts" + ] +} diff --git a/types/react-native-uuid-generator/tslint.json b/types/react-native-uuid-generator/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-uuid-generator/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-vector-icons/tsconfig.json b/types/react-native-vector-icons/tsconfig.json index 31ca0d3dce..9d3b080960 100644 --- a/types/react-native-vector-icons/tsconfig.json +++ b/types/react-native-vector-icons/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 61b240e370..647f29a8cc 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -25,6 +25,7 @@ // Mickael Wegerich // Max Davidson // Alec Hill +// Lachlan Young // Jason Killian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -374,7 +375,9 @@ export interface NavigationToggleDrawerAction { export interface NavigationStackViewConfig { mode?: 'card' | 'modal'; headerMode?: HeaderMode; + headerBackTitleVisible?: boolean; headerTransitionPreset?: 'fade-in-place' | 'uikit'; + headerLayoutPreset?: 'left' | 'center'; cardStyle?: StyleProp; transitionConfig?: ( transitionProps: NavigationTransitionProps, diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index 0b5596201e..0c4c65983e 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -154,6 +154,7 @@ const initialRouteParams: StartScreenNavigationParams = { id: 1, s: "Start", }; + const routeConfigMap: NavigationRouteConfigMap = { [ROUTE_NAME_START_SCREEN]: { path: "start", @@ -169,6 +170,7 @@ export const AppNavigator = createStackNavigator( { initialRouteName: ROUTE_NAME_START_SCREEN, initialRouteKey: ROUTE_KEY_START_SCREEN, + headerLayoutPreset: 'center', initialRouteParams, navigationOptions, }, @@ -643,7 +645,6 @@ createStackNavigator( ); // Test NavigationEvents component - const ViewWithNavigationEvents = ( // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -33,7 +33,11 @@ declare namespace ReactReconciler { // Unique identifier of this child. key: null | string; - // The function/class/module associated with this fiber. + // The value of element.type which is used to preserve the identity during + // reconciliation of this child. + elementType: any; + + // The resolved function/class/ associated with this fiber. type: any; // The local state associated with this fiber. @@ -74,7 +78,7 @@ declare namespace ReactReconciler { firstContextDependency: ContextDependency | null; // Bitfield that describes properties about the fiber and its subtree. E.g. - // the AsyncMode flag indicates whether the subtree should be async-by- + // the ConcurrentMode flag indicates whether the subtree should be async-by- // default. When a fiber is created, it inherits the mode of its // parent. Additional flags can be set at creation time, but after that the // value should remain unchanged throughout the fiber's lifetime, particularly @@ -361,7 +365,7 @@ declare namespace ReactReconciler { ): ExpirationTime; createContainer( containerInfo: Container, - isAsync: boolean, + isConcurrent: boolean, hydrate: boolean, ): OpaqueRoot; updateContainer( @@ -458,10 +462,10 @@ declare namespace ReactReconciler { nextScheduledRoot: FiberRoot | null; } - // The following attributes are only used by interaction tracking builds. + // The following attributes are only used by interaction tracing builds. // They enable interactions to be associated with their async work, // And expose interaction metadata to the React DevTools Profiler plugin. - // Note that these attributes are only defined when the enableSchedulerTracking flag is enabled. + // Note that these attributes are only defined when the enableSchedulerTracing flag is enabled. interface ProfilingOnlyFiberRootProperties { interactionThreadID: number; memoizedInteractions: Set; @@ -473,7 +477,7 @@ declare namespace ReactReconciler { // react-reconciler/ReactFiberScheduler interface Deadline { - timeRemaining: () => number; + timeRemaining(): number; didTimeout: boolean; } @@ -510,7 +514,7 @@ declare namespace ReactReconciler { lastCapturedEffect: Update | null; } - // schedule/Tracking + // scheduler/Tracing interface Interaction { __count: number; @@ -580,7 +584,9 @@ declare namespace ReactReconciler { | 13 | 14 | 15 - | 16; + | 16 + | 17 + | 18; } export = ReactReconciler; diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 2e1cfb902b..f62fc44b18 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -117,7 +117,7 @@ export interface match { // Omit taken from https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html export type Omit = Pick>; -export function matchPath(pathname: string, props: RouteProps, parent?: match | null): match | null; +export function matchPath(pathname: string, props: string | RouteProps, parent?: match | null): match | null; export function generatePath(pattern: string, params?: { [paramName: string]: string | number | boolean }): string; diff --git a/types/react-stripe-elements/index.d.ts b/types/react-stripe-elements/index.d.ts index 32a94b0639..534bfde9ec 100644 --- a/types/react-stripe-elements/index.d.ts +++ b/types/react-stripe-elements/index.d.ts @@ -12,12 +12,12 @@ import * as React from 'react'; export namespace ReactStripeElements { - import ElementChangeResponse = stripe.elements.ElementChangeResponse; - import ElementsOptions = stripe.elements.ElementsOptions; - import TokenOptions = stripe.TokenOptions; - import TokenResponse = stripe.TokenResponse; - import SourceResponse = stripe.SourceResponse; - import SourceOptions = stripe.SourceOptions; + type ElementChangeResponse = stripe.elements.ElementChangeResponse; + type ElementsOptions = stripe.elements.ElementsOptions; + type TokenOptions = stripe.TokenOptions; + type TokenResponse = stripe.TokenResponse; + type SourceResponse = stripe.SourceResponse; + type SourceOptions = stripe.SourceOptions; /** * There's a bug in @types/stripe which defines the property as diff --git a/types/react-syntax-highlighter/index.d.ts b/types/react-syntax-highlighter/index.d.ts index 8bfd8e3756..c631dea9f7 100644 --- a/types/react-syntax-highlighter/index.d.ts +++ b/types/react-syntax-highlighter/index.d.ts @@ -5,11 +5,14 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +type lineTagPropsFunction = (lineNumber: number) => React.DOMAttributes + interface SyntaxHighlighterProps { language?: string; style?: any; customStyle?: any; - codeTagProps?: HTMLElement; + lineProps?: lineTagPropsFunction | React.DOMAttributes + codeTagProps?: React.DOMAttributes; useInlineStyles?: boolean; showLineNumbers?: boolean; startingLineNumber?: number; diff --git a/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx b/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx index 2abddb4a49..c516d9f610 100644 --- a/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx +++ b/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx @@ -61,3 +61,84 @@ function primsLightHighlighter(): JSX.Element { ) } + +function codeTagProps() { + const codeString: string = `class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + public version(): string { + return this.version; + } + } + `; + + const codeTagProps = { + className: 'some-classname', + style: { + opacity: 0, + }, + onMouseOver: (event: React.MouseEvent) => "foo", + } + + return ( + + ) +} + +function linePropsObject() { + const codeString: string = `class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + public version(): string { + return this.version; + } + } + `; + + const lineProps = { + otherProp: 'otherProp', + className: 'some-classname', + style: { + opacity: 0, + }, + onMouseOver: (event: React.MouseEvent) => "foo" + } + + return ( + + ) +} + +function lineTagPropsFunction() { + const codeString: string = `class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + public version(): string { + return this.version; + } + } + `; + + const lineProps = (lineNumber: number) => ({ + otherProp: 'otherProp', + className: 'some-classname', + style: { + opacity: 0, + }, + onMouseOver: (event: React.MouseEvent) => lineNumber * 5 + }) + + return ( + + ) +} + diff --git a/types/react-table/index.d.ts b/types/react-table/index.d.ts index 0d03604ae9..560abfecc0 100644 --- a/types/react-table/index.d.ts +++ b/types/react-table/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for react-table 6.7 // Project: https://github.com/react-tools/react-table -// Definitions by: Roy Xue , Pavel Sakalo , Krzysztof Porębski , Andy S +// Definitions by: Roy Xue +// Pavel Sakalo +// Krzysztof Porębski +// Grzegorz Rozdzialik +// Andy S // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-table/lib/hoc/selectTable.d.ts b/types/react-table/lib/hoc/selectTable.d.ts new file mode 100644 index 0000000000..d70d84eb78 --- /dev/null +++ b/types/react-table/lib/hoc/selectTable.d.ts @@ -0,0 +1,56 @@ +import { ComponentType } from 'react'; + +import { TableProps } from '../../index'; + +export type SelectType = 'checkbox' | 'radio'; + +export interface SelectInputComponentProps { + selectType: SelectType; + onClick: (key: string, shiftKeyPressed: boolean, row: any) => any; + checked: boolean; + id: string; + row: any; +} + +export interface SelectAllInputComponent { + selectType: SelectType; + checked: boolean; + onClick: () => any; +} + +export interface SelectTableAdditionalProps { + /** + * Default: _id + */ + keyField?: string; + + isSelected?: (key: string) => boolean; + + selectAll?: boolean; + + toggleAll?: SelectAllInputComponent['onClick']; + + toggleSelection?: SelectInputComponentProps['onClick']; + + /** + * Default: checkbox + */ + selectType?: SelectType; + + SelectInputComponent?: ComponentType; + SelectAllInputComponent?: ComponentType; +} + +export interface SelectTableHOCOptions { + /** + * Default: false + */ + floatingLeft?: boolean; +} + +declare function selectTableHOC>( + Component: ComponentType, + options?: SelectTableHOCOptions +): ComponentType; + +export default selectTableHOC; diff --git a/types/react-table/lib/hoc/treeTable.d.ts b/types/react-table/lib/hoc/treeTable.d.ts new file mode 100644 index 0000000000..35d1522119 --- /dev/null +++ b/types/react-table/lib/hoc/treeTable.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; + +import { TableProps } from '../../index'; + +declare function treeTableHOC>( + Component: ComponentType +): ComponentType; + +export default treeTableHOC; diff --git a/types/react-table/test/select-table-tests.tsx b/types/react-table/test/select-table-tests.tsx new file mode 100644 index 0000000000..1a29ed07c1 --- /dev/null +++ b/types/react-table/test/select-table-tests.tsx @@ -0,0 +1,36 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; + +import ReactTable, { Column } from 'react-table'; +import selectTableHOC, { + SelectTableAdditionalProps +} from 'react-table/lib/hoc/selectTable'; + +import 'react-table/react-table.css'; + +const SelectTable = selectTableHOC(ReactTable); + +const selectTableAdditionalProps: SelectTableAdditionalProps = { + isSelected: () => true, + keyField: 'id', + selectAll: true, + selectType: 'checkbox', + toggleAll: () => null, + toggleSelection: () => null +}; + +const data = [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }]; + +const columns: Column[] = [ + { Header: 'ID', accessor: 'id' }, + { Header: 'Name', accessor: 'name' } +]; + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/types/react-table/test/tree-table-tests.tsx b/types/react-table/test/tree-table-tests.tsx new file mode 100644 index 0000000000..14ad8265de --- /dev/null +++ b/types/react-table/test/tree-table-tests.tsx @@ -0,0 +1,21 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; + +import ReactTable, { Column } from 'react-table'; +import treeTableHOC from 'react-table/lib/hoc/treeTable'; + +import 'react-table/react-table.css'; + +const SelectTable = treeTableHOC(ReactTable); + +const data = [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }]; + +const columns: Column[] = [ + { Header: 'ID', accessor: 'id' }, + { Header: 'Name', accessor: 'name' } +]; + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/types/react-table/tsconfig.json b/types/react-table/tsconfig.json index de6f3f8e69..ef6f8f22a1 100644 --- a/types/react-table/tsconfig.json +++ b/types/react-table/tsconfig.json @@ -20,6 +20,10 @@ }, "files": [ "index.d.ts", - "react-table-tests.tsx" + "lib/hoc/selectTable.d.ts", + "lib/hoc/treeTable.d.ts", + "react-table-tests.tsx", + "test/select-table-tests.tsx", + "test/tree-table-tests.tsx" ] } \ No newline at end of file diff --git a/types/rebass/index.d.ts b/types/rebass/index.d.ts index be203061ee..220f394f13 100644 --- a/types/rebass/index.d.ts +++ b/types/rebass/index.d.ts @@ -1,31 +1,36 @@ -// Type definitions for Rebass 0.3.7 +// Type definitions for Rebass 0.3.8 // Project: https://github.com/jxnblk/rebass // Definitions by: rhysd // ryee-dev +// jamesmckenzie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; export interface BaseProps extends React.ClassAttributes { - className?: string; - m?: number; - mt?: number; - mr?: number; - mb?: number; - ml?: number; - mx?: number; - my?: number; - p?: number; - pt?: number; - pr?: number; - pb?: number; - pl?: number; - px?: number; - py?: number; + className?: string; + as?: string; } -export interface BoxProps extends BaseProps { +export interface SpaceProps extends BaseProps { + m?: number; + mt?: number; + mr?: number; + mb?: number; + ml?: number; + mx?: number; + my?: number; + p?: number; + pt?: number; + pr?: number; + pb?: number; + pl?: number; + px?: number; + py?: number; +} + +export interface BoxProps extends SpaceProps { className?: string; width?: number | number[]; fontSize?: number | number[]; @@ -36,82 +41,67 @@ export interface BoxProps extends BaseProps { type BoxClass = React.StatelessComponent; export declare const Box: BoxClass; -export interface ButtonProps extends BaseProps { - fontWeight?: string; - border?: number; - borderColor?: string; - borderRadius?: number; - variant?: string; - bg?: string; - color?: string; +export interface ButtonProps extends BoxProps { + fontWeight?: string; + border?: number; + borderColor?: string; + borderRadius?: number; + variant?: string; } type ButtonClass = React.StatelessComponent; export declare const Button: ButtonClass; -export interface CardProps extends BaseProps { - border?: number; - borderColor?: string; - borderRadius?: number; - boxShadow?: string; - bg?: string; - backgroundImage?: string; - backgroundSize?: string; - backgroundPosition?: string; - backgroundRepeat?: string; - opacity?: number; - fontSize?: number | number[]; - fontWeight?: string; - width?: number | number[]; +export interface CardProps extends BoxProps { + border?: number; + borderColor?: string; + borderRadius?: number; + boxShadow?: string; + backgroundImage?: string; + backgroundSize?: string; + backgroundPosition?: string; + backgroundRepeat?: string; + opacity?: number; + variant?: string; } type CardClass = React.StatelessComponent; export declare const Card: CardClass; -export interface FlexProps extends BaseProps { - alignItems?: string; - justifyContent?: string, - flexDirection?: string, - flexWrap?: string, - width?: number | number[]; +export interface FlexProps extends BoxProps { + alignItems?: string; + justifyContent?: string; + flexDirection?: string; + flexWrap?: string; } -type FlexClass = React.StatelessComponent +type FlexClass = React.StatelessComponent; export declare const Flex: FlexClass; -export interface HeadingProps extends BaseProps { - fontSize?: number | number[]; - fontWeight?: string; - color?: string; - fontFamily?: string; - textAlign?: string; - lineHeight?: number; - letterSpacing?: number; -} -type HeadingClass = React.StatelessComponent -export declare const Heading: HeadingClass; - -export interface ImageProps extends BaseProps { +export interface ImageProps extends BoxProps { height?: number; borderRadius?: number; src?: string; alt?: string; - width?: number | number[]; } -type ImageClass = React.StatelessComponent +type ImageClass = React.StatelessComponent; export declare const Image: ImageClass; -export interface LinkProps extends BaseProps { - href?: string; +export interface LinkProps extends BoxProps { + href?: string; } -type LinkClass = React.StatelessComponent +type LinkClass = React.StatelessComponent; export declare const Link: LinkClass; -export interface TextProps extends BaseProps { - fontSize?: number | number[]; - fontWeight?: string; - color?: string; - fontFamily?: string; - textAlign?: string; - lineHeight?: number; - letterSpacing?: number; +export interface TextProps extends BoxProps { + fontSize?: number | number[]; + fontWeight?: string; + color?: string; + fontFamily?: string; + textAlign?: string; + lineHeight?: number; + letterSpacing?: number; } -type TextClass = React.StatelessComponent +type TextClass = React.StatelessComponent; export declare const Text: TextClass; + +export interface HeadingProps extends TextProps {} +type HeadingClass = React.StatelessComponent; +export declare const Heading: HeadingClass; diff --git a/types/rebass/rebass-tests.tsx b/types/rebass/rebass-tests.tsx index cc701a5c71..5980963829 100644 --- a/types/rebass/rebass-tests.tsx +++ b/types/rebass/rebass-tests.tsx @@ -8,7 +8,6 @@ const RebassTests = () => ( Hi, I'm text. { textAnchor?: 'start' | 'middle' | 'end' | 'inherit'; verticalAnchor?: 'start' | 'middle' | 'end'; style?: object; + capHeight?: string; + lineHeight?: string; } export class Text extends React.Component { } diff --git a/types/recharts/recharts-tests.tsx b/types/recharts/recharts-tests.tsx index 6388a94d65..ec86acf21d 100644 --- a/types/recharts/recharts-tests.tsx +++ b/types/recharts/recharts-tests.tsx @@ -5,7 +5,7 @@ import { CartesianGrid, Line, LineChart, PieChart, Pie, Sector, XAxis, YAxis, Tooltip, ReferenceLine, ReferenceArea, ResponsiveContainer, Label, LabelList, Brush, - ScatterChart, ZAxis, Legend, Scatter, Bar, BarChart + ScatterChart, ZAxis, Legend, Scatter, Bar, BarChart, Text } from 'recharts'; interface ComponentState { @@ -21,6 +21,14 @@ class Component extends React.Component<{}, ComponentState> { console.log(`Handling a click on a chart: ${JSON.stringify(args)}`); } + renderYAxisTitle = () => { + return ( + + pv of page + + ); + } + render() { const data = [ { name: 'Page A', uv: 4000, pv: 2400, amt: 2400 }, @@ -85,7 +93,7 @@ class Component extends React.Component<{}, ComponentState> { }; return (
    - + @@ -108,7 +116,7 @@ class Component extends React.Component<{}, ComponentState> { /> - + @@ -131,7 +139,7 @@ class Component extends React.Component<{}, ComponentState> { /> - + @@ -150,14 +158,14 @@ class Component extends React.Component<{}, ComponentState> { /> - + } dataKey="value" activeIndex={this.state.activeIndex} activeShape={renderActiveShape} - data={data} + data={data2} cx={300} cy={200} innerRadius={60} @@ -168,7 +176,7 @@ class Component extends React.Component<{}, ComponentState> { - + @@ -178,7 +186,7 @@ class Component extends React.Component<{}, ComponentState> { - + {
    ; case "inline": return Hello world; - case "text": - return

    Hello world

    ; default: return undefined; } } } - - onChange(change: Change): void { - change.blur(); + onChange = (change: {operations: Immutable.List, value: Value}) => { + console.log(change.value); } } @@ -37,11 +35,10 @@ class MyEditor extends React.Component { value: Value.create() }; } - render() { return ; + renderNode={ myPlugin.renderNode } + onChange={ myPlugin.onChange }/>; } } diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index 8f80ba4615..3ea0d97817 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -42,7 +42,7 @@ export interface Rules { max?: number; match?: ObjectAndType | ObjectAndType[]; }>; - normalize?: (change: Change, error: SlateError) => void; + normalize?: (editor: Editor, error: SlateError) => void; parent?: ObjectAndType | ObjectAndType[]; text?: RegExp; } @@ -145,7 +145,6 @@ export class Value extends Immutable.Record({}) { static fromJS(properties: ValueJSON): Value; static isValue(maybeValue: any): maybeValue is Value; - change(): Change; toJSON(): ValueJSON; addMark(path: Path, offset: number, length: number, mark: Mark): Value; insertNode(path: Path, node: Node): Value; @@ -578,487 +577,6 @@ export class Mark extends Immutable.Record({}) { toJSON(): MarkProperties; } -export interface ChangeOption { - normalize?: boolean; -} - -export class Change extends Immutable.Record({}) { - object: "change"; - value: Value; - operations: Immutable.List; - - call(customChange: (change: Change, ...args: any[]) => Change): Change; - - applyOperations(operations: Operation[]): Change; - applyOperation(operation: Operation): Change; - - withoutNormalization(fn: (change: Change) => void): Change; - setOperationFlag(key: string, value: any): Change; - getFlag(key: string, options?: object): any; - unsetOperationFlag(key: string): Change; - - // Full Value Change - setValue(properties: Value | ValueProperties): Change; - - // Current Value Changes - deleteBackward(n: number): Change; - deleteForward(n: number): Change; - delete(): Change; - insertBlock(block: Block | BlockProperties | string): Change; - insertFragment(fragment: Document): Change; - insertInline(inline: Inline | InlineProperties): Change; - insertText(text: string): Change; - addMark(mark: Mark | MarkProperties | string): Change; - setBlocks(properties: BlockProperties | string): Change; - setInlines(properties: InlineProperties | string): Change; - splitBlock(depth: number): Change; - splitInline(depth: number): Change; - removeMark(mark: Mark | MarkProperties | string): Change; - replaceMark( - mark: Mark | MarkProperties | string, - newMark: Mark | MarkProperties | string - ): Change; - toggleMark(mark: Mark | MarkProperties | string): Change; - unwrapBlock(properties: BlockProperties | string): Change; - unwrapInline(properties: InlineProperties | string): Change; - wrapBlock(properties: BlockProperties | string): Change; - wrapInline(properties: InlineProperties | string): Change; - wrapText(prefix: string, suffix?: string): Change; - - // Selection Changes - blur(): Change; - - flip(): Change; - focus(): Change; - move(n: number): Change; - - moveAnchorBackward(n?: number): Change; - moveAnchorForward(n?: number): Change; - moveAnchorTo(path: Path, offset: number): Change; - moveAnchorToEndOfBlock(): Change; - moveAnchorToEndOfInline(): Change; - moveAnchorToEndOfDocument(): Change; - moveAnchorToEndOfNextBlock(): Change; - moveAnchorToEndOfNextInline(): Change; - moveAnchorToEndOfNextText(): Change; - moveAnchorEndOfNode(node: Node): Change; - moveAnchorToEndOfPreviousBlock(): Change; - moveAnchorToEndOfPreviousInline(): Change; - moveAnchorToEndOfPreviousText(): Change; - moveAnchorToEndOfText(): Change; - moveAnchorToStartOfBlock(): Change; - moveAnchorToStartOfDocument(): Change; - moveAnchorToStartOfInline(): Change; - moveAnchorToStartOfNextBlock(): Change; - moveAnchorToStartOfNextInline(): Change; - moveAnchorToStartOfNextText(): Change; - moveAnchorToStartOfNode(node: Node): Change; - moveAnchorToStartOfPreviousBlock(): Change; - moveAnchorToStartOfPreviousInline(): Change; - moveAnchorToStartOfPreviousText(): Change; - moveAnchorToStartOfText(): Change; - - moveBackward(point: Point, n?: number): Change; - moveEndBackward(point: Point, n?: number): Change; - moveEndForward(point: Point, n?: number): Change; - - moveEndTo(path: Path, offset: number): Change; - moveEndToEndOfBlock(): Change; - moveEndToEndOfDocument(): Change; - moveEndToEndOfInline(): Change; - moveEndToEndOfNextBlock(): Change; - moveEndToEndOfNextInline(): Change; - moveEndToEndOfNextText(): Change; - moveEndToEndOfNode(node: Node): Change; - moveEndToEndOfPreviousBlock(): Change; - moveEndToEndOfPreviousInline(): Change; - moveEndToEndOfPreviousText(): Change; - moveEndToEndOfText(): Change; - moveEndToStartOfBlock(): Change; - moveEndToStartOfDocument(): Change; - moveEndToStartOfInline(): Change; - moveEndToStartOfNextBlock(): Change; - moveEndToStartOfNextInline(): Change; - moveEndToStartOfNextText(): Change; - moveEndToStartOfNode(node: Node): Change; - moveEndToStartOfPreviousBlock(): Change; - moveEndToStartOfPreviousInline(): Change; - moveEndToStartOfPreviousText(): Change; - moveEndToStartOfText(): Change; - - moveFocusBackward(n?: number): Change; - moveFocusForward(n?: number): Change; - moveFocusTo(point: Point, n?: number): Change; - moveFocusToEndOfBlock(): Change; - moveFocusToEndOfDocument(): Change; - moveFocusToEndOfInline(): Change; - moveFocusToEndOfNextBlock(): Change; - moveFocusToEndOfNextInline(): Change; - moveFocusToEndOfNextText(): Change; - moveFocusToEndOfNode(node: Node): Change; - moveFocusToEndOfPreviousBlock(): Change; - moveFocusToEndOfPreviousInline(): Change; - moveFocusToEndOfPreviousText(): Change; - moveFocusToEndOfText(): Change; - moveFocusToStartOfBlock(): Change; - moveFocusToStartOfDocument(): Change; - moveFocusToStartOfInline(): Change; - moveFocusToStartOfNextBlock(): Change; - moveFocusToStartOfNextInline(): Change; - moveFocusToStartOfNextText(): Change; - moveFocusToStartOfNode(node: Node): Change; - moveFocusToStartOfPreviousBlock(): Change; - moveFocusToStartOfPreviousInline(): Change; - moveFocusToStartOfPreviousText(): Change; - moveFocusToStartOfText(): Change; - - moveForward(point: Point, n?: number): Change; - - moveStartForward(point: Point, n?: number): Change; - moveStartBackward(point: Point, n?: number): Change; - moveStartTo(point: Point, n?: number): Change; - moveStartToEndOfBlock(): Change; - moveStartToEndOfDocument(): Change; - moveStartToEndOfInline(): Change; - moveStartToEndOfNextBlock(): Change; - moveStartToEndOfNextInline(): Change; - moveStartToEndOfNextText(): Change; - moveStartToEndOfNode(node: Node): Change; - moveStartToEndOfPreviousBlock(): Change; - moveStartToEndOfPreviousInline(): Change; - moveStartToEndOfPreviousText(): Change; - moveStartToEndOfText(): Change; - moveStartToStartOfBlock(): Change; - moveStartToStartOfDocument(): Change; - moveStartToStartOfInline(): Change; - moveStartToStartOfNextBlock(): Change; - moveStartToStartOfNextInline(): Change; - moveStartToStartOfNextText(): Change; - moveStartToStartOfNode(node: Node): Change; - moveStartToStartOfPreviousBlock(): Change; - moveStartToStartOfPreviousInline(): Change; - moveStartToStartOfPreviousText(): Change; - moveStartToStartOfText(): Change; - - moveTo(path: Path, offset: number): Change; - moveToAnchor(): Change; - moveToFocus(): Change; - moveToStart(): Change; - moveToEnd(): Change; - moveToEndOfBlock(): Change; - moveToEndOfDocument(): Change; - moveToEndOfInline(): Change; - moveToEndOfNextBlock(): Change; - moveToEndOfNextInline(): Change; - moveToEndOfNextText(): Change; - moveToEndOfNode(node: Node): Change; - moveToEndOfPreviousBlock(): Change; - moveToEndOfPreviousInline(): Change; - moveToEndOfPreviousText(): Change; - moveToEndOfText(): Change; - moveToStartOfBlock(): Change; - moveToStartOfDocument(): Change; - moveToStartOfInline(): Change; - moveToStartOfNextBlock(): Change; - moveToStartOfNextInline(): Change; - moveToStartOfNextText(): Change; - moveToStartOfNode(node: Node): Change; - moveToStartOfPreviousBlock(): Change; - moveToStartOfPreviousInline(): Change; - moveToStartOfPreviousText(): Change; - moveToStartOfText(): Change; - - moveToRangeOfDocument(): Change; - moveToRangeOfNode(node: Node): Change; - select(properties: Range | RangeProperties, options: ChangeOption): Change; - setAnchor(point: Point): Change; - setEnd(point: Point): Change; - setFocus(point: Point): Change; - setStart(point: Point): Change; - snapshotSelection(): Change; - deselect(): Change; - - // Document Changes - deleteCharBackwardAtRange(range: Range, options?: ChangeOption): Change; - deleteLineBackwardAtRange(range: Range, options?: ChangeOption): Change; - deleteWordBackwardAtRange(range: Range, options?: ChangeOption): Change; - deleteBackwardAtRange(range: Range, options?: ChangeOption): Change; - deleteCharForwardAtRange(range: Range, options?: ChangeOption): Change; - deleteLineForwardAtRange(range: Range, options?: ChangeOption): Change; - deleteWordForwardAtRange(range: Range, options?: ChangeOption): Change; - deleteForwardAtRange(range: Range, options?: ChangeOption): Change; - deleteAtRange(range: Range, options?: ChangeOption): Change; - insertBlockAtRange( - range: Range, - block: Block | BlockProperties | string, - options?: ChangeOption - ): Change; - insertFragmentAtRange( - range: Range, - fragment: Document, - options?: ChangeOption - ): Change; - insertInlineAtRange( - range: Range, - inline: Inline | InlineProperties, - options?: ChangeOption - ): Change; - insertTextAtRange( - range: Range, - text: string, - marks?: Immutable.Set, - options?: ChangeOption - ): Change; - addMarkAtRange( - range: Range, - mark: Mark | MarkProperties | string, - options?: ChangeOption - ): Change; - addMarksAtRange( - range: Range, - marks: Mark[] | MarkProperties[] | string[], - options?: ChangeOption - ): Change; - setBlocksAtRange( - range: Range, - properties: BlockProperties | string, - options?: ChangeOption - ): Change; - setInlinesAtRange( - range: Range, - properties: InlineProperties | string, - options?: ChangeOption - ): Change; - splitBlockAtRange( - range: Range, - depth: number, - height?: number, - options?: ChangeOption - ): Change; - splitInlineAtRange( - range: Range, - depth: number, - height?: number, - options?: ChangeOption - ): Change; - removeMarkAtRange( - range: Range, - mark: Mark | MarkProperties | string, - options?: ChangeOption - ): Change; - toggleMarkAtRange( - range: Range, - mark: Mark | MarkProperties | string, - options?: ChangeOption - ): Change; - unwrapBlockAtRange( - range: Range, - properties: BlockProperties | string, - options?: ChangeOption - ): Change; - unwrapInlineAtRange( - range: Range, - properties: InlineProperties | string, - options?: ChangeOption - ): Change; - wrapBlockAtRange( - range: Range, - properties: BlockProperties | string, - options?: ChangeOption - ): Change; - wrapInlineAtRange( - range: Range, - properties: InlineProperties | string, - options?: ChangeOption - ): Change; - wrapTextAtRange( - range: Range, - prefix: string, - suffix?: string, - options?: ChangeOption - ): Change; - - // Node Changes - addMarkByKey( - key: string, - offset: number, - length: number, - mark: Mark - ): Change; - insertNodeByKey(key: string, index: number, node: Node): Change; - insertFragmentByKey(key: string, index: number, fragment: Document): Change; - insertTextByKey( - key: string, - offset: number, - text: string, - marks?: Immutable.Set | Mark[] - ): Change; - moveNodeByKey(key: string, newKey: string, newIndex: number): Change; - removeMarkByKey( - key: string, - offset: number, - length: number, - mark: Mark - ): Change; - removeNodeByKey(key: string): Change; - replaceNodeByKey(key: string, node: Node): Change; - removeTextByKey(key: string, offset: number, length: number): Change; - setMarkByKey( - key: string, - offset: number, - length: number, - mark: Mark, - properties: MarkProperties - ): Change; - setNodeByKey( - key: string, - properties: BlockProperties | InlineProperties | string - ): Change; - splitNodeByKey(key: string, offset: number): Change; - unwrapInlineByKey( - key: string, - properties: InlineProperties | string - ): Change; - unwrapBlockByKey(key: string, properties: BlockProperties | string): Change; - unwrapNodeByKey(key: string): Change; - wrapInlineByKey(key: string, properties: InlineProperties | string): Change; - wrapBlockByKey(key: string, properties: BlockProperties | string): Change; - wrapNodeByKey(key: string): Change; - - // by path - addMarkByPath( - path: Path, - offset: number, - length: number, - mark: MarkProperties | Mark | string, - options: ChangeOption - ): Change; - insertFragmentByPath( - path: Path, - index: number, - fragment: Document, - options: ChangeOption - ): Change; - insertNodeByPath( - path: Path, - index: number, - node: Node, - options: ChangeOption - ): Change; - insertTextByPath( - path: Path, - offset: number, - text: string, - marks: Immutable.Set | null | undefined, - options: ChangeOption - ): Change; - mergeNodeByPath(path: Path, options: ChangeOption): Change; - mergeNodeByKey(key: string, options: ChangeOption): Change; - moveNodeByPath( - path: Path, - newPath: Path, - newIndex: number, - options: ChangeOption - ): Change; - removeMarkByPath( - path: Path, - offset: number, - length: number, - mark: MarkProperties | Mark | string, - options: ChangeOption - ): Change; - removeAllMarksByPath(path: Path, options: ChangeOption): Change; - removeAllMarksByKey(key: string, options: ChangeOption): Change; - removeNodeByPath(path: Path, options: ChangeOption): Change; - removeTextByPath( - path: Path, - offset: number, - length: number, - options: ChangeOption - ): Change; - replaceNodeByPath(path: Path, newNode: Node, options: ChangeOption): Change; - replaceTextByPath( - path: Path, - offset: number, - length: number, - text: string, - marks: Immutable.Set | null | undefined, - options: ChangeOption - ): Change; - replaceTextByKey( - key: string, - offset: number, - length: number, - text: string, - marks: Immutable.Set | null | undefined, - options: ChangeOption - ): Change; - setMarksByPath( - path: Path, - offset: number, - length: number, - mark: Mark, - properties: MarkProperties, - options: ChangeOption - ): Change; - setNodeByPath( - path: Path, - properties: NodeProperties, - options: ChangeOption - ): Change; - setTextByPath( - path: Path, - text: string, - marks: Immutable.Set | null | undefined, - options: ChangeOption - ): Change; - setTextByKey( - key: string, - text: string, - marks: Immutable.Set | null | undefined, - options: ChangeOption - ): Change; - splitNodeByPath( - path: Path, - position: number, - options?: ChangeOption - ): Change; - splitDescendantByPath( - path: Path, - textPath: Path, - textOffset: number, - options: ChangeOption - ): Change; - unwrapInlineByPath( - path: Path, - properties: InlineProperties, - options: ChangeOption - ): Change; - unwrapBlockByPath( - path: Path, - properties: BlockProperties, - options: ChangeOption - ): Change; - unwrapNodeByPath(path: Path, options: ChangeOption): Change; - wrapBlockByPath(path: Path, block: Block, options: ChangeOption): Change; - wrapInlineByPath(path: Path, inline: Inline, options: ChangeOption): Change; - wrapNodeByPath(path: Path, node: Node): Change; - - normalize(options: ChangeOption): Change; - normalizeDocument(options: ChangeOption): Change; - normalizeNodeByKey(key: string, options: ChangeOption): Change; - normalizeAncestorsByKey(key: string): Change; - normalizeParentByKey(key: string, options: ChangeOption): Change; - normalizeNodeByPath(path: Path, options: ChangeOption): Change; - normalizeParentByPath(path: Path, options: ChangeOption): Change; - normalizeNodeAndChildren(node: Node, schema: Schema): Change; - normalizeNode(node: Node, schema: Schema): Change; - - // History Changes - redo(): Change; - undo(): Change; -} - export interface SelectionProperties { anchor?: Point; focus?: Point; @@ -1530,7 +1048,7 @@ export interface PathUtils { } export interface EditorProperties { - onChange?: (change: Change) => void; + onChange?: (change: { operations: Immutable.List, value: Value }) => void; plugins?: any[]; readOnly?: boolean; value?: Value; @@ -1538,21 +1056,1070 @@ export interface EditorProperties { export class Editor { object: "editor"; - onChange: (change: Change) => void; + onChange: (change: { operations: Immutable.List, value: Value }) => void; plugins: any[]; readOnly: boolean; value: Value; constructor(attributes: EditorProperties) - change(customChange: (change: Change, ...args: any[]) => Change): void; + /** + * Apply an `operation` to the editor, updating its value. + */ + applyOperation(operation: Operation): Editor; + + /** + * Synchronously flush the current changes to editor, calling onChange. + * In normal operation you never need to use this method! Reserved for testing. + */ + flush(): Editor; + command(name: string, ...args: any[]): void; - event(handler: string, event: Event | SyntheticEvent): void; query(query: string, ...args: any[]): any; + + /** + * Add a new command by type with the editor. This will make the command available as a top-level method on the editor + */ registerCommand(command: string): void; + + /** + * Add a new query by type with the editor. This will make the query available as a top-level method on the editor. + */ registerQuery(query: string): void; + + /** + * Run the middleware stack by key with args, returning its result. + * In normal operation you never need to use this method! Reserved for testing. + */ run(key: string, ...args: any[]): any; setReadOnly(readOnly: boolean): Editor; - setValue(value: Value, options?: object): Editor; + + /** + * Set the editor's value state. + * You can optionally provide a normalize option to either for the editor to completely re-normalize the new value based on its schema or not. + * By default, the editor will re-normalize only if the value is not equal to its previously seen value (which it knows was normalized). + */ + setValue(value: Value, options?: { normalize: boolean }): Editor; + + // Built in Command Operations // + // Current Selection Commands // + /** + * Add a mark to the characters in the current selection + */ + addMark(mark: Mark | MarkProperties | string): Editor; + + /** + * Delete everything in the current selection. + */ + delete(): Editor; + + /** + * Delete backward n characters at the current cursor. + * If the selection is expanded, behaviour is equivalent to delete() + */ + deleteBackward(n: number): Editor; + + /** + * Delete backward n characters at the current cursor. + * If the selection is expanded, behaviour is equivalent to delete() + */ + deleteForward(n: number): Editor; + + /** + * Insert a new block at the same level as the current block, splitting the current block to make room if it is non-empty. + * If the selection is expanded, it will be deleted first. + */ + insertBlock(block: Block | BlockProperties | string): Editor; + + /** + * Insert a document fragment at the current selection. If the selection is expanded, it will be deleted first. + */ + insertFragment(fragment: Document): Editor; + + /** + * Insert a new inline at the current cursor position, splitting the text to make room if it is non-empty. + * If the selection is expanded, it will be deleted first. + */ + insertInline(inline: Inline | InlineProperties): Editor; + + /** + * Insert a string of text at the current selection. If the selection is expanded, it will be deleted first + */ + insertText(text: string): Editor; + + /** + * Set the properties of the Blocks in the current selection. + * Passing a string will set the blocks' type only. + */ + setBlocks(properties: BlockProperties | string): Editor; + + /** + * Set the properties of the Inlines nodes in the current selection. + * Passing a string will set the nodes' type only. + */ + setInlines(properties: InlineProperties | string): Editor; + + /** + * Split the Block in the current selection by depth levels. + * If the selection is expanded, it will be deleted first. + */ + splitBlock(depth: number): Editor; + + /** + * Split the Inline node in the current selection by depth levels. + * If the selection is expanded, it will be deleted first + */ + splitInline(depth: number): Editor; + + /** + * Remove a mark from the characters in the current selection. + * Passing a string will implicitly create a Mark of that type for removal. + */ + removeMark(mark: Mark | MarkProperties | string): Editor; + + /** + * Remove a mark from the characters in the current selection. + * Passing a string will implicitly create a Mark of that type. + */ + replaceMark( + mark: Mark | MarkProperties | string, + newMark: Mark | MarkProperties | string + ): Editor; + + /** + * Add or remove a mark from the characters in the current selection, depending on it already exists on any or not. + * Passing a string will implicitly create a Mark of that type to toggle. + */ + toggleMark(mark: Mark | MarkProperties | string): Editor; + + /** + * Unwrap all Block nodes in the current selection that match a type and/or data + */ + unwrapBlock(properties: BlockProperties | string): Editor; + + /** + * Unwrap all Inline nodes in the current selection that match a type and/or data + */ + unwrapInline(properties: InlineProperties | string): Editor; + + /** + * Wrap the Block nodes in the current selection with a new Block + */ + wrapBlock(properties: BlockProperties | string): Editor; + + /** + * Wrap the Block nodes in the current selection with a new Inline + */ + wrapInline(properties: InlineProperties | string): Editor; + + /** + * Surround the text in the current selection with prefix and suffix strings. + * If the suffix is ommitted, the prefix will be used instead. + */ + wrapText(prefix: string, suffix?: string): Editor; + + // Selection Commands // + /** + * Blur the current selection + */ + blur(): Editor; + + /** + * Unset the selection + */ + deselect(): Editor; + + /** + * Flip the selection + */ + flip(): Editor; + + /** + * Focus the current selection + */ + focus(): Editor; + + /** + * Move the anchor of the current selection backward n characters + */ + moveAnchorBackward(n?: number): Editor; + /** + * Move the anchor of the current selection forward n characters + */ + moveAnchorForward(n?: number): Editor; + /** + * Move the anchor of the current selection to a new path and offset + */ + moveAnchorTo(path: Path, offset?: number): Editor; + /** + * Move the anchor of the current selection to the end of the closest block parent. + */ + moveAnchorToEndOfBlock(): Editor; + /** + * Move the anchor of the current selection to the end of the closest inline parent. + */ + moveAnchorToEndOfInline(): Editor; + /** + * Move the anchor of the current selection to the end of the document. + */ + moveAnchorToEndOfDocument(): Editor; + /** + * Move the anchor of the current selection to the end of the next block. + */ + moveAnchorToEndOfNextBlock(): Editor; + /** + * Move the anchor of the current selection to the end of the next inline. + */ + moveAnchorToEndOfNextInline(): Editor; + /** + * Move the anchor of the current selection to the end of the next text. + */ + moveAnchorToEndOfNextText(): Editor; + /** + * Move the anchor of the current selection to the end of the provided node. + */ + moveAnchorEndOfNode(node: Node): Editor; + /** + * Move the anchor of the current selection to the end of the previous block. + */ + moveAnchorToEndOfPreviousBlock(): Editor; + /** + * Move the anchor of the current selection to the end of the previous inline. + */ + moveAnchorToEndOfPreviousInline(): Editor; + /** + * Move the anchor of the current selection to the end of the previous text. + */ + moveAnchorToEndOfPreviousText(): Editor; + /** + * Move the anchor of the current selection to the end of the current text node. + */ + moveAnchorToEndOfText(): Editor; + /** + * Move the anchor of the current selection to the start of the closest block parent. + */ + moveAnchorToStartOfBlock(): Editor; + /** + * Move the anchor of the current selection to the start of the document. + */ + moveAnchorToStartOfDocument(): Editor; + /** + * Move the anchor of the current selection to the start of the closest inline parent. + */ + moveAnchorToStartOfInline(): Editor; + /** + * Move the anchor of the current selection to the start of the next block. + */ + moveAnchorToStartOfNextBlock(): Editor; + /** + * Move the anchor of the current selection to the start of the next inline. + */ + moveAnchorToStartOfNextInline(): Editor; + /** + * Move the anchor of the current selection to the start of the next text node. + */ + moveAnchorToStartOfNextText(): Editor; + /** + * Move the anchor of the current selection to the start of the provided node. + */ + moveAnchorToStartOfNode(node: Node): Editor; + /** + * Move the anchor of the current selection to the start of the previous block. + */ + moveAnchorToStartOfPreviousBlock(): Editor; + /** + * Move the anchor of the current selection to the start of the previous inline. + */ + moveAnchorToStartOfPreviousInline(): Editor; + /** + * Move the anchor of the current selection to the start of the previous text node. + */ + moveAnchorToStartOfPreviousText(): Editor; + /** + * Move the anchor of the current selection to the start of the current text node. + */ + moveAnchorToStartOfText(): Editor; + + /** + * Move the end of the selection backward n characters + */ + moveEndBackward(n?: number): Editor; + /** + * Move the end of the selection foward n characters + */ + moveEndForward(n?: number): Editor; + + /** + * Move the end of the selection to a new path and offset + */ + moveEndTo(path: Path, offset?: number): Editor; + /** + * Move the end of the current selection to the end of the closest block parent. + */ + moveEndToEndOfBlock(): Editor; + /** + * Move the end of the current selection to the end of the document. + */ + moveEndToEndOfDocument(): Editor; + /** + * Move the end of the current selection to the end of the closest inline parent. + */ + moveEndToEndOfInline(): Editor; + /** + * Move the anchor of the current selection to the end of the next block. + */ + moveEndToEndOfNextBlock(): Editor; + /** + * Move the end of the current selection to the end of the next inline. + */ + moveEndToEndOfNextInline(): Editor; + /** + * Move the end of the current selection to the end of the next text. + */ + moveEndToEndOfNextText(): Editor; + /** + * Move the end of the current selection to the end of the provided node. + */ + moveEndToEndOfNode(node: Node): Editor; + /** + * Move the end of the current selection to the end of the previous block. + */ + moveEndToEndOfPreviousBlock(): Editor; + /** + * Move the end of the current selection to the end of the previous inline. + */ + moveEndToEndOfPreviousInline(): Editor; + /** + * Move the editor of the current selection to the end of the previous text. + */ + moveEndToEndOfPreviousText(): Editor; + /** + * Move the end of the current selection to the end of the current text node. + */ + moveEndToEndOfText(): Editor; + /** + * Move the end of the current selection to the start of the closest block parent. + */ + moveEndToStartOfBlock(): Editor; + /** + * Move the end of the current selection to the start of the document. + */ + moveEndToStartOfDocument(): Editor; + /** + * Move the end of the current selection to the start of the closest inline parent. + */ + moveEndToStartOfInline(): Editor; + /** + * Move the end of the current selection to the start of the next block. + */ + moveEndToStartOfNextBlock(): Editor; + /** + * Move the end of the current selection to the start of the next inline. + */ + moveEndToStartOfNextInline(): Editor; + /** + * Move the end of the current selection to the start of the next text node. + */ + moveEndToStartOfNextText(): Editor; + /** + * Move the end of the current selection to the start of the provided node. + */ + moveEndToStartOfNode(node: Node): Editor; + /** + * Move the end of the current selection to the start of the previous block. + */ + moveEndToStartOfPreviousBlock(): Editor; + /** + * Move the end of the current selection to the start of the previous inline. + */ + moveEndToStartOfPreviousInline(): Editor; + /** + * Move the end of the current selection to the start of the previous text node. + */ + moveEndToStartOfPreviousText(): Editor; + /** + * Move the end of the current selection to the start of the current text node. + */ + moveEndToStartOfText(): Editor; + + /** + * Move the focus of the current selection backward n characters + */ + moveFocusBackward(n?: number): Editor; + /** + * Move the focus of the current selection forward n characters + */ + moveFocusForward(n?: number): Editor; + /** + * Move the focus of the current selection to a new path and offset + */ + moveFocusTo(path: Path, offset?: number): Editor; + /** + * Move the focus of the current selection to the end of the closest block parent. + */ + moveFocusToEndOfBlock(): Editor; + /** + * Move the focus of the current selection to the end of the document. + */ + moveFocusToEndOfDocument(): Editor; + /** + * Move the focus of the current selection to the end of the closest inline parent. + */ + moveFocusToEndOfInline(): Editor; + /** + * Move the focus of the current selection to the end of the next block. + */ + moveFocusToEndOfNextBlock(): Editor; + /** + * Move the focus of the current selection to the end of the next inline. + */ + moveFocusToEndOfNextInline(): Editor; + /** + * Move the focus of the current selection to the end of the next text. + */ + moveFocusToEndOfNextText(): Editor; + /** + * Move the focus of the current selection to the end of the provided node. + */ + moveFocusToEndOfNode(node: Node): Editor; + /** + * Move the focus of the current selection to the end of the previous block. + */ + moveFocusToEndOfPreviousBlock(): Editor; + /** + * Move the focus of the current selection to the end of the previous inline. + */ + moveFocusToEndOfPreviousInline(): Editor; + /** + * Move the focus of the current selection to the end of the previous text. + */ + moveFocusToEndOfPreviousText(): Editor; + /** + * Move the focus of the current selection to the end of the current text node. + */ + moveFocusToEndOfText(): Editor; + /** + * Move the focus of the current selection to the start of the closest block parent. + */ + moveFocusToStartOfBlock(): Editor; + /** + * Move the focus of the current selection to the start of the document. + */ + moveFocusToStartOfDocument(): Editor; + /** + * Move the focus of the current selection to the start of the closest inline parent. + */ + moveFocusToStartOfInline(): Editor; + /** + * Move the focus of the current selection to the start of the next block. + */ + moveFocusToStartOfNextBlock(): Editor; + /** + * Move the focus of the current selection to the start of the next inline. + */ + moveFocusToStartOfNextInline(): Editor; + /** + * Move the focus of the current selection to the start of the next text node. + */ + moveFocusToStartOfNextText(): Editor; + /** + * Move the focus of the current selection to the start of the provided node. + */ + moveFocusToStartOfNode(node: Node): Editor; + /** + * Move the focus of the current selection to the start of the previous block. + */ + moveFocusToStartOfPreviousBlock(): Editor; + /** + * Move the focus of the current selection to the start of the previous inline. + */ + moveFocusToStartOfPreviousInline(): Editor; + /** + * Move the focus of the current selection to the start of the previous text node. + */ + moveFocusToStartOfPreviousText(): Editor; + /** + * Move the focus of the current selection to the start of the current text node. + */ + moveFocusToStartOfText(): Editor; + + /** + * Move the start of the current selection backward n characters + */ + moveStartForward(n?: number): Editor; + /** + * Move the start of the current selection forward n characters + */ + moveStartBackward(n?: number): Editor; + /** + * Move the start of the current selection to a new path and offset + */ + moveStartTo(path: Path, n?: number): Editor; + /** + * Move the start of the current selection to the end of the closest block parent. + */ + moveStartToEndOfBlock(): Editor; + /** + * Move the start of the current selection to the end of the document. + */ + moveStartToEndOfDocument(): Editor; + /** + * Move the start of the current selection to the end of the closest inline parent. + */ + moveStartToEndOfInline(): Editor; + /** + * Move the start of the current selection to the end of the next block. + */ + moveStartToEndOfNextBlock(): Editor; + /** + * Move the start of the current selection to the end of the next inline. + */ + moveStartToEndOfNextInline(): Editor; + /** + * Move the start of the current selection to the end of the next text. + */ + moveStartToEndOfNextText(): Editor; + /** + * Move the start of the current selection to the end of the provided node. + */ + moveStartToEndOfNode(node: Node): Editor; + /** + * Move the start of the current selection to the end of the previous block. + */ + moveStartToEndOfPreviousBlock(): Editor; + /** + * Move the start of the current selection to the end of the previous inline. + */ + moveStartToEndOfPreviousInline(): Editor; + /** + * Move the start of the current selection to the end of the previous text. + */ + moveStartToEndOfPreviousText(): Editor; + /** + * Move the start of the current selection to the end of the current text node. + */ + moveStartToEndOfText(): Editor; + /** + * Move the start of the current selection to the start of the closest block parent. + */ + moveStartToStartOfBlock(): Editor; + /** + * Move the start of the current selection to the start of the document. + */ + moveStartToStartOfDocument(): Editor; + /** + * Move the start of the current selection to the start of the closest inline parent. + */ + moveStartToStartOfInline(): Editor; + /** + * Move the start of the current selection to the start of the next block. + */ + moveStartToStartOfNextBlock(): Editor; + /** + * Move the start of the current selection to the start of the next inline. + */ + moveStartToStartOfNextInline(): Editor; + /** + * Move the start of the current selection to the start of the next text node. + */ + moveStartToStartOfNextText(): Editor; + /** + * Move the start of the current selection to the start of the provided node. + */ + moveStartToStartOfNode(node: Node): Editor; + /** + * Move the start of the current selection to the start of the previous block. + */ + moveStartToStartOfPreviousBlock(): Editor; + /** + * Move the start of the current selection to the start of the previous inline. + */ + moveStartToStartOfPreviousInline(): Editor; + /** + * Move the start of the current selection to the start of the previous text node. + */ + moveStartToStartOfPreviousText(): Editor; + /** + * Move the start of the current selection to the start of the current text node. + */ + moveStartToStartOfText(): Editor; + + /** + * Move the anchor and focus of the selection backward n characters. + */ + moveBackward(n?: number): Editor; + /** + * Move the anchor and focus of the selection forward n characters. + */ + moveForward(n?: number): Editor; + /** + * Collapse the current selection at the provided new path and offset. + */ + moveTo(path: Path, offset?: number): Editor; + /** + * Collapse the current selection at the anchor. + */ + moveToAnchor(): Editor; + /** + * Collapse the current selection at the focus. + */ + moveToFocus(): Editor; + /** + * Collapse the current selection at the start. + */ + moveToStart(): Editor; + /** + * Collapse the current selection at the end. + */ + moveToEnd(): Editor; + /** + * Collapse the current selection at the end of the closest block parent. + */ + moveToEndOfBlock(): Editor; + /** + * Collapse the current selection at the end of the document. + */ + moveToEndOfDocument(): Editor; + /** + * Collapse the current selection at the end of the closest inline parent. + */ + moveToEndOfInline(): Editor; + /** + * Collapse the current selection at the end of the next block. + */ + moveToEndOfNextBlock(): Editor; + /** + * Collapse the current selection at the end of the inline. + */ + moveToEndOfNextInline(): Editor; + /** + * Collapse the current selection at the end of the next text node. + */ + moveToEndOfNextText(): Editor; + /** + * Collapse the current selection at the end of the provided node. + */ + moveToEndOfNode(node: Node): Editor; + /** + * Collapse the current selection at the end of the previous block. + */ + moveToEndOfPreviousBlock(): Editor; + /** + * Collapse the current selection at the end of the previous inline. + */ + moveToEndOfPreviousInline(): Editor; + /** + * Collapse the current selection at the end of the previous text node. + */ + moveToEndOfPreviousText(): Editor; + /** + * Collapse the current selection at the end of the current text node. + */ + moveToEndOfText(): Editor; + /** + * Collapse the current selection at the start of the nearest block parent. + */ + moveToStartOfBlock(): Editor; + /** + * Collapse the current selection at the start of the document. + */ + moveToStartOfDocument(): Editor; + /** + * Collapse the current selection at the start of the nearest inline parent. + */ + moveToStartOfInline(): Editor; + /** + * Collapse the current selection at the start of the next block. + */ + moveToStartOfNextBlock(): Editor; + /** + * Collapse the current selection at the start of the next inline. + */ + moveToStartOfNextInline(): Editor; + /** + * Collapse the current selection at the start of the next text node. + */ + moveToStartOfNextText(): Editor; + /** + * Collapse the current selection at the start of the provided node. + */ + moveToStartOfNode(node: Node): Editor; + /** + * Collapse the current selection at the start of the previous block. + */ + moveToStartOfPreviousBlock(): Editor; + /** + * Collapse the current selection at the start of the previous inline. + */ + moveToStartOfPreviousInline(): Editor; + /** + * Collapse the current selection at the start of the previous text node. + */ + moveToStartOfPreviousText(): Editor; + /** + * Collapse the current selection at the start of the current text node. + */ + moveToStartOfText(): Editor; + + /** + * Move the current selection's anchor to the start of the document and its focus to the end of it, selecting everything. + */ + moveToRangeOfDocument(): Editor; + /** + * Move the current selection's anchor to the start of the provided node and its focus to the end of it. + */ + moveToRangeOf(node: Node): Editor; + /** + * Merge the current selection with the provided properties + */ + select(properties: Range | RangeProperties): Editor; + + // Document Range Commands // + + /** + * Add a mark to the characters in the range. + * Passing a string as `mark` will implicitly create a mark with that `type` + */ + addMarkAtRange(range: Range, mark: Mark | MarkProperties | string): Editor; + /** + * Delete everything in the range + */ + deleteAtRange(range: Range): Editor; + /** + * Delete backward until the char boundary at a range + */ + deleteCharBackwardAtRange(range: Range): Editor; + /** + * Delete backward until the line boundary at a range + */ + deleteLineBackwardAtRange(range: Range): Editor; + /** + * Delete backward until the word boundary at a range + */ + deleteWordBackwardAtRange(range: Range): Editor; + /** + * Delete backward n characters at a range + */ + deleteBackwardAtRange(range: Range, n: number): Editor; + /** + * Delete forward until the char boundary at a range + */ + deleteCharForwardAtRange(range: Range): Editor; + /** + * Delete forward until the line boundary at a range + */ + deleteLineForwardAtRange(range: Range): Editor; + /** + * Delete forward until the word boundary at a range + */ + deleteWordForwardAtRange(range: Range): Editor; + /** + * Delete forward n characters at a range + */ + deleteForwardAtRange(range: Range, n: number): Editor; + + /** + * Insert a block node at range, splitting text to make room if it is non-empty. + * If the range is expanded, it will be deleted first. + */ + insertBlockAtRange(range: Range, block: Block | BlockProperties | string): Editor; + /** + * Insert a document fragment at a range, if the range is expanded, it will be deleted first. + */ + insertFragmentAtRange(range: Range, fragment: Document): Editor; + /** + * Insert a new inline at range, splitting text to make room if it is non-empty. + * If the range is expanded, it will be deleted first. + */ + insertInlineAtRange(range: Range, inline: Inline | InlineProperties): Editor; + /** + * Insert text at range. If the range is expanded it will be deleted first + */ + insertTextAtRange(range: Range, text: string): Editor; + /** + * Set the properties of the block nodes in a range. + * Passing a string will set the nodes' type only + */ + setBlocksAtRange(range: Range, properties: BlockProperties | string): Editor; + /** + * Set the properties of the inline nodes in a range. + * Passing a string will set the nodes' type only + */ + setInlinesAtRange(range: Range, properties: InlineProperties | string): Editor; + /** + * Split the block in a range by depth levels. If the range is expanded it will be deleted first. + */ + splitBlockAtRange(range: Range, depth: number): Editor; + /** + * Split the inline in a range by depth levels. If the range is expanded it will be deleted first. + */ + splitInlineAtRange(range: Range, depth: number): Editor; + /** + * Remove a mark from characters in the range. Passing a string will + * implicitly create a mark of that type for deletion. + */ + removeMarkAtRange(range: Range, mark: Mark | MarkProperties | string): Editor; + /** + * Add or remove a mark from characters in the range. Passing a string will + * implicitly create a mark of that type for deletion. + */ + toggleMarkAtRange(range: Range, mark: Mark | MarkProperties | string): Editor; + /** + * Unwrap all block nodes in a range that match properties + */ + unwrapBlockAtRange(range: Range, properties: BlockProperties | string): Editor; + /** + * Unwrap all inline nodes in a range that match properties + */ + unwrapInlineAtRange(range: Range, properties: InlineProperties | string): Editor; + /** + * wrap all block nodes in a range with a new block node with the provided properties + */ + wrapBlockAtRange(range: Range, properties: BlockProperties | string): Editor; + /** + * wrap all inline nodes in a range with a new inline node with the provided properties + */ + wrapInlineAtRange(range: Range, properties: InlineProperties | string): Editor; + /** + * Surround the text in a range with a prefix and suffix. If the suffix is ommitted, + * the prefix will be used instead. + */ + wrapTextAtRange(range: Range, prefix: string, suffix?: string): Editor; + + // Node commands // + /** + * Add a mark to length characters starting at an offset in a node by key + */ + addMarkByKey( + key: string, + offset: number, + length: number, + mark: MarkProperties | Mark | string + ): Editor; + /** + * Add a mark to length characters starting at an offset in a node by path + */ + addMarkByPath( + path: Path, + offset: number, + length: number, + mark: MarkProperties | Mark | string + ): Editor; + /** + * Insert a node at index inside a parent node by key + */ + insertNodeByKey(key: string, index: number, node: Node): Editor; + /** + * Insert a node at index inside a parent node by apth + */ + insertNodeByPath(path: Path, index: number, node: Node): Editor; + /** + * Insert a document fragment at index inside a parent node by key + */ + insertFragmentByKey(key: string, index: number, fragment: Document): Editor; + /** + * Insert a document fragment at index inside a parent node by path + */ + insertFragmentByPath(path: Path, index: number, fragment: Document): Editor; + /** + * Insert text at an offset in a text node by its key with optional marks + */ + insertTextByKey( + key: string, + offset: number, + text: string, + marks?: Immutable.Set | Mark[] + ): Editor; + /** + * Insert text at an offset in a text node by its path with optional marks + */ + insertTextByPath( + path: Path, + offset: number, + text: string, + marks?: Immutable.Set | Mark[] + ): Editor; + /** + * Merge a node by its key with its previous sibling + */ + mergeNodeByKey(key: string): Editor; + /** + * Merge a node by its path with its previous sibling + */ + mergeNodeByPath(path: Path): Editor; + /** + * Move a node by its key to a new parent node with with newkey at newindex + */ + moveNodeByKey(key: string, newKey: string, newIndex: number): Editor; + /** + * Move a node by its path to a new parent node with with newpath at newindex + */ + moveNodeByPath(path: Path, newPath: Path, newIndex: number): Editor; + /** + * Remove a mark from length characters starting at an offset in a node by key + */ + removeMarkByKey( + key: string, + offset: number, + length: number, + mark: Mark | Mark | string + ): Editor; + /** + * Remove a mark from length characters starting at an offset in a node by path + */ + removeMarkByPath( + path: Path, + offset: number, + length: number, + mark: MarkProperties | Mark | string + ): Editor; + /** + * Remove a node from the document by its key + */ + removeNodeByKey(key: string): Editor; + /** + * Remove a node from the document by its path + */ + removeNodeByPath(path: Path): Editor; + /** + * Replace a node in the document with a new node by key + */ + replaceNodeByKey(key: string, node: Node): Editor; + /** + * Replace a node in the document with a new node by path + */ + replaceNodeByPath(path: Path, newNode: Node): Editor; + /** + * Remove length characters of text starting at an offset in a node by key + */ + removeTextByKey(key: string, offset: number, length: number): Editor; + /** + * Remove length characters of text starting at an offset in a node by path + */ + removeTextByPath(path: Path, offset: number, length: number): Editor; + /** + * Set a dictionary of properties on a mark by its key. + */ + setMarkByKey( + key: string, + offset: number, + length: number, + mark: Mark, + properties: MarkProperties + ): Editor; + /** + * Set a dictionary of properties on a mark by its path. + */ + setMarksByPath( + path: Path, + offset: number, + length: number, + mark: Mark, + properties: MarkProperties + ): Editor; + /** + * Set a dictionary of properties on a node by its key. + */ + setNodeByKey(key: string, properties: BlockProperties | InlineProperties | string): Editor; + /** + * Set a dictionary of properties on a node by its key. + */ + setNodeByPath(path: Path, properties: NodeProperties | InlineProperties | string): Editor; + /** + * Split a node by its key at an offset + */ + splitNodeByKey(key: string, offset: number): Editor; + /** + * Split a node by its path at an offset + */ + splitNodeByPath(path: Path, position: number): Editor; + /** + * Unwrap all inner content of an inline node by its key that match properties + */ + unwrapInlineByKey(key: string, properties: InlineProperties | string): Editor; + /** + * Unwrap all inner content of an inline node by its path that match properties + */ + unwrapInlineByPath(path: Path, properties: InlineProperties | string): Editor; + /** + * Unwrap all inner content of a block node by its key that match properties + */ + unwrapBlockByKey(key: string, properties: BlockProperties | string): Editor; + /** + * Unwrap all inner content of a block node by its path that match properties + */ + unwrapBlockByPath(path: Path, properties: BlockProperties | string): Editor; + /** + * Unwrap a single node from its parent. if the node is surrounded with siblings the parent will be split. + * If the node is an only child, it will replace the parent + */ + unwrapNodeByKey(key: string): Editor; + /** + * Unwrap a single node from its parent. if the node is surrounded with siblings the parent will be split. + * If the node is an only child, it will replace the parent + */ + unwrapNodeByPath(path: Path): Editor; + /** + * Wrap the given node by key in an Inline node that matches properties. + */ + wrapInlineByKey(key: string, properties: InlineProperties | string): Editor; + /** + * Wrap the given node by path in an Inline node that matches properties. + */ + wrapInlineByPath(path: Path, properties: InlineProperties | string): Editor; + /** + * Wrap the given node by key in a block node that matches properties. + */ + wrapBlockByKey(key: string, properties: BlockProperties | string): Editor; + /** + * Wrap the given node by path in a block node that matches properties. + */ + wrapBlockByPath(path: Path, block: Block | string): Editor; + /** + * Wrap the node with the specified key with the parent node, this will clear all children of the parent. + */ + wrapNodeByKey(key: string, parent: Node): Editor; + /** + * Wrap the node with the specified key with the parent node, this will clear all children of the parent. + */ + wrapNodeByPath(path: Path, parent: Node): Editor; + + // Miscellaneous Commands // + /** + * Normalizes the document with the value's schema. Run automatically unless manually disabled. + * Use it sparingly and strategically, as it can be very expensive. + */ + normalize(): Editor; + /** + * Calls the provided function with the current editor as the first argument. + * Normalization does not occur while the function is executing and is deferred to execute immediately after completion. + * + * This allows for sequence change operations to not be interrupted by normalization + */ + withoutNormalizing(fn: () => void): Editor; + /** + * By default all operations are saved to the editor's history. If you have + * changes that you don't want to show up in history, use this function. + */ + withoutSaving(fn: () => void): Editor; + /** + * Usually all command operations are merged into a single save point in history, + * if more control is desired, create single save points using this function. + */ + withoutMerging(fn: () => void): Editor; + + // History Commands // + /** + * Move forward one step in the history + */ + redo(): Editor; + /** + * Move backward one step in the history + */ + undo(): Editor; + /** + * Snapshot the current selection for undo purposes. + */ + snapshotSelection(): Editor; } export {}; diff --git a/types/slate/slate-tests.ts b/types/slate/slate-tests.ts index 7eb81633bf..8466784bf8 100644 --- a/types/slate/slate-tests.ts +++ b/types/slate/slate-tests.ts @@ -1,28 +1,7 @@ -import { Value, Data, BlockJSON, Document, Editor, Change, KeyUtils } from "slate"; +import { Value, Data, BlockJSON, Document, Editor, KeyUtils, Range, Point, Inline, Mark } from "slate"; const data = Data.create({ foo: "bar " }); const value = Value.create({ data }); -const change = value - .change() - .focus() - .moveAnchorToStartOfDocument() - .moveFocusToEndOfDocument() - .delete() - .insertText("A bit of rich text, followed by...") - .moveToStartOfText() - .move(10) - .moveFocusForward(4) - .addMark("bold") - .moveToEndOfNextBlock() - .insertBlock({ - type: "image", - data: { - src: "http://placekitten.com/200/300", - alt: "Kittens", - className: "img-responsive" - } - }) - .insertBlock("paragraph"); const node: BlockJSON = { object: "block", @@ -30,6 +9,7 @@ const node: BlockJSON = { nodes: [ { object: "text", + key: "a", leaves: [ { text: "example", @@ -47,9 +27,10 @@ const doc = Document.fromJSON({ }); const editor = new Editor({ value }); -editor.change((change: Change) => { - return change.insertText("test"); -}); +const point = Point.create({ key: "a", offset: 0 }); +const range = Range.create({ anchor: point, focus: point }); +const inline = Inline.create("text"); +const mark = Mark.create("bold"); editor.registerQuery("testQuery"); editor.registerCommand("testCommand"); @@ -57,7 +38,246 @@ editor.setReadOnly(true).setValue(value); editor.command("testCommand"); editor.query("testQuery"); editor.run("testCommand"); -editor.event("mouseDown", new Event("mouseDown")); + +// Test all editor commands +editor +.addMark("bold") +.addMarkAtRange(range, "italic") +.addMarkByKey("a", 0, 1, "bold") +.addMarkByPath("a", 0, 1, "bold") +.blur() +.delete() +.deleteAtRange(range) +.deleteBackward(0) +.deleteBackwardAtRange(range, 0) +.deleteCharBackwardAtRange(range) +.deleteCharForwardAtRange(range) +.deleteForward(0) +.deleteForwardAtRange(range, 0) +.deleteLineBackwardAtRange(range) +.deleteLineForwardAtRange(range) +.deleteWordBackwardAtRange(range) +.deleteWordForwardAtRange(range) +.deselect() +.flip() +.flush() +.focus() +.insertBlock({ + type: "image", + key: "b", + data: { + src: "http://placekitten.com/200/300", + alt: "Kittens", + className: "img-responsive" + } +}) +.insertBlockAtRange(range, "text") +.insertFragment(doc) +.insertFragmentAtRange(range, doc) +.insertFragmentByKey("a", 0, doc) +.insertFragmentByPath("a", 0, doc) +.insertInline(inline) +.insertInlineAtRange(range, inline) +.insertNodeByKey("a", 0, inline) +.insertNodeByPath("a", 0, inline) +.insertText("A bit of rich text, followed by...") +.insertTextAtRange(range, "More text") +.insertTextByKey("a", 0, "text") +.insertTextByPath("a", 0, "text") +.mergeNodeByKey("b") +.mergeNodeByPath("b") +.moveAnchorBackward() +.moveAnchorEndOfNode(inline) +.moveAnchorForward() +.moveAnchorTo("a", 0) +.moveAnchorToEndOfBlock() +.moveAnchorToEndOfDocument() +.moveAnchorToEndOfInline() +.moveAnchorToEndOfNextBlock() +.moveAnchorToEndOfNextInline() +.moveAnchorToEndOfNextText() +.moveAnchorToEndOfPreviousBlock() +.moveAnchorToEndOfPreviousInline() +.moveAnchorToEndOfPreviousText() +.moveAnchorToEndOfText() +.moveAnchorToStartOfBlock() +.moveAnchorToStartOfDocument() +.moveAnchorToStartOfInline() +.moveAnchorToStartOfNextBlock() +.moveAnchorToStartOfNextInline() +.moveAnchorToStartOfNextText() +.moveAnchorToStartOfNode(inline) +.moveAnchorToStartOfPreviousBlock() +.moveAnchorToStartOfPreviousInline() +.moveAnchorToStartOfPreviousText() +.moveAnchorToStartOfText() +.moveBackward() +.moveEndBackward() +.moveEndForward() +.moveEndTo("a", 0) +.moveEndToEndOfBlock() +.moveEndToEndOfDocument() +.moveEndToEndOfInline() +.moveEndToEndOfNextBlock() +.moveEndToEndOfNextInline() +.moveEndToEndOfNextText() +.moveEndToEndOfNode(inline) +.moveEndToEndOfPreviousBlock() +.moveEndToEndOfPreviousInline() +.moveEndToEndOfPreviousText() +.moveEndToEndOfText() +.moveEndToStartOfBlock() +.moveEndToStartOfDocument() +.moveEndToStartOfInline() +.moveEndToStartOfNextBlock() +.moveEndToStartOfNextInline() +.moveEndToStartOfNextText() +.moveEndToStartOfNode(inline) +.moveEndToStartOfPreviousBlock() +.moveEndToStartOfPreviousInline() +.moveEndToStartOfPreviousText() +.moveEndToStartOfText() +.moveFocusBackward() +.moveFocusForward() +.moveFocusTo("a", 0) +.moveFocusToEndOfBlock() +.moveFocusToEndOfDocument() +.moveFocusToEndOfInline() +.moveFocusToEndOfNextBlock() +.moveFocusToEndOfNextInline() +.moveFocusToEndOfNextText() +.moveFocusToEndOfNode(inline) +.moveFocusToEndOfPreviousBlock() +.moveFocusToEndOfPreviousInline() +.moveFocusToEndOfPreviousText() +.moveFocusToEndOfText() +.moveFocusToStartOfBlock() +.moveFocusToStartOfDocument() +.moveFocusToStartOfInline() +.moveFocusToStartOfNextBlock() +.moveFocusToStartOfNextInline() +.moveFocusToStartOfNextText() +.moveFocusToStartOfNode(inline) +.moveFocusToStartOfPreviousBlock() +.moveFocusToStartOfPreviousInline() +.moveFocusToStartOfPreviousText() +.moveFocusToStartOfText() +.moveForward() +.moveNodeByKey("b", "c", 2) +.moveNodeByPath("c", "b", 1) +.moveStartBackward() +.moveStartForward() +.moveStartTo("a", 0) +.moveStartToEndOfBlock() +.moveStartToEndOfDocument() +.moveStartToEndOfInline() +.moveStartToEndOfNextBlock() +.moveStartToEndOfNextInline() +.moveStartToEndOfNextText() +.moveStartToEndOfNode(inline) +.moveStartToEndOfPreviousBlock() +.moveStartToEndOfPreviousInline() +.moveStartToEndOfPreviousText() +.moveStartToEndOfText() +.moveStartToStartOfBlock() +.moveStartToStartOfDocument() +.moveStartToStartOfInline() +.moveStartToStartOfNextBlock() +.moveStartToStartOfNextInline() +.moveStartToStartOfNextText() +.moveStartToStartOfNode(inline) +.moveStartToStartOfPreviousBlock() +.moveStartToStartOfPreviousInline() +.moveStartToStartOfPreviousText() +.moveStartToStartOfText() +.moveTo("a", 0) +.moveToAnchor() +.moveToEnd() +.moveToEndOfBlock() +.moveToEndOfDocument() +.moveToEndOfInline() +.moveToEndOfNextBlock() +.moveToEndOfNextInline() +.moveToEndOfNextText() +.moveToEndOfNode(inline) +.moveToEndOfPreviousBlock() +.moveToEndOfPreviousInline() +.moveToEndOfPreviousText() +.moveToEndOfText() +.moveToFocus() +.moveToRangeOf(inline) +.moveToRangeOfDocument() +.moveToStart() +.moveToStartOfBlock() +.moveToStartOfDocument() +.moveToStartOfInline() +.moveToStartOfNextBlock() +.moveToStartOfNextInline() +.moveToStartOfNextText() +.moveToStartOfNode(inline) +.moveToStartOfPreviousBlock() +.moveToStartOfPreviousInline() +.moveToStartOfPreviousText() +.moveToStartOfText() +.normalize() +.redo() +.removeMark("bold") +.removeMarkAtRange(range, "bold") +.removeMarkByKey("a", 0, 1, "bold") +.removeMarkByPath("a", 0, 1, "bold") +.removeNodeByKey("b") +.removeNodeByPath("b") +.removeTextByKey("a", 0, 1) +.removeTextByPath("a", 0, 1) +.replaceMark("bold", "italic") +.replaceNodeByKey("a", inline) +.replaceNodeByPath("a", inline) +.select(range) +.setBlocks("paragraph") +.setBlocksAtRange(range, "paragraph") +.setInlines("paragraph") +.setInlinesAtRange(range, "paragraph") +.setMarkByKey("a", 0, 1, mark, { type: "bold" }) +.setMarksByPath("a", 0, 1, mark, { type: "bold" }) +.setNodeByKey("a", "paragraph") +.setNodeByPath("a", "paragraph") +.setReadOnly(true) +.setValue(value) +.snapshotSelection() +.splitBlock(0) +.splitBlockAtRange(range, 0) +.splitInline(0) +.splitInlineAtRange(range, 0) +.splitNodeByKey("a", 0) +.splitNodeByPath("a", 0) +.toggleMark("bold") +.toggleMarkAtRange(range, "bold") +.undo() +.unwrapBlock("paragraph") +.unwrapBlockAtRange(range, "paragraph") +.unwrapBlockByKey("a", "paragraph") +.unwrapBlockByPath("a", "paragraph") +.unwrapInline("paragraph") +.unwrapInlineAtRange(range, "paragraph") +.unwrapInlineByKey("a", "paragraph") +.unwrapInlineByPath("a", "paragraph") +.unwrapNodeByKey("a") +.unwrapNodeByPath("a") +.withoutMerging(() => { /* noop */ }) +.withoutNormalizing(() => { /* noop */ }) +.withoutSaving(() => { /* noop */ }) +.wrapBlock("paragraph") +.wrapBlockAtRange(range, "paragraph") +.wrapBlockByKey("a", "paragraph") +.wrapBlockByPath("a", "paragraph") +.wrapInline("paragraph") +.wrapInlineAtRange(range, "paragraph") +.wrapInlineByKey("a", "paragraph") +.wrapInlineByPath("a", "paragraph") +.wrapNodeByKey("a", inline) +.wrapNodeByPath("a", inline) +.wrapText("a", "b") +.wrapTextAtRange(range, "a"); KeyUtils.setGenerator(() => "Test"); KeyUtils.create(); diff --git a/types/smooth-scroll/index.d.ts b/types/smooth-scroll/index.d.ts new file mode 100644 index 0000000000..87f90cc298 --- /dev/null +++ b/types/smooth-scroll/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for smooth-scroll 14.2 +// Project: https://github.com/cferdinandi/smooth-scroll +// Definitions by: Andrei Horodinca +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export as namespace SmoothScroll; + +export = SmoothScroll; + +declare namespace SmoothScroll { + type Easing = + | "Linear" + | "easeInQuad" + | "easeInCubic" + | "easeInQuart" + | "easeInQuint" + | "easeInOutQuad" + | "easeInOutCubic" + | "easeInOutQuart" + | "easeInOutQuint" + | "easeOutQuad" + | "easeOutCubic" + | "easeOutQuart" + | "easeOutQuint"; + + interface Options { + // Selectors + ignore?: string; + header?: string; + topOnEmptyHash?: boolean; + + // Speed & Easing + speed?: number; + clip?: boolean; + offset?: + | number + | (( + anchor?: Element | number | null, + toggle?: Element | null + ) => number); + easing?: Easing; + customEasing?: (time: number) => number; + + // History + updateURL?: boolean; + popstate?: boolean; + + // Custom Events + emitEvents?: boolean; + } +} + +declare class SmoothScroll { + constructor(selector?: string, options?: SmoothScroll.Options); + + init(options?: SmoothScroll.Options): void; + + destroy(): void; + + animateScroll( + anchor: Element | number | null, + toggle?: Element | null, + options?: SmoothScroll.Options + ): void; + + cancelScroll(noEvent?: boolean): void; +} diff --git a/types/smooth-scroll/test/smooth-scroll-global.test.ts b/types/smooth-scroll/test/smooth-scroll-global.test.ts new file mode 100644 index 0000000000..e230635f9e --- /dev/null +++ b/types/smooth-scroll/test/smooth-scroll-global.test.ts @@ -0,0 +1,34 @@ +// Initialize and destroy SmoothScroll +const example1 = new SmoothScroll('a[href*="#"]', { + ignore: ".ignore", + header: '[data-scroll="header"]', + topOnEmptyHash: false, + speed: 1000, + clip: true, + offset: () => 10, + easing: "easeInCubic", + customEasing: () => 50, + updateURL: false, + popstate: false, + emitEvents: false +}); +example1.destroy(); + +// Scrolling to an anchor +const example2 = () => { + const scroll = new SmoothScroll(); + const anchor = document.querySelector("#bazinga"); + scroll.animateScroll(anchor, null, { speed: 1000 }); +}; + +// Scrolling to a specific Y-position +const example3 = () => { + const scroll = new SmoothScroll('a[href*="#"]'); + scroll.animateScroll(750); +}; + +// Cancel scroll +const example4 = () => { + const scroll = new SmoothScroll(); + scroll.cancelScroll(); +}; diff --git a/types/smooth-scroll/test/smooth-scroll.test.ts b/types/smooth-scroll/test/smooth-scroll.test.ts new file mode 100644 index 0000000000..a64b8bd2d0 --- /dev/null +++ b/types/smooth-scroll/test/smooth-scroll.test.ts @@ -0,0 +1,36 @@ +import SmoothScroll = require("smooth-scroll"); + +// Initialize and destroy SmoothScroll +const example1 = new SmoothScroll('a[href*="#"]', { + ignore: ".ignore", + header: '[data-scroll="header"]', + topOnEmptyHash: false, + speed: 1000, + clip: true, + offset: () => 10, + easing: "easeInCubic", + customEasing: () => 50, + updateURL: false, + popstate: false, + emitEvents: false +}); +example1.destroy(); + +// Scrolling to an anchor +const example2 = () => { + const scroll = new SmoothScroll(); + const anchor = document.querySelector("#bazinga"); + scroll.animateScroll(anchor, null, { speed: 1000 }); +}; + +// Scrolling to a specific Y-position +const example3 = () => { + const scroll = new SmoothScroll('a[href*="#"]'); + scroll.animateScroll(750); +}; + +// Cancel scroll +const example4 = () => { + const scroll = new SmoothScroll(); + scroll.cancelScroll(); +}; diff --git a/types/smooth-scroll/tsconfig.json b/types/smooth-scroll/tsconfig.json new file mode 100644 index 0000000000..8d1fa8372b --- /dev/null +++ b/types/smooth-scroll/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 + }, + "files": [ + "index.d.ts", + "test/smooth-scroll-global.test.ts", + "test/smooth-scroll.test.ts" + ] +} diff --git a/types/smooth-scroll/tslint.json b/types/smooth-scroll/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/smooth-scroll/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 95a9ff1b4f..f5e6c5fd00 100644 --- a/types/socket.io/index.d.ts +++ b/types/socket.io/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for socket.io 1.4.5 +// Type definitions for socket.io 2.1 // Project: http://socket.io/ // Definitions by: PROGRE // Damian Connolly @@ -188,7 +188,7 @@ declare namespace SocketIO { * with a '/' * @return The Namespace */ - of( nsp: string ): Namespace; + of( nsp: string | RegExp | Function ): Namespace; /** * Closes the server connection diff --git a/types/socket.io/socket.io-tests.ts b/types/socket.io/socket.io-tests.ts index 60f0d70551..5a70af45db 100644 --- a/types/socket.io/socket.io-tests.ts +++ b/types/socket.io/socket.io-tests.ts @@ -103,6 +103,15 @@ function testRestrictingYourselfToANamespace() { }); } +function testDynamicNamespace() { + var io = socketIO.listen(80); + var dynamic = io + .of(/^\/dynamic-\d+$/) + .on('connection', function (socket) { + socket.emit('item', { dynamic: 'item' }); + }); +} + function testSendingVolatileMessages() { var io = socketIO.listen(80); @@ -188,4 +197,4 @@ function testSocketUse() { console.log(packet); }); }); -} \ No newline at end of file +} diff --git a/types/socket.io/v1/index.d.ts b/types/socket.io/v1/index.d.ts new file mode 100644 index 0000000000..95a9ff1b4f --- /dev/null +++ b/types/socket.io/v1/index.d.ts @@ -0,0 +1,850 @@ +// Type definitions for socket.io 1.4.5 +// Project: http://socket.io/ +// Definitions by: PROGRE +// Damian Connolly +// Florent Poujol +// KentarouTakeda +// Alexey Snigirev +// Ezinwa Okpoechi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare const SocketIO: SocketIOStatic; +export = SocketIO; +/** @deprecated Available as a global for backwards-compatibility. */ +export as namespace SocketIO; + +interface SocketIOStatic { + /** + * Default Server constructor + */ + (): SocketIO.Server; + + /** + * Creates a new Server + * @param srv The HTTP server that we're going to bind to + * @param opts An optional parameters object + */ + (srv: any, opts?: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Creates a new Server + * @param port A port to bind to, as a number, or a string + * @param An optional parameters object + */ + (port: string|number, opts?: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Creates a new Server + * @param A parameters object + */ + (opts: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Backwards compatibility + * @see io().listen() + */ + listen: SocketIOStatic; +} + +declare namespace SocketIO { + interface Server { + engine: { ws: any }; + + /** + * A dictionary of all the namespaces currently on this Server + */ + nsps: {[namespace: string]: Namespace}; + + /** + * The default '/' Namespace + */ + sockets: Namespace; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Server; + + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the clients are not ready to receive messages + */ + volatile: Server; + + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node + */ + local: Server; + + /** + * Server request verification function, that checks for allowed origins + * @param req The http.IncomingMessage request + * @param fn The callback to be called. It should take one parameter, err, + * which will be null if there was no problem, and one parameter, success, + * of type boolean + */ + checkRequest( req:any, fn:( err: any, success: boolean ) => void ):void; + + /** + * Gets whether we're serving the client.js file or not + * @default true + */ + serveClient(): boolean; + + /** + * Sets whether we're serving the client.js file or not + * @param v True if we want to serve the file, false otherwise + * @default true + * @return This Server + */ + serveClient( v: boolean ): Server; + + /** + * Gets the client serving path + * @default '/socket.io' + */ + path(): string; + + /** + * Sets the client serving path + * @param v The path to serve the client file on + * @default '/socket.io' + * @return This Server + */ + path( v: string ): Server; + + /** + * Gets the adapter that we're going to use for handling rooms + * @default typeof Adapter + */ + adapter(): any; + + /** + * Sets the adapter (class) that we're going to use for handling rooms + * @param v The class for the adapter to create + * @default typeof Adapter + * @return This Server + */ + adapter( v: any ): Server; + + /** + * Gets the allowed origins for requests + * @default "*:*" + */ + origins(): string|string[]; + + /** + * Sets the allowed origins for requests + * @param v The allowed origins, in host:port form + * @default "*:*" + * return This Server + */ + origins( v: string|string[] ): Server; + + /** + * Attaches socket.io to a server + * @param srv The http.Server that we want to attach to + * @param opts An optional parameters object + * @return This Server + */ + attach( srv: any, opts?: ServerOptions ): Server; + + /** + * Attaches socket.io to a port + * @param port The port that we want to attach to + * @param opts An optional parameters object + * @return This Server + */ + attach( port: number, opts?: ServerOptions ): Server; + + /** + * @see attach( srv, opts ) + */ + listen( srv: any, opts?: ServerOptions ): Server; + + /** + * @see attach( port, opts ) + */ + listen( port: number, opts?: ServerOptions ): Server; + + /** + * Binds socket.io to an engine.io intsance + * @param src The Engine.io (or compatible) server to bind to + * @return This Server + */ + bind( srv: any ): Server; + + /** + * Called with each incoming connection + * @param socket The Engine.io Socket + * @return This Server + */ + onconnection( socket: any ): Server; + + /** + * Looks up/creates a Namespace + * @param nsp The name of the NameSpace to look up/create. Should start + * with a '/' + * @return The Namespace + */ + of( nsp: string ): Namespace; + + /** + * Closes the server connection + */ + close( fn ?: () => void ):void; + + /** + * The event fired when we get a new connection + * @param event The event being fired: 'connection' + * @param listener A listener that should take one parameter of type Socket + * @return The default '/' Namespace + */ + on( event: 'connection', listener: ( socket: Socket ) => void ): Namespace; + + /** + * @see on( 'connection', listener ) + */ + on( event: 'connect', listener: ( socket: Socket ) => void ): Namespace; + + /** + * Base 'on' method to add a listener for an event + * @param event The event that we want to add a listener for + * @param listener The callback to call when we get the event. The parameters + * for the callback depend on the event + * @return The default '/' Namespace + */ + on( event: string, listener: Function ): Namespace; + + /** + * Targets a room when emitting to the default '/' Namespace + * @param room The name of the room that we're targeting + * @return The default '/' Namespace + */ + to( room: string ): Namespace; + + /** + * @see to( room ) + */ + in( room: string ): Namespace; + + /** + * Registers a middleware function, which is a function that gets executed + * for every incoming Socket, on the default '/' Namespace + * @param fn The function to call when we get a new incoming socket. It should + * take one parameter of type Socket, and one callback function to call to + * execute the next middleware function. The callback can take one optional + * parameter, err, if there was an error. Errors passed to middleware callbacks + * are sent as special 'error' packets to clients + * @return The default '/' Namespace + */ + use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace; + + /** + * Emits an event to the default Namespace + * @param event The event that we want to emit + * @param args Any number of optional arguments to pass with the event. If the + * last argument is a function, it will be called as an ack. The ack should + * take whatever data was sent with the packet + * @return The default '/' Namespace + */ + emit( event: string, ...args: any[]): Namespace; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + * @return The default '/' Namespace + */ + send( ...args: any[] ): Namespace; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Namespace; + + /** + * Gets a list of clients + * @return The default '/' Namespace + */ + clients( ...args: any[] ): Namespace; + + /** + * Sets the compress flag + * @return The default '/' Namespace + */ + compress( ...args: any[] ): Namespace; + } + + /** + * Options to pass to our server when creating it + */ + interface ServerOptions { + + /** + * The path to server the client file to + * @default '/socket.io' + */ + path?: string; + + /** + * Should we serve the client file? + * @default true + */ + serveClient?: boolean; + + /** + * The adapter to use for handling rooms. NOTE: this should be a class, + * not an object + * @default typeof Adapter + */ + adapter?: Adapter; + + /** + * Accepted origins + * @default '*:*' + */ + origins?: string|string[]; + + /** + * How many milliseconds without a pong packed to consider the connection closed (engine.io) + * @default 60000 + */ + pingTimeout?: number; + + /** + * How many milliseconds before sending a new ping packet (keep-alive) (engine.io) + * @default 25000 + */ + pingInterval?: number; + + /** + * How many bytes or characters a message can be when polling, before closing the session + * (to avoid Dos) (engine.io) + * @default 10E7 + */ + maxHttpBufferSize?: number; + + /** + * A function that receives a given handshake or upgrade request as its first parameter, + * and can decide whether to continue or not. The second argument is a function that needs + * to be called with the decided information: fn( err, success ), where success is a boolean + * value where false means that the request is rejected, and err is an error code (engine.io) + * @default null + */ + allowRequest?: (request:any, callback: (err: number, success: boolean) => void) => void; + + /** + * Transports to allow connections to (engine.io) + * @default ['polling','websocket'] + */ + transports?: string[]; + + /** + * Whether to allow transport upgrades (engine.io) + * @default true + */ + allowUpgrades?: boolean; + + /** + * parameters of the WebSocket permessage-deflate extension (see ws module). + * Set to false to disable (engine.io) + * @default true + */ + perMessageDeflate?: Object|boolean; + + /** + * Parameters of the http compression for the polling transports (see zlib). + * Set to false to disable, or set an object with parameter "threshold:number" + * to only compress data if the byte size is above this value (1024) (engine.io) + * @default true|1024 + */ + httpCompression?: Object|boolean; + + /** + * Name of the HTTP cookie that contains the client sid to send as part of + * handshake response headers. Set to false to not send one (engine.io) + * @default "io" + */ + cookie?: string|boolean; + } + + /** + * The Namespace, sandboxed environments for sockets, each connection + * to a Namespace requires a new Socket + */ + interface Namespace extends NodeJS.EventEmitter { + + /** + * The name of the NameSpace + */ + name: string; + + /** + * The controller Server for this Namespace + */ + server: Server; + + /** + * A dictionary of all the Sockets connected to this Namespace, where + * the Socket ID is the key + */ + sockets: { [id: string]: Socket }; + + /** + * A dictionary of all the Sockets connected to this Namespace, where + * the Socket ID is the key + */ + connected: { [id: string]: Socket }; + + /** + * The Adapter that we're using to handle dealing with rooms etc + */ + adapter: Adapter; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Namespace; + + /** + * Registers a middleware function, which is a function that gets executed + * for every incoming Socket + * @param fn The function to call when we get a new incoming socket. It should + * take one parameter of type Socket, and one callback function to call to + * execute the next middleware function. The callback can take one optional + * parameter, err, if there was an error. Errors passed to middleware callbacks + * are sent as special 'error' packets to clients + * @return This Namespace + */ + use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace; + + /** + * Targets a room when emitting + * @param room The name of the room that we're targeting + * @return This Namespace + */ + to( room: string ): Namespace; + + /** + * @see to( room ) + */ + in( room: string ): Namespace; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + * @return This Namespace + */ + send( ...args: any[] ): Namespace; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Namespace; + + /** + * The event fired when we get a new connection + * @param event The event being fired: 'connection' + * @param listener A listener that should take one parameter of type Socket + * @return This Namespace + */ + on( event: 'connection', listener: ( socket: Socket ) => void ): this; + + /** + * @see on( 'connection', listener ) + */ + on( event: 'connect', listener: ( socket: Socket ) => void ): this; + + /** + * Base 'on' method to add a listener for an event + * @param event The event that we want to add a listener for + * @param listener The callback to call when we get the event. The parameters + * for the callback depend on the event + * @ This Namespace + */ + on( event: string, listener: Function ): this; + + /** + * Gets a list of clients. + * @return This Namespace + */ + clients( fn: Function ): Namespace; + + /** + * Sets the compress flag. + * @param compress If `true`, compresses the sending data + * @return This Namespace + */ + compress( compress: boolean ): Namespace; + } + + interface Packet extends Array { + /** + * Event name + */ + [0]: string; + /** + * Packet data + */ + [1]: any; + /** + * Ack function + */ + [2]: (...args: any[]) => void; + } + + /** + * The socket, which handles our connection for a namespace. NOTE: while + * we technically extend NodeJS.EventEmitter, we're not putting it here + * as we have a problem with the emit() event (as it's overridden with a + * different return) + */ + interface Socket extends NodeJS.EventEmitter{ + + /** + * The namespace that this socket is for + */ + nsp: Namespace; + + /** + * The Server that our namespace is in + */ + server: Server; + + /** + * The Adapter that we use to handle our rooms + */ + adapter: Adapter; + + /** + * The unique ID for this Socket. Regenerated at every connection. This is + * also the name of the room that the Socket automatically joins on connection + */ + id: string; + + /** + * The http.IncomingMessage request sent with the connection. Useful + * for recovering headers etc + */ + request: any; + + /** + * The Client associated with this Socket + */ + client: Client; + + /** + * The underlying Engine.io Socket instance + */ + conn: EngineSocket; + + /** + * The list of rooms that this Socket is currently in, where + * the ID the the room ID + */ + rooms: { [id: string]: string }; + + /** + * Is the Socket currently connected? + */ + connected: boolean; + + /** + * Is the Socket currently disconnected? + */ + disconnected: boolean; + + /** + * The object used when negociating the handshake + */ + handshake: Handshake; + /** + * Sets the 'json' flag when emitting an event + */ + json: Socket; + + /** + * Sets the 'volatile' flag when emitting an event. Volatile messages are + * messages that can be dropped because of network issues and the like. Use + * for high-volume/real-time messages where you don't need to receive *all* + * of them + */ + volatile: Socket; + + /** + * Sets the 'broadcast' flag when emitting an event. Broadcasting an event + * will send it to all the other sockets in the namespace except for yourself + */ + broadcast: Socket; + + /** + * Targets a room when broadcasting + * @param room The name of the room that we're targeting + * @return This Socket + */ + to( room: string ): Socket; + + /** + * @see to( room ) + */ + in( room: string ): Socket; + + /** + * Registers a middleware, which is a function that gets executed for every incoming Packet and receives as parameter the packet and a function to optionally defer execution to the next registered middleware. + * + * Errors passed to middleware callbacks are sent as special error packets to clients. + */ + use( fn: ( packet: Packet, next: (err?: any) => void ) => void ): Socket; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + */ + send( ...args: any[] ): Socket; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Socket; + + /** + * Joins a room. You can join multiple rooms, and by default, on connection, + * you join a room with the same name as your ID + * @param name The name of the room that we want to join + * @param fn An optional callback to call when we've joined the room. It should + * take an optional parameter, err, of a possible error + * @return This Socket + */ + join( name: string|string[], fn?: ( err?: any ) => void ): Socket; + + /** + * Leaves a room + * @param name The name of the room to leave + * @param fn An optional callback to call when we've left the room. It should + * take on optional parameter, err, of a possible error + */ + leave( name: string, fn?: Function ): Socket; + + /** + * Leaves all the rooms that we've joined + */ + leaveAll(): void; + + /** + * Disconnects this Socket + * @param close If true, also closes the underlying connection + * @return This Socket + */ + disconnect( close?: boolean ): Socket; + + /** + * Returns all the callbacks for a particular event + * @param event The event that we're looking for the callbacks of + * @return An array of callback Functions, or an empty array if we don't have any + */ + listeners( event: string ):Function[]; + + /** + * Sets the compress flag + * @param compress If `true`, compresses the sending data + * @return This Socket + */ + compress( compress: boolean ): Socket; + } + + interface Handshake { + /** + * The headers passed along with the request. e.g. 'host', + * 'connection', 'accept', 'referer', 'cookie' + */ + headers: any; + + /** + * The current time, as a string + */ + time: string; + + /** + * The remote address of the connection request + */ + address: string; + + /** + * Is this a cross-domain request? + */ + xdomain: boolean; + + /** + * Is this a secure request? + */ + secure: boolean; + + /** + * The timestamp for when this was issued + */ + issued: number; + + /** + * The request url + */ + url: string; + + /** + * Any query string parameters in the request url + */ + query: any; + } + + /** + * The interface describing a room + */ + interface Room { + sockets: {[id: string]: boolean }; + length: number; + } + + /** + * The interface describing a dictionary of rooms + * Where room is the name of the room + */ + + interface Rooms { + [room: string]: Room; + } + + /** + * The interface used when dealing with rooms etc + */ + interface Adapter extends NodeJS.EventEmitter { + + /** + * The namespace that this adapter is for + */ + nsp: Namespace; + + /** + * A dictionary of all the rooms that we have in this namespace + */ + rooms: Rooms; + + /** + * A dictionary of all the socket ids that we're dealing with, and all + * the rooms that the socket is currently in + */ + sids: {[id: string]: {[room: string]: boolean}}; + + /** + * Adds a socket to a room. If the room doesn't exist, it's created + * @param id The ID of the socket to add + * @param room The name of the room to add the socket to + * @param callback An optional callback to call when the socket has been + * added. It should take an optional parameter, error, if there was a problem + */ + add( id: string, room: string, callback?: ( err?: any ) => void ): void; + + /** + * Removes a socket from a room. If there are no more sockets in the room, + * the room is deleted + * @param id The ID of the socket that we're removing + * @param room The name of the room to remove the socket from + * @param callback An optional callback to call when the socket has been + * removed. It should take on optional parameter, error, if there was a problem + */ + del( id: string, room: string, callback?: ( err?: any ) => void ): void; + + /** + * Removes a socket from all the rooms that it's joined + * @param id The ID of the socket that we're removing + */ + delAll( id: string ):void; + + /** + * Broadcasts a packet + * @param packet The packet to broadcast + * @param opts Any options to send along: + * - rooms: An optional list of rooms to broadcast to. If empty, the packet is broadcast to all sockets + * - except: A list of Socket IDs to exclude + * - flags: Any flags that we want to send along ('json', 'volatile', 'broadcast') + */ + broadcast( packet: any, opts: { rooms?: string[]; except?: string[]; flags?: {[flag: string]: boolean} } ):void; + } + + /** + * The client behind each socket (can have multiple sockets) + */ + interface Client { + /** + * The Server that this client belongs to + */ + server: Server; + + /** + * The underlying Engine.io Socket instance + */ + conn: EngineSocket; + + /** + * The ID for this client. Regenerated at every connection + */ + id: string; + + /** + * The http.IncomingMessage request sent with the connection. Useful + * for recovering headers etc + */ + request: any; + + /** + * The dictionary of sockets currently connect via this client (i.e. to different + * namespaces) where the Socket ID is the key + */ + sockets: {[id: string]: Socket}; + + /** + * A dictionary of all the namespaces for this client, with the Socket that + * deals with that namespace + */ + nsps: {[nsp: string]: Socket}; + } + + /** + * A reference to the underlying engine.io Socket connection. + */ + interface EngineSocket extends NodeJS.EventEmitter { + /** + * The ID for this socket - matches Client.id + */ + id: string; + + /** + * The Engine.io Server for this socket + */ + server: any; + + /** + * The ready state for the client. Either 'opening', 'open', 'closing', or 'closed' + */ + readyState: string; + + /** + * The remote IP for this connection + */ + remoteAddress: string; + + /** + * whether the transport has been upgraded + */ + upgraded: boolean; + + /** + * (http.IncomingMessage): request that originated the Socket + */ + request: any; + + /** + * (Transport): transport reference + */ + transport: any; + } +} diff --git a/types/socket.io/v1/socket.io-tests.ts b/types/socket.io/v1/socket.io-tests.ts new file mode 100644 index 0000000000..60f0d70551 --- /dev/null +++ b/types/socket.io/v1/socket.io-tests.ts @@ -0,0 +1,191 @@ +import socketIO = require('socket.io'); + +function testUsingWithNodeHTTPServer() { + var app = require('http').createServer(handler); + var io: socketIO.Server = socketIO(app); + var fs = require('fs'); + + app.listen(80); + + function handler(req: any, res: any) { + fs.readFile(__dirname + '/index.html', + function (err: any, data: any) { + if (err) { + res.writeHead(500); + return res.end('Error loading index.html'); + } + + res.writeHead(200); + res.end(data); + }); + } + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingWithExpress() { + var app = require('express')(); + var server = require('http').Server(app); + var io = socketIO(server); + + server.listen(80); + + app.get('/', function (req: any, res: any) { + res.sendfile(__dirname + '/index.html'); + }); + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingWithTheExpressFramework() { + var app = require('express').createServer(); + var io = socketIO(app); + + app.listen(80); + + app.get('/', function (req: any, res: any) { + res.sendfile(__dirname + '/index.html'); + }); + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testSendingAndReceivingEvents() { + var io = socketIO(80); + + io.on('connection', function (socket) { + io.emit('this', { will: 'be received by everyone' }); + + socket.on('private message', function (from: any, msg: any) { + console.log('I received a private message by ', from, ' saying ', msg); + }); + + socket.on('disconnect', function () { + io.sockets.emit('user disconnected'); + }); + }); +} + +function testRestrictingYourselfToANamespace() { + var io = socketIO.listen(80); + var chat = io + .of('/chat') + .on('connection', function (socket) { + socket.emit('a message', { + that: 'only' + , '/chat': 'will get' + }); + chat.emit('a message', { + everyone: 'in' + , '/chat': 'will get' + }); + }); + + var news = io + .of('/news') + .on('connection', function (socket) { + socket.emit('item', { news: 'item' }); + }); +} + +function testSendingVolatileMessages() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + var tweets = setInterval(function () { + socket.volatile.emit('bieber tweet', {}); + }, 100); + + socket.on('disconnect', function () { + clearInterval(tweets); + }); + }); +} + +function testSendingAndGettingData() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.on('ferret', function (name: any, fn: any) { + fn('woot'); + }); + }); +} + +function testBroadcastingMessages() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.broadcast.emit('user connected'); + }); +} + +function testUsingItJustAsACrossBrowserWebSocket() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.on('message', function () { }); + socket.on('disconnect', function () { }); + }); +} + +function testSocketConnection() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + console.log(socket.client.conn === socket.conn); + console.log(socket.client.request.httpVersion); + console.log(socket.conn.id); + console.log(socket.conn.upgraded); + console.log(socket.conn.readyState); + + socket.on('packet', function(message :string, ping :string){ + console.log(message, ping); + });; + }); +} + +function testClosingServerWithCallback() { + var io = socketIO.listen(80); + io.close(function() { + }); +} + +function testClosingServerWithoutCallback() { + var io = socketIO.listen(80); + io.close(); +} + +function testLocalServerMessages() { + var io = socketIO.listen(80); + io.local.emit('local', 'Local data'); +} + +function testVolatileServerMessages() { + var io = socketIO.listen(80); + io.volatile.emit('volatile', 'Lost data'); +} + +function testSocketUse() { + var io = socketIO.listen(80); + io.on('connection', (socket) => { + socket.use((packet, next) => { + console.log(packet); + }); + }); +} \ No newline at end of file diff --git a/types/socket.io/v1/tsconfig.json b/types/socket.io/v1/tsconfig.json new file mode 100644 index 0000000000..8f7bad0ba7 --- /dev/null +++ b/types/socket.io/v1/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "socket.io": [ "socket.io/v1" ] + } + }, + "files": [ + "index.d.ts", + "socket.io-tests.ts" + ] +} diff --git a/types/socket.io/v1/tslint.json b/types/socket.io/v1/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/socket.io/v1/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/sonic-boom/index.d.ts b/types/sonic-boom/index.d.ts index 292770bd0d..0ae54bc997 100644 --- a/types/sonic-boom/index.d.ts +++ b/types/sonic-boom/index.d.ts @@ -31,7 +31,7 @@ declare class SonicBoom extends EventEmitter { /** * Reopen the file in place, useful for log rotation. */ - reopen(file: string): void; + reopen(fileDescriptor?: string | number): void; /** * Flushes the buffered data synchronously. This is a costly operation. diff --git a/types/sonic-boom/sonic-boom-tests.ts b/types/sonic-boom/sonic-boom-tests.ts index a3beb06d0c..4ed8e1bee5 100644 --- a/types/sonic-boom/sonic-boom-tests.ts +++ b/types/sonic-boom/sonic-boom-tests.ts @@ -7,6 +7,8 @@ sonic.flush(); sonic.flushSync(); +sonic.reopen(); + sonic.end(); sonic.destroy(); diff --git a/types/sql-template/index.d.ts b/types/sql-template/index.d.ts new file mode 100644 index 0000000000..c05ae75516 --- /dev/null +++ b/types/sql-template/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for sql-template 1.2 +// Project: https://github.com/131/sql-template +// Definitions by: Jaap Taal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = SQL; +declare function SQL(parts: TemplateStringsArray, ...values: any[]): SQL.Fragment; + +declare namespace SQL { + interface Fragment { + raw: string; + text: string; + values?: any[]; + } + + type ChainFn = (values: any[], part: string) => string; + + type Transformer = (values: any[], str: string, chain: ChainFn) => void; + + function insert(table: string, values: object): Fragment; + function insert_bulk(table: string, keys: string[], values: any[][]): Fragment; + function update(table: string, values: object, where?: any): Fragment; + function select(table: string, where?: any, cols?: string, extra?: string): Fragment; + function search_blob(search_field: string, qs: string, main_field?: string, LIKE?: string): Fragment | false; + + const transformers: {[key: string]: Transformer}; +} diff --git a/types/sql-template/sql-template-tests.ts b/types/sql-template/sql-template-tests.ts new file mode 100644 index 0000000000..4b44f1d3a7 --- /dev/null +++ b/types/sql-template/sql-template-tests.ts @@ -0,0 +1,21 @@ +import SQL = require("sql-template"); + +const query = SQL`INSERT INTO table (column) VALUES (${"value"})`; +SQL.transformers["in"]([], "", () => ""); + +SQL.insert("table", {column: "value"}); +SQL.insert_bulk("table", ["column"], [["value"]]); + +SQL.update("table", {column: "value"}); +SQL.update("table", {column: "value"}, true); +SQL.update("table", {column: "value2"}, {column: "value1"}); +SQL.update("table", {column: "value2"}, SQL`column = ${"value1"}`); + +SQL.select("table"); +SQL.select("table", {column: "value"}); +SQL.select("table", {column: "value"}, "a, b"); +SQL.select("table", {column: "value"}, "a, b", "GROUP BY x"); + +SQL.search_blob("column", "value"); +SQL.search_blob("column", "value #1", "user_id"); +SQL.search_blob("column", "value #1", "user_id", "LIKE"); diff --git a/types/sql-template/tsconfig.json b/types/sql-template/tsconfig.json new file mode 100644 index 0000000000..27ac3eba34 --- /dev/null +++ b/types/sql-template/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", + "sql-template-tests.ts" + ] +} diff --git a/types/sql-template/tslint.json b/types/sql-template/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sql-template/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/storybook__react/index.d.ts b/types/storybook__react/index.d.ts index 3aa3445f61..41ce7b45bb 100644 --- a/types/storybook__react/index.d.ts +++ b/types/storybook__react/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for @storybook/react 3.0 +// Type definitions for @storybook/react 4.0 // Project: https://github.com/storybooks/storybook // Definitions by: Joscha Feth // Anton Izmailov +// Dan Dean // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -12,15 +13,21 @@ import * as React from 'react'; export type Renderable = React.ComponentType | JSX.Element; export type RenderFunction = () => Renderable | Renderable[]; +export interface DecoratorParameters { + [key: string]: any; +} export type StoryDecorator = (story: RenderFunction, context: { kind: string, story: string }) => Renderable | null; export interface Story { readonly kind: string; - add(storyName: string, callback: RenderFunction): this; + add(storyName: string, callback: RenderFunction, parameters?: DecoratorParameters): this; addDecorator(decorator: StoryDecorator): this; + addParameters(parameters: DecoratorParameters): this; } export function addDecorator(decorator: StoryDecorator): void; +export function addParameters(parameters: DecoratorParameters): void; +export function clearDecorators(): void; export function configure(fn: () => void, module: NodeModule): void; export function setAddon(addon: object): void; export function storiesOf(name: string, module: NodeModule): Story; diff --git a/types/storybook__react/storybook__react-tests.tsx b/types/storybook__react/storybook__react-tests.tsx index 12edecb219..bf7094c580 100644 --- a/types/storybook__react/storybook__react-tests.tsx +++ b/types/storybook__react/storybook__react-tests.tsx @@ -1,7 +1,8 @@ import * as React from 'react'; -import { storiesOf, setAddon, addDecorator, configure, getStorybook, RenderFunction, Story, forceReRender } from '@storybook/react'; +import { storiesOf, setAddon, addDecorator, addParameters, configure, getStorybook, RenderFunction, Story, forceReRender, DecoratorParameters, clearDecorators } from '@storybook/react'; const Decorator = (story: RenderFunction) =>
    {story()}
    ; +const parameters: DecoratorParameters = { parameter: 'foo' }; forceReRender(); @@ -9,10 +10,13 @@ storiesOf('Welcome', module) // local addDecorator .addDecorator(Decorator) .add('to Storybook', () =>
    ) - .add('to Storybook as Array', () => [
    ,
    ]); + .add('to Storybook as Array', () => [
    ,
    ]) + .add('and a story with additional parameters', () =>
    , parameters); // global addDecorator addDecorator(Decorator); +addParameters(parameters); +clearDecorators(); // setAddon interface AnyAddon { @@ -30,6 +34,7 @@ storiesOf('withAnyAddon', module) .addWithSideEffect('more', () =>
    ) .add('another story', () =>
    ) .add('to Storybook as Array', () => [
    ,
    ]) + .add('and a story with additional parameters', () =>
    , parameters) .addWithSideEffect('even more', () =>
    ); // configure diff --git a/types/stripe-checkout/index.d.ts b/types/stripe-checkout/index.d.ts index c84fdeeb1d..d0e283504c 100644 --- a/types/stripe-checkout/index.d.ts +++ b/types/stripe-checkout/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Chris Wrench // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface StripeCheckoutStatic { configure(options: StripeCheckoutOptions): StripeCheckoutHandler; @@ -16,7 +16,8 @@ interface StripeCheckoutHandler { interface StripeCheckoutOptions { key?: string; - token?(token: stripe.StripeCardTokenResponse): void; + token?(token: stripe.Token): void; + source?(source: stripe.Source): void; image?: string; name?: string; description?: string; diff --git a/types/stripe-checkout/stripe-checkout-tests.ts b/types/stripe-checkout/stripe-checkout-tests.ts index 6cd221debf..e310c2e7d0 100644 --- a/types/stripe-checkout/stripe-checkout-tests.ts +++ b/types/stripe-checkout/stripe-checkout-tests.ts @@ -1,9 +1,9 @@ // Test the minimum amount of configuration required. let handler = StripeCheckout.configure({ - key: "my-secret-key", - token: (token: stripe.StripeTokenResponse) => { - console.log(token.id); - } + key: "my-secret-key", + token: (token: stripe.Token) => { + console.log(token.id); + } }); handler.open(); @@ -12,10 +12,13 @@ handler.close(); // Test all configuration options. const options: StripeCheckoutOptions = { - key: "my-secret-key", - token: (token: stripe.StripeTokenResponse) => { - console.log(token.id); - }, + key: "my-secret-key", + token: (token: stripe.Token) => { + console.log(token.id); + }, + source: (src: stripe.Source) => { + console.log(src.id); + }, image: "http://placehold.it/128x128", name: "Definitely Typed", description: "A DefinitelyTyped test for Stripe Checkout", diff --git a/types/styled-system/dist/styles.d.ts b/types/styled-system/dist/styles.d.ts index 5851c51f79..224b9a9392 100644 --- a/types/styled-system/dist/styles.d.ts +++ b/types/styled-system/dist/styles.d.ts @@ -299,7 +299,7 @@ export interface JustifyContentProps { export function justifyContent(...args: any[]): any; -export type FlexWrapValue = true | "nowrap" | "wrap" | "wrap-reverse"; +export type FlexWrapValue = "nowrap" | "wrap" | "wrap-reverse"; export type ResponsiveFlexWrapValue = ResponsiveValue; export interface FlexWrapProps { diff --git a/types/styled-theming/index.d.ts b/types/styled-theming/index.d.ts new file mode 100644 index 0000000000..fab32a7617 --- /dev/null +++ b/types/styled-theming/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for styled-theming 2.2 +// Project: https://github.com/styled-components/styled-theming#readme +// Definitions by: Arjan Jassal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +declare function theme(name: string, values: theme.ThemeMap): theme.ThemeSet; + +declare namespace theme { + type ThemeValueFn = (props: object) => string; + type ThemeValue = string | ThemeValueFn; + + interface ThemeMap { + [key: string]: ThemeValue; + } + + interface VariantMap { + [key: string]: ThemeMap; + } + + type ThemeSet = (props: object) => string; + type VariantSet = (props: object) => string; + + function variants( + name: string, + prop: string, + values: VariantMap + ): VariantSet; +} + +export = theme; diff --git a/types/styled-theming/styled-theming-tests.ts b/types/styled-theming/styled-theming-tests.ts new file mode 100644 index 0000000000..2d9e947009 --- /dev/null +++ b/types/styled-theming/styled-theming-tests.ts @@ -0,0 +1,13 @@ +import theme from "styled-theming"; + +const textColor = theme("mode", { + dark: "white", + light: "black" +}); + +const backgroundColor = theme.variants("mode", "variant", { + default: { light: "gray", dark: "darkgray" }, + primary: { light: "blue", dark: "darkblue" }, + success: { light: "green", dark: "darkgreen" }, + warning: { light: "orange", dark: "darkorange" } +}); diff --git a/types/styled-theming/tsconfig.json b/types/styled-theming/tsconfig.json new file mode 100644 index 0000000000..57714000f6 --- /dev/null +++ b/types/styled-theming/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "esModuleInterop": true, + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "styled-theming-tests.ts"] +} diff --git a/types/styled-theming/tslint.json b/types/styled-theming/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/styled-theming/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/terser/index.d.ts b/types/terser/index.d.ts new file mode 100644 index 0000000000..44a3e1cdb7 --- /dev/null +++ b/types/terser/index.d.ts @@ -0,0 +1,648 @@ +// Type definitions for terser 3.8 +// Project: https://github.com/terser-js/terser +// Definitions by: JordiAnderl +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import * as MOZ_SourceMap from "source-map"; + +export interface Tokenizer { + /** + * The type of this token. + * "comment1" and "comment2" are for single-line, respectively multi-line comments. + */ + type: "num" | "string" | "regexp" | "operator" | "punc" | "atom" | "name" | "keyword" | "comment1" | "comment2"; + + /** + * The name of the file where this token originated from. Useful when compressing multiple files at once to generate the proper source map. + */ + file: string; + + /** + * The "value" of the token. + * That's additional information and depends on the token type: "num", "string" and "regexp" tokens you get their literal value. + * - For "operator" you get the operator. + * - For "punc" it's the punctuation sign (parens, comma, semicolon etc). + * - For "atom", "name" and "keyword" it's the name of the identifier + * - For comments it's the body of the comment (excluding the initial "//" and "/*". + */ + value: string; + + /** + * The line number of this token in the original code. + * 1-based index. + */ + line: number; + + /** + * The column number of this token in the original code. + * 0-based index. + */ + col: number; + + /** + * Short for "newline before", it's a boolean that tells us whether there was a newline before this node in the original source. It helps for automatic semicolon insertion. + * For multi-line comments in particular this will be set to true if there either was a newline before this comment, or * * if this comment contains a newline. + */ + nlb: boolean; + + /** + * This doesn't apply for comment tokens, but for all other token types it will be an array of comment tokens that were found before. + */ + comments_before: string[]; +} + +export class AST_Node { + // The first token of this node + start: AST_Node; + + // The last token of this node + end: AST_Node; + + value?: string | number; + file?: string; + property?: string; + key?: string; + + transform(tt: TreeTransformer): AST_Toplevel; + + walk(walker: TreeWalker): void; +} + +export class AST_Toplevel extends AST_Node { + // Terser contains a scope analyzer which figures out variable/function definitions, references etc. + // You need to call it manually before compression or mangling. + // The figure_out_scope method is defined only on the AST_Toplevel node. + figure_out_scope(): void; + + // Get names that are optimized for GZip compression (names will be generated using the most frequent characters first) + compute_char_frequency(): void; + + mangle_names(): void; + + print(stream: OutputStream): void; + + print_to_string(options?: BeautifierOptions): string; +} + +export interface MinifyOptions { + spidermonkey?: boolean; + outSourceMap?: string; + sourceRoot?: string; + inSourceMap?: string; + fromString?: boolean; + warnings?: boolean; + mangle?: boolean | MangleOptions; + output?: OutputOptions; + compress?: boolean | CompressOptions; + nameCache?: {}; +} + +export interface MinifyOutput { + code: string; + map: string; + warnings?: string[]; + error?: string; + ast?: boolean | AST_Toplevel; +} + +export function minify(files: {}, options?: MinifyOptions): MinifyOutput; + +export interface ParseOptions { + // Default is false + strict?: boolean; + + // Input file name, default is null + filename?: string; + + // Default is null + toplevel?: AST_Toplevel; +} +export interface CompressOptions { + /** Replace `arguments[index]` with function parameter name whenever possible. */ + arguments?: boolean; + /** Various optimizations for boolean context, for example `!!a ? b : c → a ? b : c` */ + booleans?: boolean; + /** Collapse single-use non-constant variables, side effects permitting. */ + collapse_vars?: boolean; + /** Apply certain optimizations to binary nodes, e.g. `!(a <= b) → a > b,` attempts to negate binary nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc */ + comparisons?: boolean; + /** Apply optimizations for `if-s` and conditional expressions. */ + conditionals?: boolean; + /** Remove unreachable code */ + dead_code?: boolean; + /** + * Pass `true` to discard calls to console.* functions. + * If you wish to drop a specific function call such as `console.info` and/or retain side effects from function + * arguments after dropping the function call then use `pure_funcs` instead. + */ + drop_console?: boolean; + /** Remove `debugger;` statements */ + drop_debugger?: boolean; + /** Attempt to evaluate constant expressions */ + evaluate?: boolean; + /** Pass `true` to preserve completion values from terminal statements without `return`, e.g. in bookmarklets. */ + expression?: boolean; + global_defs?: object; + /** hoist function declarations */ + hoist_funs?: boolean; + /** + * Hoist properties from constant object and array literals into regular variables subject to a set of constraints. + * For example: `var o={p:1, q:2}; f(o.p, o.q);` is converted to `f(1, 2);`. Note: `hoist_props` works best with mangle enabled, + * the compress option passes set to 2 or higher, and the compress option toplevel enabled. + */ + hoist_props?: boolean; + /** Hoist var declarations (this is `false` by default because it seems to increase the size of the output in general) */ + hoist_vars?: boolean; + /** Optimizations for if/return and if/continue */ + if_return?: boolean; + /** + * Inline calls to function with simple/return statement + * - false -- same as `Disabled` + * - `Disabled` -- disabled inlining + * - `SimpleFunctions` -- inline simple functions + * - `WithArguments` -- inline functions with arguments + * - `WithArgumentsAndVariables` -- inline functions with arguments and variables + * - true -- same as `WithArgumentsAndVariables` + */ + inline?: boolean | InlineFunctions; + /** join consecutive `var` statements */ + join_vars?: boolean; + /** Prevents the compressor from discarding unused function arguments. You need this for code which relies on `Function.length` */ + keep_fargs?: boolean; + /** Pass true to prevent the compressor from discarding function names. Useful for code relying on `Function.prototype.name`. */ + keep_fnames?: boolean; + /** Pass true to prevent Infinity from being compressed into `1/0`, which may cause performance issues on `Chrome` */ + keep_infinity?: boolean; + /** Optimizations for `do`, `while` and `for` loops when we can statically determine the condition. */ + loops?: boolean; + /** negate `Immediately-Called Function Expressions` where the return value is discarded, to avoid the parens that the code generator would insert. */ + negate_iife?: boolean; + /** The maximum number of times to run compress. In some cases more than one pass leads to further compressed code. Keep in mind more passes will take more time. */ + passes?: number; + /** Rewrite property access using the dot notation, for example `foo["bar"]` to `foo.bar` */ + properties?: boolean; + /** + * An array of names and UglifyJS will assume that those functions do not produce side effects. + * DANGER: will not check if the name is redefined in scope. + * An example case here, for instance `var q = Math.floor(a/b)`. + * If variable q is not used elsewhere, UglifyJS will drop it, but will still keep the `Math.floor(a/b)`, + * not knowing what it does. You can pass `pure_funcs: [ 'Math.floor' ]` to let it know that this function + * won't produce any side effect, in which case the whole statement would get discarded. The current + * implementation adds some overhead (compression will be slower). + */ + pure_funcs?: string[]; + pure_getters?: boolean | 'strict'; + /** + * Allows single-use functions to be inlined as function expressions when permissible allowing further optimization. + * Enabled by default. Option depends on reduce_vars being enabled. Some code runs faster in the Chrome V8 engine if + * this option is disabled. Does not negatively impact other major browsers. + */ + reduce_funcs?: boolean; + /** Improve optimization on variables assigned with and used as constant values. */ + reduce_vars?: boolean; + sequences?: boolean; + /** Pass false to disable potentially dropping functions marked as "pure". */ + side_effects?: boolean; + /** De-duplicate and remove unreachable `switch` branches. */ + switches?: boolean; + /** Drop unreferenced functions ("funcs") and/or variables ("vars") in the top level scope (false by default, true to drop both unreferenced functions and variables) */ + toplevel?: boolean; + /** Prevent specific toplevel functions and variables from unused removal (can be array, comma-separated, RegExp or function. Implies toplevel) */ + top_retain?: boolean; + typeofs?: boolean; + unsafe?: boolean; + /** Compress expressions like a `<= b` assuming none of the operands can be (coerced to) `NaN`. */ + unsafe_comps?: boolean; + /** Compress and mangle `Function(args, code)` when both args and code are string literals. */ + unsafe_Function?: boolean; + /** Optimize numerical expressions like `2 * x * 3` into `6 * x`, which may give imprecise floating point results. */ + unsafe_math?: boolean; + /** Optimize expressions like `Array.prototype.slice.call(a)` into `[].slice.call(a)` */ + unsafe_proto?: boolean; + /** Enable substitutions of variables with `RegExp` values the same way as if they are constants. */ + unsafe_regexp?: boolean; + unsafe_undefined?: boolean; + unused?: boolean; + /** display warnings when dropping unreachable code or unused declarations etc. */ + warnings?: boolean; +} + +export enum InlineFunctions { + Disabled = 0, + SimpleFunctions = 1, + WithArguments = 2, + WithArgumentsAndVariables = 3 +} + +export interface MangleOptions { + /** Pass true to mangle names visible in scopes where `eval` or with are used. */ + eval?: boolean; + /** Pass true to not mangle function names. Useful for code relying on `Function.prototype.name`. */ + keep_fnames?: boolean; + /** Pass an array of identifiers that should be excluded from mangling. Example: `["foo", "bar"]`. */ + reserved?: string[]; + /** Pass true to mangle names declared in the top level scope. */ + toplevel?: boolean; + properties?: boolean | ManglePropertiesOptions; +} + +export interface ManglePropertiesOptions { + /** Use true to allow the mangling of builtin DOM properties. Not recommended to override this setting. */ + builtins?: boolean; + /** Mangle names with the original name still present. Pass an empty string "" to enable, or a non-empty string to set the debug suffix. */ + debug?: boolean; + /** Only mangle unquoted property names */ + keep_quoted?: boolean; + /** Pass a RegExp literal to only mangle property names matching the regular expression. */ + regex?: RegExp; + /** Do not mangle property names listed in the reserved array */ + reserved?: string[]; +} + +export interface OutputOptions { + ascii_only?: boolean; + beautify?: boolean; + braces?: boolean; + comments?: boolean | 'all' | 'some' | RegExp; + indent_level?: number; + indent_start?: boolean; + inline_script?: boolean; + keep_quoted_props?: boolean; + max_line_len?: boolean | number; + preamble?: string; + preserve_line?: boolean; + quote_keys?: boolean; + quote_style?: OutputQuoteStyle; + semicolons?: boolean; + shebang?: boolean; + webkit?: boolean; + width?: number; + wrap_iife?: boolean; +} + +export enum OutputQuoteStyle { + PreferDouble = 0, + AlwaysSingle = 1, + AlwaysDouble = 2, + AlwaysOriginal = 3 +} + +/** + * The parser creates a custom abstract syntax tree given a piece of JavaScript code. + * Perhaps you should read about the AST first. + */ +export function parse(code: string, options?: ParseOptions): AST_Toplevel; + +export interface BeautifierOptions { + /** + * Start indentation on every line (only when `beautify`) + */ + indent_start?: number; + + /** + * Indentation level (only when `beautify`) + */ + indent_level?: number; + + /** + * Quote all keys in {} literals? + */ + quote_keys?: boolean; + + /** + * Add a space after colon signs? + */ + space_colon?: boolean; + + /** + * Output ASCII-safe? (encodes Unicode characters as ASCII) + */ + ascii_only?: boolean; + + /** + * Escape " void): void; + + // This is used to output blocks in curly brackets. + // It'll print an open bracket at current point, then call newline() and with the next indentation level it calls your func. + // Lastly, it'll print an indented closing bracket. As usual, if beautification is off you'll just get {x} where x is whatever func outputs. + with_block(func: () => void): void; + + // Adds parens around the output that your function prints. + with_parens(func: () => void): void; + + // Adds square brackets around the output that your function prints. + with_square(func: () => void): void; + + // If options.source_map is set, this will generate a source mapping between the given token (which should be an AST_Token-like {}) and the current line/col. + // The name is optional; in most cases it will be inferred from the token. + add_mapping(token: AST_Node, name?: string): void; + + // Returns the option with the given name. + option(name: string): any; + + // Returns the current line in the output (1-based). + line(): number; + + // Returns the current column in the output (zero-based). + col(): number; + + // Push the given node into an internal stack. This is used to keep track of current node's parent(s). + push_node(node: AST_Node): void; + + // Pops the top of the stack and returns it. + pop_node(): AST_Node; + + // Returns that internal stack. + stack(): any; + + // Returns the n-th parent node (where zero means the direct parent). + parent(n: number): AST_Node; +} + +/** + * The code generator is a recursive process of getting back source code from an AST returned by the parser. + * Every AST node has a “print” method that takes an OutputStream and dumps the code from that node into it. + * The stream {} supports a lot of options that control the output. + * You can specify whether you'd like to get human-readable (indented) output, the indentation level, whether you'd like to quote all properties in {} literals etc. + */ +export function OutputStream(options?: BeautifierOptions): OutputStream; + +export interface SourceMapOptions { + /** + * The compressed file name + */ + file?: string; + + /** + * The root URL to the original sources + */ + root?: string; + + /** + * The input source map. + * Useful when you compress code that was generated from some other source (possibly other programming language). + * If you have an input source map, pass it in this argument and Terser will generate a mapping that maps back + * to the original source (as opposed to the compiled code that you are compressing). + */ + orig?: {} | JSON; +} + +export interface SourceMap { + add(source: string, gen_line: number, gen_col: number, orig_line: number, orig_col: number, name?: string): void; + get(): MOZ_SourceMap.SourceMapGenerator; + toString(): string; +} + +/** + * The output stream keeps track of the current line/column in the output and can trivially generate a source mapping to the original code via Mozilla's source-map library. + * To use this functionality, you must load this library (it's automatically require-d by Terser in the NodeJS version, but in a browser you must load it yourself) + * and make it available via the global MOZ_SourceMap variable. + */ +export function SourceMap(options?: SourceMapOptions): SourceMap; + +export interface CompressorOptions { + // Join consecutive statemets with the “comma operator” + sequences?: boolean; + + // Optimize property access: a["foo"] → a.foo + properties?: boolean; + + // Discard unreachable code + dead_code?: boolean; + + // Discard “debugger” statements + drop_debugger?: boolean; + + // Some unsafe optimizations (see below) + unsafe?: boolean; + + // Optimize if-s and conditional expressions + conditionals?: boolean; + + // Optimize comparisons + comparisons?: boolean; + + // Evaluate constant expressions + evaluate?: boolean; + + // Optimize boolean expressions + booleans?: boolean; + + // Optimize loops + loops?: boolean; + + // Drop unused variables/functions + unused?: boolean; + + // Hoist function declarations + hoist_funs?: boolean; + + // Hoist variable declarations + hoist_vars?: boolean; + + // Optimize if-s followed by return/continue + if_return?: boolean; + + // Join var declarations + join_vars?: boolean; + + // Try to cascade `right` into `left` in sequences + cascade?: boolean; + + // Drop side-effect-free statements + side_effects?: boolean; + + // Warn about potentially dangerous optimizations/code + warnings?: boolean; + + // Global definitions + global_defs?: {}; +} + +/** + * The compressor is a tree transformer which reduces the code size by applying various optimizations on the AST + */ +export function Compressor(options?: CompressorOptions): AST_Toplevel; + +// TODO: + +/** + * Terser provides a TreeWalker {} and every node has a walk method that given a walker will apply your visitor to each node in the tree. + * Your visitor can return a non-falsy value in order to prevent descending the current node. + */ +export class TreeWalker { + constructor(visitor: visitor); + parent: () => AST_Scope; + stack: AST_Scope[]; +} + +export type visitor = (node: AST_Node, descend: () => void) => boolean | void; + +// TODO: + +/** + * The tree transformer is a special case of a tree walker. + * In fact it even inherits from TreeWalker and you can use the same methods, but initialization and visitor protocol are a bit different. + */ +export class TreeTransformer extends TreeWalker { + constructor(visitor: visitor, after: visitor); +} + +// TODO: http://lisperator.net/uglifyjs/ast + +export class AST_PropAccess extends AST_Node { +} + +export class AST_ObjectKeyVal extends AST_Node { +} + +export class AST_Scope extends AST_Node { + find_variable(name: string): AST_SymbolDeclaration; +} + +export class AST_Symbol extends AST_Node { + scope?: AST_Scope; + name: string; + thedef: unknown; +} + +export class AST_SymbolDeclaration extends AST_Symbol { + orig: AST_SymbolDeclaration[]; + references: AST_SymbolRef[]; + global: boolean; + undeclared: boolean; + constant: boolean; + mangledName?: string; + mangled_name?: string; +} + +export class AST_SymbolRef extends AST_Symbol { +} + +export class AST_Call extends AST_Node { + expression: { name?: string, property?: string }; + args: AST_Node[]; +} +export class AST_String extends AST_Node { + value: string; +} +export class AST_Lambda extends AST_Node { + name?: string; +} +export class AST_SymbolMethod extends AST_Node { + name?: string; +} +export class AST_ConciseMethod extends AST_Node { +} +export class AST_SymbolVar extends AST_Node { + name?: string; +} diff --git a/types/terser/package.json b/types/terser/package.json new file mode 100644 index 0000000000..25c65e7595 --- /dev/null +++ b/types/terser/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "source-map": "*" + } +} diff --git a/types/terser/terser-tests.ts b/types/terser/terser-tests.ts new file mode 100644 index 0000000000..49b9190070 --- /dev/null +++ b/types/terser/terser-tests.ts @@ -0,0 +1,33 @@ +/// + +import { OutputQuoteStyle, minify } from 'terser'; + +let code: any; + +code = { + "file1.js": "function add(first, second) { return first + second; }", + "file2.js": "console.log(add(1 + 2, 3 + 4));" +}; + +minify(code); + +code = "function add(first, second) { return first + second; }"; +minify(code); + +minify(code); + +const output = minify(code, { + warnings: true, + mangle: { + properties: { + regex: /reg/ + } + }, + compress: { + arguments: true + } +}); + +if (output.warnings) { + output.warnings.filter(x => x === 'Dropping unused variable'); +} diff --git a/types/terser/tsconfig.json b/types/terser/tsconfig.json new file mode 100644 index 0000000000..937a5d1350 --- /dev/null +++ b/types/terser/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", + "terser-tests.ts" + ] +} diff --git a/types/terser/tslint.json b/types/terser/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/terser/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/three/index.d.ts b/types/three/index.d.ts index 74ce9ac0ee..63bf98bcfe 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -21,6 +21,8 @@ // Ethan Kay , // Methuselah96 // Dilip Ramirez +// Julian Strecker +// Zhang Hao // Definitions: https://github.com//DefinitelyTyped // TypeScript Version: 2.8 @@ -32,7 +34,7 @@ export * from "./three-copyshader"; export * from "./three-css3drenderer"; export * from "./three-ctmloader"; export * from "./three-ddsloader"; -export * from './three-dragcontrols'; +export * from "./three-dragcontrols"; export * from "./three-editorcontrols"; export * from "./three-effectcomposer"; export * from "./three-examples"; diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 66276bb1f4..5576a4b511 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -1127,7 +1127,8 @@ export class EventDispatcher { export interface Event { type: string; - target: any; + target?: any; + [attachment: string]: any; } /** @@ -3277,9 +3278,7 @@ export interface HSL { * @see src/math/Color.js */ export class Color { - constructor(color?: Color); - constructor(color?: string); - constructor(color?: number); + constructor(color?: Color|string|number); constructor(r: number, g: number, b: number); /** @@ -6688,11 +6687,17 @@ export namespace SceneUtils { export function attach(child: Object3D, scene: Scene, parent: Object3D): void; } +interface Vec2 +{ + x: number; + y: number; +} + export namespace ShapeUtils { - export function area(contour: number[]): number; - export function triangulate(contour: number[], indices: boolean): number[]; - export function triangulateShape(contour: number[], holes: any[]): number[]; - export function isClockWise(pts: number[]): boolean; + export function area(contour: Vec2[]): number; + export function triangulate(contour: Vec2[], indices: boolean): number[]; + export function triangulateShape(contour: Vec2[], holes: Vec2[]): number[][]; + export function isClockWise(pts: Vec2[]): boolean; } // Extras / Audio ///////////////////////////////////////////////////////////////////// diff --git a/types/three/three-fbxloader.d.ts b/types/three/three-fbxloader.d.ts index 5175a6683f..4ecd1e70a7 100644 --- a/types/three/three-fbxloader.d.ts +++ b/types/three/three-fbxloader.d.ts @@ -1,14 +1,17 @@ // https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/FBXLoader.js import { LoadingManager } from "./three-core"; -import {Group} from "./three-core"; +import { AnimationClip, Group } from "./three-core"; +interface IFbxSceneGraph extends Group { + animations: AnimationClip[]; +} export class FBXLoader { constructor(manager?: LoadingManager); manager: LoadingManager; - load(url: string, onLoad: (group: Group) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; + load(url: string, onLoad: (group: IFbxSceneGraph) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; parse(FBXText: string, resourceDirectory: string) : Group; -} \ No newline at end of file +} diff --git a/types/three/three-orbitcontrols.d.ts b/types/three/three-orbitcontrols.d.ts index 1d4979217f..6d8627c6ad 100644 --- a/types/three/three-orbitcontrols.d.ts +++ b/types/three/three-orbitcontrols.d.ts @@ -32,6 +32,7 @@ export class OrbitControls { mouseButtons: {ORBIT: MOUSE; ZOOM: MOUSE; PAN: MOUSE;}; enableDamping: boolean; dampingFactor: number; + screenSpacePanning: boolean; rotateLeft(angle?: number): void; diff --git a/types/three/three-unrealbloompass.d.ts b/types/three/three-unrealbloompass.d.ts index dec35b3da7..ed58b853ac 100644 --- a/types/three/three-unrealbloompass.d.ts +++ b/types/three/three-unrealbloompass.d.ts @@ -22,6 +22,8 @@ export class UnrealBloomPass extends Pass { camera: OrthographicCamera; scene: Scene; quad: Mesh; + radius: number; + threshold: number; dispose(): void; getSeparableBlurMaterial(): ShaderMaterial; getCompositeMaterial(): ShaderMaterial; diff --git a/types/tiny-secp256k1/tsconfig.json b/types/tiny-secp256k1/tsconfig.json index 377e6d639c..db31e22d15 100644 --- a/types/tiny-secp256k1/tsconfig.json +++ b/types/tiny-secp256k1/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es5" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/tough-cookie/index.d.ts b/types/tough-cookie/index.d.ts index d4e9a58548..e68496d302 100644 --- a/types/tough-cookie/index.d.ts +++ b/types/tough-cookie/index.d.ts @@ -30,7 +30,7 @@ export function canonicalDomain(str: string): string; * The str is the "current" domain-name and the domStr is the "cookie" domain-name. * Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". * - * The canonicalize parameter will run the other two paramters through canonicalDomain or not. + * The canonicalize parameter will run the other two parameters through canonicalDomain or not. */ export function domainMatch(str: string, domStr: string, canonicalize?: boolean): boolean; diff --git a/types/universal-router/index.d.ts b/types/universal-router/index.d.ts index c510352338..eb698fc8bf 100644 --- a/types/universal-router/index.d.ts +++ b/types/universal-router/index.d.ts @@ -9,7 +9,7 @@ import pathToRegexp = require('path-to-regexp'); /** - * Params is a key/value object that represents extracted URL paramters. + * Params is a key/value object that represents extracted URL parameters. * Each URL parameter resolves to a string. */ export interface Params { diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 5b245440bd..5670547317 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -513,6 +513,7 @@ declare module "victory" { /** * Default theme */ + grayscale: VictoryThemeDefinition; material: VictoryThemeDefinition; } diff --git a/types/vimeo__player/index.d.ts b/types/vimeo__player/index.d.ts index cf7475f246..2ef9555813 100755 --- a/types/vimeo__player/index.d.ts +++ b/types/vimeo__player/index.d.ts @@ -70,8 +70,8 @@ export interface VimeoCuePoint { id: string; } -export interface VimeoCuePointData extends Object { - customKey: string; +export interface VimeoCuePointData { + [key: string]: any; } export interface VimeoTextTrack { diff --git a/types/vuex-i18n/index.d.ts b/types/vuex-i18n/index.d.ts index e1f607ef39..f6b75afa1a 100644 --- a/types/vuex-i18n/index.d.ts +++ b/types/vuex-i18n/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for vuex-i18n 1.7 +// Type definitions for vuex-i18n 1.10 // Project: https://github.com/dkfbasel/vuex-i18n // Definitions by: Cedric Kemp // Noam Kfir +// Suleimanov Artem // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.9 import _Vue, { PluginObject } from "vue"; @@ -17,13 +18,21 @@ declare module "vue/types/vue" { } } +export interface i18nState { + fallback: string | null; + locale: string | null; + translations: { + [key: string]: Translations; + }; +} + export interface Translations { [key: string]: string | Translations; } export interface Ii18n { /** get the current locale */ - locale(): string; + locale(): string | null; /** get all the registered locales */ locales(): string[]; @@ -81,9 +90,14 @@ export interface Ii18n { localeExists(locale: string): boolean; /** - * check if the given key is available in the current or fallback locale + * check if the given key is available + * optional with a second parameter to limit the scope + * strict: only current locale (exact match) + * locale: current locale and parent language locale (i.e. en-us & en) + * fallback: current locale, parent language locale and fallback locale + * the default is fallback */ - keyExists(key: string): boolean; + keyExists(key: string, scope?: string): boolean; } declare const _default: { diff --git a/types/vuex-i18n/vuex-i18n-tests.ts b/types/vuex-i18n/vuex-i18n-tests.ts index 82d9d864d9..11010df30b 100644 --- a/types/vuex-i18n/vuex-i18n-tests.ts +++ b/types/vuex-i18n/vuex-i18n-tests.ts @@ -3,11 +3,16 @@ import Vue from "vue"; import { Store } from "vuex"; // load vuex i18n module -import vuexI18n from "vuex-i18n"; +import vuexI18n, { i18nState } from "vuex-i18n"; + +// declare interface for store's root state +interface RootState { + i18n: i18nState; +} // initialize the vuex store using the vuex module. note that you can change the -// name of the module if you wish -const store = new Store({}); +// name of the module if you wish +const store = new Store({}); // initialize the internationalization plugin on the vue instance. note that // the store must be passed to the plugin. the plugin will then generate some diff --git a/types/w3c-gamepad/index.d.ts b/types/w3c-gamepad/index.d.ts new file mode 100644 index 0000000000..bff1d30567 --- /dev/null +++ b/types/w3c-gamepad/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for W3C Gamepad API +// Project: http://www.w3.org/TR/gamepad/ +// Definitions by: Kon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Gamepad{ + /** + * This interface defines an individual gamepad device. + */ + export interface Gamepad{ + /** + * An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID. + * @readonly + */ + id:string; + + /** + * The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused. + * @readonly + */ + index:number; + + /** + * Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp. + * @readonly + */ + timestamp:number; + + /** + * Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick. + * @readonly + */ + axes:number[]; + + /** + * Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array. + * @readonly + */ + buttons:GamepadButton[]; + + /** + * Indicates whether the physical device represented by this object is still connected to the system. When a gamepad becomes unavailable, whether by being physically disconnected, powered off or otherwise unusable, the connected attribute must be set to false. + * @readonly + */ + connected:boolean; + + /** + * The mapping in use for this device. If the user agent has knowledge of the layout of the device, then it should indicate that a mapping is in use by setting this property to a known mapping name. Currently the only known mapping is "standard", which corresponds to the Standard Gamepad layout. If the user agent does not have knowledge of the device layout and is simply providing the controls as represented by the driver in use, then it must set the mapping property to an empty string. + * @readonly + */ + mapping:string; + } + + /** + * + */ + export interface GamepadEvent extends Event{ + /** + * The single gamepad attribute provides access to the associated gamepad data for this event. + * @readonly + */ + gamepad:Gamepad; + } + + export interface GamepadList{ + [index: number]: Gamepad; + length: number; + } + + export interface GamepadButton{ + pressed: boolean; + value: number; + } + + /* + * @event gamepadconnected + * A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis. + */ + + /* + * @event gamepaddisconnected + * When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched. + */ +} + +interface Navigator{ + /** + * The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices. + * @readonly + */ + getGamepads(): Gamepad.Gamepad[]; + + webkitGetGamepads(): Gamepad.GamepadList; + + // Not supported yet :( + // mozGetGamepads(): Gamepad[]; +} diff --git a/types/w3c-gamepad/tsconfig.json b/types/w3c-gamepad/tsconfig.json new file mode 100644 index 0000000000..e8a490bcf2 --- /dev/null +++ b/types/w3c-gamepad/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "w3c-gamepad-tests.ts" + ] +} diff --git a/types/w3c-gamepad/tslint.json b/types/w3c-gamepad/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/w3c-gamepad/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/w3c-gamepad/w3c-gamepad-tests.ts b/types/w3c-gamepad/w3c-gamepad-tests.ts new file mode 100644 index 0000000000..af3095adb0 --- /dev/null +++ b/types/w3c-gamepad/w3c-gamepad-tests.ts @@ -0,0 +1,70 @@ + + + +()=>{ + function runAnimation() + { + window.requestAnimationFrame(runAnimation); + + var gamepads = navigator.getGamepads(); + + for (var i = 0; i < gamepads.length; ++i) + { + var pad = gamepads[i]; + // todo; simple demo of displaying pad.axes and pad.buttons + } + } + + window.requestAnimationFrame(runAnimation); +}; + +(()=>{ + var gamepadconnected = (e: Gamepad.GamepadEvent) => { + console.log('Gamepad ' + e.gamepad.index + ' connected!'); + if(e.gamepad.mapping == 'standard'){ + console.log("The Gamepad's controls have been mapped to the Standard Gamepad layout."); + } + }; + var gamepaddisconnected = (e: Gamepad.GamepadEvent) => { + console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); + }; + + window.addEventListener('GamepadConnected', gamepadconnected, false); + window.addEventListener('GamepadDisconnected', gamepaddisconnected, false); + window.addEventListener('webkitGamepadConnected', gamepadconnected, false); + window.addEventListener('webkitGamepadDisconnected', gamepaddisconnected, false); + window.addEventListener('mozGamepadConnected', gamepadconnected, false); + window.addEventListener('mozGamepadDisconnected', gamepaddisconnected, false); + + var requestAnimationFrame = window.requestAnimationFrame || (window).mozRequestAnimationFrame; + var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads; + if(getGamepads){ + function runAnimation() + { + requestAnimationFrame.call(window, runAnimation); + + var gamepads: Gamepad.Gamepad[] = getGamepads.call(navigator); + for(var i = 0; i < gamepads.length; i++){ + var pad: Gamepad.Gamepad = gamepads[i]; + if(pad && pad.connected){ + for (var k = 0; k < pad.buttons.length; k++) + { + var button: Gamepad.GamepadButton = pad.buttons[k]; + if(button.pressed){ + console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" button[' + k + '] = ' + button.value); + } + } + for (var k = 0; k < pad.axes.length; k++) + { + var axis = pad.axes[k]; + if(Math.abs(axis) > 0.1){ + console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" axis[' + k + '] = ' + axis); + } + } + } + } + } + + runAnimation(); + } +})(); \ No newline at end of file diff --git a/types/wavesurfer.js/index.d.ts b/types/wavesurfer.js/index.d.ts index c468df6e05..49a9757558 100644 --- a/types/wavesurfer.js/index.d.ts +++ b/types/wavesurfer.js/index.d.ts @@ -90,7 +90,7 @@ declare namespace WaveSurfer { } class WaveSurferPlugin { - constructor(ws: WaveSurfer, params: object); + constructor(params: object, ws: WaveSurfer); static create(params: object): PluginDefinition; init(): void; destroy(): void; @@ -151,7 +151,7 @@ declare namespace WaveSurfer { staticProps?: object; deferInit?: boolean; params: object; - instance: { new(ws: WaveSurfer, params: object): WaveSurferPlugin }; + instance: { new(params: object, ws: WaveSurfer): WaveSurferPlugin }; } interface ListenerDescriptor { diff --git a/types/wavesurfer.js/wavesurfer.js-tests.ts b/types/wavesurfer.js/wavesurfer.js-tests.ts index 49f0136d54..dc7521e59b 100644 --- a/types/wavesurfer.js/wavesurfer.js-tests.ts +++ b/types/wavesurfer.js/wavesurfer.js-tests.ts @@ -1,5 +1,3 @@ -/// -import * as fs from "fs"; import * as WaveSurfer from "wavesurfer.js"; // https://www.npmjs.com/package/wavesurfer.js#api-in-examples @@ -29,7 +27,7 @@ wsNewed.empty(); // - create an instance with plugins class SamplePlugin { - constructor(ws: WaveSurfer, params: object) { } + constructor(params: object, ws: WaveSurfer) { } static create(params: object): WaveSurfer.PluginDefinition { return { name: "samplePlugin", diff --git a/types/web3/index.d.ts b/types/web3/index.d.ts index 12ab849a94..3b1fe0c562 100644 --- a/types/web3/index.d.ts +++ b/types/web3/index.d.ts @@ -18,6 +18,7 @@ // Asgeir Sognefest // Donam Kim // Doug Kent +// Daniel Zhou // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 diff --git a/types/web3/tslint.json b/types/web3/tslint.json index dc6622bc53..99ea174f67 100644 --- a/types/web3/tslint.json +++ b/types/web3/tslint.json @@ -1,5 +1,6 @@ -{ "extends": "dtslint/dt.json", -"rules": { - "strict-export-declare-modifiers": false - } +{ + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false + } } diff --git a/types/web3/types.d.ts b/types/web3/types.d.ts index c3d681d60f..87e6eee21b 100644 --- a/types/web3/types.d.ts +++ b/types/web3/types.d.ts @@ -36,7 +36,7 @@ export interface TransactionReceipt { events?: { [eventName: string]: EventLog; }; - status: string; + status: boolean; } export interface EncodedTransaction { diff --git a/types/web3/web3-tests.ts b/types/web3/web3-tests.ts index ed30d4fce4..170a8b22c3 100644 --- a/types/web3/web3-tests.ts +++ b/types/web3/web3-tests.ts @@ -28,7 +28,9 @@ const sendSignedTransactionTxReceipt0: PromiEvent = web3.eth const sendSignedTransactionTxReceipt1: PromiEvent = web3.eth.sendSignedTransaction("") .on("transactionHash", (txHash: string) => { }); const sendSignedTransactionTxReceipt2: PromiEvent = web3.eth.sendSignedTransaction("") - .on("receipt", (txReceipt: TransactionReceipt) => { }); + .on("receipt", (txReceipt: TransactionReceipt) => { + const { status }: { status: boolean } = txReceipt; + }); const sendSignedTransactionTxReceipt3: PromiEvent = web3.eth.sendSignedTransaction("") .on("confirmation", (confNumber: number, receipt: TransactionReceipt) => { }); const sendSignedTransactionTxReceipt4: PromiEvent = web3.eth.sendSignedTransaction("") diff --git a/types/webidl2/index.d.ts b/types/webidl2/index.d.ts index 90a938b22a..2e04cc413c 100644 --- a/types/webidl2/index.d.ts +++ b/types/webidl2/index.d.ts @@ -96,7 +96,7 @@ export interface CallbackType { name: string; /** An IDL Type describing what the callback returns. */ idlType: IDLTypeDescription; - /** A list of arguments, as in function paramters. */ + /** A list of arguments, as in function parameters. */ arguments: Argument[]; /** A list of extended attributes. */ extAttrs: ExtendedAttributes[]; diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index df1263f1b2..94974500eb 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -289,9 +289,7 @@ declare namespace wx { * 需要用户授权 scope.writePhotosAlbum * @version 1.2.0 */ - function saveImageToPhotosAlbum( - options: SaveImageToPhotosAlbumOptions - ): void; + function saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; // 媒体-----录音 interface StartRecordAudioOptions extends BaseOptions { /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ @@ -387,13 +385,9 @@ declare namespace wx { /** 录音恢复事件 */ onResume(callback?: () => void): void; /** 录音停止事件,会回调文件地址 */ - onStop( - callback?: (options: OnRecorderManagerStopOptions) => void - ): void; + onStop(callback?: (options: OnRecorderManagerStopOptions) => void): void; /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ - onFrameRecorded( - callback?: (options: OnFrameRecordedOptions) => void - ): void; + onFrameRecorded(callback?: (options: OnFrameRecordedOptions) => void): void; /** 录音错误事件, 会回调错误信息 */ onError(callback?: (err: ErrMsgResponse) => void): void; } @@ -974,7 +968,7 @@ declare namespace wx { * 异步获取当前storage的相关信息 */ function getStorageInfo(options: GetStorageInfoOptions): void; - function getStorageInfoSync(): GetStorageInfoOptions; + function getStorageInfoSync(): StorageInfo; interface RemoveStorageOptions extends BaseOptions { key: string; success?(res: DataResponse): void; @@ -1066,9 +1060,7 @@ declare namespace wx { /** * 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 wx.openLocation */ - getCenterLocation( - options: GetCenterLocationOptions - ): OpenLocationOptions; + getCenterLocation(options: GetCenterLocationOptions): OpenLocationOptions; /** * 将地图中心移动到当前定位点,需要配合map组件的show-location使用 */ @@ -2611,6 +2603,9 @@ declare namespace wx { } type LineCapType = "butt" | "round" | "square"; type LineJoinType = "bevel" | "round" | "miter"; + interface CanvasGradient { + addColorStop(index: number, color: string): void; + } /** * context只是一个记录方法调用的容器,用于生成记录绘制行为的actions数组。context跟不存在对应关系,一个context生成画布的绘制动作数组可以应用于多个。 */ @@ -2873,7 +2868,7 @@ declare namespace wx { y0: number, x1: number, y1: number - ): void; + ): CanvasGradient; /** * 创建一个颜色的渐变点。 * Tip: 小于最小 stop 的部分会按最小 stop 的 color 来渲染,大于最大 stop 的部分会按最大 stop 的 color 来渲染。 @@ -3613,6 +3608,30 @@ declare namespace wx { enableDebug: boolean; } // #region App里的onLaunch、onShow回调参数 + + // #region Account + interface AccountInfo { + /* 小程序账号信息 */ + miniProgram: { + /*小程序 appId */ + appId: string; + }; + /* 插件账号信息(仅在插件中调用时包含这一项) */ + plugin?: { + /* 插件 appId */ + appId: string; + /* 插件版本号 */ + version: string; + }; + } + + /** + * 获取当前账号信息 + * @version >= 2.2.2 + */ + function getAccountInfoSync(): AccountInfo; + // #endregion + /** * App 实现的接口对象 * 开发者可以添加任意的函数或数据到 Object 参数中,用 this 可以访问 @@ -3670,8 +3689,7 @@ declare namespace wx { Data, Methods, Props - > = CombinedInstance & - Component; + > = CombinedInstance & Component; // CombinedInstance models the `this`, i.e. instance type for (user defined) component type CombinedInstance< @@ -3702,9 +3720,7 @@ declare namespace wx { type ArrayPropsDefinition = Array; - type PropsDefinition = - | ArrayPropsDefinition - | RecordPropsDefinition; + type PropsDefinition = ArrayPropsDefinition | RecordPropsDefinition; interface ComponentRelation { /** 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant */ @@ -3838,9 +3854,7 @@ declare namespace wx { * 类似于mixins和traits的组件间代码复用机制 * 参见 [behaviors](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/custom-component/behaviors.html) */ - behaviors?: Array< - (ComponentOptions>) | string - >; + behaviors?: Array<(ComponentOptions>) | string>; /** * 组件生命周期声明对象,组件的生命周期:created、attached、ready、moved、detached将收归到lifetimes字段内进行声明, @@ -4084,25 +4098,22 @@ declare namespace wx { /** * 当场景为由从另一个小程序或公众号或App打开时,返回此字段 */ - referrerInfo: object; - /** - * 来源小程序或公众号或App的 appId,详见下方说明 - */ - "referrerInfo.appId": string; - /** - * 来源小程序传过来的数据,scene=1037或1038时支持 - */ - "referrerInfo.extraData": object; + referrerInfo: { + /* 来源小程序或公众号或App的 appId,详见下方说明 */ + appId: string; + /* 来源小程序传过来的数据,scene=1037或1038时支持 */ + extraData: object; + }; // #endregion } // 云开发 // 文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/getting-started.html - interface cloud { + interface Cloud { /** * 初始化方法(全局只需一次) */ - init: (options: initCloudOptions) => void; + init: (options: InitCloudOptions) => void; /** * 接受一个可选对象参数 env:环境 ID,获取数据库的引用 */ @@ -4115,12 +4126,12 @@ declare namespace wx { /** * 定义了云开发的默认配置,该配置会作为之后调用其他所有云 API 的默认配置 */ - interface initCloudOptions { + interface InitCloudOptions { /** * 默认环境配置,传入字符串形式的环境 ID 可以指定所有服务的默认环境,传入对象 initCloudEnvOptions 可以分别指定各个服务的默认环境 * 默认值: default */ - env?: string | initCloudEnvOptions; + env?: string | InitCloudEnvOptions; /** * 是否在将用户访问记录到用户管理中,在控制台中可见 * 默认值: false @@ -4130,7 +4141,7 @@ declare namespace wx { /** * initCloudOptions 的 env 参数,可以指定各个服务的默认环境 */ - interface initCloudEnvOptions { + interface InitCloudEnvOptions { /** * 数据库 API 默认环境配置 * 默认值: default diff --git a/types/weixin-app/weixin-app-tests.ts b/types/weixin-app/weixin-app-tests.ts index cacdeaee70..7333dce911 100644 --- a/types/weixin-app/weixin-app-tests.ts +++ b/types/weixin-app/weixin-app-tests.ts @@ -469,3 +469,8 @@ wx.getSystemInfo({ } = res; } }); + +function testAccountInfo(): string { + const accountInfo: wx.AccountInfo = wx.getAccountInfoSync(); + return accountInfo.miniProgram.appId; +} diff --git a/types/winston-syslog/index.d.ts b/types/winston-syslog/index.d.ts index b0409ad4c4..c868ef5abc 100644 --- a/types/winston-syslog/index.d.ts +++ b/types/winston-syslog/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/winstonjs/winston-syslog // Definitions by: Chris Barth , Felix Hochgruber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import * as Transport from 'winston-transport'; import * as dgram from 'dgram'; diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 3fc9a33fcd..6e037366ed 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -163,7 +163,7 @@ export interface ArraySchema extends Schema { min(limit: number | Ref, message?: string): ArraySchema; max(limit: number | Ref, message?: string): ArraySchema; ensure(): ArraySchema; - compact(rejector: (value: any) => boolean): ArraySchema; + compact(rejector?: (value: any) => boolean): ArraySchema; } export interface ObjectSchemaConstructor {