diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index de68dd4e47..f4f973d6c8 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,6 +6,7 @@ /types/abbrev/ @BendingBender /types/abs/ @AyaMorisawa /types/absolute/ @AyaMorisawa +/types/abstract-leveldown/ @MeirionHughes @danwbyrne /types/acc-wizard/ @cyrilschumacher /types/accept-language-parser/ @kampfgnom /types/accepts/ @bomret @brikou @@ -16,6 +17,7 @@ /types/acorn/ @RReverser @e-cloud /types/actioncable/ @zhu1230 /types/actions-on-google/ @joelhegg +/types/activedirectory2/ @pasthelod /types/activex-access/ @zspitz /types/activex-adodb/ @zspitz /types/activex-adox/ @zspitz @@ -46,6 +48,7 @@ /types/adone/ @s0m3on3 @maxveres /types/aframe/ @devpaul @bertoritger @twastvedt /types/agenda/ @meirgottlieb @princjef +/types/agent-base/ @Shinigami92 /types/aggregate-error/ @BendingBender /types/agora-rtc-sdk/ @menthays /types/ajv-errors/ @afshawnlotfi @@ -55,6 +58,7 @@ /types/algebra.js/ @CaselIT /types/algoliasearch/ @cbaptiste @haroenv @aherve @samouss /types/allure-js-commons/ @zaqqaz +/types/almost-equal/ @cmaddalozzo /types/alt/ @Shearerbeard /types/amazon-cognito-auth-js/ @scottescue /types/amazon-product-api/ @MattiLehtinen @alien35 @@ -74,7 +78,7 @@ /types/angular/ @diegovilar @thorn0 @calebstdenis @leonard-thieu @scipper /types/angular-agility/ @rolandzwaga /types/angular-animate/ @michelsalib @adidahiya @rasch @codyschaaf -/types/angular-block-ui/ @lassebn @sclassen +/types/angular-block-ui/ @lassebn @sclassen @renjfk /types/angular-bootstrap-calendar/ @Odrin /types/angular-bootstrap-lightbox/ @rolandzwaga /types/angular-breadcrumb/ @marctalary @@ -109,15 +113,16 @@ /types/angular-material/ @blbigelow @PeterHajdu @Dona278 @geertjansen @eknowles /types/angular-media-queries/ @jpmnteiro /types/angular-meteor/ @pgrm -/types/angular-mocks/ @diegovilar @daltin +/types/angular-mocks/ @diegovilar @daltin @thorn0 /types/angular-modal/ @paullessing /types/angular-oauth2/ @anteriovieira /types/angular-pdfjs-viewer/ @bastienmoulia /types/angular-permission/ @vmishevski /types/angular-promise-tracker/ @rufusl +/types/angular-q-extras/ @mistic100 /types/angular-q-spread/ @rafw87 /types/angular-resource/ @diegovilar @miffels -/types/angular-route/ @park9140 +/types/angular-route/ @park9140 @gkalpak /types/angular-sanitize/ @diegovilar /types/angular-scenario/ @RomanoLindano /types/angular-scroll/ @samherrmann @@ -129,7 +134,7 @@ /types/angular-toasty/ @muenchdo /types/angular-tooltips/ @leonard-thieu /types/angular-translate/ @michelsalib @GabrielGil -/types/angular-ui-bootstrap/ @xt0rted @ry8806 +/types/angular-ui-bootstrap/ @xt0rted @ry8806 @alfiej /types/angular-ui-router/ @michelsalib @matiishyn @mikehaas763 /types/angular-ui-scroll/ @marknadig /types/angular-ui-sortable/ @thgreasi @@ -145,6 +150,7 @@ /types/animejs/ @A-Babin /types/annyang/ @hisham @theluk /types/ansi-colors/ @rogierschouten +/types/ansi-escape-sequences/ @aomarks /types/ansi-escapes/ @jacobbubu /types/ansi-regex/ @mvachhar /types/ansi-styles/ @brynbellomy @plylrnsdy @@ -167,7 +173,7 @@ /types/appframework/ @kyo-ago /types/applepayjs/ @martincostello /types/appletvjs/ @brainded -/types/applicationinsights-js/ @kamilszostak +/types/applicationinsights-js/ @kamilszostak @markwolff /types/aqb/ @Athenkosi-Mase /types/arangodb/ @pluma /types/arbiter/ @arash16 @@ -185,6 +191,7 @@ /types/arr-union/ @mrmlnc /types/array-find-index/ @samverschueren /types/array-foreach/ @skysteve +/types/array-sort/ @DanielMSchmidt /types/array-uniq/ @DanielRosenwasser /types/array-unique/ @CSLTech /types/arrify/ @wanganjun @@ -223,8 +230,9 @@ /types/auth0-angular/ @homesar /types/auth0-js/v7/ @advancedrei /types/auth0-js/ @adrianchia @mdurrant @peterblazejewicz -/types/auth0-lock/ @carusology @goldcaddy77 @lfaudreejr +/types/auth0-lock/ @carusology @goldcaddy77 @lfaudreejr @willcaul /types/auth0.widget/ @advancedrei +/types/auto-bind/ @sseppola /types/auto-launch/ @rhysd @unindented /types/auto-sni/ @janwo /types/autobahn/ @darkl @valepu @@ -234,7 +242,7 @@ /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 +/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 /types/aws-serverless-express/ @threesquared @jcaffey @mattmeye @albertovasquez /types/aws4/ @ajcrites /types/axe-webdriverjs/ @JoshuaKGoldberg @@ -255,6 +263,11 @@ /types/babel-types/ @yortus @baxtersa @marvinhagemeister @bcherny /types/babel-webpack-plugin/ @j-f1 /types/babel__code-frame/ @mohsen1 @ForbesLindesay +/types/babel__core/ @yortus @marvinhagemeister @mgroenhoff +/types/babel__generator/ @yortus @johnnyestilles @mgroenhoff +/types/babel__parser/ @yortus @marvinhagemeister @mgroenhoff +/types/babel__template/ @yortus @marvinhagemeister @mgroenhoff +/types/babel__traverse/ @yortus @marvinhagemeister @rpetrich @mgroenhoff /types/babelify/ @TeamworkGuy2 @marvinhagemeister /types/babylon/ @yortus @marvinhagemeister /types/babylon-walk/ @czbuchi @@ -265,7 +278,7 @@ /types/backbone-relational/ @eirikhm /types/backbone.layoutmanager/ @hejiang2000 /types/backbone.localstorage/ @lgrignon -/types/backbone.marionette/ @zhamid @nvivo @sventschui @razorness +/types/backbone.marionette/ @zhamid @nvivo @sventschui @razorness @confususs /types/backbone.paginator/ @Nyamazing /types/backbone.radio/ @alphaleonis /types/backgrid/ @jlujan @@ -274,6 +287,7 @@ /types/backoff/ @BendingBender /types/baconjs/ @alexander-matsievsky @gekkio /types/bagpipes/ @micmro +/types/barbellweights/ @evelijn /types/barcode/ @pvomhoff /types/bardjs/ @TepigMC /types/base-64/ @dolanmiu @@ -290,6 +304,7 @@ /types/bazinga-translator/ @alexndlm /types/bcrypt/ @codeanimal @IOAyman @dstapleton92 /types/bcryptjs/ @RafaelKr +/types/bdfjs/ @jeremejevs /types/beats/ @urish /types/bech32/ @micksatana /types/behavior3/ @carrrywu @@ -297,6 +312,8 @@ /types/bem-cn/ @selkinvitaly /types/bencode/ @tobenna /types/better-curry/ @pocesar +/types/better-queue/ @maozedong +/types/better-scroll/ @stoneChen /types/better-sqlite3/ @Morfent @matrumz /types/bezier-easing/ @ptlis /types/bezier-js/ @danmarshall @@ -331,6 +348,7 @@ /types/blocked/ @l-jonas /types/blockies/ @LogvinovLeon /types/blocks/ @ksmigiel +/types/bloem/ @danwbyrne /types/bloomfilter/ @slawiko /types/blue-tape/ @sodatea /types/bluebird/v1/ @Bartvds @@ -378,6 +396,7 @@ /types/braintree-web/ @chlela /types/breeze/ @borisyankov /types/bricks.js/ @kondi +/types/bro-fs/ @ffflorian /types/brorand/ @chrootsu /types/browser-bunyan/ @PaulLockwood @kryops /types/browser-fingerprint/ @LKay @@ -399,7 +418,7 @@ /types/bufferstream/ @Bartvds /types/builtin-modules/ @ajafff /types/bull/v2/ @bgrieder @JProgrammer -/types/bull/ @bgrieder @JProgrammer @marshall007 @weeco @blaugold @iamolegga @koblas +/types/bull/ @bgrieder @JProgrammer @marshall007 @weeco @blaugold @iamolegga @koblas @bondz @wuha-team @aleccool213 /types/bump-regex/ @silkentrance /types/bunnymq/ @cyrilschumacher /types/bunyan/ @amikhalev @@ -431,6 +450,7 @@ /types/canvas-gauges/ @Mikhus /types/canvasjs/ @brutalimp /types/capitalize/ @frederickfogerty +/types/capture-console/ @AustonZ /types/card-validator/ @ChanceM /types/case-sensitive-paths-webpack-plugin/ @r3nya /types/caseless/ @downace @mastermatt @@ -439,14 +459,15 @@ /types/cassandra-driver/ @Svjard @pc-jedi /types/catbox/v7/ @jasonswearingen @AJamesPhillips /types/catbox/ @jasonswearingen @AJamesPhillips @saboya +/types/catbox-redis/ @SimonSchick /types/cbor/ @pushplay /types/ccap/ @taoqf -/types/cesium/ @Zuzon @hnipps @szechyjs +/types/cesium/ @Zuzon @hnipps @szechyjs @golyalpha /types/chai/v2/ @Bartvds @AGBrown /types/chai/ @jedmao @Bartvds @AGBrown @olivr70 @mwistrand @joshuakgoldberg @shaunluttin @Naktibalda @micksatana @ErikSchierboom /types/chai-arrays/ @clementprevot /types/chai-as-promised/ @jt000 @Kuniwak @leonard-thieu @lazerwalker @mattbishop -/types/chai-datetime/ @cliffburger +/types/chai-datetime/ @cliffburger @mattbishop /types/chai-dom/ @mattlewis92 /types/chai-enzyme/ @asvetliakov /types/chai-fuzzy/ @Bartvds @@ -455,6 +476,7 @@ /types/chai-jquery/ @kazimanzurrashid /types/chai-json-schema/ @ulrichheiniger /types/chai-oequal/ @mizunashi-mana +/types/chai-roughly/ @swist /types/chai-spies/ @kuzn-ilya @harm-less @jounisuo /types/chai-string/ @nmalaguti /types/chai-subset/ @delta62 @AGBrown @@ -466,8 +488,9 @@ /types/chardet/ @Gebatzens /types/charm/ @Xananax /types/charset/ @cspotcode -/types/chart.js/ @anuti @FabienLavocat @KentarouTakeda @larrybahr @mernen @josefpaij @danmana @guillaume-ro-fr @chicoxyzzy @archy-bold @braincore @gebeto @frabnt @alexdor +/types/chart.js/ @anuti @FabienLavocat @KentarouTakeda @larrybahr @mernen @josefpaij @danmana @guillaume-ro-fr @chicoxyzzy @archy-bold @braincore @gebeto @frabnt @alexdor @mahnuh /types/chartist/ @mtgibbs @psimonski @clottman @affilnost @sunnyrjuneja +/types/chartmogul-node/ @chartmogul /types/chayns/ @HenningKuehl /types/check-sum/ @BendingBender /types/check-types/ @idchlife @@ -508,6 +531,7 @@ /types/cli-spinner/ @janslow /types/cli-table/ @arylo /types/cli-table2/ @mgroenhoff +/types/cli-truncate/ @danwbyrne /types/client-sessions/ @netroy /types/clientjs/ @icopp /types/cliff/ @brynbellomy @@ -558,6 +582,7 @@ /types/common-errors/ @icopp /types/common-prefix/ @seangenabe /types/common-tags/ @zuzusik @tzupengwang +/types/commondir/ @leonard-thieu /types/commonmark/ @nicojs @leonard-thieu /types/compare-version/ @jpevarnek /types/compare-versions/ @LogvinovLeon @@ -591,7 +616,8 @@ /types/connect-redis/ @xstoudi @morcerf /types/connect-slashes/ @samherrmann /types/connect-timeout/ @cyrilschumacher -/types/console-stamp/ @ericbyers +/types/console-log-level/ @ofrobots +/types/console-stamp/ @ericbyers @guusdegraeve /types/consolidate/ @soywiz @theosherry @nicolashenry /types/consul/ @chrootsu /types/content-disposition/ @bomret @@ -641,7 +667,7 @@ /types/cosmiconfig/v4/ @ozum /types/cosmiconfig/ @ozum @szeck87 @saadq @jinwoo /types/cote/ @makepost -/types/couchbase/ @maouida +/types/couchbase/ @maouida @fluggo /types/countdown/ @gjuchault /types/counterpart/ @santiagodoldan /types/countries-and-timezones/ @zero51 @@ -669,6 +695,7 @@ /types/crossroads/ @diullei /types/cryptiles/ @awendland /types/crypto-js/ @misak113 +/types/crypto-random-string/ @MrManny /types/cryptojs/ @giabao /types/cson/ @stpettersens /types/csprng/ @winksaville @@ -676,7 +703,9 @@ /types/css/ @ilich /types/css-font-loading-module/ @slikts /types/css-modules/ @NeekSandhu +/types/css-to-style/ @bengry /types/cssbeautify/ @rictic +/types/cssnano/ @odnamrataizem /types/csso/ @screendriver /types/csurf/ @horiuchi /types/csv-parse/ @davidm77 @obi-jan-kenobi @@ -714,12 +743,12 @@ /types/d3-format/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-geo/ @ledragon @tomwanzek @gustavderdrache @borisyankov /types/d3-hexbin/ @uncovertruth @tomwanzek -/types/d3-hierarchy/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-hierarchy/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-hsv/ @arrayjam @denisname /types/d3-interpolate/ @tomwanzek @gustavderdrache @borisyankov /types/d3-path/ @tomwanzek @gustavderdrache @borisyankov /types/d3-polygon/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-quadtree/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-quadtree/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-queue/ @tomwanzek @gustavderdrache @borisyankov /types/d3-random/ @tomwanzek @gustavderdrache @borisyankov /types/d3-request/ @Ledragon @gustavderdrache @borisyankov @tomwanzek @@ -764,11 +793,12 @@ /types/dateformat/ @aicest /types/datejs/ @rupertavery /types/daterangepicker/ @SirMartin @smasala @nertzy +/types/dav/ @ToastHawaii /types/db-migrate-base/ @nickiannone /types/db-migrate-pg/ @nickiannone /types/db.js/ @cgwrench /types/dc/ @hansrwindhoff @mtraynham @MatthiasJobst -/types/dd-trace/ @ColinBradley +/types/dd-trace/ @ColinBradley @alloy /types/deasync/ @Sicilica /types/debessmann/ @vkorehov /types/debounce/ @denis-sokolov @@ -814,6 +844,7 @@ /types/detect-indent/ @Bartvds @BendingBender /types/detect-it/ @thomastilkema /types/detect-newline/ @BendingBender +/types/detect-node/ @LogvinovLeon /types/detect-passive-events/ @thomastilkema /types/detect-pointer/ @thomastilkema /types/detect-port/ @lith-light-g @@ -823,8 +854,10 @@ /types/df-visible/ @Litee /types/dhtmlxgantt/ @mkozhukh @chriscamicas /types/dhtmlxscheduler/ @mkozhukh +/types/di/ @johnjbarton /types/di-lite/ @dcrusader /types/diacritics/ @otociulis +/types/dialogflow/ @dyladan /types/diff/ @vvakame @szdc /types/diff2html/ @rtfpessoa /types/dir-resolve/ @andy-ms @@ -832,16 +865,18 @@ /types/discourse-sso/ @championswimmer /types/dispatchr/ @Ragg- /types/disposable-email-domains/ @geoffreak -/types/dnssd/ @angelmerino +/types/dnssd/ @angelmerino @Maxr1998 /types/doccookies/ @jonegerton /types/dockerode/ @seikho @nlaplante @isac322 @lazarusx @meisenzahl @thegecko /types/docopt/ @giggio /types/doctrine/ @rictic /types/document-promises/ @NotWoods +/types/document-ready/ @Jack-Works /types/documentdb/ @NoelAbrahams @brettferdosi @ctstone @yifanwu /types/documentdb-server/ @lith-light-g /types/documentdb-session/ @DanielRosenwasser /types/dojo/ @vansimke +/types/dom-clipboard-api/ @43081j /types/dom-inputevent/ @diagramatics /types/dom-to-image/ @JipSterk /types/dom4/ @adidahiya @giladgray @@ -902,7 +937,7 @@ /types/easy-xapi/ @DeadAlready /types/easy-xapi-utils/ @DeadAlready /types/ebongarde-root/ @Ebongarde -/types/echarts/ @xieisabug @AntiMoron @liveangela +/types/echarts/ @xieisabug @AntiMoron @liveangela @Ovilia /types/ecma-proposal-math-extensions/ @ksm2 /types/ecurve/ @mhegazy /types/ed25519/ @erikma @@ -928,19 +963,22 @@ /types/electron-settings/ @icopp @nrlquaker /types/electron-spellchecker/ @unindented /types/electron-store/ @unindented @jsynowiec +/types/electron-unhandled/ @jeremejevs /types/electron-util/ @kputh /types/electron-window-state/ @rhysd /types/electron-winstaller/ @shiftkey @unindented +/types/elegant-spinner/ @danwbyrne /types/element-ready/ @BendingBender /types/element-resize-detector/ @saranshkataria /types/element-resize-event/ @rogierschouten @plgregoire +/types/elementtree/ @dwieeb /types/elm/ @thSoft /types/email-templates/ @cyrilschumacher @gurisko @blankstar85 /types/ember/v1/ @jedmao /types/ember/ @jedmao @bttf @dwickern @chriskrycho @theroncross @mfeckie @alexlafroscia @mike-north /types/ember-data/ @dwickern @mike-north @chriskrycho /types/ember-feature-flags/ @tansongyang -/types/ember-mocha/ @dwickern +/types/ember-mocha/ @dwickern @simonihmig /types/ember-modal-dialog/ @tansongyang /types/ember-qunit/v2/ @dwickern /types/ember-qunit/ @dwickern @@ -949,7 +987,7 @@ /types/ember-testing-helpers/ @chriskrycho /types/ember__test-helpers/ @dfreeman @jamescdavis /types/emissary/ @vvakame -/types/emoji-mart/ @Kovensky +/types/emoji-mart/ @Kovensky @Nicell /types/emoji-regex/ @iKBAHT /types/emojione/ @dbrgn /types/empower/ @vvakame @@ -962,6 +1000,7 @@ /types/enquire.js/ @screendriver /types/ent/ @rogierschouten /types/entities/ @aliceklipper +/types/env-paths/ @danwbyrne /types/env-to-object/ @MugeSo /types/envify/ @tkQubo /types/enzyme/ @MarianPalkus @NoHomey @jwbay @huhuanming @MartynasZilinskas @thovden @hotell @@ -975,7 +1014,9 @@ /types/epilogue/ @micksatana /types/epub/ @julien-c /types/eq.js/ @stephenlautier +/types/error-subclass/ @fitbit /types/errorhandler/ @santialbo +/types/es-feature-detection/ @Jack-Works /types/es6-collections/ @rbuckton /types/es6-promisify/ @harryshipton @bschlenk /types/es6-shim/ @rbuckton @@ -992,12 +1033,13 @@ /types/esprima/v2/ @teppeis @RReverser /types/esprima/ @teppeis @RReverser @peter-scott /types/esprima-walk/ @tswaters -/types/espruino/ @stasberkov +/types/espruino/ @stasberkov @createdbyjurand /types/esri-leaflet/ @strajuser /types/esri-leaflet-geocoder/ @BendingBender /types/estraverse/ @sanex3339 /types/estree/ @RReverser /types/etag/ @BendingBender +/types/eth-lightwallet/ @LogvinovLeon /types/ethereum-protocol/ @LogvinovLeon /types/ethereumjs-abi/ @LogvinovLeon /types/ethereumjs-tx/ @LogvinovLeon @@ -1027,6 +1069,7 @@ /types/expect-puppeteer/ @JoshuaKGoldberg @tkrotoff /types/expect.js/ @teppeis /types/expectations/ @vvakame +/types/expired-storage/ @intolerance /types/expo/v23/ @KonstantinKai /types/expo/v24/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger /types/expo/v25/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @@ -1047,7 +1090,7 @@ /types/express-domain-middleware/ @hookclaw /types/express-ejs-layouts/ @erikma /types/express-enforces-ssl/ @kevinstubbs -/types/express-fileupload/ @Naktibalda +/types/express-fileupload/ @Naktibalda @silkimen /types/express-flash/ @iMobs /types/express-flash-2/ @mathsalmi /types/express-flash-notification/ @Mister4Eyes @@ -1077,6 +1120,7 @@ /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-xml-bodyparser/ @noticeMaker @macedigital @@ -1086,6 +1130,7 @@ /types/extract-stack/ @BendingBender /types/extract-text-webpack-plugin/ @flying-sheep @katyo /types/extract-zip/ @mizunashi-mana +/types/extsprintf/ @AlexHankins /types/eyes/ @brynbellomy /types/ez-plus/ @AndersonFriaca /types/f1/ @neolwc @@ -1138,11 +1183,13 @@ /types/fetch-mock/ @asvetliakov @tamird @merrywhether @chrissinclair @matttennison @quentinbouygues /types/fetch.io/ @newraina /types/ffi/ @loyd @waitingsong +/types/ffi-napi/ @keerthi16 @KiranNiranjan /types/ffmpeg-static/ @iamstevetran /types/ffprobe-static/ @iamstevetran /types/fhir-js-client/ @rmchndrng /types/fibers/ @soywiz /types/fibjs/ @richardo2016 +/types/figlet/ @Ailrun /types/figures/ @BendingBender /types/file-exists/ @BendingBender /types/file-saver/ @cyrilschumacher @DaIgeb @chrismbarr @@ -1155,6 +1202,8 @@ /types/finalhandler/ @chrootsu /types/finch/ @DavidSichau /types/find/ @andypyrope +/types/find-parent-dir/ @ikatyang +/types/find-project-root/ @ikatyang /types/find-root/ @Alorel /types/find-up/ @BendingBender /types/find-versions/ @LogvinovLeon @@ -1180,6 +1229,7 @@ /types/flot/ @burlandm @Anticom @admiralsmaster /types/flowjs/ @ryan10132 /types/fluent-ffmpeg/ @tcaesvk @DingWeizhe +/types/flush-write-stream/ @djcsdy /types/flux/ @stkb @GiedriusGrabauskas /types/fluxible/ @xbim /types/fluxible-router/ @xbim @@ -1192,8 +1242,8 @@ /types/forever-agent/ @yavanosta /types/forever-monitor/ @shuntksh @wrboyce /types/forge-di/ @adamcarr -/types/fork-ts-checker-webpack-plugin/ @JounQin /types/form-data/ @soywiz @leonyu @BendingBender +/types/form-serialize/ @tyler-johnson /types/form-serializer/ @flqw /types/form-urlencoded/ @alepee /types/format-duration/ @Roaders @@ -1206,6 +1256,7 @@ /types/foundation/ @borisyankov /types/fpsmeter/ @alampros /types/framebus/ @kbukum +/types/frctl__fractal/ @pmccloghrylaing /types/freedom/ @jpevarnek /types/freeport/ @atd-schubert /types/fresh/ @BendingBender @@ -1229,7 +1280,7 @@ /types/fs-promise/ @tarruda /types/fs-readdir-recursive/ @pscanf /types/fs-readfile-promise/ @mtsg -/types/fscreen/ @joscha +/types/fscreen/ @joscha @terrymun /types/fsevents/ @BendingBender /types/ftdomdelegate/ @dotnetnerd /types/ftp/ @rogierschouten @@ -1238,12 +1289,14 @@ /types/fullpage.js/ @jodiwarren /types/fusioncharts/ @rohitkr @shivarajkv /types/fuzzaldrin/ @mhegazy -/types/fuzzaldrin-plus/ @jeancroy @jkillian +/types/fuzzaldrin-plus/ @jeancroy @jkillian @reyronald /types/fuzzyset/ @lgrignon @narainsagar /types/fuzzyset.js/ @lgrignon @narainsagar /types/fxn/ @charrondev /types/gae.channel.api/ @vvakame +/types/gamedig/ @ivansieder /types/gamequery/ @Laubi +/types/ganache-core/ @LogvinovLeon /types/gandi-livedns/ @xstoudi /types/gapi/ @sgtfrankieboy /types/gapi.analytics/ @gatsbimantico @@ -1383,6 +1436,7 @@ /types/gapi.youtube/ @sgtfrankieboy /types/gapi.youtubeanalytics/ @sgtfrankieboy /types/gaussian/ @scttcper +/types/gc-stats/ @vfernandestoptal /types/geetest/ @plantain-00 /types/gen-readlines/ @CodeAnimal /types/generate-changelog/ @ffflorian @@ -1396,6 +1450,7 @@ /types/geokdbush/ @DenisCarriere /types/geometry-dom/ @nakakura /types/geopattern/ @Gaelan +/types/gestalt/ @serranoarevalo /types/get-caller-file/ @ajafff /types/get-folder-size/ @mszczepanczyk /types/get-node-dimensions/ @vincekovacs @@ -1412,6 +1467,8 @@ /types/git-branch/ @rynclark /types/git-config/ @stpettersens /types/git-remote-origin-url/ @janslow +/types/git-url-parse/ @ajafff +/types/github-url-to-object/ @ajafff /types/github-username-regex/ @BehindTheMath /types/gitlab/ @yanqing6628780 @Arylo /types/gl-matrix/ @mattijskneppers @tatchx @nbabanov @auzmartist @surtr-isaz @@ -1426,7 +1483,7 @@ /types/glob-stream/ @Bartvds @mrmlnc /types/glob-to-regexp/ @whatasoda /types/global-tunnel-ng/ @BendingBender -/types/globalize/ @gcastre @afromogli +/types/globalize/ @gcastre @afromogli @bryanforbes /types/globalize-compiler/ @iclanton /types/globby/ @douglasduteil @ikatyang /types/globule/ @durad @@ -1436,9 +1493,9 @@ /types/google-adwords-scripts/ @jafaircl /types/google-apps-script/ @motemen @grant /types/google-apps-script-oauth2/ @dhayab -/types/google-cloud__datastore/ @beaulac -/types/google-cloud__pubsub/ @pheromonez @LunaPg -/types/google-cloud__storage/ @blove @nbperry @welkie +/types/google-cloud__datastore/ @beaulac @ogawa0071 @ThomasdenH +/types/google-cloud__pubsub/ @pheromonez @LunaPg @msiviero +/types/google-cloud__storage/ @blove @nbperry @welkie @ogawa0071 /types/google-earth/ @icholy /types/google-images/ @dolanmiu /types/google-libphonenumber/ @leonyu @winfinit @@ -1451,12 +1508,13 @@ /types/google.geolocation/ @vbortone /types/google.picker/ @grapswiz /types/google.visualization/ @danludwig @gmoore-sjcorg @danmana @mlcheng @IvanBisultanov @glebm -/types/googlemaps/ @cgwrench @nertzy @xaolas @mrmcnerd @martincostello @svenkreiss @bolatovumar +/types/googlemaps/ @cgwrench @nertzy @xaolas @mrmcnerd @martincostello @svenkreiss @bolatovumar @gauthierm /types/googlemaps.infobubble/ @Dashue -/types/googlepay/ @Fluccioni +/types/googlepay/ @Fluccioni @Radu-Raicea /types/got/ @BendingBender @LinusU @ikokostya /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 @@ -1516,6 +1574,7 @@ /types/gulp-if/ @joeskeen /types/gulp-image/ @Aankhen /types/gulp-image-resize/ @Aankhen +/types/gulp-imagemin/ @romain-faust /types/gulp-inject/ @k-kagurazaka /types/gulp-insert/ @shantmarouti /types/gulp-install/ @peterjuras @@ -1523,6 +1582,7 @@ /types/gulp-jasmine/ @andypyrope /types/gulp-jasmine-browser/ @tkrotoff /types/gulp-json-editor/ @peterjuras +/types/gulp-jsonmin/ @romain-faust /types/gulp-jsonminify/ @pine /types/gulp-jspm/ @peterjuras /types/gulp-less/ @k-kagurazaka @@ -1536,6 +1596,7 @@ /types/gulp-plumber/ @joeskeen /types/gulp-protractor/ @tkrotoff /types/gulp-pug/ @remisery +/types/gulp-pug-i18n/ @romain-faust /types/gulp-remember/ @tomc974 /types/gulp-responsive-images/ @aankhen /types/gulp-rev/ @tkrotoff @@ -1549,6 +1610,7 @@ /types/gulp-svg-sprite/ @tkqubo /types/gulp-svgmin/ @Aankhen /types/gulp-task-listing/ @joeskeen +/types/gulp-template/ @pe8ter /types/gulp-tsd/ @k-kagurazaka /types/gulp-uglify/ @ChristopherHaws @leonard-thieu /types/gulp-useref/ @tkrotoff @@ -1579,10 +1641,12 @@ /types/has-ansi/ @BendingBender /types/hash-file/ @HiromiShikata /types/hash-stream/ @BendingBender +/types/hash-sum/ @DanielRosenwasser /types/hasha/ @BendgingBender /types/hasher/ @flyfishMT /types/hashids/ @pocesar /types/hashmap/ @outring +/types/hat/ @tup1tsa /types/haversine/ @screendriver /types/hbs/ @davidm77 /types/hdkey/ @LogvinovLeon @@ -1616,6 +1680,7 @@ /types/hjson/ @crunchie84 /types/hls.js/ @jgainfort /types/hoek/ @prashaantt +/types/hoist-non-react-statics/ @JounQin /types/holderjs/ @renjfk /types/hooker/ @misak113 /types/hopscotch/ @pimterry @Aurimas1 @@ -1672,6 +1737,7 @@ /types/i18next-sprintf-postprocessor/ @cyrilschumacher /types/i18next-xhr-backend/ @jamuhl @GiedriusGrabauskas /types/i2c-bus/ @101100 +/types/iarna__toml/ @ajafff /types/iban/ @cyrilschumacher /types/ibm-mobilefirst/ @nacho4d /types/ibm_db/ @agov @@ -1686,11 +1752,16 @@ /types/iframe-resizer/ @arminbaljic /types/ignite-ui/ @IgniteUI /types/ignore-styles/ @tai2 -/types/iltorb/ @Alorel +/types/iltorb/ @Alorel @reconbot /types/image-size/ @elisee /types/imagemagick/ @soywiz /types/imagemagick-native/ @horiuchi /types/imagemapster/ @delphinus35 +/types/imagemin/ @romain-faust +/types/imagemin-gifsicle/ @romain-faust +/types/imagemin-jpegtran/ @romain-faust +/types/imagemin-optipng/ @romain-faust +/types/imagemin-svgo/ @romain-faust /types/images/ @DingWeizhe /types/imagesloaded/ @coldacid @apexskier /types/imap/ @psnider @@ -1712,11 +1783,10 @@ /types/iniparser/ @chrootsu /types/inline-css/ @philipisapain /types/inline-style-prefixer/ @ahz @dpetrezselyova -/types/inquirer/ @tkQubo @ppathan @jouderianjr @bang88 @bitjson @synarque @jrockwood @kwkelly +/types/inquirer/ @tkQubo @ppathan @jouderianjr @bang88 @bitjson @synarque @jrockwood @kwkelly @Ailrun /types/insert-module-globals/ @leonard-thieu /types/insight/ @vvakame /types/integer/ @Morfent -/types/interact.js/ @dduugg @adidahiya @thasner /types/intercom-client/ @jineshshah36 @peping /types/intercom-web/ @fongandrew @salbahra @onatm /types/intercomjs/ @spencerwi @@ -1724,16 +1794,20 @@ /types/intl/ @RagibHasin /types/intl-locales-supported/ @Slessi /types/intl-messageformat/ @mhegazy +/types/intl-relativeformat/ @mohsen1 /types/intl-tel-input/ @fdnhkj @leonard-thieu /types/into-stream/ @BendingBender +/types/intrinsic-scale/ @shalomdotnet /types/intro.js/ @anahkiasen /types/invariant/ @bennett000 /types/inversify-devtools/ @inversify /types/ion-rangeslider/v1/ @dduugg @Karel-van-de-Plassche /types/ion-rangeslider/ @Karel-van-de-Plassche -/types/ioredis/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 +/types/ioredis/v3/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot +/types/ioredis/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot /types/iota.lib.js/ @fogsh /types/ip/ @codeanimal +/types/ip-address/ @danwbyrne /types/ip-regex/ @unindented /types/ipcheck/ @bengry /types/irc/ @phillips1012 @@ -1744,6 +1818,7 @@ /types/is-archive/ @mhegazy /types/is-array/ @pine /types/is-binary-path/ @DanielRosenwasser +/types/is-callable/ @nieltg /types/is-ci/ @atd-schubert /types/is-color/ @VitorLuizC /types/is-compressed/ @mhegazy @@ -1763,6 +1838,7 @@ /types/is-relative-url/ @mhegazy /types/is-root/ @mhegazy /types/is-root-path/ @mhegazy +/types/is-running/ @danwbyrne /types/is-scoped/ @postcrafter /types/is-stream/ @me /types/is-svg/ @BendingBender @@ -1770,6 +1846,7 @@ /types/is-touch-device/ @screendriver /types/is-url/ @RyotaMurohoshi /types/is-url-superb/ @kryops +/types/is-uuid/ @tedre191 /types/is-windows/ @mizunashi-mana /types/isbn-utils/ @elhaard /types/iscroll/ @csrakowski @devlato @@ -1805,7 +1882,7 @@ /types/jasmine-promise-matchers/ @matthewjh /types/jasmine_dom_matchers/ @devoto13 /types/jasminewd2/ @sjelin -/types/java/ @jimlloyd @hrl7 +/types/java/ @jimlloyd @hrl7 @darti /types/java-applet/ @cyrilschumacher /types/javascript-astar/ @ptlis /types/javascript-bignum/ @sandersn @@ -1816,7 +1893,7 @@ /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 +/types/jest/ @NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang @wsmd @JamieMason @douglasduteil @ahnpnl @joshuakgoldberg @UselessPickles @r3nya @hotell @sebald /types/jest-axe/ @JoshuaKGoldberg /types/jest-diff/ @myabc /types/jest-docblock/ @ikatyang @@ -1830,7 +1907,9 @@ /types/jest-matchers/ @joscha /types/jest-specific-snapshot/ @dawnmist /types/jest-validate/ @ikatyang +/types/jexl/ @m-tomczyk /types/jfs/ @tlaziuk +/types/jira-client/ @KOPTE3 @orta /types/jjv/ @Nemo157 /types/jjve/ @Nemo157 /types/jmespath/ @pushplay @@ -1887,7 +1966,7 @@ /types/jquery-sticky/ @maixiu /types/jquery-tags-input/ @AndersonFriaca /types/jquery-timeentry/ @marknadig -/types/jquery-toast-plugin/ @viqashussain +/types/jquery-toast-plugin/ @viqashussain @astegmaier /types/jquery-toastmessage-plugin/ @joeskeen /types/jquery-truncate-html/ @abraaoalves /types/jquery-urlparam/ @stpettersens @@ -1994,6 +2073,7 @@ /types/jsesc/ @Bartvds /types/jsfl/ @soywiz /types/jsforce/ @dolanmiu @netes @amphro @tnoonan-salesforce @whiteabelincoln +/types/jsgraph/ @rosinbum /types/jshamcrest/ @dharkness /types/jsmockito/ @shiver-me-timbers /types/jsnox/ @stkb @DovydasNavickas @@ -2005,15 +2085,16 @@ /types/json-pointer/ @Bartvds /types/json-query/ @mtraynham /types/json-rpc-ws/ @npenin @mlamp -/types/json-schema/ @bcherny @cyrilletuzi @lucianbuzzo +/types/json-schema/ @bcherny @cyrilletuzi @lucianbuzzo @rolandjitsu /types/json-socket/ @svi3c /types/json-stable-stringify/ @mhfrantz /types/json-stringify-safe/ @BendingBender /types/json2csv/ @juanjoDiaz /types/json2md/ @MartynasZilinskas /types/json3/ @NN--- +/types/json5/ @Esemesek /types/jsonata/ @nick121212 -/types/jsoneditor/ @alejo90 +/types/jsoneditor/ @alejo90 @errietta /types/jsoneditor-for-react/ @joshuakgoldberg /types/jsoneditoronline/ @vbortone /types/jsonfile/ @dbowring @@ -2037,7 +2118,7 @@ /types/jsreport-phantom-pdf/ @taoqf /types/jsreport-xlsx/ @taoqf /types/jsrp/ @harryshipton -/types/jss/ @appsforartists @kof @pelotom +/types/jss/ @appsforartists @kof @pelotom @eps1lon /types/jssha/ @randombk @SrTobi /types/jstimezonedetect/ @olamothe /types/jstorage/ @dflor003 @@ -2089,7 +2170,7 @@ /types/klaw/ @mceachen /types/klaw-sync/ @shiftkey /types/kms-json/ @sunnyone -/types/knex/ @tkQubo @baronfel @MeLlamoPablo @mastermatt @micksatana @shreyjain1994 +/types/knex/ @tkQubo @MeLlamoPablo @mastermatt @micksatana @shreyjain1994 /types/knex-postgis/ @vesse /types/knockback/ @borisyankov /types/knockout/ @borisyankov @Igorbek @moonpyk @EnableSoftware @BenjaminEckardt @ffMathy @@ -2112,18 +2193,22 @@ /types/ko.plus/ @conficient /types/koa/ @DavidCai1993 @jkeylu @brikou /types/koa-basic-auth/ @Tobias4872 +/types/koa-better-body/ @danwbyrne /types/koa-bodyparser/ @hellopao @anup-2s /types/koa-cache-control/ @pe8ter /types/koa-compose/ @jkeylu /types/koa-compress/ @hellopao /types/koa-conditional-get/ @wingsbob +/types/koa-convert/ @danwbyrne +/types/koa-cors/ @romain-faust /types/koa-csrf/ @haskaalo /types/koa-etag/ @wingsbob /types/koa-favicon/ @hellopao /types/koa-generic-session/ @nsimmons @Ragg- /types/koa-hbs/ @jcbmln @mudkipme /types/koa-helmet/ @me -/types/koa-joi-router/ @wingsbob +/types/koa-html-minifier/ @romain-faust +/types/koa-joi-router/ @wingsbob @move-zig /types/koa-json/ @brooklyndev /types/koa-json-error/ @mudkipme /types/koa-logger/ @geoffreak @tlaziuk @@ -2136,9 +2221,10 @@ /types/koa-pug/ @Xstoudi /types/koa-range/ @strax /types/koa-redis/ @nsimmons -/types/koa-response-time/ @thorsedeke +/types/koa-redis-cache/ @dimamukhin +/types/koa-response-time/ @thorsedeke @sjmcdowall /types/koa-route/ @migstopheles @jacogr -/types/koa-router/ @hellopao @schfkt @JounQin +/types/koa-router/ @hellopao @schfkt @JounQin @romain-faust /types/koa-send/ @pe8ter @tlaziuk /types/koa-session/ @kerol2r20 @tlaziuk /types/koa-session-minimal/ @longztian @@ -2147,10 +2233,11 @@ /types/koa-static-cache/ @JounQin /types/koa-views/ @brooklyndev /types/koa-webpack/ @malj @leebenson @miZyind @tlaziuk -/types/koa-websocket/ @moimael @jacogr +/types/koa-websocket/ @moimael @jacogr @zdila /types/koa-xml-body/ @uwinkelvos /types/koa2-cors/ @xialeistudio -/types/koa__cors/ @Xstoudi @izayoiko @stevehipwell +/types/koa2-session-redis/ @DimaMukhin +/types/koa__cors/ @Xstoudi @izayoiko @stevehipwell @sjmcdowall /types/kolite/ @borisyankov /types/konami.js/ @mareek /types/kraken-js/ @darkwebdev @micksatana @@ -2206,11 +2293,12 @@ /types/less2sass/ @gatimus /types/lestate/ @thelambdaparty /types/level-sublevel/ @basp -/types/leveldown/ @tarruda +/types/leveldown/ @tarruda @LinusU /types/levelup/ @blittle @tarruda /types/leven/ @jmalonzo /types/levenshtein/ @geoffreak /types/libpq/ @Lodin +/types/libsodium-wrappers/ @ffflorian /types/libxmljs/ @fdecampredon @ComFreek /types/libxslt/ @alejo90 /types/license-checker/ @rogierschouten @unindented @@ -2218,6 +2306,7 @@ /types/lime-js/ @arthur-xavier /types/line-by-line/ @etomsen /types/line-reader/ @stpettersens +/types/linear-gradient/ @Jack-Works /types/lingui__core/ @huan086 /types/lingui__react/ @huan086 /types/linkify-it/ @praxxis @@ -2230,6 +2319,7 @@ /types/loadware/ @ALyman /types/lobibox/ @itboy87 /types/local-dynamo/ @Sicilica +/types/local-storage/ @tup1tsa /types/localized-countries/ @coderslagoon /types/localizejs-library/ @salbahra /types/locate-path/ @me @@ -2566,12 +2656,15 @@ /types/main-bower-files/ @k-kagurazaka /types/make-dir/ @ikatyang @BendingBender /types/maker.js/ @danmarshall +/types/mali/ @danwbyrne /types/mandrill-api/ @pocesar /types/map-obj/ @BendingBender /types/mapbox/ @anahkiasen /types/mapbox-gl/ @dobrud @patrickr /types/mapbox-gl-leaflet/ @agorshkov23 +/types/mapbox__geo-viewport/ @fnberta /types/mapbox__geojson-area/ @n0nick +/types/mapbox__polyline/ @Kern0 @mklopets /types/mapbox__shelf-pack/ @Perlmint /types/mapnik/ @ipv4sec /types/mapsjs/ @davismj @@ -2580,6 +2673,7 @@ /types/markdown-it/ @rapropos /types/markdown-it-anchor/ @seryl /types/markdown-it-container/ @hronex +/types/markdown-pdf/ @MonsieurMan /types/markdownlint/ @ark120202 /types/marked/ @worr @BendingBender @CrossR /types/marker-animate-unobtrusive/ @viskin @@ -2639,6 +2733,7 @@ /types/mem-fs/ @MyFoodBag /types/mem-fs-editor/ @MyFoodBag /types/memcached/ @KentarouTakeda +/types/memjs/ @leizongmin /types/memoize-one/ @karol-majewski @franklixuefei /types/memoizee/ @juanpicado /types/memory-cache/ @jedigo @thieman @@ -2646,7 +2741,7 @@ /types/memwatch-next/ @cyrilschumacher /types/meow/ @KnisterPeter @praxxis @bitjson /types/merge-descriptors/ @danny8002 -/types/merge-stream/ @k-kagurazaka @daniel-zazula +/types/merge-stream/ @k-kagurazaka @tomxtobin @daniel-zazula @djcsdy /types/merge2/ @tkrotoff @smac89 /types/merkle/ @kerol2r20 /types/mermaid/ @ggilmore @@ -2662,7 +2757,7 @@ /types/meteor-prime8consulting-oauth2/ @vangorra /types/meteor-publish-composite/ @vangorra /types/meteor-roles/ @vangorra @mattmm3d -/types/meteor-univserse-i18n/ @mathewmeconry +/types/meteor-universe-i18n/ @mathewmeconry /types/method-override/ @santialbo /types/methods/ @cprecioso /types/metric-suffix/ @davidm77 @@ -2685,6 +2780,7 @@ /types/mimos/ @AJamesPhillips /types/mina/ @lhk @mattanja @kant2002 /types/mini-css-extract-plugin/ @JounQin +/types/minimal-bit-array/ @jeremejevs /types/minimatch/ @vvakame @shantmarouti /types/minimist/ @Bartvds @Necroskillz @kamranayub /types/minimist-options/ @ikatyang @@ -2728,13 +2824,14 @@ /types/moment-shortformat/ @whatasoda /types/moment-strftime2/ @dex4er /types/moment-timezone/ @michelsalib @alanblins +/types/money-math/ @taoqf /types/mongo-sanitize/ @CedricCazin -/types/mongodb/v2/ @CaselIT @alanmarcell @kikar @bitjson @dante-101 @mcortesi -/types/mongodb/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi @EnricoPicci @AJCStriker @julien-c @daprahamian @denys-bushulyak @BastienAr @sindbach +/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 /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 +/types/mongoose/ @horiuchi @sindrenm @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @jussikinnula @ondratra @alfirin @idandrd /types/mongoose-auto-increment/ @AyaMorisawa /types/mongoose-deep-populate/ @AyaMorisawa /types/mongoose-geojson-schema/ @bondz @@ -2751,7 +2848,7 @@ /types/morgan/ @staticfunction @pscanf /types/morphdom/ @arvitaly /types/morris.js/ @mareek @sindilevich -/types/mosca/ @GabrielGouv +/types/mosca/ @GabrielGouv @jerray /types/motor-hat/ @muntyan /types/mousetrap/ @qcz /types/move-concurrently/ @mgroenhoff @@ -2788,13 +2885,14 @@ /types/mv/ @nenadalm /types/mysql/ @wjohnsto @kacepe @kpping @jdmunro /types/mz/ @ThomasHickman -/types/n3/ @phreed +/types/n3/ @phreed @rubensworks /types/named-regexp-groups/ @jewbre /types/named-routes/ @qqilihq /types/nano/ @timjacobi @vincekovacs /types/nanoajax/ @nathancahill +/types/nanoevents/ @nju33 /types/nanographql/ @cdaringe -/types/nanoid/ @bash +/types/nanoid/ @bash @fadezhanger /types/nanomsg/ @titan /types/nanoscroller/ @zihark17 /types/nanp/ @karn @@ -2819,6 +2917,7 @@ /types/negotiator/ @BendingBender /types/neo4j/ @cyrilschumacher /types/nes/ @NoHomey @saboya +/types/nested-error-stacks/ @woutervh- /types/net-keepalive/ @hertzg /types/netmask/ @mhfrantz /types/network-interfaces/ @anderswestberg @@ -2828,7 +2927,7 @@ /types/newrelic/ @mastermatt /types/nexpect/ @vvakame /types/next/ @dru89 @brikou @jthegedus @resir014 @scottdj92 @joaovieira -/types/next-redux-wrapper/ @stevegeek +/types/next-redux-wrapper/ @stevegeek @Jungwoo-An /types/ng-command/ @stephenlautier /types/ng-cordova/ @ksachdeva /types/ng-dialog/ @stephenlautier @@ -2861,8 +2960,8 @@ /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 -/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 +/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 @matthieusieben /types/node-7z/ @erkie /types/node-array-ext/ @Beng89 /types/node-cache/ @chrootsu @dthunell @useltmann @@ -2875,7 +2974,7 @@ /types/node-emoji/ @jonestristand @styu /types/node-fetch/ @torstenwerner @nikcorg /types/node-fibers/ @caryhaynie -/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 +/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung /types/node-gcm/ @horiuchi /types/node-geocoder/ @rosek86 /types/node-getopt/ @kcauchy @@ -2911,6 +3010,7 @@ /types/node-xmpp-core/ @PJakcson /types/node-zookeeper-client/ @plantain-00 @jessezhang91 /types/node-zopfli/ @Alorel +/types/node-zopfli-es/ @Alorel /types/node_redis/ @borisyankov /types/nodecredstash/ @migstopheles /types/nodegit/ @dolanmiu @tniessen @@ -2941,15 +3041,15 @@ /types/npm/ @SomaticIT /types/npm-package-arg/ @mgroenhoff /types/npm-packlist/ @ajafff -/types/npmlog/ @DanielMSchmidt +/types/npmlog/ @DanielMSchmidt @littlepiggy03 /types/ns-api/ @Archcry /types/nslog/ @unindented /types/nsqjs/ @cezaryrk /types/nuka-carousel/ @Romic /types/number-is-nan/ @mhegazy /types/number-to-words/ @frederickfogerty -/types/numeral/ @vbortone -/types/numjs/ @taoqf +/types/numeral/ @vbortone @BehindTheMath @klujanrosas +/types/numjs/ @taoqf @mattmm3d /types/nunjucks/ @RubenSlabbert /types/nunjucks-date/ @kruncher /types/nvd3/ @PjMitchell @@ -2958,7 +3058,7 @@ /types/o.js/ @IceOnFire @bradzacher @janhommes @jcchalte /types/oauth/ @nonAlgebraic /types/oauth.js/ @nobuoka -/types/oauth2-server/ @vangorra @cirick +/types/oauth2-server/ @vangorra @cirick @d-fischer /types/oauth2orize/ @wokim @heycalmdown @stevehipwell /types/obelisk.js/ @bdrupieski /types/obj-file-parser/ @benc-uk @@ -2966,10 +3066,12 @@ /types/object-diff/ @rogierschouten /types/object-hash/ @misak113 /types/object-inspect/ @demurgos +/types/object-keys/ @VitorLuizC /types/object-map/ @wolfgang42 /types/object-merge/ @OpenByteDev /types/object-path/ @pocesar /types/object-refs/ @3fd +/types/object.getownpropertydescriptors/ @VitorLuizC /types/oblo-util/ @Oblosys /types/oboe/ @optical /types/observe-js/ @herrmanno @@ -2980,8 +3082,10 @@ /types/offline-js/ @cgwrench /types/oibackoff/ @geoffreak /types/oidc-token-manager/ @rosieks +/types/oja/ @buffcode /types/okta__okta-vue/ @innovation-team /types/ol/ @yairtawil +/types/omggif/ @ffflorian /types/on-finished/ @czechboy0 @BendingBender /types/on-headers/ @jjeffery @BendingBender /types/once/ @denis-sokolov @BendingBender @@ -2996,7 +3100,7 @@ /types/openjscad/ @danmarshall /types/openlayers/v2/ @bolhovsky /types/openlayers/v3/ @osechet @matthiasdailey-ccri -/types/openlayers/ @osechet @wb14123 @ailrun @mylen @iamthechad @danmana @yairtawil @pierremarc @hauke96 +/types/openlayers/ @osechet @wb14123 @ailrun @mylen @iamthechad @danmana @yairtawil @pierremarc @hauke96 @gberaudo /types/openpgp/ @errietta /types/openstack-wrapper/ @sanjaymadane /types/opentok/ @westy92 @CatGuardian @@ -3005,7 +3109,7 @@ /types/optics-agent/ @crevil /types/optimist/ @soywiz @chbrown /types/optimize-css-assets-webpack-plugin/ @odnamrataizem -/types/ora/v0/ @screendriver +/types/ora/v0/ @basarat @screendriver /types/ora/ @basarat @screendriver @BendingBender @azasypkin /types/oracledb/ @Bigous /types/orchestrator/ @tkQubo @TeamworkGuy2 @@ -3061,11 +3165,13 @@ /types/package-json/ @jinwoo /types/packery/ @piraveen @hanssens /types/pad/ @mhegazy +/types/page/ @43081j /types/paho-mqtt/ @amikhalev /types/pako/ @cappellin @calebegg /types/pangu/ @plantain-00 -/types/papaparse/ @torpedro @rainshen49 @jfloff @johnnyreilly @albertorestifo -/types/paper/ @clark-stevenson @Xakaloz @sebaswebdev +/types/papaparse/ @torpedro @rainshen49 @jfloff @johnnyreilly @albertorestifo @BehindTheMath @3af +/types/paper/ @clark-stevenson @Xakaloz @sebaswebdev @rfried +/types/parallel-transform/ @djcsdy /types/paralleljs/ @jbaldwin /types/parcel-env/ @fathyb /types/parent-package-json/ @sgmccli @@ -3074,6 +3180,7 @@ /types/parity-poe/ @leovujanic /types/parse/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas /types/parse-git-config/ @leonard-thieu @deltaidea +/types/parse-github-url/ @ajafff /types/parse-glob/ @glen-84 /types/parse-json/ @mrmlnc /types/parse-link-header/ @zelein @@ -3089,11 +3196,13 @@ /types/parse5-plain-text-conversion-stream/ @inikulin /types/parse5-sax-parser/ @inikulin /types/parse5-serializer-stream/ @inikulin +/types/parsecurrency/ @cristianrgreco /types/parseurl/ @bomret /types/parsimmon/ @Bartvds @mizunashi-mana @bcherny @bvanreeven @leonard-thieu @MrJohz /types/passport/ @horiuchi @enaeseth @theigor @tlaziuk @danielpa9708 /types/passport-anonymous/ @0x6368656174 /types/passport-beam/ @AtlasDev +/types/passport-cognito/ @mbutsykin /types/passport-discord/ @kzay /types/passport-facebook/ @staticfunction @lucasmacosta /types/passport-facebook-token/ @rmartone @mrand01 @@ -3111,7 +3220,7 @@ /types/passport-oauth2/ @pasieronen @WangZishi /types/passport-oauth2-client-password/ @akaNightmare /types/passport-remember-me-extended/ @AylaJK -/types/passport-saml/ @cjbarth +/types/passport-saml/ @cjbarth @dassennato /types/passport-steam/ @kzay /types/passport-strategy/ @liorm /types/passport-twitter/ @staticfunction @@ -3130,6 +3239,7 @@ /types/paypal-cordova-plugin/ @Justin-Credible /types/paypal-rest-sdk/ @trainerbill /types/pbf/ @cschwarz +/types/pbkdf2/ @timonegk /types/pdfjs-dist/ @jbaldwin /types/pdfkit/ @erichillah /types/pdfmake/ @m1llen1um @radziksh @@ -3147,6 +3257,7 @@ /types/pg-ears/ @bradleyayers /types/pg-escape/ @khell /types/pg-format/ @zopf +/types/pg-large-object/ @mateuszkrupa /types/pg-pool/ @aleung /types/pg-query-stream/ @asmarques /types/pg-types/ @waratuman @@ -3168,20 +3279,21 @@ /types/pick-weight/ @rsxdalv /types/pickadate/ @theodorejb @leonard-thieu /types/picturefill/ @alaz -/types/pidusage/ @cyrilschumacher +/types/pidusage/ @cyrilschumacher @mx601595686 /types/pify/ @samverschueren @mad-mike @c7hm4r /types/pigpio/ @manerfan /types/pikaday/ @MidnightDesign @wake42 /types/pikaday-time/ @Sayan751 /types/pinkyswear/ @chances /types/pino/v3/ @psnider -/types/pino/ @psnider @BendingBender @screendriver +/types/pino/ @psnider @BendingBender @screendriver @paambaati /types/pino-multi-stream/ @JakeGinnivan /types/pinterest-sdk/ @adamburmister /types/pinyin/ @wanganjun /types/piwik-tracker/ @lbguilherme /types/pixelmatch/ @iamolegga /types/pixi.js/ @clark-stevenson +/types/pkg-conf/ @jorgegonzalez /types/pkg-dir/ @NK-WEB-Git /types/pkijs/ @microshine /types/platform/ @JakeH @@ -3189,12 +3301,13 @@ /types/playerframework/ @ricardosabino /types/playmusic/ @nickp10 /types/pleasejs/ @nakakura -/types/plotly.js/ @chrisgervang @martinduparc @frederikaalund @taoqf @Dadstart @szechyjs @MercifulCode @soorajpudiyadath +/types/plotly.js/ @chrisgervang @martinduparc @frederikaalund @taoqf @Dadstart @szechyjs @MercifulCode @soorajpudiyadath @jonfreedman @meganrm /types/plugapi/ @BNedry /types/plugin-error/ @rogierschouten /types/plupload/ @patrickbussmann /types/pluralize/ @ukyo @karol-majewski /types/png-async/ @kanreisa +/types/png.js/ @ffflorian /types/pngjs/ @jason0x43 /types/pngquant-bin/ @hikoma /types/podcast/ @nikeee @@ -3227,7 +3340,7 @@ /types/pouchdb-mapreduce/ @spaulg @geppy @fredgalvao /types/pouchdb-node/ @spaulg @geppy @fredgalvao /types/pouchdb-replication/ @trubit @tiangolo -/types/pouchdb-upsert/ @keithdmoore @hotforfeature @apolkingg8 +/types/pouchdb-upsert/ @keithdmoore @hotforfeature @apolkingg8 @zamb3zi /types/power-assert/ @vvakame /types/power-assert-formatter/ @vvakame /types/powerbi-visuals-tools/ @zBritva @Microsoft @@ -3239,7 +3352,7 @@ /types/pretty-bytes/v4/ @plantain-00 /types/pretty-bytes/ @plantain-00 @danielasy /types/pretty-format/ @ikatyang -/types/pretty-ms/ @BendingBender +/types/pretty-ms/ @BendingBender @ocboogie /types/printf/ @AluisioASG /types/priorityqueuejs/ @geoffreak /types/prismic-dom/ @nickw444 @sbilstein @@ -3270,7 +3383,7 @@ /types/prompt-sync/ @MugeSo /types/prompt-sync-history/ @MugeSo /types/promptly/ @danrspencer -/types/prop-types/ @DovydasNavickas +/types/prop-types/ @DovydasNavickas @ferdaber /types/proper-lockfile/ @qlonik /types/properties-reader/ @Goldsmith42 /types/prosemirror-collab/ @bradleyayers @davidka @timjb @patsimm @@ -3320,6 +3433,7 @@ /types/q-io/ @Bartvds /types/q-retry/ @vilic /types/qhistory/ @Kovensky +/types/qiniu-js/ @taoqf /types/qlik/ @RubenSlabbert @AginicX /types/qlik-engineapi/ @konne /types/qlik-visualizationextensions/ @konne @@ -3331,18 +3445,18 @@ /types/query-string/ @SamVerschueren @tkrotoff @huhuanming @MadaraUchiha @shssoichiro /types/querystringify/ @ilich /types/quick-lru/ @BendingBender -/types/quill/ @sumitkm @guillaume-ro-fr @43081j @AnielloFalcone +/types/quill/ @sumitkm @guillaume-ro-fr @43081j @AnielloFalcone @mhamri /types/quixote/ @greybax /types/qunit/v1/ @diullei -/types/qunit/ @waratuman +/types/qunit/ @waratuman @mike-north /types/qunit-dom/ @happycollision /types/quoted-printable/ @pushplay /types/qwest/ @lindsayevans /types/r-script/ @NaridaL /types/rabbit.js/ @wokim -/types/radium/ @alexgorbatchev @nupplaphil @asvetliakov @mihe +/types/radium/ @alexgorbatchev @nupplaphil @asvetliakov /types/radius/ @codeanimal -/types/ramda/ @donnut @tycho01 @mdekrey @mrdziuban @sbking @afharo @teves-castro @1M0reBug @hojberg @charlespwd @samsonkeung @angeloocana @raynerd @googol @moshensky @ethanresnick @leighman @CaptJakk @deftomat @deptno @blimusiek @biern @rayhaneh +/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/random-js/ @pistacchio /types/random-number/ @OpenByteDev /types/random-seed/ @endel @@ -3370,28 +3484,32 @@ /types/rbac-a/ @tlaziuk /types/rc/ @DanielRosenwasser /types/rc-select/ @DenisTirilis -/types/rc-slider/ @mantasmarcinkus @mattoni @paustint @j-fro +/types/rc-slider/ @mantasmarcinkus @mattoni @paustint @j-fro @Deanna2 /types/rc-tree/ @johnnyreilly @Methuselah96 /types/rcloader/ @panuhorsmalahti /types/rdf-data-model/ @rubensworks /types/rdf-js/ @rubensworks +/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 +/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-alice-carousel/ @endigo /types/react-amplitude/ @rayzor65 /types/react-animate-on-scroll/ @ralbuque /types/react-app/ @prakarshpandey /types/react-aria-menubutton/ @forabi @crohlfs +/types/react-aria-modal/ @forabi /types/react-autocomplete/ @lstanden /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-big-calendar/ @piotrwitek @paustint @pikpok @eps1lon /types/react-body-classname/ @mhegazy -/types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @mretolaza @katbusch @vitosamson @LKay @aaronbeall @jrakotoharisoa @r3nya +/types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @mretolaza @katbusch @vitosamson @LKay @aaronbeall @jrakotoharisoa @r3nya @t49tran /types/react-bootstrap-date-picker/ @LKay @ssi-hu-antal-bodnar /types/react-bootstrap-daterangepicker/ @ianks /types/react-bootstrap-table/v2/ @flaub @alelode @UJosue10 @@ -3415,7 +3533,7 @@ /types/react-content-loader/ @alaatm @samwalshnz /types/react-copy-to-clipboard/ @mabels @BernabeFelix /types/react-copy-write/ @samhh @davej -/types/react-credit-cards/ @vstrimaitis +/types/react-credit-cards/ @vstrimaitis @olefrank /types/react-cropper/ @stepancar /types/react-css-modules/ @KostyaEsmukov @skirsdeda /types/react-css-transition-replace/ @LKay @@ -3429,17 +3547,16 @@ /types/react-daterange-picker/ @uncovertruth @MartynasZilinskas /types/react-dates/ @ArturAmpilogov @NathanNZ /types/react-daum-postcode/ @Sa-ryong -/types/react-dnd-html5-backend/ @oizie -/types/react-dnd-multi-backend/ @dawnmist -/types/react-dnd-test-backend/ @gustavohenke -/types/react-dnd-touch-backend/ @mleko @dawnmist +/types/react-dnd-multi-backend/ @dawnmist @beeequeue +/types/react-dnd-touch-backend/ @mleko @dawnmist @beeequeue /types/react-document-title/ @cleverguy25 /types/react-dom/v15/ @MartynasZilinskas /types/react-dom/ @MartynasZilinskas @theruther4d /types/react-dom-factories/ @jgoz +/types/react-dragtastic/ @nscarcella /types/react-dropzone/v2/ @matdube @LynxEyes @goblindegook @benbayard /types/react-dropzone/v3/ @matdube @LynxEyes @goblindegook @benbayard @LKay -/types/react-dropzone/ @matdube @LynxEyes @goblindegook @benbayard @LKay @codeaid @jurosh +/types/react-dropzone/ @matdube @LynxEyes @goblindegook @benbayard @LKay @codeaid @jurosh @ekilah /types/react-dynamic-number/ @eugrdn /types/react-easy-chart/ @danzel /types/react-event-listener/ @asvetliakov @@ -3448,6 +3565,7 @@ /types/react-faux-dom/ @alitaheri @cleverguy25 @deviousm @hanai /types/react-file-input/ @dmitryrogozhny /types/react-file-reader-input/ @dmitryrogozhny @alitaheri +/types/react-flag-icon-css/ @jonfreedman /types/react-flags-select/ @senukartur /types/react-flatpickr/ @begincalendar /types/react-flex/ @pushplay @@ -3468,14 +3586,15 @@ /types/react-helmet/v4/ @evanbb @isman-usoh /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-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 -/types/react-i18next/ @GiedriusGrabauskas @chnoch @beheh +/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 @@ -3483,10 +3602,12 @@ /types/react-imageloader/ @stephenjelfs /types/react-infinite/ @rhysd /types/react-infinite-calendar/ @christianchown -/types/react-infinite-scroll-component/ @sroy3 +/types/react-infinite-scroll-component/ @sroy3 @burtek @davidkevork /types/react-infinite-scroller/ @Lapanti @psrebniak +/types/react-input-autosize/ @jsonunger @franklixuefei /types/react-input-calendar/ @stepancar -/types/react-input-mask/ @apare +/types/react-input-mask/v1/ @apare +/types/react-input-mask/ @apare @dima7a14 /types/react-intl/v1/ @bgrieder /types/react-intl/ @bgrieder @cdroulers @gyzerok @tillwolff @LKay @bhouser @kristerkari @formatlos /types/react-intl-redux/ @LKay @@ -3505,7 +3626,7 @@ /types/react-loadable/ @Kovensky @odensc @ianks @tlaziuk @iMobs /types/react-loader/ @artfuldev /types/react-mailchimp-subscribe/ @osdiab -/types/react-map-gl/ @rimig +/types/react-map-gl/ @rimig @fnberta /types/react-maskedinput/ @LKay @lavoaster @CarlosBonetti /types/react-mce/ @morphologue /types/react-mdl/ @bradzacher @@ -3515,16 +3636,18 @@ /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 +/types/react-native/ @alloy @huhuanming @iRoachie @timwangdev @kamal @nelyousfi @alexdunne @swissmanu @bm-software @tkrotoff @a-tarasyuk @mvdam /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-communications/ @huhuanming @PaitoAnderson /types/react-native-custom-tabs/ @philnova /types/react-native-datepicker/ @jacobbaskin /types/react-native-dialog/ @MrLuje +/types/react-native-dialogflow/ @jasonmerino /types/react-native-doc-viewer/ @iRoachie /types/react-native-document-picker/ @plantain-00 /types/react-native-drawer/ @jnbt @suniahk @@ -3549,6 +3672,7 @@ /types/react-native-mixpanel/ @r3nya /types/react-native-modalbox/ @iRoachie /types/react-native-multi-slider/ @Slessi +/types/react-native-navbar/ @ryokik /types/react-native-orientation/ @MoLow /types/react-native-permissions/ @vincentlanglet /types/react-native-photo-view/ @christianchown @@ -3560,7 +3684,7 @@ /types/react-native-sensor-manager/ @SahinVardar /types/react-native-settings-list/ @MrLuje /types/react-native-share/ @marknelissen -/types/react-native-snap-carousel/ @jnbt @j-fro @gazaret +/types/react-native-snap-carousel/ @jnbt @j-fro @gazaret @VitorLuizC /types/react-native-sortable-grid/ @j-fro /types/react-native-sortable-list/ @sivolobov @RookY2K /types/react-native-sqlite-storage/ @dryganets @cavarzan @@ -3577,23 +3701,29 @@ /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 +/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 +/types/react-navigation-material-bottom-tabs/ @iRoachie +/types/react-no-ssr/ @rafalfilipek /types/react-notification-system/ @GiedriusGrabauskas @DeividasBakanas @LKay @sztobar /types/react-notification-system-redux/ @LKay /types/react-notify-toast/ @klaascuvelier -/types/react-numeric-input/ @heatherbooker +/types/react-numeric-input/ @heatherbooker @akx /types/react-onclickoutside/v5/ @LKay /types/react-onclickoutside/ @LKay /types/react-onsenui/ @salim7 @jemmyw /types/react-overlays/ @aaronbeall @vitosamson /types/react-owl-carousel/ @tbounsiar @igorissen @KennethanCeyer -/types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold +/types/react-paginate/v4/ @deevus @wouterhardeman @pegel03 @archy-bold +/types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke /types/react-places-autocomplete/ @guilhermehubner @r3nya +/types/react-plotly.js/ @jonfreedman /types/react-pointable/ @istefo @mdibyo /types/react-popover/ @jacoporicare -/types/react-portal/ @shuntksh +/types/react-portal/v3/ @shuntksh +/types/react-portal/ @shuntksh @HorusGoul /types/react-primitives/ @aghoneim92 /types/react-props-decorators/ @tkqubo +/types/react-qr-reader/ @davidkevork /types/react-radio-group/ @jsonunger /types/react-recaptcha/ @mhegazy @zzanol /types/react-redux/v5/ @tkqubo @thasner @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva @@ -3601,8 +3731,9 @@ /types/react-redux-epic/ @forabi /types/react-redux-i18n/ @clementdevos /types/react-redux-toastr/ @Smiche @artyomsv @kulmajaba -/types/react-relay/ @graphcool @voxmatt @alloy @npirotte @ckknight -/types/react-resize-detector/ @matthew-matvei @aMoniker +/types/react-relay/ @graphcool @voxmatt @alloy @npirotte @ckknight @kastermester +/types/react-request/ @dannycochran +/types/react-resize-detector/ @matthew-matvei @aMoniker @rdrgn /types/react-resolver/ @forabi /types/react-responsive/v1/ @asvetliakov /types/react-responsive/ @asvetliakov @alechill @xaviergonz @@ -3613,6 +3744,7 @@ /types/react-router-bootstrap/ @vlesierse @LKay @olmobrutall /types/react-router-config/ @lith-light-g /types/react-router-dom/ @tkrotoff @huy-nguyen @p-jackson +/types/react-router-hash-link/ @zoompie /types/react-router-native/ @ezintz @fhelwanger /types/react-router-navigation/ @kaoDev /types/react-router-navigation-core/ @kaoDev @@ -3623,10 +3755,11 @@ /types/react-s-alert/ @mitsuruog /types/react-scroll/ @sudoplz @GiedriusGrabauskas /types/react-scrollbar/ @stephenjelfs -/types/react-select/ @Hesquibet @giladgray @iebaker @skirsdeda @vujevits @devrelm @MartynasZilinskas @onatm @ninjaferret @tehbi4 @misantronic @darkartur +/types/react-select/v1/ @Hesquibet @giladgray @iebaker @skirsdeda @vujevits @devrelm @MartynasZilinskas @onatm @ninjaferret @tehbi4 @misantronic @darkartur @eps1lon @endurance @RCGuillaume +/types/react-select/ @claasahl @jonfreedman /types/react-share/ @icopp /types/react-show-more/ @naortor -/types/react-side-effect/ @remojansen +/types/react-side-effect/ @remojansen @0xcaff /types/react-sidebar/ @jeroenvervaeke /types/react-sketchapp/ @ricokahler @DomiR /types/react-slick/ @andrewBalekha @GiedriusGrabauskas @r3nya @@ -3634,14 +3767,14 @@ /types/react-smooth-scrollbar/ @asvetliakov /types/react-sortable-hoc/ @NoHomey @charlesrey /types/react-sortable-pane/ @rhysd -/types/react-sortable-tree/ @wouterhardeman @jzoric @kevinsperrine +/types/react-sortable-tree/ @wouterhardeman @jzoric @kevinsperrine @acemac +/types/react-sound/ @koss-lebedev /types/react-spinkit/v1/ @tkqubo @mleko @pelotom /types/react-spinkit/ @tkqubo @mleko @pelotom @zzanol -/types/react-sticky/ @curtisw0 +/types/react-sticky/ @curtisw0 @ajhyndman /types/react-sticky-el/ @jbraithwaite /types/react-stickynode/ @tstirrat /types/react-stripe-elements/ @dan-j @santiagodoldan @sonnysangha @9y5 @thchia -/types/react-svg/ @viccrubs @chrisgarber /types/react-svg-inline/ @kiyopikko /types/react-svg-pan-zoom/ @huy-nguyen /types/react-swf/ @stepancar @@ -3658,24 +3791,25 @@ /types/react-test-renderer/v15/ @arvitaly @lochbrunner @lochbrunner @johnnyreilly /types/react-test-renderer/ @arvitaly @lochbrunner @johnnyreilly @jgoz /types/react-tether/ @ryprice -/types/react-text-mask/ @guilhermehubner @cavarzan +/types/react-text-mask/ @guilhermehubner @cavarzan @needpower /types/react-textarea-autosize/ @asvetliakov @zry656565 /types/react-timeout/ @kerwynrg /types/react-toastify/ @icopp /types/react-toastr/ @shssoichiro @DanRegazzi -/types/react-toggle/v2/ @LKay +/types/react-toggle/v2/ @LKay @jsonunger /types/react-toggle/ @LKay /types/react-tooltip/ @DeividasBakanas /types/react-touch/ @grzesie2k /types/react-tracking/ @alloy /types/react-transition-group/v1/ @LKay -/types/react-transition-group/ @LKay @Epskampie +/types/react-transition-group/ @LKay @Epskampie @ybiquitous /types/react-treeview/ @janslow /types/react-truncate/ @mattvperry -/types/react-twitter-auth/ @paulfasola +/types/react-twitter-auth/ @paulfasola @loginwashere /types/react-user-tour/ @ccancellieri +/types/react-vertical-timeline-component/ @stephane-monnot /types/react-virtual-keyboard/ @bsurai -/types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @kraenhansen @Stevearzh @mgoszcz2 +/types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @kraenhansen @Stevearzh @mgoszcz2 @brandonhall /types/react-virtualized-select/ @seansfkelley /types/react-webcam/ @squat /types/react-weui/ @tairan @@ -3699,9 +3833,10 @@ /types/reapop/ @Barrokgl /types/recaptcha2/ @l-jonas /types/recase/ @18steps -/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong @richbai90 @caspeco-dan @pkeuter @jrsaunde @paulmelnikow +/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong @richbai90 @caspeco-dan @pkeuter @jrsaunde @paulmelnikow @crusectrl @apalugniok /types/recluster/ @dex4er /types/recompose/ @iskandersierra @mrapogee @clayne11 @Pajn @lucasterra +/types/reconnect-core/ @thw0rted /types/reconnectingwebsocket/ @nguarracino /types/recursive-readdir/v1/ @elisee /types/recursive-readdir/ @elisee @MicahZoltu @@ -3712,11 +3847,12 @@ /types/redis-scripto/ @westy92 /types/redlock/v2/ @chrootsu /types/redlock/ @chrootsu @BendingBender -/types/redom/ @RauliL +/types/redom/ @RauliL @nemoinho /types/reduce-reducers/ @huy-nguyen /types/redux-action/ @newraina /types/redux-action-utils/ @tkqubo /types/redux-actions/ @jaysoo @alexgorbatchev @alechill @alexey-pelykh +/types/redux-async-queue/ @andreiho /types/redux-auth-wrapper/v1/ @LKay /types/redux-auth-wrapper/ @LKay /types/redux-batched-subscribe/ @mDibyo @@ -3731,7 +3867,7 @@ /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 @reggino @maddijoyce +/types/redux-form/ @carsonf @aikoven @LKay @bancek @alsiola @tehbi4 @huwmartin @ethanresnick @reggino @maddijoyce /types/redux-immutable/ @oizie @sebald @gavingregory /types/redux-immutable-state-invariant/ @remojansen @highflying /types/redux-infinite-scroll/ @silkyfray @@ -3752,6 +3888,7 @@ /types/redux-promise-middleware/ @ianks /types/redux-recycle/ @LKay /types/redux-router/ @stepancar +/types/redux-saga-tester/ @BenLorantfy /types/redux-shortcuts/ @tstirrat /types/redux-socket.io/ @snakeego /types/redux-storage/ @asvetliakov @@ -3762,10 +3899,15 @@ /types/redux-ui/ @andyshuxin /types/ref/ @loyd /types/ref-array/ @loyd +/types/ref-array-di/ @keerthi16 @KiranNiranjan +/types/ref-napi/ @keerthi16 @KiranNiranjan /types/ref-struct/ @loyd +/types/ref-struct-di/ @keerthi16 @KiranNiranjan /types/ref-union/ @loyd +/types/ref-union-di/ @keerthi16 @KiranNiranjan /types/reflux/v0/ @mauricedb /types/reflux/ @mauricedb @LiangZugeng +/types/registry-auth-token/ @mauricedb @LiangZugeng /types/relateurl/ @tkrotoff /types/relaxed-json/ @18steps /types/relay-runtime/ @voxmatt @alloy @@ -3774,11 +3916,13 @@ /types/remove-markdown/ @RagibHasin /types/rename/ @Aankhen /types/replace-ext/ @DeividasBakanas +/types/req-cwd/ @Alorel /types/request/ @soywiz @bonnici @Bartvds @joeskeen @ccurrens @lookfirst @mastermatt @josecolella /types/request-as-curl/ @atd-schubert /types/request-ip/ @mrhen /types/request-promise/ @cglantschnig @joeskeen @AyaMorisawa @mastermatt /types/request-promise-native/ @gustavohenke @mastermatt +/types/requestidlecallback/ @hax /types/requestretry/ @EricByers @trainerbill /types/require-dir/ @weekens /types/require-directory/ @Igmat @@ -3831,11 +3975,12 @@ /types/roads-server/ @dancespiele /types/roll/ @icopp /types/rolling-rate-limiter/ @l-jonas -/types/rollup-plugin-json/ @asmockler +/types/rollup-plugin-json/ @asmockler @hotell /types/ronomon__crypto-async/ @BendingBender /types/rosie/ @abner @subvertallchris @abukurov /types/roslib/ @Pro @skycoop @dgorobopec /types/rot-js/ @atiaxi +/types/round-to/ @seangenabe /types/route-parser/ @ianks @bobbuehler /types/routie/ @Adilson /types/royalslider/ @csrakowski @@ -3884,8 +4029,9 @@ /types/sanctuary/ @davidchambers @cortopy @piq9117 /types/sandboxed-module/ @svi3c /types/sane/ @BendingBender +/types/sane-email-validation/ @ForbesLindesay /types/sanitize-filename/ @Nemo157 -/types/sanitize-html/ @rogierschouten @afshin @BehindTheMath +/types/sanitize-html/ @rogierschouten @afshin @BehindTheMath @biermeester /types/sap__xsenv/ @mad-mike /types/sass-graph/ @marvinhagemeister /types/sass-webpack-plugin/ @AepKill @@ -3904,8 +4050,10 @@ /types/scroller/ @haskellcamargo /types/scrollreveal/ @Davidblkx /types/scrolltofixed/ @bmdixon +/types/scrypt/ @WhiteAbeLincoln /types/scrypt-async/ @xStrom @stesix /types/scryptsy/ @micksatana +/types/sdp-transform/ @loc /types/seamless/ @danmana /types/seamless-immutable/ @alex3165 @xsburg @geirsagberg /types/secp256k1/ @anler @@ -3951,6 +4099,7 @@ /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-cursor-pagination/ @pilagod /types/sequelize-fixtures/ @cschwarz /types/sequencify/ @npenin /types/sequester/ @Strate @@ -3961,6 +4110,7 @@ /types/serve-favicon/ @urossmolnik /types/serve-index/ @tkrotoff /types/serve-static/ @urossmolnik @LinusU +/types/server/ @sant123 @iddan /types/server-destroy/ @gyszalai /types/servicenow/ @bryceg /types/session-file-store/ @blendsdk @rokt33r @@ -3968,8 +4118,10 @@ /types/set-value/ @DanielRosenwasser /types/settings/ @shreyjain1994 /types/sha1/ @arcdev1 +/types/shallow-equals/ @rsolomon /types/shallowequal/ @seansfkelley -/types/shapefile/ @DenisCarriere +/types/shapefile/ @DenisCarriere @Thw0rted +/types/sharedb/ @soney /types/sharedworker/ @nakakura /types/sharepoint/ @gandjustas @andrei-markeev @baywet @teroarvola @dennispg /types/sharp/ @lith-light-g @wooseopkim @@ -3981,7 +4133,7 @@ /types/shimmer/ @kjin /types/shipit/ @cyrilschumacher /types/shipit-utils/ @cyrilschumacher -/types/shopify-buy/ @openminder @straiforos +/types/shopify-buy/ @openminder @straiforos @totemika /types/shortid/ @stpettersens @despairblue /types/shot/ @AJamesPhillips /types/should-sinon/ @Arylo @@ -4000,7 +4152,8 @@ /types/simple-cw-node/ @vvakame /types/simple-lru/ @NN--- /types/simple-mock/ @leonyu -/types/simple-oauth2/ @mad-mike @troy-lamerton +/types/simple-oauth2/v1/ @mad-mike @troy-lamerton @netux +/types/simple-oauth2/ @mad-mike @troy-lamerton @netux /types/simple-peer/ @tlaziuk /types/simple-url-cache/ @a-lucas /types/simple-websocket/ @dex4er @@ -4011,6 +4164,7 @@ /types/simplesmtp/ @rogierschouten /types/simplestorage.js/ @axelcostaspena @mxl /types/single-line-log/ @ffflorian +/types/single-spa-react/ @Garrett-Smith-iq /types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg /types/sinon-as-promised/ @igrayson /types/sinon-chai/v2/ @kazimanzurrashid @jedmao @@ -4029,11 +4183,12 @@ /types/skatejs/ @Hotell /types/ski/ @AyaMorisawa /types/skyway/ @nakakura +/types/slack-mock/ @kkalavantavanich /types/slack-node/ @geoffreak /types/slack-winston/ @BlueHatbRit /types/slackdown/ @nju33 /types/slackify-html/ @hypexr -/types/slate/ @andykent @majelbstoat @JanLoebel @YangusKhan +/types/slate/ @andykent @majelbstoat @JanLoebel @YangusKhan @kalley @Kornil /types/slate-base64-serializer/ @YangusKhan /types/slate-html-serializer/ @YangusKhan /types/slate-irc/ @elisee @@ -4050,6 +4205,7 @@ /types/smtp-server/v1/ @markisme @Taisiias /types/smtp-server/ @markisme @Taisiias @dex4er /types/smtpapi/ @a-morales +/types/snappy/ @reconbot /types/snapsvg/ @lhk @mattanja @kant2002 /types/snazzy-info-window/ @milosd92 /types/snekfetch/ @ANekoIsFineToo @ShayBox @Dev-Yukine @@ -4088,7 +4244,7 @@ /types/speakeasy/ @legendecas @mrOlorin @xeoneux /types/speakingurl/ @Goldsmith42 /types/spectacle/ @zmaybury -/types/spectrum/ @M-Zuber +/types/spectrum/ @M-Zuber @Ailrun /types/split/ @marcinporebski /types/split.js/ @icholy /types/split2/ @mugeso @@ -4100,13 +4256,14 @@ /types/sprintf-js/ @jasonswearingen @BendingBender /types/sql-bricks/ @adn05 @paleo /types/sql.js/ @Hozuki +/types/sqlanywhere/ @pkeuter /types/sqlite3/ @nmalaguti @dpyro @BehindTheMath /types/sqlstring/ @marvinhagemeister /types/squirejs/ @bradleyayers /types/srp/ @Patman64 /types/ssh-key-decrypt/ @BendingBender /types/ssh2/ @tkQubo @rbuckton -/types/ssh2-sftp-client/ @igrayson @ascariandrea +/types/ssh2-sftp-client/ @igrayson @ascariandrea @kartik2406 /types/ssh2-streams/ @rbuckton /types/sshpk/ @mabels /types/stack-mapper/ @rogierschouten @@ -4125,33 +4282,39 @@ /types/std-mocks/ @jdxcode /types/steam/ @kant2002 /types/steam-client/ @Slessi +/types/steam-login/ @Nicell /types/steam-totp/ @phenomax /types/steamid/ @Slessi /types/steed/ @Paul-Isache -/types/stellar-sdk/ @carl-foster @tristonj @pselden +/types/stellar-sdk/ @carl-foster @tristonj @pselden @maxbause /types/stemmer/ @will-ockmore /types/sticky-cluster/ @paustint /types/stompjs/ @jimic @Dr4k4n /types/stoppable/ @EricByers -/types/storejs/ @vbortone @harry0000 +/types/store/ @vbortone @harry0000 @Ky6uk +/types/storybook-addon-jsx/ @jameslnewell /types/storybook__addon-a11y/ @hyunseob -/types/storybook__addon-actions/ @joscha +/types/storybook__addon-actions/ @joscha @jicjjang /types/storybook__addon-backgrounds/ @hyunseob +/types/storybook__addon-centered/ @kiyopikko /types/storybook__addon-info/ @mkornblum @fyrkant -/types/storybook__addon-knobs/ @joscha @martynaskadisa +/types/storybook__addon-jest/ @halfmatthalfcat +/types/storybook__addon-knobs/ @joscha @martynaskadisa @amacleay /types/storybook__addon-links/ @joscha @jessepinho /types/storybook__addon-notes/ @joscha @amacleay /types/storybook__addon-options/ @joscha @simonhn @amacleay /types/storybook__addon-storyshots/ @bradleyayers /types/storybook__react/ @joscha @wapgear -/types/storybook__react-native/ @joscha @wapgear @alechill +/types/storybook__react-native/ @joscha @wapgear @alechill @iRoachie /types/storybook__vue/ @pntgupta /types/stream-buffers/ @Jason3S /types/stream-chain/ @uhop /types/stream-csv-as-json/ @uhop +/types/stream-each/ @djcsdy /types/stream-json/ @uhop /types/stream-meter/ @mugeso /types/stream-series/ @k-kagurazaka +/types/stream-shift/ @djcsdy /types/stream-to-array/v0/ @Bartvds /types/stream-to-array/ @Bartvds @BendingBender /types/stream-to-promise/ @Alorel @@ -4161,6 +4324,7 @@ /types/strftime/ @cyrilschumacher /types/strict-uri-encode/ @hoishin /types/string/ @basp +/types/string-format/ @lal12 /types/string-hash/ @ethanrubio /types/string-similarity/ @ragtime /types/string-template/ @TonyPythoneer @@ -4170,7 +4334,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 +/types/stripe/ @wjohnsto @codeanimal @sampsonjoliver @LinusU @brannon @kkamperschroer @starhoshi @bruun @galtalmor @htunnicliff @squirly @tzarger /types/stripe-checkout/ @cgwrench /types/stripe-v2/ @ejsmith @amritk @adamcmiel @jleider @galuszkak /types/stripe-v3/ @ejsmith @amritk @adamcmiel @jleider @galuszkak @@ -4179,8 +4343,10 @@ /types/strong-log-transformer/ @azasypkin /types/strophe/ @DavidKDeutsch /types/structured-source/ @azu +/types/styled-components/ @Igorbek /types/styled-jsx/ @R1ZZU -/types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh +/types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh @lavoaster +/types/stylelint/v7/ @alan-agius4 /types/stylelint/ @alan-agius4 /types/stylelint-webpack-plugin/ @bahlo /types/stylus/ @SomaticIT @@ -4193,10 +4359,12 @@ /types/sumo-logger/ @forabi @clementallen /types/suncalc/ @horiuchi /types/superagent/v2/ @varju @NicoZelaya @mxl -/types/superagent/ @NicoZelaya @mxl @paplorinc @shreyjain1994 @zopf +/types/superagent/ @NicoZelaya @mxl @paplorinc @shreyjain1994 @zopf @beeequeue +/types/superagent-bunyan/ @bricka /types/superagent-no-cache/ @mxl /types/superagent-prefix/ @mxl /types/supercluster/ @DenisCarriere +/types/superstruct/ @edwardsnare /types/supertest/ @varju /types/supertest-as-promised/ @tkrotoff /types/supports-color/v3/ @mgroenhoff @@ -4204,6 +4372,7 @@ /types/svg-injector/ @poke /types/svg-parser/ @mrmlnc /types/svg-path-bounding-box/ @NotWoods +/types/svg-path-parser/ @tyru /types/svg-sprite/ @tkqubo /types/svg-sprite-loader/ @rynclark /types/svg2png/ @hansrwindhoff @sccgithub @@ -4255,7 +4424,9 @@ /types/tar/ @SomaticIT @connor4312 /types/tar-fs/ @Umoxfo /types/tar-stream/ @glicht +/types/task-graph-runner/ @mgroenhoff /types/tcp-ping/ @stegano +/types/teddy/ @lannonbr /types/tedious/ @rogierschouten @cjthompson @v-suhame /types/tedious-connection-pool/ @sandorfr /types/telebot/ @mariotsi @@ -4274,9 +4445,12 @@ /types/text-encoding-utf-8/ @trxcllnt /types/text-table/ @saadq /types/textarea-caret/ @shiftkey +/types/textract/ @lal12 /types/textversionjs/ @aaronosher /types/tgfancy/ @Dabolus -/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas @NotWoods @sethk +/types/theming/ @eps1lon +/types/thepiratebay/ @jsorrell +/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas @NotWoods @sethk @elk941 @Methuselah96 /types/thrift/ @kamek-pf @kevin-greene-ck @jessezhang91 /types/throng/ @cyrilschumacher @tatethurston /types/throttle/ @BendingBender @@ -4295,8 +4469,9 @@ /types/tinajs__tina/ @Jimexist /types/tinajs__tina-redux/ @Jimexist /types/tinder/ @pingec +/types/tingle.js/ @ajafff /types/tiny-slider-react/ @screendriver -/types/tinycolor2/ @M-Zuber @geertjansen @nvh +/types/tinycolor2/ @M-Zuber @geertjansen @nvh @Ailrun /types/tinycon/ @dwaxweiler /types/tinycopy/ @vvatanabe /types/tinymce/ @martinduparc @ipoul @nicohartto @@ -4319,6 +4494,7 @@ /types/topojson-client/ @denisname @ricardo-mello /types/topojson-simplify/ @denisname @ricardo-mello /types/topojson-specification/ @denisname +/types/toposort/ @danwbyrne /types/torrent-stream/ @xstoudi /types/touch/ @mizunashi-mana @BendingBender /types/touch-events/ @kevinb7 @@ -4335,10 +4511,12 @@ /types/trayballoon/ @korve /types/tress/ @sindilevich /types/trim/ @skysteve +/types/triple-beam/ @danwbyrne /types/triplesec/ @threesquared /types/trunk8/ @niemyjski /types/tryer/ @bengry /types/tspromise/ @soywiz +/types/ttf2woff2/ @ThomasdenH /types/tunnel/ @BendingBender /types/tus-js-client/ @kevhiggins /types/tv4/ @Bartvds @psnider @@ -4347,7 +4525,8 @@ /types/tweezer.js/ @praxxis /types/twig/ @soywiz @enko /types/twilio/ @nickiannone @ashleybrener -/types/twit/ @Volox @lostfictions @sapphiredev @abraham +/types/twit/ @Volox @sapphiredev @abraham @siwalikm @plhery +/types/twitch-ext/ @beheh /types/twitter/ @chitoku-k /types/twitter-stream-channels/ @adrianbardan /types/twitter-text/ @rhysd @@ -4358,12 +4537,12 @@ /types/type-is/ @BendingBender /types/type-name/ @armorik83 /types/typeahead/ @igochkov @gjunge -/types/typed.js/ @Dona278 /types/typedarray-pool/ @pawsong /types/typeof/ @OpenByteDev /types/typescript-deferred/ @DirtyHairy /types/tz-format/ @samverschueren /types/ua-parser-js/ @superduper @legendecas @MeLlamoPablo +/types/uglify-es/ @alan-agius4 /types/uglify-js/v2/ @tkrotoff /types/uglify-js/ @alan-agius4 @tkrotoff @johnnyreilly /types/uglifycss/ @blendsdk @@ -4377,12 +4556,13 @@ /types/ultra-strftime/ @dex4er /types/umbraco/ @DeCareSystemsIreland /types/umd/ @TeamworkGuy2 -/types/umzug/ @drinchev @mlamp @trodi -/types/underscore/ @borisyankov @jbaldwin @ccurrens @clottman +/types/umzug/ @drinchev @mlamp @trodi @emmanuelgautier +/types/underscore/ @borisyankov @jbaldwin @ccurrens @clottman @confususs /types/underscore-ko/ @MagicMau /types/underscore.string/ @rygine /types/undertaker/ @tkqubo @GiedriusGrabauskas /types/undertaker-registry/ @GiedriusGrabauskas +/types/unidecode/ @vfernandestoptal /types/uniq/ @hansrwindhoff /types/uniqid/ @idchlife /types/unique-hash-stream/ @BendingBender @@ -4390,6 +4570,7 @@ /types/unist/ @bizen241 /types/unity-webapi/ @jmvrbanac /types/universal-analytics/ @Bartvds @DarkerTV +/types/universal-cookie/ @tomi /types/universal-router/ @jtmthf @tlaziuk @Lodin /types/unorm/ @chbrown /types/untildify/ @BendingBender @@ -4401,15 +4582,15 @@ /types/upng-js/ @plantain-00 /types/uppercamelcase/ @plantain-00 /types/urbanairship-cordova/ @Justin-Credible -/types/uri-templates/ @Bartvds +/types/uri-templates/ @Bartvds @barnski /types/urijs/ @RodneyJT @xt0rted @petejohanson /types/uritemplate/ @teyc @rubensworks /types/url-assembler/ @wolfgang42 /types/url-join/ @rogierschouten @devrelm /types/url-metadata/ @mrkmg /types/url-params/ @danielsogl -/types/url-parse/ @ChernenkoPaul @harisiva -/types/url-regex/ @unindented +/types/url-parse/ @ChernenkoPaul @harisiva @DimitryDushkin +/types/url-regex/ @unindented @sosukesuzuki /types/url-safe-base64/ @johngeorgewright /types/url-search-params/ @nick121212 @nrathi /types/url-template/ @marcinporebski @@ -4436,11 +4617,13 @@ /types/valdr-message/ @ilbertz /types/valerie/ @conficient /types/vali-date/ @SamVerschueren +/types/valiant/ @whatasoda /types/valid-url/ @stevehipwell /types/validator/ @tgfjt @chrootsu @IOAyman @louy @kacepe @deptno @builtinnya @qqilihq /types/validatorjs/ @LKay @danmana /types/vanilla-modal/ @samnau /types/vanilla-tilt/ @BrunnerLivio +/types/varint/ @dbrockman /types/vary/ @BendingBender /types/vast-client/ @jgainfort /types/vec3/ @xstoudi @@ -4451,16 +4634,17 @@ /types/vertx3-eventbus-client/ @oddeirik /types/vex-js/ @gdcohan /types/vexdb/ @MayorMonty -/types/vexflow/ @rquiring @sebastianhaas @bohoffi +/types/vexflow/ @rquiring @sebastianhaas @bohoffi @sschmidTU /types/vfile/ @bizen241 @rokt33r /types/vfile-location/ @ikatyang /types/victory/ @asvetliakov @snerks @Havret @alredyExist -/types/video.js/ @vbortone @scleriot @SWBennett06 @IgelCampus @giofreitas @gjanblaszczyk @sroucheray +/types/video.js/ @vbortone @scleriot @SWBennett06 @IgelCampus @giofreitas @gjanblaszczyk @sroucheray @AkxeOne /types/viewability-helper/ @lironzluf /types/viewerjs/ @lrh3321 +/types/viewport-mercator-project/ @fnberta /types/viewporter/ @borisyankov /types/vimeo/ @DazWilkin -/types/vimeo__player/ @denisyilmaz @timc13 +/types/vimeo__player/ @denisyilmaz @timc13 @terrymun /types/vinyl/v0/ @jedmao /types/vinyl/ @vvakame @jedmao @thorn0 /types/vinyl-buffer/ @tkQubo @@ -4468,7 +4652,7 @@ /types/vinyl-paths/ @tkQubo /types/virtual-dom/ @chbrown /types/virtual-keyboard/ @bsurai -/types/vis/ @MichaelBitard @macleodbroad-wf @adripanico @seveves @kaktus40 @mmaitre314 @supercargo @takato1314 @alex-kachura +/types/vis/ @MichaelBitard @macleodbroad-wf @adripanico @seveves @kaktus40 @mmaitre314 @supercargo @takato1314 @alex-kachura @dcop @avrahamcool /types/vision/v4/ @jasonswearingen @AJamesPhillips /types/vision/ @jasonswearingen @AJamesPhillips @lenovouser /types/vitalsigns/ @cyrilschumacher @@ -4484,6 +4668,7 @@ /types/vue-markdown/ @neodon /types/vue-resource/ @kaorun343 /types/vue-scrollto/ @vincekovacs +/types/vue-select/ @silh /types/vue2-datepicker/ @ChristianStornowski /types/vuex-i18n/ @jaeggerr @noamkfir /types/w2ui/ @Ptival @@ -4509,10 +4694,12 @@ /types/weapp-api/ @vargeek /types/web-animations-js/ @kritollm /types/web-bluetooth/ @urish -/types/web3/ @simon-jentzsch @nitzantomer @zurbo @yxliang01 @phra @naddison36 @icaroharry @linusnorton @jpeletier @anneau @matrushka @andrevmatos @levino +/types/web3/ @simon-jentzsch @nitzantomer @zurbo @yxliang01 @phra @naddison36 @icaroharry @linusnorton @jpeletier @anneau @matrushka @andrevmatos @levino @zlumer @archangel-irk /types/web3-eth-abi/ @LogvinovLeon +/types/web3-provider-engine/ @LogvinovLeon /types/webappsec-credential-management/ @iainmcgin /types/webassembly-js-api/ @periklis +/types/webassembly-web-api/ @jhenninger /types/webcl/ @NCARalph /types/webcomponents.js/ @adidahiya /types/webcrypto/ @iislucas @@ -4522,8 +4709,9 @@ /types/webgl2/ @nkemnitz @karhu /types/webidl2/ @saschanaz /types/webmidi/ @lostfictions -/types/webpack/v3/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @ahmed-taj @alan-agius4 @elliottsj @jason0x43 @christophehurpeau -/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @ahmed-taj @alan-agius4 @elliottsj @jason0x43 @dennispg @christophehurpeau @ZSkycat @johnnyreilly +/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-assets-manifest/ @FranklinWhale /types/webpack-bundle-analyzer/ @kryops /types/webpack-chain/ @eirikurn @psachs21 /types/webpack-chunk-hash/ @mtraynham @@ -4548,14 +4736,18 @@ /types/webpack-stream/ @iclanton @bumbleblym /types/webpack-validator/ @deevus /types/webpackbar/ @rynclark +/types/webpagetest/ @ksm2 /types/webrtc/ @nakakura +/types/webscopeio__react-textarea-autocomplete/ @michauzo +/types/websequencediagrams/ @ffflorian /types/website-scraper/ @screendriver /types/websocket/ @loyd @flynetworks @zhaoleimxd @jdneo -/types/webspeechapi/ @saschanaz +/types/websocket-async/ @bigbeno37 /types/websql/ @TeamworkGuy2 /types/webtorrent/ @niieani @tlaziuk /types/webvr-api/ @efokschaner /types/week/ @sindrenm +/types/wegame-api/ @jcyuan /types/weighted/ @ccitro /types/weixin-app/ @taoqf @AlexStacker @Jimexist /types/wellknown/ @yairtawil @@ -4567,7 +4759,9 @@ /types/wheel/ @BTOdell /types/when/ @derekcicerone @Nemo157 /types/which/ @vvakame @cspotcode +/types/which-pm/ @jorgegonzalez /types/wicg-mediasession/ @jucrouzet +/types/wif/ @danwbyrne /types/wiiu/ @mzsm /types/window-or-global/ @vvakame /types/window-size/ @pmkary @@ -4577,11 +4771,13 @@ /types/winjs/v1/ @adamhewitt627 @craigktreasure @xirzec /types/winjs/v2/ @adamhewitt627 @craigktreasure @xirzec /types/winjs/ @adamhewitt627 @craigktreasure @xirzec +/types/wink-tokenizer/ @lal12 /types/winreg/ @RX14 @BobBuehler /types/winrt-uwp/ @saschanaz @taylor224 /types/winston-dynamodb/ @nickiannone /types/winston-mail/ @idono87 -/types/winston-syslog/ @cjbarth +/types/winston-syslog/v1/ @cjbarth +/types/winston-syslog/ @cjbarth @felix-hoc /types/wiring-pi/ @NoHomey /types/wnumb/ @acoreyj /types/wonder.js/ @yyc-git @@ -4642,9 +4838,11 @@ /types/yeoman-generator/ @armorik83 @janslow @ikatyang /types/yeoman-test/ @ikatyang /types/yesql/ @Sumolari +/types/yoctodelay/ @seangenabe /types/yog-bigpipe/ @ssddi456 /types/yog-log/ @ssddi456 /types/yog2-kernel/ @ssddi456 +/types/yoga-layout/ @tnobody /types/yosay/ @armorik83 /types/youtube/ @DazWilkin @JoshuaKGoldberg @eliotfallon213 /types/youtube-dl/ @bsurai @@ -4662,10 +4860,11 @@ /types/zeromq/ @davemckeown @erikma @TitaneBoy /types/zip-webpack-plugin/ @blaise-io /types/zip.js/ @lgrignon -/types/zipcodes/ @headdetect +/types/zipcodes/ @headdetect @dobesv /types/zipkin-context-cls/ @plantain-00 /types/zipkin-instrumentation-express/ @plantain-00 /types/zipkin-instrumentation-fetch/ @plantain-00 +/types/zipkin-javascript-opentracing/ @laurentgilly /types/zipkin-transport-http/ @plantain-00 /types/zmq/ @davemckeown /types/zookeeper/ @xialeistudio diff --git a/notNeededPackages.json b/notNeededPackages.json index 4e66976014..e1a2f2e6cd 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -390,6 +390,12 @@ "sourceRepoURL": "https://github.com/MikeMcl/decimal.js", "asOfVersion": "7.4.0" }, + { + "libraryName": "delay", + "typingsPackageName": "delay", + "sourceRepoURL": "https://github.com/sindresorhus/delay", + "asOfVersion": "3.1.0" + }, { "libraryName": "DevExtreme", "typingsPackageName": "devextreme", @@ -972,6 +978,12 @@ "sourceRepoURL": "https://github.com/mqttjs/MQTT.js", "asOfVersion": "2.5.0" }, + { + "libraryName": "nano", + "typingsPackageName": "nano", + "sourceRepoURL": "https://github.com/apache/couchdb-nano", + "asOfVersion": "7.0.0" + }, { "libraryName": "ng-table", "typingsPackageName": "ng-table", @@ -1266,6 +1278,12 @@ "sourceRepoURL": "https://github.com/zalmoxisus/redux-devtools-extension", "asOfVersion": "2.13.2" }, + { + "libraryName": "redux-little-router", + "typingsPackageName": "redux-little-router", + "sourceRepoURL": "https://github.com/FormidableLabs/redux-little-router", + "asOfVersion": "15.1.0" + }, { "libraryName": "redux-persist", "typingsPackageName": "redux-persist", diff --git a/types/abstract-leveldown/abstract-leveldown-tests.ts b/types/abstract-leveldown/abstract-leveldown-tests.ts index c5edadf069..070065f425 100644 --- a/types/abstract-leveldown/abstract-leveldown-tests.ts +++ b/types/abstract-leveldown/abstract-leveldown-tests.ts @@ -11,3 +11,7 @@ const test = (levelDown: AbstractLevelDOWN) => { test(new AbstractLevelDOWN('here')); // $ExpectType void test(AbstractLevelDOWN('there')); +// $ExpectType void +test(new AbstractLevelDOWN('here')); +// $ExpectType void +test(AbstractLevelDOWN('there')); diff --git a/types/abstract-leveldown/index.d.ts b/types/abstract-leveldown/index.d.ts index 2caf073432..ad8fab5d74 100644 --- a/types/abstract-leveldown/index.d.ts +++ b/types/abstract-leveldown/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Meirion Hughes // Daniel Byrne // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export interface AbstractOptions { readonly [k: string]: any; @@ -21,7 +22,7 @@ export interface AbstractGetOptions extends AbstractOptions { asBuffer?: boolean; } -export interface AbstractLevelDOWN extends AbstractOptions { +export interface AbstractLevelDOWN extends AbstractOptions { open(cb: ErrorCallback): void; open(options: AbstractOpenOptions, cb: ErrorCallback): void; @@ -38,17 +39,23 @@ export interface AbstractLevelDOWN extends AbstractOptions { batch(): AbstractChainedBatch; batch(array: ReadonlyArray>, cb: ErrorCallback): AbstractChainedBatch; - batch(array: ReadonlyArray>, options: AbstractOptions, cb: ErrorCallback): AbstractChainedBatch; + batch( + array: ReadonlyArray>, + options: AbstractOptions, + cb: ErrorCallback, + ): AbstractChainedBatch; iterator(options?: AbstractIteratorOptions): AbstractIterator; } export interface AbstractLevelDOWNConstructor { - new (location: string): AbstractLevelDOWN; - (location: string): AbstractLevelDOWN; + // tslint:disable-next-line no-unnecessary-generics + new (location: string): AbstractLevelDOWN; + // tslint:disable-next-line no-unnecessary-generics + (location: string): AbstractLevelDOWN; } -export interface AbstractIteratorOptions extends AbstractOptions { +export interface AbstractIteratorOptions extends AbstractOptions { gt?: K; gte?: K; lt?: K; @@ -61,20 +68,20 @@ export interface AbstractIteratorOptions extends AbstractOptions { valueAsBuffer?: boolean; } -export type AbstractBatch = PutBatch | DelBatch; +export type AbstractBatch = PutBatch | DelBatch; -export interface PutBatch { +export interface PutBatch { readonly type: 'put'; readonly key: K; readonly value: V; } -export interface DelBatch { +export interface DelBatch { readonly type: 'del'; readonly key: K; } -export interface AbstractChainedBatch extends AbstractChainedBatchConstructor, AbstractOptions { +export interface AbstractChainedBatch extends AbstractOptions { put: (key: K, value: V) => this; del: (key: K) => this; clear: () => this; @@ -83,19 +90,23 @@ export interface AbstractChainedBatch extends AbstractChainedBatchConstruc } export interface AbstractChainedBatchConstructor { - new(db: any): AbstractChainedBatch; - (db: any): AbstractChainedBatch; + // tslint:disable-next-line no-unnecessary-generics + new (db: any): AbstractChainedBatch; + // tslint:disable-next-line no-unnecessary-generics + (db: any): AbstractChainedBatch; } -export interface AbstractIterator extends AbstractChainedBatchConstructor { +export interface AbstractIterator extends AbstractOptions { db: AbstractLevelDOWN; next(cb: ErrorKeyValueCallback): this; end(cb: ErrorCallback): void; } export interface AbstractIteratorConstructor { - new(db: any): AbstractIterator; - (db: any): AbstractIterator; + // tslint:disable-next-line no-unnecessary-generics + new (db: any): AbstractIterator; + // tslint:disable-next-line no-unnecessary-generics + (db: any): AbstractIterator; } export const AbstractLevelDOWN: AbstractLevelDOWNConstructor; diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index b405de0273..075d063e5f 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -1,345 +1,476 @@ -// Type definitions for AFRAME 0.7 +// Type definitions for AFRAME 0.8 // Project: https://aframe.io/ // Definitions by: Paul Shannon // Roberto Ritger // Trygve Wastvedt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /** - * Extended tests available at https://github.com/devpaul/aframe-typings.git + * Extended tests and examples available at https://github.com/devpaul/aframe-experiments.git */ -/// /// -// Globals -declare var AFRAME: AFrame.AFrameGlobal; -declare var hasNativeWebVRImplementation: boolean; +import * as three from 'three'; +import * as tween from '@tweenjs/tween.js'; -interface Document { - createElement(tagName: string): AFrame.Entity; - querySelector(selectors: 'a-scene'): AFrame.Scene; - querySelector(selectors: string): AFrame.Entity; - querySelectorAll(selectors: string): NodeListOf | Element>; +export type ThreeLib = typeof three; +export type TweenLib = typeof tween; + +export interface ObjectMap { + [key: string]: T; } -// Interfaces -declare namespace AFrame { - interface ObjectMap { - [ key: string ]: T; - } +export interface Animation { + attribute: string; + begin: string | number; + delay: number; + direction: 'alternate' | 'alternateReverse' | 'normal' | 'reverse'; + dur: number; + easing(): void; + end: string; + fill: 'backwards' | 'both' | 'forwards' | 'none'; + from: any; // TODO type + repeat: number | 'indefinite'; + to: number; +} - interface AFrameGlobal { - AEntity: Entity; - ANode: ANode; - AScene: Scene; - components: { [ key: string ]: ComponentDescriptor }; - geometries: { [ key: string ]: GeometryDescriptor }; - primitives: { [ key: string ]: Entity }; - registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; - registerElement(name: string, element: ANode): void; - registerGeometry(name: string, geometry: GeometryDefinition): GeometryConstructor; - registerPrimitive(name: string, primitive: PrimitiveDefinition): void; - registerShader(name: string, shader: T): ShaderConstructor; - registerSystem(name: string, definition: SystemDefinition): SystemConstructor; - schema: SchemaUtils; - shaders: { [ key: string ]: ShaderDescriptor }; - systems: { [key: string]: SystemConstructor }; - THREE: typeof THREE; - TWEEN: typeof TWEEN; - utils: Utils; - version: string; - } +export interface ANode extends HTMLElement { + // Only public APIs added. Many methods intentionally left out. + // createdCallback + // attachedCallback + // attributeChangedCallback + closestScene(): Scene; + closest(selector: string): ANode; + // detachedCallback + hasLoaded: boolean; + load(cb?: () => void, childFilter?: (el: Element) => boolean): void; + // updateMixins + registerMixin(id: string): void; + setAttribute(type: string, newValue: any): void; + unregisterMixin(id: string): void; + removeMixinListener(id: string): void; + attachMixinListener(mixin: HTMLElement): void; + emit(name: string, detail?: any, bubbles?: boolean): void; + emitter(name: string, detail?: any, bubbles?: boolean): () => void; +} - interface Animation { - attribute: string; - begin: string | number; - delay: number; - direction: 'alternate' | 'alternateReverse' | 'normal' | 'reverse'; - dur: number; - easing(): void; - end: string; - fill: 'backwards' | 'both' | 'forwards' | 'none'; - from: any; // TODO type - repeat: number | 'indefinite'; - to: number; - } +export interface Behavior { + tick(): void; +} - interface ANode extends HTMLElement { - // Only public APIs added. Many methods intentionally left out. - // createdCallback - // attachedCallback - // attributeChangedCallback - closestScene(): Scene; - closest(selector: string): ANode; - // detachedCallback - hasLoaded: boolean; - load(cb?: () => void, childFilter?: (el: Element) => boolean): void; - // updateMixins - registerMixin(id: string): void; - setAttribute(type: string, newValue: any): void; - unregisterMixin(id: string): void; - removeMixinListener(id: string): void; - attachMixinListener(mixin: HTMLElement): void; - emit(name: string, detail?: any, bubbles?: boolean): void; - emitter(name: string, detail?: any, bubbles?: boolean): () => void; - } +export interface Component { + attrName?: string; + data: T; + dependencies?: string[]; + el: Entity; + id: string; + multiple?: boolean; + name: string; + schema: Schema; + system: S | undefined; - interface Behavior { - tick(): void; - } + init(data?: T): void; + pause(): void; + play(): void; + remove(): void; + tick?(time: number, timeDelta: number): void; + update(oldData: T): void; + updateSchema?(): void; - interface Component { - attrName?: string; - data: T; - dependencies?: string[]; - el: Entity; - id: string; - multiple?: boolean; + extendSchema(update: Schema): void; + flushToDOM(): void; +} + +export interface ComponentConstructor { + new (el: Entity, attrValue: string, id: string): T & Component; + prototype: T & { name: string; - schema: Schema; - system: S | undefined; - - init(this: this, data?: T): void; - pause(this: this): void; - play(this: this): void; - remove(this: this): void; - tick?(this: this, time: number, timeDelta: number): void; - update(this: this, oldData: T): void; - updateSchema?(this: this): void; - - extendSchema(this: this, update: Schema): void; - flushToDOM(this: this): void; - } - - interface ComponentConstructor { - new (el: Entity, attrValue: string, id: string): T; - } - - type ComponentDefinition = Partial; - - interface ComponentDescriptor { - Component: ComponentConstructor; - dependencies: string[] | undefined; - multiple: boolean | undefined; - - // internal APIs2 - // parse - // parseAttrValueForCache - // schema - // stringify - // type - } - - interface Coordinate { - x: number; - y: number; - z: number; - } - - interface DefaultComponents { - position: Component; - rotation: Component; - scale: Component; - } - - interface Entity> extends ANode { - components: C & DefaultComponents; - isPlaying: boolean; - object3D: THREE.Object3D; - object3DMap: ObjectMap; - sceneEl?: Scene; - - addState(name: string): void; - flushToDOM(recursive?: boolean): void; - /** - * @deprecated since 0.4.0 - */ - getComputedAttribute(attr: string): Component; - getDOMAttribute(attr: string): any; - getObject3D(type: string): THREE.Object3D; - getOrCreateObject3D(type: string, construct: any): THREE.Object3D; - is(stateName: string): boolean; - pause(): void; + system: System; play(): void; - setObject3D(type: string, obj: THREE.Object3D): void; - removeAttribute(attr: string, property?: string): void; - removeObject3D(type: string): void; - removeState(stateName: string): void; - - // getAttribute specific usages - getAttribute(type: string): any; - getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate; - - // setAttribute specific usages - setAttribute(attr: string, value: any): void; - setAttribute(attr: string, property: string, componentAttrValue?: any): void; - setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void; - - // addEventListener specific usages - addEventListener(type: K, listener: (event: Event & EntityEventMap[K]) => void, useCapture?: boolean): void; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - } - - type DetailEvent = Event & { - detail: D; - target: EventTarget & Entity; + pause(): void; }; +} - interface EntityEventMap { - 'child-attached': DetailEvent<{ el: Element | Entity }>; - 'child-detached': DetailEvent<{ el: Element | Entity }>; - 'componentchanged': DetailEvent<{ - name: string, - id: string - }>; - 'componentremoved': DetailEvent<{ - name: string, - id: string, - newData: any, - oldData: any - }>; - 'loaded': EventListener; - 'pause': EventListener; - 'play': EventListener; - 'stateadded': DetailEvent<{ state: string }>; - 'stateremoved': DetailEvent<{ state: string }>; - 'schemachanged': DetailEvent<{ componentName: string }>; - } +export interface ComponentDescriptor { + Component: ComponentConstructor; + dependencies: string[] | undefined; + multiple: boolean | undefined; - interface Geometry { + // internal APIs2 + // parse + // parseAttrValueForCache + // schema + // stringify + // type +} + +export interface Coordinate { + x: number; + y: number; + z: number; +} + +export interface DefaultComponents { + position: Component; + rotation: Component; + scale: Component; +} + +export interface Entity> extends ANode { + components: C & DefaultComponents; + isPlaying: boolean; + object3D: THREE.Object3D; + object3DMap: ObjectMap; + sceneEl?: Scene; + + addState(name: string): void; + flushToDOM(recursive?: boolean): void; + /** + * @deprecated since 0.4.0 + */ + getComputedAttribute(attr: string): Component; + getDOMAttribute(attr: string): any; + getObject3D(type: string): THREE.Object3D; + getOrCreateObject3D(type: string, construct: any): THREE.Object3D; + is(stateName: string): boolean; + pause(): void; + play(): void; + setObject3D(type: string, obj: THREE.Object3D): void; + removeAttribute(attr: string, property?: string): void; + removeObject3D(type: string): void; + removeState(stateName: string): void; + + // getAttribute specific usages + getAttribute(type: string): any; + getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate; + + // setAttribute specific usages + setAttribute(attr: string, value: any): void; + setAttribute(attr: string, property: string, componentAttrValue?: any): void; + setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void; + + // addEventListener specific usages + addEventListener( + type: K, + listener: (event: Event & EntityEventMap[K]) => void, + useCapture?: boolean + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + useCapture?: boolean + ): void; +} + +export type DetailEvent = Event & { + detail: D; + target: EventTarget & Entity; +}; + +export interface EntityEventMap { + 'child-attached': DetailEvent<{ el: Element | Entity }>; + 'child-detached': DetailEvent<{ el: Element | Entity }>; + componentchanged: DetailEvent<{ name: string; - geometry: THREE.Geometry; - schema: Schema; + id: string; + }>; + componentremoved: DetailEvent<{ + name: string; + id: string; + newData: any; + oldData: any; + }>; + loaded: EventListener; + pause: EventListener; + play: EventListener; + stateadded: DetailEvent<{ state: string }>; + stateremoved: DetailEvent<{ state: string }>; + schemachanged: DetailEvent<{ componentName: string }>; +} - init(this: this, data: { [P in keyof this['schema']]: any }): void; - // Would like the above to be: - // init?(this: this, data?: { [P in keyof T['schema']]: T['schema'][P]['default'] } ): void; - // I think this is prevented by the following issue: https://github.com/Microsoft/TypeScript/issues/21760. - } +export interface Geometry { + data: T; + name: string; + geometry: THREE.Geometry; + schema: Schema; - interface GeometryConstructor { - new (): T; - } + init(data: any): void; +} - type GeometryDefinition = Partial; +export interface GeometryConstructor { + new (): T & Geometry; +} - interface GeometryDescriptor { - Geometry: GeometryConstructor; - schema: Schema; - } +export interface GeometryDescriptor { + Geometry: GeometryConstructor; + schema: Schema; +} - type MultiPropertySchema = { - [P in keyof T]: SinglePropertySchema | T[P]; +export type MultiPropertySchema = { + [P in keyof T]: SinglePropertySchema | T[P] +}; + +export type PropertyTypes = + | 'array' + | 'asset' + | 'audio' + | 'boolean' + | 'color' + | 'int' + | 'map' + | 'model' + | 'number' + | 'selector' + | 'selectorAll' + | 'string' + | 'vec2' + | 'vec3' + | 'vec4'; + +export type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart'; + +export interface Scene extends Entity { + behaviors: Behavior[]; + camera: THREE.Camera; + canvas: HTMLCanvasElement; + effect: THREE.VREffect; + isMobile: boolean; + object3D: THREE.Scene; + renderer: THREE.WebGLRenderer; + renderStarted: boolean; + systems: ObjectMap; + time: number; + + enterVR(): Promise | void; + exitVR(): Promise | void; + reload(): void; + + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + useCapture?: boolean + ): void; + addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void; +} + +export type Schema = SinglePropertySchema | MultiPropertySchema; + +export interface SchemaUtils { + isSingleProperty(schema: Schema): boolean; + process(schema: Schema): boolean; +} + +export interface Shader { + name: string; + data: object; + schema: Schema; + material: THREE.Material; + vertexShader: string; + fragmentShader: string; + + init(data?: this['data']): void; + tick?(time: number, timeDelta: number): void; + update(oldData: this['data']): void; +} + +export interface ShaderConstructor { + new (): T; +} + +export interface ShaderDescriptor { + Shader: ShaderConstructor; + schema: Schema; +} + +export interface SinglePropertySchema { + type?: PropertyTypes; + default?: T; + parse?(value: string): T; + stringify?(value: T): string; +} + +export interface System { + data: T; + schema: Schema; + init(): void; + pause(): void; + play(): void; + tick?(t: number, dt: number): void; +} + +export interface SystemConstructor { + new (scene: Scene): T & System; +} + +export interface Utils { + coordinates: { + isCoordinate(value: string): boolean; + parse(value: string): Coordinate; + stringify(coord: Coordinate): string; }; + entity: { + getComponentProperty(entity: Entity, componentName: string, delimiter?: string): any; + setComponentProperty( + entity: Entity, + componentName: string, + value: any, + delimiter?: string + ): void; + }; + styleParser: { + parse(value: string): object; + stringify(data: object): string; + }; + deepEqual(a: any, b: any): boolean; + diff(a: object, b: object): object; + extend(target: object, ...source: object[]): object; + extendDeep(target: object, ...source: object[]): object; - interface PrimitiveDefinition { - defaultComponents?: any; // TODO cleanup type - deprecated?: boolean; - mappings?: any; // TODO cleanup type - transforms?: any; // TODO cleanup type - } + throttle( + tickFunction: () => void, + minimumInterval: number, + optionalContext?: {} + ): (t: number, dt: number) => void; + throttleTick( + tickFunction: (t: number, dt: number) => void, + minimumInterval: number, + optionalContext?: {} + ): (t: number, dt: number) => void; +} - type PropertyTypes = 'array' | 'asset' | 'audio' | 'boolean' | 'color' | - 'int' | 'map' | 'model' | 'number' | 'selector' | 'selectorAll' | - 'string' | 'vec2' | 'vec3' | 'vec4'; +// Definitions +// used as mixins to register functions to create classes (newable functions) in A-Frame +export type ComponentDefinition = T & Partial; +export type GeometryDefinition = T & Partial>; +export type NodeDefinition = T & Partial; +export interface PrimitiveDefinition { + defaultComponents?: any; // TODO cleanup type + deprecated?: boolean; + mappings?: any; // TODO cleanup type + transforms?: any; // TODO cleanup type +} +export interface MinimalShaderDefinition { + schema: Shader['schema']; +} +export type ShaderDefinition = T & + Partial; +export type SystemDefinition = T & Partial; - type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart'; +// root export +export interface AFrame { + AComponent: Component; + AEntity: Entity; + ANode: ANode; + AScene: Scene; - interface Scene extends Entity { - behaviors: Behavior[]; - camera: THREE.Camera; - canvas: HTMLCanvasElement; - effect: THREE.VREffect; - isMobile: boolean; - object3D: THREE.Scene; - renderer: THREE.WebGLRenderer; - renderStarted: boolean; - systems: ObjectMap; - time: number; - - enterVR(): Promise | void; - exitVR(): Promise | void; - reload(): void; - - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void; - } - - type Schema = SinglePropertySchema | MultiPropertySchema; - - interface SchemaUtils { - isSingleProperty(schema: Schema): boolean; - process(schema: Schema): boolean; - } - - interface Shader { - name: string; - data: { [key: string]: any }; - schema: Schema; - material: THREE.Material; - vertexShader: string; - fragmentShader: string; - - init(this: this, data?: this['data']): void; - tick?(this: this, time: number, timeDelta: number): void; - update(this: this, oldData: this['data']): void; - } - - interface ShaderConstructor { - new (): T; - } - - type ShaderDefinition = Partial; - - interface ShaderDescriptor { - Shader: ShaderConstructor; - schema: Schema; - } - - interface SinglePropertySchema { - type?: PropertyTypes; - 'default'?: T; - parse?(value: string): T; - stringify?(value: T): string; - } - - interface System { - data: { [key: string]: any }; - schema: Schema; - init(this: this): void; - pause(this: this): void; - play(this: this): void; - tick?(this: this, t: number, dt: number): void; - } - - interface SystemConstructor { - new (scene: Scene): T; - } - - type SystemDefinition = Partial; - - interface Utils { - coordinates: { - isCoordinate(value: string): boolean; - parse(value: string): Coordinate; - stringify(coord: Coordinate): string; + components: ObjectMap; + geometries: ObjectMap; + primitives: { + getMeshMixin(): { + defaultComponents: { material: object }; + mappings: { [key: string]: any }; // TODO improve any type }; - entity: { - getComponentProperty(entity: Entity, componentName: string, delimiter?: string): any; - setComponentProperty(entity: Entity, componentName: string, value: any, delimiter?: string): void; - }; - styleParser: { - parse(value: string): object; - stringify(data: object): string; - }; - deepEqual(a: any, b: any): boolean; - diff(a: object, b: object): object; - extend(target: object, ... source: object[]): object; - extendDeep(target: object, ... source: object[]): object; + primitives: ObjectMap; + }; + scenes: Scene[]; + schema: SchemaUtils; + shaders: ObjectMap; + systems: ObjectMap; + THREE: ThreeLib; + TWEEN: TweenLib; + utils: Utils; + version: string; - throttle(tickFunction: () => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void; - throttleTick(tickFunction: (t: number, dt: number) => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void; + registerComponent( + name: string, + component: ComponentDefinition + ): ComponentConstructor; + registerElement(name: string, element: object): void; + registerGeometry( + name: string, + geometry: GeometryDefinition + ): GeometryConstructor; + registerPrimitive(name: string, primitive: PrimitiveDefinition): void; + registerShader( + name: string, + shader: ShaderDefinition + ): ShaderConstructor; + registerSystem( + name: string, + definition: SystemDefinition + ): SystemConstructor; +} + +// module.exports +export const AComponent: AFrame['AComponent']; +export const AEntity: AFrame['AEntity']; +export const ANode: AFrame['ANode']; +export const AScene: AFrame['AScene']; +export const components: AFrame['components']; +export const geometries: AFrame['geometries']; +export const primitives: AFrame['primitives']; +export const scenes: AFrame['scenes']; +export const schema: AFrame['schema']; +export const shaders: AFrame['shaders']; +export const systems: AFrame['systems']; +export const THREE: AFrame['THREE']; +export const TWEEN: AFrame['TWEEN']; +export const utils: AFrame['utils']; +export const version: AFrame['version']; +export const registerComponent: AFrame['registerComponent']; +export const registerElement: AFrame['registerElement']; +export const registerGeometry: AFrame['registerGeometry']; +export const registerPrimitive: AFrame['registerPrimitive']; +export const registerShader: AFrame['registerShader']; +export const registerSystem: AFrame['registerSystem']; + +// global exports +declare global { + var hasNativeWebVRImplementation: boolean; + + namespace AFRAME { + const AComponent: AFrame['AComponent']; + const AEntity: AFrame['AEntity']; + const ANode: AFrame['ANode']; + const AScene: AFrame['AScene']; + const components: AFrame['components']; + const geometries: AFrame['geometries']; + const primitives: AFrame['primitives']; + const scenes: AFrame['scenes']; + const schema: AFrame['schema']; + const shaders: AFrame['shaders']; + const systems: AFrame['systems']; + const THREE: AFrame['THREE']; + const TWEEN: AFrame['TWEEN']; + const utils: AFrame['utils']; + const version: string; + + const registerComponent: AFrame['registerComponent']; + const registerElement: AFrame['registerElement']; + const registerGeometry: AFrame['registerGeometry']; + const registerPrimitive: AFrame['registerPrimitive']; + const registerShader: AFrame['registerShader']; + const registerSystem: AFrame['registerSystem']; + } + + /** + * Custom elements augment document methods to return custom HTML + */ + interface Document { + createElement(tagName: string): Entity; + querySelector(selectors: 'a-scene'): Scene; + querySelector(selectors: string): Entity; + querySelectorAll(selectors: string): NodeListOf | Element>; + } + + interface HTMLCollection extends HTMLCollectionBase { + /** + * Retrieves a select object or an object from an options collection. + */ + namedItem(name: string): Element | Entity | null; + item(index: number): Element | Entity; + [index: number]: Element | Entity; } } diff --git a/types/aframe/test/aframe-io-tests.ts b/types/aframe/test/aframe-io-tests.ts new file mode 100644 index 0000000000..77fe716390 --- /dev/null +++ b/types/aframe/test/aframe-io-tests.ts @@ -0,0 +1,1044 @@ +import { Component, Coordinate, Entity, Scene, THREE, ANode } from 'aframe'; + +/** + * These tests are examples from https://aframe.io pulled directly from the sample gallery. + * Types and some formatting have been added, but for the most part they remain unchanged. + */ + +// disable checks for things done in the original, JS examples +/* tslint:disable:object-literal-shorthand */ +/* tslint:disable:no-var-keyword */ +/* tslint:disable:prefer-const */ +/* tslint:disable:only-arrow-functions */ +/* tslint:disable:one-variable-per-declaration */ + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// 360 picture gallery +// Taken from https://glitch.com/edit/#!/aframe-gallery + +/** + * Component that listens to an event, fades out an entity, swaps the texture, and fades it + * back in. + */ +AFRAME.registerComponent('set-image', { + schema: { + on: { type: 'string' }, + target: { type: 'selector' }, + src: { type: 'string' }, + dur: { type: 'number', default: 300 } + }, + + init: function() { + var data = this.data; + var el = this.el!; + + this.setupFadeAnimation(); + + el.addEventListener(data.on, function() { + // Fade out image. + data.target.emit('set-image-fade'); + // Wait for fade to complete. + setTimeout(function() { + // Set image. + data.target.setAttribute('material', 'src', data.src); + }, data.dur); + }); + }, + + /** + * Setup fade-in + fade-out. + */ + setupFadeAnimation: function() { + var data = this.data; + var targetEl = this.data.target; + + // Only set up once. + if (targetEl.dataset.setImageFadeSetup) { + return; + } + targetEl.dataset.setImageFadeSetup = true; + + // Create animation. + targetEl.setAttribute('animation__fade', { + property: 'material.color', + startEvents: 'set-image-fade', + dir: 'alternate', + dur: data.dur, + from: '#FFF', + to: '#000' + }); + } +}); + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// 360 video example +// Taken from https://glitch.com/edit/#!/aframe-360-video-example + +AFRAME.registerComponent('arrow-key-rotation', { + directionX: 0, + directionY: 0, + + schema: { + enabled: { default: true }, + dx: { default: 2.0 }, + dy: { default: 2.0 } + }, + init: function() { + this.onKeyDown = this.onKeyDown.bind(this); + this.onKeyUp = this.onKeyUp.bind(this); + this.directionX = 0; + this.directionY = 0; + }, + play: function() { + window.addEventListener('keydown', this.onKeyDown); + window.addEventListener('keyup', this.onKeyUp); + }, + pause: function() { + window.removeEventListener('keydown', this.onKeyDown); + window.removeEventListener('keyup', this.onKeyUp); + }, + onKeyDown: function(evt: KeyboardEvent) { + switch (evt.keyCode) { + case 37: + this.directionX = 1; + break; + case 38: + this.directionY = 1; + break; + case 39: + this.directionX = -1; + break; + case 40: + this.directionY = -1; + break; + } + }, + onKeyUp: function(evt: KeyboardEvent) { + switch (evt.keyCode) { + case 37: + this.directionX = 0; + break; + case 38: + this.directionY = 0; + break; + case 39: + this.directionX = 0; + break; + case 40: + this.directionY = 0; + break; + } + }, + tick: function() { + if (!this.data.enabled) { + return; + } + var rotation = this.el!.getAttribute('rotation'); + if (!rotation) { + return; + } + if (this.directionX || this.directionY) { + rotation.x += this.data.dx * this.directionY; + rotation.y += this.data.dy * this.directionX; + this.el!.setAttribute('rotation', rotation); + } + } +}); + +AFRAME.registerComponent('hide-once-playing', { + schema: { type: 'selector' }, + init: function() { + this.onPlaying = this.onPlaying.bind(this); + this.onPause = this.onPause.bind(this); + }, + play: function() { + if (this.data) { + this.data.addEventListener('playing', this.onPlaying); + this.data.addEventListener('pause', this.onPause); + } + }, + pause: function() { + if (this.data) { + this.data.removeEventListener('playing', this.onPlaying); + this.data.removeEventListener('pause', this.onPause); + } + }, + onPlaying: function() { + this.el!.setAttribute('visible', false); + }, + onPause: function() { + this.el!.setAttribute('visible', true); + } +}); + +AFRAME.registerComponent('play-on-vrdisplayactivate-or-enter-vr', { + init: function() { + this.playVideo = this.playVideo.bind(this); + this.playVideoNextTick = this.playVideoNextTick.bind(this); + }, + play: function() { + window.addEventListener('vrdisplayactivate', this.playVideo); + this.el!.sceneEl!.addEventListener('enter-vr', this.playVideoNextTick); + }, + pause: function() { + this.el!.sceneEl!.removeEventListener('enter-vr', this.playVideoNextTick); + window.removeEventListener('vrdisplayactivate', this.playVideo); + }, + playVideoNextTick: function() { + setTimeout(this.playVideo); + }, + playVideo: function() { + // TODO improve type + var video = (this.el! as Entity).components.material.material.map.image; + if (!video) { + return; + } + video.play(); + } +}); + +AFRAME.registerComponent('play-on-window-click', { + init: function() { + this.onClick = this.onClick.bind(this); + }, + play: function() { + window.addEventListener('click', this.onClick); + }, + pause: function() { + window.removeEventListener('click', this.onClick); + }, + onClick: function() { + var video = (this.el! as Entity).components.material.material.map.image; + if (!video) { + return; + } + video.play(); + } +}); + +AFRAME.registerComponent('toggle-play-on-window-click', { + init: function() { + this.onClick = this.onClick.bind(this); + }, + play: function() { + window.addEventListener('click', this.onClick); + }, + pause: function() { + window.removeEventListener('click', this.onClick); + }, + onClick: function() { + var video = (this.el! as Entity).components.material.material.map.image; + if (!video) { + return; + } + video.paused ? video.play() : video.pause(); + } +}); + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Animation +// Taken from https://github.com/processprocess/lazerGlazer_Viz + +interface Appender extends HTMLElement { + // append is part of living standard HTML + append(n: Node): void; +} +let scene = document.querySelector('a-scene') as Scene & Appender; +let sky = document.querySelector('a-sky'); +let objectContainer = document.querySelector('#object-container'); + +// random num generator +function getRandomNumber(x: number, y: number) { + return Math.floor(Math.random() * x + y); +} + +// get random hex color +function getRandomColor() { + let letters = '0123456789abcdef'; + let randomColor = ''; + for (let i = 0; i < 6; i++) { + randomColor += letters[Math.floor(Math.random() * 16)]; + } + return randomColor; +} + +// set sky values +sky.setAttribute('color', `#${getRandomColor()}`); +sky.setAttribute( + 'animation__color', + `property: color; dir: alternate; dur: 2000; easing: easeInOutSine; loop: true; to: #${getRandomColor()}` +); + +// change this value for more or less rings +let totalRingElements = 10; + +function generateAllElements() { + for (let a = 0; a < totalRingElements; a++) { + // element params + let totalCircleElements = getRandomNumber(10, 3); + let elementScale = getRandomNumber(3, 1); + let scaleDuration = getRandomNumber(3000, 1000); + + // path params + let pathValOne = getRandomNumber(21, -10); + let pathValTwo = getRandomNumber(11, -20); + let pathDuration = getRandomNumber(6000, 5000); + + for (let i = 1; i <= totalCircleElements; i++) { + let currentRotation = (360 / totalCircleElements) * i; + let rotateContainer = document.createElement('a-entity'); + rotateContainer.setAttribute('rotation', `0 0 ${currentRotation}`); + + // generate circle element and set params + let circleElementContainer = document.createElement('a-entity'); + circleElementContainer.setAttribute('position', `0 1 0`); + let circleElement = document.createElement('a-entity'); + circleElement.setAttribute('class', `circleElement`); + circleElement.setAttribute('scale', `${elementScale} ${elementScale} ${elementScale}`); + circleElement.setAttribute( + 'material', + `color:#${getRandomColor()}; metalness: 0; roughness: 0` + ); + circleElement.setAttribute('geometry', `primitive: sphere; radius: 1.5`); + circleElement.setAttribute( + 'animation__yoyo', + `property: scale; dir: alternate; dur: ${scaleDuration}; easing: easeInOutSine; loop: true; to: 0 0 0` + ); + circleElementContainer.appendChild(circleElement); + rotateContainer.appendChild(circleElementContainer); + + // generate path and apply it + let track1: Appender = document.createElement('a-curve') as any; + track1.setAttribute('class', `track${a}`); + scene.append(track1); + let point1 = document.createElement('a-curve-point'); + point1.setAttribute('position', '0 0 0'); + track1.append(point1); + let point2 = document.createElement('a-curve-point'); + point2.setAttribute('position', `${pathValOne} ${pathValTwo} ${pathValOne}`); + track1.append(point2); + let point3 = document.createElement('a-curve-point'); + point3.setAttribute('position', `${pathValTwo} ${pathValOne} ${pathValTwo}`); + track1.append(point3); + let point4 = document.createElement('a-curve-point'); + point4.setAttribute('position', '0 0 0'); + track1.append(point4); + circleElement.setAttribute( + `alongpath`, + `curve: .track${a}; dur: ${pathDuration}; loop: true` + ); + + // append element to main container + objectContainer.appendChild(rotateContainer); + } + } +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Audio Visualization +// Taken from https://github.com/ngokevin/kframe/tree/b78fb6a17d39556fcf61d00f5afb8b835651e473/components/audioanalyser +/** + * Scale children based on audio frequency levels. + */ +AFRAME.registerComponent('audioanalyser-levels-scale', { + schema: { + analyserEl: { type: 'selector' }, + max: { default: 20 }, + multiplier: { default: 100 } + }, + + tick: function(time) { + var analyserEl; + var children; + var data = this.data; + var levels; + + analyserEl = data.analyserEl || this.el; + levels = analyserEl.components.audioanalyser.levels; + if (!levels) { + return; + } + + children = this.el!.children; + for (var i = 0; i < children.length; i++) { + (children[i] as ANode).setAttribute('scale', { + x: 1, + y: Math.min(data.max, Math.max(levels[i] * data.multiplier, 0.05)), + z: 1 + }); + } + } +}); + +AFRAME.registerComponent('audioanalyser-volume-bind', { + schema: { + analyserEl: { type: 'selector' }, + component: { type: 'string' }, + property: { type: 'string' }, + max: { type: 'number' }, + multiplier: { type: 'number' } + }, + + tick: function() { + var analyserComponent; + var data = this.data; + var el = this.el!; + var value; + + analyserComponent = data.analyserEl.components.audioanalyser; + if (!analyserComponent.analyser) { + return; + } + + value = Math.min(data.max, analyserComponent.volume * data.multiplier); + el.setAttribute(data.component, data.property, value); + } +}); + +AFRAME.registerComponent('audioanalyser-volume-scale', { + schema: { + analyserEl: { type: 'selector' }, + multiplier: { type: 'number', default: 1 } + }, + + tick: function() { + var analyserEl = this.data.analyserEl || this.el; + var analyserComponent; + var el = this.el!; + var volume; + + analyserComponent = analyserEl.components.audioanalyser; + if (!analyserComponent.analyser) { + return; + } + + volume = analyserComponent.volume * this.data.multiplier; + el.setAttribute('scale', { + x: volume, + y: volume, + z: volume + }); + } +}); + +var perlin = ImprovedNoise(); + +var RINGCOUNT = 160; +var SEGMENTS = 512; + +interface AnalyserComponent extends Component { + analyser: any; + volume: number; + waveform: number[]; +} + +/** + * Generate rings (THREE.Line) and transform them using audioanalyser waveform data. + * Adapted from https://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/ + */ +AFRAME.registerComponent('audioanalyser-waveform', { + dependencies: ['audioanalyser'], + + schema: { + maxHeight: { default: 0.2 }, + multiplier: { default: 0.01 }, + radius: { default: 1 } + }, + + init: function(this: any /* TODO improve types */) { + this.colors = []; + this.geometry; + this.levels = []; + this.noisePos = 0; + this.rings = []; + }, + + update: function(this: any /* TODO improve types */) { + var data = this.data; + var el = this.el; + var i; + var lineMesh; + var loopShape; + var material; + var scale; + + // Create ring geometries. + loopShape = new THREE.Shape(); + loopShape.absarc(0, 0, data.radius, 0, Math.PI * 2, false); + this.geometry = loopShape.createPointsGeometry(SEGMENTS / 2); + this.geometry.dynamic = true; + + // Create container object. + el.setObject3D('waveformContainer', new THREE.Object3D()); + + // Create rings. + scale = 1; + for (i = 0; i < RINGCOUNT; i++) { + material = new THREE.LineBasicMaterial({ + color: 0xffffff, + linewidth: 1, + opacity: 0.7, + blending: THREE.AdditiveBlending, + depthTest: true, + transparent: true + }); + lineMesh = new THREE.Line(this.geometry, material); + + scale *= 1.05; + lineMesh.scale.x = scale; + lineMesh.scale.y = scale; + el.getObject3D('waveformContainer').add(lineMesh); + + this.rings.push(lineMesh); + this.levels.push(0); + this.colors.push(0); + } + }, + + tick: function(this: any /* TODO improve types */) { + var VOL_SENS; + var analyserComponent: AnalyserComponent; + var colors = this.colors; + var data = this.data; + var el = this.el; + var levels = this.levels; + var rings = this.rings; + + analyserComponent = el.components.audioanalyser; + if (!analyserComponent.analyser) { + return; + } + + VOL_SENS = 2; + levels.push((analyserComponent.volume / 256) * VOL_SENS); // 256 is max level. + levels.shift(1); + + // Add a new color onto the list. + this.noisePos += 0.005; + colors.push(Math.abs(perlin.noise(this.noisePos, 0, 0))); + colors.shift(1); + + // Write current waveform into all rings. + this.geometry.vertices.forEach(function(vertex: { z: number }, index: number) { + vertex.z = Math.min( + analyserComponent.waveform[index] * data.multiplier, + data.maxHeight + ); + }); + + // Link up last segment. + this.geometry.vertices[this.geometry.vertices.length - 1].z = this.geometry.vertices[0].z; + this.geometry.verticesNeedUpdate = true; + + rings.forEach(function transformRing(ring: THREE.Line, index: number) { + var normLevel; + normLevel = levels[RINGCOUNT - index - 1] + 0.01; // Avoid scaling by 0. + (ring.material as THREE.LineBasicMaterial).color.setHSL(colors[index], 1, normLevel); + ring.material.linewidth = normLevel * 3; + ring.material.opacity = normLevel; + ring.scale.z = normLevel; + }); + }, + + remove: function() { + this.el!.removeObject3D('waveformContainer'); + } +}); + +/** + * http://mrl.nyu.edu/~perlin/noise/ + */ +function ImprovedNoise() { + var p = [ + 151, + 160, + 137, + 91, + 90, + 15, + 131, + 13, + 201, + 95, + 96, + 53, + 194, + 233, + 7, + 225, + 140, + 36, + 103, + 30, + 69, + 142, + 8, + 99, + 37, + 240, + 21, + 10, + 23, + 190, + 6, + 148, + 247, + 120, + 234, + 75, + 0, + 26, + 197, + 62, + 94, + 252, + 219, + 203, + 117, + 35, + 11, + 32, + 57, + 177, + 33, + 88, + 237, + 149, + 56, + 87, + 174, + 20, + 125, + 136, + 171, + 168, + 68, + 175, + 74, + 165, + 71, + 134, + 139, + 48, + 27, + 166, + 77, + 146, + 158, + 231, + 83, + 111, + 229, + 122, + 60, + 211, + 133, + 230, + 220, + 105, + 92, + 41, + 55, + 46, + 245, + 40, + 244, + 102, + 143, + 54, + 65, + 25, + 63, + 161, + 1, + 216, + 80, + 73, + 209, + 76, + 132, + 187, + 208, + 89, + 18, + 169, + 200, + 196, + 135, + 130, + 116, + 188, + 159, + 86, + 164, + 100, + 109, + 198, + 173, + 186, + 3, + 64, + 52, + 217, + 226, + 250, + 124, + 123, + 5, + 202, + 38, + 147, + 118, + 126, + 255, + 82, + 85, + 212, + 207, + 206, + 59, + 227, + 47, + 16, + 58, + 17, + 182, + 189, + 28, + 42, + 223, + 183, + 170, + 213, + 119, + 248, + 152, + 2, + 44, + 154, + 163, + 70, + 221, + 153, + 101, + 155, + 167, + 43, + 172, + 9, + 129, + 22, + 39, + 253, + 19, + 98, + 108, + 110, + 79, + 113, + 224, + 232, + 178, + 185, + 112, + 104, + 218, + 246, + 97, + 228, + 251, + 34, + 242, + 193, + 238, + 210, + 144, + 12, + 191, + 179, + 162, + 241, + 81, + 51, + 145, + 235, + 249, + 14, + 239, + 107, + 49, + 192, + 214, + 31, + 181, + 199, + 106, + 157, + 184, + 84, + 204, + 176, + 115, + 121, + 50, + 45, + 127, + 4, + 150, + 254, + 138, + 236, + 205, + 93, + 222, + 114, + 67, + 29, + 24, + 72, + 243, + 141, + 128, + 195, + 78, + 66, + 215, + 61, + 156, + 180 + ]; + for (var i = 0; i < 256; i++) { + p[256 + i] = p[i]; + } + function fade(t: number) { + return t * t * t * (t * (t * 6 - 15) + 10); + } + function lerp(t: number, a: number, b: number) { + return a + t * (b - a); + } + function grad(hash: number, x: number, y: number, z: number) { + var h = hash & 15; + var u = h < 8 ? x : y, + v = h < 4 ? y : h === 12 || h === 14 ? x : z; + return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v); + } + return { + noise: function(x: number, y: number, z: number) { + var floorX = ~~x, + floorY = ~~y, + floorZ = ~~z; + var X = floorX & 255, + Y = floorY & 255, + Z = floorZ & 255; + x -= floorX; + y -= floorY; + z -= floorZ; + var xMinus1 = x - 1, + yMinus1 = y - 1, + zMinus1 = z - 1; + var u = fade(x), + v = fade(y), + w = fade(z); + var A = p[X] + Y, + AA = p[A] + Z, + AB = p[A + 1] + Z, + B = p[X + 1] + Y, + BA = p[B] + Z, + BB = p[B + 1] + Z; + return lerp( + w, + lerp( + v, + lerp(u, grad(p[AA], x, y, z), grad(p[BA], xMinus1, y, z)), + lerp(u, grad(p[AB], x, yMinus1, z), grad(p[BB], xMinus1, yMinus1, z)) + ), + lerp( + v, + lerp(u, grad(p[AA + 1], x, y, zMinus1), grad(p[BA + 1], xMinus1, y, z - 1)), + lerp( + u, + grad(p[AB + 1], x, yMinus1, zMinus1), + grad(p[BB + 1], xMinus1, yMinus1, zMinus1) + ) + ) + ); + } + }; +} + +AFRAME.registerComponent('color-on-beat', { + schema: { + analyserEl: { type: 'selector' } + }, + + init: function() { + var analyserEl = this.data.analyserEl || this.el; + var el = this.el!; + + analyserEl.addEventListener('audioanalyser-beat', function() { + el.setAttribute( + 'material', + 'color', + '#' + new THREE.Color(Math.random(), Math.random(), Math.random()).getHexString() + ); + }); + } +}); + +AFRAME.registerComponent('remove-on-event', { + schema: { + el: { type: 'selector' }, + event: { type: 'string' } + }, + + init: function() { + this._removeEntity = this._removeEntity.bind(this); + }, + + update: function() { + var data = this.data; + var el = data.el || this.el; + this.removeEventListener(); + el.addEventListener(data.event, this._removeEntity); + }, + + remove: function() { + this.removeEventListener(); + }, + + removeEventListener: function() { + var data = this.data; + var el = this.el!; + el.removeEventListener(data.event, this._removeEntity); + }, + + _removeEntity: function() { + var el = this.el!; + if ((el as any).parentEl) { + (el as any).parentEl.removeChild(el); + } + if (el.parentNode) { + el.parentNode.removeChild(el); + } + } +}); + +/** + * Create expanding ring on audioanalyser beat. + */ +AFRAME.registerComponent('ring-on-beat', { + schema: { + analyserEl: { type: 'selector' } + }, + + init: function(this: any) { + var analyserEl = this.data.analyserEl || this.el; + var el = this.el; + var rings: Entity[] = (this.rings = []); + + analyserEl.addEventListener('audioanalyser-beat', function() { + var ringEl = document.createElement('a-ring'); + ringEl.setAttribute('material', 'opacity', '0.6'); + ringEl.setAttribute('position', '0 0.1 0'); + ringEl.setAttribute('rotation', '-90 0 0'); + el.appendChild(ringEl); + + ringEl.addEventListener('loaded', function() { + rings.push(ringEl); + setTimeout(function() { + el.removeChild(ringEl); + rings.splice(rings.indexOf(ringEl), 1); + }, 2000); + }); + }); + }, + + /** + * Expand ring radii. + */ + tick: function(this: any) { + this.rings.forEach(function(ringEl: Entity) { + var scale = ringEl.getComputedAttribute('scale') as Component & Coordinate; + ringEl.setAttribute('scale', { + x: scale.x * 1.06 + 0.05, + y: scale.y * 1.06 + 0.05, + z: scale.z + }); + }); + } +}); + +/* + * Change color at different levels of scale. + */ +AFRAME.registerComponent('scale-y-color', { + schema: { + from: { type: 'vec3', default: { x: 0, y: 0, z: 0 } }, + to: { type: 'vec3', default: { x: 255, y: 255, z: 255 } }, + maxScale: { default: 20 } + }, + + tick: function(this: any, time: number) { + var data = this.data; + var el = this.el; + + if (time - this.time < 50) { + return; + } + this.time = time; + + var scaleY = el.getComputedAttribute('scale').y; + var percentage = scaleY / data.maxScale; + el.setAttribute( + 'material', + 'color', + '#' + + rgbToHex( + (data.to.x - data.from.x) * percentage, + (data.to.y - data.from.y) * percentage, + (data.to.z - data.from.z) * percentage + ) + ); + } +}); + +function rgbToHex(r: number, g: number, b: number) { + var bin = (r << 16) | (g << 8) | b; + return (function(h) { + return new Array(7 - h.length).join('0') + h; + })(bin.toString(16).toUpperCase()); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Lights +// Taken from https://github.com/aframevr/aframe/blob/master/examples/showcase/dynamic-lights/index.html + +AFRAME.registerComponent('random-material', { + init: function() { + this.el!.setAttribute('material', { + color: this.getRandomColor(), + metalness: Math.random(), + roughness: Math.random() + }); + }, + getRandomColor: function() { + var letters = '0123456789ABCDEF'.split(''); + var color = '#'; + for (var i = 0; i < 6; i++) { + color += letters[Math.floor(Math.random() * 16)]; + } + return color; + } +}); + +AFRAME.registerComponent('random-torus-knot', { + init: function() { + this.el!.setAttribute('geometry', { + primitive: 'torusKnot', + radius: Math.random() * 10, + radiusTubular: Math.random() * 0.75, + p: Math.round(Math.random() * 10), + q: Math.round(Math.random() * 10) + }); + } +}); diff --git a/types/aframe/aframe-tests.ts b/types/aframe/test/aframe-tests.ts similarity index 67% rename from types/aframe/aframe-tests.ts rename to types/aframe/test/aframe-tests.ts index 5e2bd23e36..2d6ff5bb7e 100644 --- a/types/aframe/aframe-tests.ts +++ b/types/aframe/test/aframe-tests.ts @@ -1,3 +1,14 @@ +import { + Component, + Entity, + MultiPropertySchema, + System, + SystemDefinition, + THREE, + Geometry, + registerComponent +} from 'aframe'; + // Global const threeCamera = new AFRAME.THREE.Camera(); AFRAME.TWEEN.Easing; @@ -16,7 +27,7 @@ entity.setAttribute('material', 'color', 'red'); entity.components['geometry'].data; -type MyEntity = AFrame.Entity<{ +type MyEntity = Entity<{ camera: THREE.Camera; material: THREE.Material; sound: { pause(): void }; @@ -33,29 +44,31 @@ entity.setAttribute('light', { intensity: 2.0 }); -entity.addEventListener('child-detached', (event) => { +entity.addEventListener('child-detached', event => { event.detail; }); // Components -interface TestComponent extends AFrame.Component { - multiply: (f: number) => number; +// interface TestComponent extends Component { +// multiply: (f: number) => number; +// +// data: { +// myProperty: any[], +// string: string, +// num: number +// }; +// +// system: TestSystem; +// } - data: { - myProperty: any[], - string: string, - num: number - }; - - system: TestSystem; -} - -const Component = AFRAME.registerComponent('test-component', { +const Component = registerComponent('test-component', { schema: { myProperty: { default: [], - parse() { return [true]; }, + parse() { + return [true]; + } }, string: { type: 'string' }, num: 0 @@ -69,9 +82,9 @@ const Component = AFRAME.registerComponent('test-component', { pause() {}, play() {}, - multiply(this: TestComponent, f: number) { + multiply(f: number) { // Reference to system because both were registered with the same name. - return f * this.data.num * this.system.data.counter; + return f * this.data.num * this.system!.data.counter; } }); @@ -81,13 +94,7 @@ scene.hasLoaded; // System -interface TestSystem extends AFrame.System { - data: { - counter: number; - }; -} - -const testSystem: AFrame.SystemDefinition = { +const testSystem: SystemDefinition = { schema: { counter: 0 }, @@ -101,13 +108,7 @@ AFRAME.registerSystem('test-component', testSystem); // Register Custom Geometry -interface TestGeometry extends AFrame.Geometry { - schema: AFrame.MultiPropertySchema<{ - groupIndex: number; - }>; -} - -AFRAME.registerGeometry('a-test-geometry', { +AFRAME.registerGeometry('a-test-geometry', { schema: { groupIndex: { default: 0 } }, diff --git a/types/aframe/tsconfig.json b/types/aframe/tsconfig.json index 3385a8aca7..d92e791ebd 100755 --- a/types/aframe/tsconfig.json +++ b/types/aframe/tsconfig.json @@ -21,6 +21,7 @@ }, "files": [ "index.d.ts", - "aframe-tests.ts" + "test/aframe-tests.ts", + "test/aframe-io-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 0c2d244b05..71684995a4 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1128,7 +1128,7 @@ declare namespace algoliasearch { * default: "" * https://github.com/algolia/algoliasearch-client-js#facets */ - facets?: string; + facets?: string | string[]; /** * Limit the number of facet values returned for each facet. * default: "" @@ -1375,7 +1375,7 @@ declare namespace algoliasearch { * Filter the query by a set of facets. * https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated */ - facetFilters?: string; + facetFilters?: string | string[] /** * If set to false, this query will not be taken into account in the analytics feature. * default true @@ -1421,6 +1421,10 @@ declare namespace algoliasearch { * The query for the search in this facet */ facetQuery: string; + /** + * The maximum number of facets to fetch + */ + maxFacetHits?: number; } interface Response { diff --git a/types/angular-block-ui/angular-block-ui-tests.ts b/types/angular-block-ui/angular-block-ui-tests.ts index 4446e73234..8733565449 100644 --- a/types/angular-block-ui/angular-block-ui-tests.ts +++ b/types/angular-block-ui/angular-block-ui-tests.ts @@ -36,7 +36,9 @@ app.controller('Ctrl', ($scope: ng.IScope, blockUI: angular.blockUI.BlockUIServi blockUI.stop(); blockUI.reset(); blockUI.message("Hello Types"); - blockUI.done(); + blockUI.done(() => { + console.log("blockUI stopped"); + }); const b: boolean = blockUI.isBlocking(); const myBlockUI = blockUI.instances.get("myBlockUI"); diff --git a/types/angular-block-ui/index.d.ts b/types/angular-block-ui/index.d.ts index f0dcdcd076..39cbcce194 100644 --- a/types/angular-block-ui/index.d.ts +++ b/types/angular-block-ui/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for angular-block-ui 0.2 // Project: https://github.com/McNull/angular-block-ui -// Definitions by: Lasse Nørregaard , Stephan Classen , Soner Köksal +// Definitions by: Lasse Nørregaard +// Stephan Classen +// Soner Köksal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -48,6 +50,8 @@ declare module 'angular' { * * If you don't want this behaviour and want to do all the * blocking manually you can change this value to false. + * + * The default value is 'true' */ autoBlock?: boolean; @@ -56,6 +60,8 @@ declare module 'angular' { * hide the overlay whenever an exception has occurred. * * You can set this value to false if you don't want this behaviour. + * + * The default value is 'true' */ resetOnException?: boolean; @@ -74,33 +80,42 @@ declare module 'angular' { /** * When the module is started it will inject the main block element - * by adding the block-ui directive to the body element. + * by adding the "block-ui" directive to the element. + * + * Set this to false if there no need for any fullscreen blocking or if there's + * more control required. For instance when your ng-app directive is a child + * element of the body element it is impossible for the blockUI resolve the main + * instance. In such a case the auto injection of the main block scope should + * be disabled and the main block element should be relocated. + * + * The default value is 'true' */ autoInjectBodyBlock?: boolean; /** - * A string containing the default css classes, separated by spaces, + * A string containing the default css classes (separated by spaces) * that should be applied to each block-ui element. * - * The default value is `block-ui block-ui-anim-fade` + * The default value is "block-ui block-ui-anim-fade" */ cssClass?: string; /** - * Whenever a user interface block is active, because the single page - * application is still waiting for a response from the backend server, - * the user can still navigate away using the back and forward buttons - * of the browser. + * While a user interface block is active the user can still navigate + * away using the back and forward buttons of the browser. * - * Callbacks registered to handle the responses from the server will - * be executed even if a different view/controller is currently active. - * By setting the blockBrowserNavigation property to true the - * angular-block-ui module will prevent navigation while a fullscreen + * Callbacks registered to handle responses from the server will + * be executed even if a different view/controller is active at the + * time the response arrives. + * + * You can set this value to true if you want to prevent navigation + * with the browser back and forward buttons while a fullscreen * block is active. * * Programatic location changes via the $location service are still * allowed however. - * The navigation block is disabled by default. + * + * The default value is 'false' */ blockBrowserNavigation?: boolean; } @@ -150,7 +165,7 @@ declare module 'angular' { * This can be useful whenever you wish to redirect the user * to a different location while there are still pending AJAX requests. */ - done(): void; + done(doneCallback: () => void): void; /** * Allows the message shown in the overlay to be updated diff --git a/types/angular-block-ui/tsconfig.json b/types/angular-block-ui/tsconfig.json index f5717731be..8810e02911 100644 --- a/types/angular-block-ui/tsconfig.json +++ b/types/angular-block-ui/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "angular-block-ui-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/antlr4-autosuggest/antlr4-autosuggest-tests.ts b/types/antlr4-autosuggest/antlr4-autosuggest-tests.ts new file mode 100644 index 0000000000..bfb55cdfc1 --- /dev/null +++ b/types/antlr4-autosuggest/antlr4-autosuggest-tests.ts @@ -0,0 +1,19 @@ +import * as antlr4 from 'antlr4'; +import * as autosuggest from 'antlr4-autosuggest'; + +class Antlr4JSLexer extends antlr4.Lexer { + constructor(chars: antlr4.InputStream) { + super(); + } +} + +class Antlr4JSParser extends antlr4.Parser { + constructor(tokens: antlr4.CommonTokenStream) { + super(tokens); + } +} + +const autosuggester: autosuggest.AutoSuggester = autosuggest.autosuggester(Antlr4JSLexer, Antlr4JSParser); +const suggestions: string[] = autosuggester.autosuggest('ABC'); + +const lowercase = autosuggest.autosuggester(Antlr4JSLexer, Antlr4JSParser, 'LOWER'); diff --git a/types/antlr4-autosuggest/index.d.ts b/types/antlr4-autosuggest/index.d.ts new file mode 100644 index 0000000000..45f8ab5ced --- /dev/null +++ b/types/antlr4-autosuggest/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for antlr4-autosuggest 0.0 +// Project: https://github.com/oranoran/antlr4-autosuggest-js +// Definitions by: Jon Freedman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as antlr4 from 'antlr4'; + +export type CasePreference = 'LOWER' | 'UPPER' | 'BOTH'; + +export interface AutoSuggester { + autosuggest: (inputText: string) => string[]; +} + +export interface Constructor { + new (...args: any[]): T; +} + +export function autosuggester(lexerCtr: Constructor, parserCtr: Constructor, casePref?: CasePreference | null): AutoSuggester; diff --git a/types/antlr4-autosuggest/tsconfig.json b/types/antlr4-autosuggest/tsconfig.json new file mode 100644 index 0000000000..5e7898c616 --- /dev/null +++ b/types/antlr4-autosuggest/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", + "antlr4-autosuggest-tests.ts" + ] +} diff --git a/types/redux-little-router/tslint.json b/types/antlr4-autosuggest/tslint.json similarity index 100% rename from types/redux-little-router/tslint.json rename to types/antlr4-autosuggest/tslint.json diff --git a/types/applicationinsights-js/applicationinsights-js-tests.ts b/types/applicationinsights-js/applicationinsights-js-tests.ts index 6588c3fcd3..c2adb63a30 100644 --- a/types/applicationinsights-js/applicationinsights-js-tests.ts +++ b/types/applicationinsights-js/applicationinsights-js-tests.ts @@ -17,7 +17,6 @@ const config: Microsoft.ApplicationInsights.IConfig = { autoTrackPageVisitTime: true, disableExceptionTracking: false, disableAjaxTracking: false, - disableFetchTracking: true, overridePageViewDuration: false, maxAjaxCallsPerView: -1, disableDataLossAnalysis: true, diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index 517324cde4..5fbbc3a0f5 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -1,7 +1,8 @@ // Type definitions for ApplicationInsights-JS 1.0 // Project: https://github.com/Microsoft/ApplicationInsights-JS -// Definitions by: Kamil Szostak -// Mark Wolff +// Definitions by: Mark Wolff +// Piyali Jana +// Basal Rustum // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module AI { @@ -561,7 +562,6 @@ declare module Microsoft.ApplicationInsights { samplingPercentage?: number; autoTrackPageVisitTime?: boolean; disableAjaxTracking?: boolean; - disableFetchTracking?: boolean; overridePageViewDuration?: boolean; maxAjaxCallsPerView?: number; disableDataLossAnalysis?: boolean; diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 94575006ab..5fa225eafd 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -400,10 +400,10 @@ cognitoUserPoolEvent.request.session![0].challengeName === "DEVICE_SRP_AUTH"; cognitoUserPoolEvent.request.session![0].challengeName === "DEVICE_PASSWORD_VERIFIER"; cognitoUserPoolEvent.request.session![0].challengeName === "ADMIN_NO_SRP_AUTH"; bool = cognitoUserPoolEvent.request.session![0].challengeResult; -strOrUndefined = cognitoUserPoolEvent.request.session![0].challengeMetaData; +strOrUndefined = cognitoUserPoolEvent.request.session![0].challengeMetadata; strOrUndefined = cognitoUserPoolEvent.request.challengeName; str = cognitoUserPoolEvent.request.privateChallengeParameters!["answer"]; -str = cognitoUserPoolEvent.request.challengeAnswer!["answer"]; +str = cognitoUserPoolEvent.request.challengeAnswer!; boolOrUndefined = cognitoUserPoolEvent.response.answerCorrect; strOrUndefined = cognitoUserPoolEvent.response.smsMessage; strOrUndefined = cognitoUserPoolEvent.response.emailMessage; @@ -413,7 +413,7 @@ boolOrUndefined = cognitoUserPoolEvent.response.issueTokens; boolOrUndefined = cognitoUserPoolEvent.response.failAuthentication; str = cognitoUserPoolEvent.response.publicChallengeParameters!["captchaUrl"]; str = cognitoUserPoolEvent.response.privateChallengeParameters!["answer"]; -strOrUndefined = cognitoUserPoolEvent.response.challengeMetaData; +strOrUndefined = cognitoUserPoolEvent.response.challengeMetadata; boolOrUndefined = cognitoUserPoolEvent.response.answerCorrect; // CloudFormation Custom Resource @@ -581,7 +581,7 @@ const CodePipelineEvent: AWSLambda.CodePipelineEvent = { CodePipelineEvent["CodePipeline.job"].data.encryptionKey = { type: 'KMS', id: 'key' }; /* CloudFront events, see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */ -const CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { +const CloudFrontRequestWithCustomOriginEvent: AWSLambda.CloudFrontRequestEvent = { Records: [ { cf: { @@ -630,7 +630,44 @@ const CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { "TLSv1", "TLSv1.1" ] - }, + } + } + } + } + } + ] +}; + +const CloudFrontRequestWithS3OriginEvent: AWSLambda.CloudFrontRequestEvent = { + Records: [ + { + cf: { + config: { + distributionDomainName: "d123.cloudfront.net", + distributionId: "EDFDVBD6EXAMPLE", + eventType: "viewer-request", + requestId: "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" + }, + request: { + clientIp: "2001:0db8:85a3:0:0:8a2e:0370:7334", + method: "GET", + uri: "/picture.jpg", + querystring: "size=large", + headers: { + host: [ + { + key: "Host", + value: "d111111abcdef8.cloudfront.net" + } + ], + "user-agent": [ + { + key: "User-Agent", + value: "curl/7.51.0" + } + ] + }, + origin: { s3: { authMethod: "origin-access-identity", customHeaders: { @@ -812,6 +849,56 @@ apiGtwProxyHandler = proxyHandler; const codePipelineHandler: AWSLambda.CodePipelineHandler = (event: AWSLambda.CodePipelineEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; const cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { + event = CloudFrontRequestWithCustomOriginEvent; + // $ExpectType CloudFrontRequestEvent + event; + let request = event.Records[0].cf.request; + + let s3Origin: AWSLambda.CloudFrontS3Origin = { + authMethod: 'none', + customHeaders: {}, + domainName: 'example.com', + path: '/', + region: 'us-east-1' + }; + + if (request.origin && request.origin.custom) { + request.origin.custom.domainName; + request.origin.custom.domainName = "example2.com"; + + // $ExpectError + s3Origin = request.origin.s3; + + // $ExpectError + request.origin.s3.path = '/'; + } + + let customOrigin: AWSLambda.CloudFrontCustomOrigin = { + customHeaders: {}, + domainName: 'example.com', + keepaliveTimeout: 60, + path: '/', + port: 80, + protocol: 'http', + readTimeout: 30, + sslProtocols: [] + }; + + event = CloudFrontRequestWithS3OriginEvent; + // $ExpectType CloudFrontRequestEvent + event; + request = event.Records[0].cf.request; + if (request.origin && request.origin.s3) { + request.origin.s3.path; + request.origin.s3.path = "/new_path"; + + // $ExpectError + customOrigin = request.origin.custom; + + // $ExpectError + request.origin.custom.path = '/'; + } + cb(); cb(null); cb(new Error('')); diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 35d0b1d7a6..cce721e68c 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -21,6 +21,7 @@ // Jeremy Nagel // Louis Larry // Daniel Papukchiev +// Oliver Hookins // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -250,11 +251,11 @@ export interface CognitoUserPoolTriggerEvent { session?: Array<{ challengeName: "CUSTOM_CHALLENGE" | "PASSWORD_VERIFIER" | "SMS_MFA" | "DEVICE_SRP_AUTH" | "DEVICE_PASSWORD_VERIFIER" | "ADMIN_NO_SRP_AUTH"; challengeResult: boolean; - challengeMetaData?: string; + challengeMetadata?: string; }>; challengeName?: string; privateChallengeParameters?: { [key: string]: string }; - challengeAnswer?: { [key: string]: string }; + challengeAnswer?: string; }; response: { autoConfirmUser?: boolean; @@ -266,7 +267,7 @@ export interface CognitoUserPoolTriggerEvent { failAuthentication?: boolean; publicChallengeParameters?: { [key: string]: string }; privateChallengeParameters?: { [key: string]: string }; - challengeMetaData?: string; + challengeMetadata?: string; answerCorrect?: boolean; }; } @@ -561,6 +562,9 @@ export interface CodePipelineEvent { /** * CloudFront events * http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html + * Bear in mind that the "example" event structure in the page above includes + * both an S3 and a Custom origin, which is not strictly allowed. Only one + * of these per event may be present. */ export interface CloudFrontHeaders { [name: string]: Array<{ @@ -569,6 +573,29 @@ export interface CloudFrontHeaders { }>; } +export type CloudFrontOrigin = + | { s3: CloudFrontS3Origin, custom?: never } + | { custom: CloudFrontCustomOrigin, s3?: never }; + +export interface CloudFrontCustomOrigin { + customHeaders: CloudFrontHeaders; + domainName: string; + keepaliveTimeout: number; + path: string; + port: number; + protocol: 'http' | 'https'; + readTimeout: number; + sslProtocols: string[]; +} + +export interface CloudFrontS3Origin { + authMethod: 'origin-access-identity' | 'none'; + customHeaders: CloudFrontHeaders; + domainName: string; + path: string; + region: string; +} + export interface CloudFrontResponse { status: string; statusDescription: string; @@ -581,6 +608,7 @@ export interface CloudFrontRequest { uri: string; querystring: string; headers: CloudFrontHeaders; + origin?: CloudFrontOrigin; } export interface CloudFrontEvent { diff --git a/types/bell/bell-tests.ts b/types/bell/bell-tests.ts index 65b3e5f4d5..bcd3a3d40c 100644 --- a/types/bell/bell-tests.ts +++ b/types/bell/bell-tests.ts @@ -5,6 +5,9 @@ async function run() { const server = new Server({ port: 8000 }); await server.register(bell); + bell.simulate(async () => ({})); + bell.simulate(() => ({})); + server.auth.strategy('arcgisonline', 'bell', { provider: 'twitter', password: 'some cookie password', diff --git a/types/bell/index.d.ts b/types/bell/index.d.ts index 14cdc65cb9..cf6a6866e1 100644 --- a/types/bell/index.d.ts +++ b/types/bell/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bell 9.1 +// Type definitions for bell 9.3 // Project: https://github.com/hapijs/bell // Definitions by: Simon Schick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -62,10 +62,7 @@ export type Provider = 'wordpress' | 'yahoo'; -export type RequestPassThrough = ( - request: Request, - next: (err: Error | null, credentials: AuthCredentials) => void, -) => void; +export type RequestPassThrough = (request: Request) => PromiseLike | AuthCredentials; export interface OptionalOptions { /** diff --git a/types/bip32/bip32-tests.ts b/types/bip32/bip32-tests.ts new file mode 100644 index 0000000000..4256ca6366 --- /dev/null +++ b/types/bip32/bip32-tests.ts @@ -0,0 +1,9 @@ +import { fromBase58 } from 'bip32'; + +const node = fromBase58("xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"); + +const child = node.derivePath('m/0'); + +const grandchild = child.derive(2); + +grandchild.toWIF() === 'Kxtby4wzfHeCaRXma16dBNLgUE7Ct3Xkb6sRs3aZ56Bmtf1rcNWs'; diff --git a/types/bip32/index.d.ts b/types/bip32/index.d.ts new file mode 100644 index 0000000000..99a1b8dffd --- /dev/null +++ b/types/bip32/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for bip32 1.0 +// Project: https://github.com/bitcoinjs/bip32#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +export interface NetworkType { + wif: number; // UInt8 + bip32: { + public: number; // UInt32 + private: number; // UInt32 + }; +} + +export class BIP32 { + private constructor(d: Buffer, Q: Buffer, chainCode: Buffer, network: NetworkType); + + identifier: Buffer; + fingerprint: Buffer; + privateKey: Buffer; + publicKey: Buffer; + + private depth: number; + private index: number; + private parentFingerprint: number; + private network: NetworkType; + + isNeutered(): boolean; + neutered(): BIP32; + toBase58(): string; + toWIF(): string; + derive(index: number): BIP32; + deriveHardened(index: number): BIP32; + derivePath(path: string): BIP32; + sign(hash: Buffer): Buffer; + verify(hash: Buffer, signature: Buffer): boolean; +} + +/** + * Returns a node + * @param string base58 encoded string + * @param network network type of the node + */ +export function fromBase58(string: string, network?: NetworkType): BIP32; + +/** + * Returns a hardened node + * @param privateKey node private key + * @param chainCode 256-bits entropy extension + * @param network network type of the node + */ +export function fromPrivateKey(privateKey: Buffer, chainCode: Buffer, network?: NetworkType): BIP32; + +/** + * Returns a non-hardened node + * @param publicKey node public key + * @param chainCode 256-bits entropy extension + * @param network network type of the node + */ +export function fromPublicKey(publicKey: Buffer, chainCode: Buffer, network?: NetworkType): BIP32; + +/** + * Returns a hardened node + * @param seed seed encoding node info + * @param network network type of the node + */ +export function fromSeed(seed: Buffer, network?: NetworkType): BIP32; diff --git a/types/bip32/tsconfig.json b/types/bip32/tsconfig.json new file mode 100644 index 0000000000..ca18bb2a82 --- /dev/null +++ b/types/bip32/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", + "bip32-tests.ts" + ] +} diff --git a/types/bip32/tslint.json b/types/bip32/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bip32/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts index 9576ba7289..cc24c6573b 100644 --- a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts +++ b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts @@ -1,4 +1,3 @@ -import bigi = require('bigi'); import bitcoin = require('bitcoinjs-lib'); // For testing only @@ -8,19 +7,18 @@ function rng() { // Generate a random bitcoin address const keyPair1 = bitcoin.ECPair.makeRandom({rng}); -const address = keyPair1.getAddress(); +const { address } = bitcoin.payments.p2pkh({ pubkey: keyPair1.publicKey }); keyPair1.toWIF(); // Generate an address from a SHA256 hash const hash = bitcoin.crypto.sha256(Buffer.from('correct horse battery staple', 'utf8')); -const d = bigi.fromBuffer(hash); -const keyPair2 = new bitcoin.ECPair(d); +const keyPair2 = bitcoin.ECPair.fromPrivateKey(hash); // Generate a random keypair for alternative networks -const keyPair3 = bitcoin.ECPair.makeRandom({network: bitcoin.networks.litecoin, rng}); +const keyPair3 = bitcoin.ECPair.makeRandom({network: bitcoin.networks.testnet, rng}); keyPair3.toWIF(); -keyPair3.getAddress(); -const network = keyPair3.getNetwork(); +bitcoin.payments.p2pkh({ pubkey: keyPair3.publicKey }); +const network = keyPair3.network; // Test TransactionBuilder and Transaction const txb = new bitcoin.TransactionBuilder(); @@ -41,22 +39,3 @@ bitcoin.address.toBase58Check(rsBase58Check.hash, rsBase58Check.version); bitcoin.address.toBech32(rsBech32.data, rsBech32.version, rsBech32.prefix); bitcoin.address.toOutputScript(address); bitcoin.address.toOutputScript(address, network); - -const redeemScript = bitcoin.script.multisig.output.encode( - 2, - [ - new Buffer('12345678901234567890123456789012'), - new Buffer('12345678901234567890123456789012'), - new Buffer('12345678901234567890123456789012'), - ] -); -bitcoin.script.scriptHash.input.encode( - bitcoin.script.multisig.input.encodeStack( - [ - new Buffer('12345678901234567890123456789012'), - new Buffer('12345678901234567890123456789012'), - ], - redeemScript, - ), - redeemScript, -); diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index 2d0603b87c..4fb1bb16a7 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bitcoinjs-lib 3.4 +// Type definitions for bitcoinjs-lib 4.0 // Project: https://github.com/bitcoinjs/bitcoinjs-lib // Definitions by: Mohamed Hegazy // Daniel @@ -12,8 +12,6 @@ /// -import BigInteger = require('bigi'); - export interface Out { script: Buffer; value: number; @@ -68,29 +66,23 @@ export class Block { } export class ECPair { - constructor(d: BigInteger, Q?: null, options?: { compressed?: boolean, network?: Network }); - - constructor(d: null | undefined, Q: any, options?: { compressed?: boolean, network?: Network }); // Q should be ECPoint, but not sure how to define such type - - d: BigInteger; - readonly compressed: boolean; + readonly privateKey: Buffer; + + readonly publicKey: Buffer; + readonly network: Network; - getAddress(): string; - - getNetwork(): Network; - - getPublicKeyBuffer(): Buffer; - - sign(hash: Buffer): ECSignature; + sign(hash: Buffer): Buffer; toWIF(): string; - verify(hash: Buffer, signature: ECSignature): boolean; + verify(hash: Buffer, signature: Buffer): boolean; - static fromPublicKeyBuffer(buffer: Buffer, network: Network): ECPair; + static fromPrivateKey(buffer: Buffer, options?: { compressed?: boolean, network?: Network }): ECPair; + + static fromPublicKey(buffer: Buffer, options?: { compressed?: boolean, network?: Network }): ECPair; static fromWIF(string: string, network?: Network): ECPair; @@ -99,66 +91,6 @@ export class ECPair { export type Rng = (size: number) => Buffer; -export class ECSignature { - constructor(r: BigInteger, s: BigInteger); - - toCompact(i: number, compressed: boolean): Buffer; - - toDER(): Buffer; - - toScriptSignature(hashType: number): Buffer; - - static fromDER(buffer: Buffer): ECSignature; - - static parseCompact(buffer: Buffer): { compressed: boolean, i: number, signature: ECSignature }; - - static parseScriptSignature(buffer: Buffer): { signature: ECSignature, hashType: number }; -} - -export class HDNode { - constructor(keyPair: ECPair, chainCode: Buffer); - - keyPair: ECPair; - - derive(index: number): HDNode; - - deriveHardened(index: number): HDNode; - - derivePath(path: string): HDNode; - - getAddress(): string; - - getFingerprint(): Buffer; - - getIdentifier(): Buffer; - - getNetwork(): Network; - - getPublicKeyBuffer(): Buffer; - - isNeutered(): boolean; - - neutered(): HDNode; - - sign(hash: Buffer): ECSignature; - - toBase58(): string; - - verify(hash: Buffer, signature: ECSignature): boolean; - - static HIGHEST_BIT: number; - - static LENGTH: number; - - static fromBase58(string: string, networks?: Network[] | Network): HDNode; - - static fromSeedBuffer(seed: Buffer, network?: Network): HDNode; - - static fromSeedHex(hex: string, network?: Network): HDNode; - - static MASTER_SECRET: Buffer; -} - export class Transaction { version: number; locktime: number; @@ -236,9 +168,6 @@ export interface Input { } export class TransactionBuilder { - tx: Transaction; - inputs: Input[]; - constructor(network?: Network, maximumFeeRate?: number); addInput(txhash: Buffer | string | Transaction, vout: number, sequence?: number, prevOutScript?: Buffer): number; @@ -261,7 +190,6 @@ export class TransactionBuilder { export const networks: { bitcoin: Network; - litecoin: Network; testnet: Network; }; @@ -391,7 +319,7 @@ export namespace address { /** @since 3.2.0 */ function fromBech32(address: string): { data: Buffer, prefix: string, version: number }; - function fromOutputScript(outputScript: Buffer, network?: Network): string; + function fromOutputScript(output: Buffer, network?: Network): string; function toBase58Check(hash: Buffer, version: number): string; @@ -401,26 +329,6 @@ export namespace address { function toOutputScript(address: string, network?: Network): Buffer; } -export namespace bufferutils { - function pushDataSize(i: number): number; - - function readPushDataInt(buffer: Buffer, offset: number): { opcode: number, number: number, size: number }; - - function readUInt64LE(buffer: Buffer, offset: number): number; - - function readVarInt(buffer: Buffer, offset: number): { number: number, size: number }; - - function varIntBuffer(number: number, buffer: Buffer, offset: number): Buffer; - - function varIntSize(number: number): number; - - function writePushDataInt(buffer: Buffer, number: number, offset: number): number; - - function writeUInt64LE(buffer: Buffer, value: number, offset: number): number; - - function writeVarInt(buffer: Buffer, number: number, offset: number): number; -} - export namespace crypto { function hash160(buffer: Buffer): Buffer; @@ -449,7 +357,7 @@ export namespace script { function isCanonicalPubKey(buffer: Buffer): boolean; - function isCanonicalSignature(buffer: Buffer): boolean; + function isCanonicalScriptSignature(buffer: Buffer): boolean; function isDefinedHashType(hashType: any): boolean; @@ -465,66 +373,48 @@ export namespace script { function encode(number: number): Buffer; } + namespace signature { + function decode(buffer: Buffer): { signature: Buffer, hashType: number }; + + function encode(signature: Buffer, hashType: number): Buffer; + } + const multisig: { input: { check(script: Buffer, allowIncomplete: boolean): boolean; - decode(buffer: Buffer): Array; - decodeStack(stack: Buffer[], allowIncomplete: boolean): Array; - encode(signatures: Buffer[], scriptPubKey: Buffer): Buffer; - encodeStack(signatures: Buffer[], scriptPubKey: Buffer): Buffer[]; }; output: { check(script: Buffer, allowIncomplete: boolean): boolean; - decode(buffer: Buffer, allowIncomplete: boolean): { m: number; pubKeys: Array }; - encode(m: number, pubKeys: Array): Buffer; }; }; const pubKey: { input: { check(script: Buffer): boolean; - decode(buffer: Buffer): Array; - decodeStack(stack: Buffer[]): Array; - encode(signature: Buffer): Buffer; - encodeStack(signature: Buffer): Buffer[]; }; output: { check(script: Buffer): boolean; - decode(buffer: Buffer): Buffer | number; - encode(pubKey: Buffer): Buffer; }; }; const pubKeyHash: { input: { check(script: Buffer): boolean; - decode(buffer: Buffer): { signature: Buffer; pubKey: Buffer }; - decodeStack(stack: Buffer[]): { signature: Buffer; pubKey: Buffer }; - encode(signature: Buffer, pubKey: Buffer): Buffer; - encodeStack(signature: Buffer, pubKey: Buffer): [Buffer, Buffer]; }; output: { check(script: Buffer): boolean; - decode(buffer: Buffer): Buffer; - encode(pubKeyHash: Buffer): Buffer; }; }; const scriptHash: { input: { check(script: Buffer, allowIncomplete: boolean): boolean; - decode(buffer: Buffer): { redeemScriptStack: Buffer[]; redeemScript: Buffer }; - decodeStack(stack: Buffer[]): { redeemScriptStack: Buffer[]; redeemScript: Buffer }; - encode(redeemScriptSig: Array, redeemScript: Buffer): Buffer; - encodeStack(redeemScriptStack: Buffer[], redeemScript: Buffer): Buffer[]; }; output: { check(script: Buffer): boolean; - decode(buffer: Buffer): Buffer; - encode(scriptHash: Buffer): Buffer; }; }; @@ -539,36 +429,56 @@ export namespace script { const witnessPubKeyHash: { input: { check(script: Buffer): boolean; - decodeStack(stack: Buffer[]): { signature: Buffer; pubKey: Buffer }; - encodeStack(signature: Buffer, pubKey: Buffer): [Buffer, Buffer]; }; output: { check(script: Buffer): boolean; - decode(buffer: Buffer): Buffer; - encode(pubKeyHash: Buffer): Buffer; }; }; const witnessScriptHash: { input: { check(script: Buffer, allowIncomplete: boolean): boolean; - decodeStack(stack: Buffer[]): { redeemScriptStack: Buffer[]; redeemScript: Buffer }; - encodeStack(redeemScriptStack: Buffer[], redeemScript: Buffer): Buffer[]; }; output: { check(script: Buffer): boolean; - decode(buffer: Buffer): Buffer; - encode(scriptHash: Buffer): Buffer; }; }; const nullData: { output: { check(script: Buffer): boolean; - decode(buffer: Buffer): Buffer; - encode(data: Buffer): Buffer; }; }; } + +export namespace payments { + function p2data(a: { network?: Network, output?: Buffer, data?: Buffer[] }, opts?: { validate?: boolean }): + { output: Buffer, data: Buffer[] }; + + function p2ms(a: { network?: Network, m?: number, n?: number, output?: Buffer, pubkeys?: Buffer[], signatures?: Buffer[], input?: Buffer }, opts?: { validate?: boolean }): + { output: Buffer, m: number, n: number, pubkeys: Buffer[], signatures: Buffer[], input: Buffer, witness: Buffer[] }; + + function p2pk(a: { input?: Buffer, network?: Network, output?: Buffer, pubkey?: Buffer, signature?: Buffer }, opts?: { validate?: boolean }): + { output: Buffer, pubkey: Buffer, signature: Buffer, input: Buffer, witness: Buffer[] }; + + function p2pkh(a: { address?: string, hash?: Buffer, input?: Buffer, network?: Network, output?: Buffer, pubkey?: Buffer, signature?: Buffer }, opts?: { validate?: boolean }): + { address: string, hash: Buffer, output: Buffer, pubkey: Buffer, signature: Buffer, input: Buffer, witness: Buffer[] }; + + function p2sh(a: { address?: string, hash?: Buffer, input?: Buffer, network?: Network, output?: Buffer, witness?: Buffer[], redeem?: Redeem }, opts?: { validate?: boolean }): + { address: string, hash: Buffer, output: Buffer, redeem: Redeem, input: Buffer, witness: Buffer[] }; + + function p2wpkh(a: { address?: string, hash?: Buffer, input?: Buffer, network?: Network, output?: Buffer, pubkey?: Buffer, signature?: Buffer, witness?: Buffer[] }, + opts?: { validate?: boolean }): { address: string, hash: Buffer, output: Buffer, pubkey: Buffer, signature: Buffer, input: Buffer, witness: Buffer[] }; + + function p2wsh(a: { address?: string, hash?: Buffer, input?: Buffer, network?: Network, output?: Buffer, witness?: Buffer[], redeem?: Redeem }, opts?: { validate?: boolean }): + { address: string, hash: Buffer, output: Buffer, redeem: Redeem, input: Buffer, witness: Buffer[] }; + + class Redeem { + input?: Buffer; + network?: Network; + output?: Buffer; + witness?: Buffer[]; + } +} diff --git a/types/bitwise/bits/and.d.ts b/types/bitwise/bits/and.d.ts new file mode 100644 index 0000000000..52696eee01 --- /dev/null +++ b/types/bitwise/bits/and.d.ts @@ -0,0 +1,4 @@ +export default function and( + bits1: ReadonlyArray, + bits2: ReadonlyArray +): ReadonlyArray; diff --git a/types/bitwise/bits/index.d.ts b/types/bitwise/bits/index.d.ts new file mode 100644 index 0000000000..8bc86d20af --- /dev/null +++ b/types/bitwise/bits/index.d.ts @@ -0,0 +1,33 @@ +import bitsAnd from './and'; +import bitsNor from './nor'; +import bitsNot from './not'; +import bitsOr from './or'; +import bitsReduceAnd from './reduce-and'; +import bitsReduceNand from './reduce-nand'; +import bitsReduceNor from './reduce-nor'; +import bitsReduceOr from './reduce-or'; +import bitsReduceXnor from './reduce-xnor'; +import bitsReduceXor from './reduce-xor'; +import bitsToBoolean from './to-boolean'; +import bitsToString from './to-string'; +import bitsXnor from './xnor'; +import bitsXor from './xor'; + +declare namespace bits { + const and: typeof bitsAnd; + const nor: typeof bitsNor; + const not: typeof bitsNot; + const or: typeof bitsOr; + const reduceAnd: typeof bitsReduceAnd; + const reduceNand: typeof bitsReduceNand; + const reduceNor: typeof bitsReduceNor; + const reduceOr: typeof bitsReduceOr; + const reduceXnor: typeof bitsReduceXnor; + const reduceXor: typeof bitsReduceXor; + const toBoolean: typeof bitsToBoolean; + const toString: typeof bitsToString; + const xnor: typeof bitsXnor; + const xor: typeof bitsXor; +} + +export default bits; diff --git a/types/bitwise/bits/nand.d.ts b/types/bitwise/bits/nand.d.ts new file mode 100644 index 0000000000..53338816b8 --- /dev/null +++ b/types/bitwise/bits/nand.d.ts @@ -0,0 +1,4 @@ +export default function nand( + bits1: ReadonlyArray, + bits2: ReadonlyArray +): ReadonlyArray; diff --git a/types/bitwise/bits/nor.d.ts b/types/bitwise/bits/nor.d.ts new file mode 100644 index 0000000000..cda86e1a7c --- /dev/null +++ b/types/bitwise/bits/nor.d.ts @@ -0,0 +1,4 @@ +export default function nor( + bits1: ReadonlyArray, + bits2: ReadonlyArray +): ReadonlyArray; diff --git a/types/bitwise/bits/not.d.ts b/types/bitwise/bits/not.d.ts new file mode 100644 index 0000000000..7be251c891 --- /dev/null +++ b/types/bitwise/bits/not.d.ts @@ -0,0 +1,4 @@ +export default function not( + bits1: ReadonlyArray, + bits2: ReadonlyArray +): ReadonlyArray; diff --git a/types/bitwise/bits/or.d.ts b/types/bitwise/bits/or.d.ts new file mode 100644 index 0000000000..953a50d4c2 --- /dev/null +++ b/types/bitwise/bits/or.d.ts @@ -0,0 +1,4 @@ +export default function or( + bits1: ReadonlyArray, + bits2: ReadonlyArray +): ReadonlyArray; diff --git a/types/bitwise/bits/reduce-and.d.ts b/types/bitwise/bits/reduce-and.d.ts new file mode 100644 index 0000000000..b45c023eb0 --- /dev/null +++ b/types/bitwise/bits/reduce-and.d.ts @@ -0,0 +1 @@ +export default function reduceAnd(bits: ReadonlyArray): number; diff --git a/types/bitwise/bits/reduce-nand.d.ts b/types/bitwise/bits/reduce-nand.d.ts new file mode 100644 index 0000000000..7fd8b8f6b4 --- /dev/null +++ b/types/bitwise/bits/reduce-nand.d.ts @@ -0,0 +1 @@ +export default function reduceNand(bits: ReadonlyArray): number; diff --git a/types/bitwise/bits/reduce-nor.d.ts b/types/bitwise/bits/reduce-nor.d.ts new file mode 100644 index 0000000000..9d8a64f729 --- /dev/null +++ b/types/bitwise/bits/reduce-nor.d.ts @@ -0,0 +1 @@ +export default function reduceNor(bits: ReadonlyArray): number; diff --git a/types/bitwise/bits/reduce-or.d.ts b/types/bitwise/bits/reduce-or.d.ts new file mode 100644 index 0000000000..676e4ff347 --- /dev/null +++ b/types/bitwise/bits/reduce-or.d.ts @@ -0,0 +1 @@ +export default function reduceOr(bits: ReadonlyArray): number; diff --git a/types/bitwise/bits/reduce-xnor.d.ts b/types/bitwise/bits/reduce-xnor.d.ts new file mode 100644 index 0000000000..be64ebaaa3 --- /dev/null +++ b/types/bitwise/bits/reduce-xnor.d.ts @@ -0,0 +1 @@ +export default function reduceXnor(bits: ReadonlyArray): number; diff --git a/types/bitwise/bits/reduce-xor.d.ts b/types/bitwise/bits/reduce-xor.d.ts new file mode 100644 index 0000000000..9a2107237a --- /dev/null +++ b/types/bitwise/bits/reduce-xor.d.ts @@ -0,0 +1 @@ +export default function reduceXor(bits: ReadonlyArray): number; diff --git a/types/bitwise/bits/to-boolean.d.ts b/types/bitwise/bits/to-boolean.d.ts new file mode 100644 index 0000000000..50bd8f4bc8 --- /dev/null +++ b/types/bitwise/bits/to-boolean.d.ts @@ -0,0 +1,3 @@ +export default function toBoolean( + bits: ReadonlyArray +): ReadonlyArray; diff --git a/types/bitwise/bits/to-string.d.ts b/types/bitwise/bits/to-string.d.ts new file mode 100644 index 0000000000..1fee89675d --- /dev/null +++ b/types/bitwise/bits/to-string.d.ts @@ -0,0 +1,5 @@ +export default function toString( + bit: ReadonlyArray, + spacing?: number, + spacer?: string +): string; diff --git a/types/bitwise/bits/xnor.d.ts b/types/bitwise/bits/xnor.d.ts new file mode 100644 index 0000000000..b6e11fcdf1 --- /dev/null +++ b/types/bitwise/bits/xnor.d.ts @@ -0,0 +1,4 @@ +export default function xnor( + bits1: ReadonlyArray, + bits2: ReadonlyArray +): ReadonlyArray; diff --git a/types/bitwise/bits/xor.d.ts b/types/bitwise/bits/xor.d.ts new file mode 100644 index 0000000000..a8b7816408 --- /dev/null +++ b/types/bitwise/bits/xor.d.ts @@ -0,0 +1,4 @@ +export default function xor( + bits1: ReadonlyArray, + bits2: ReadonlyArray +): ReadonlyArray; diff --git a/types/bitwise/bitwise-tests.ts b/types/bitwise/bitwise-tests.ts new file mode 100644 index 0000000000..6975cb3591 --- /dev/null +++ b/types/bitwise/bitwise-tests.ts @@ -0,0 +1,56 @@ +// Demonstrating cherry-picking +import bitwise from 'bitwise'; + +import bits from 'bitwise/bits'; +import toBoolean from 'bitwise/bits/to-boolean'; + +import buffer from 'bitwise/buffer'; +import create from 'bitwise/buffer/create'; + +import byte from 'bitwise/byte'; +import read from 'bitwise/byte/read'; + +import integer from 'bitwise/integer'; +import setBit from 'bitwise/integer/set-bit'; + +import nibble from 'bitwise/nibble'; +import nibbleRead from 'bitwise/nibble/read'; + +import string from 'bitwise/string'; +import toBits from 'bitwise/string/to-bits'; + +// Testing basic functions +const testBits = [0, 1, 1, 0, 1]; + +// $ExpectType string +bitwise.bits.toString(testBits); + +// $ExpectType ReadonlyArray +bits.toBoolean(testBits); +// $ExpectType ReadonlyArray +toBoolean(testBits); + +// $ExpectType ReadonlyArray +byte.read(12); +// $ExpectType ReadonlyArray +read(12); + +// $ExpectType Buffer +buffer.create(testBits); +// $ExpectType Buffer +create(testBits); + +// $ExpectType ReadonlyArray +integer.setBit(12, 1, 0); +// $ExpectType ReadonlyArray +setBit(12, 1, 0); + +// $ExpectType ReadonlyArray +nibble.read(15); +// $ExpectType ReadonlyArray +nibbleRead(15); + +// $ExpectType ReadonlyArray +string.toBits('10 10 12$%_.0'); +// $ExpectType ReadonlyArray +toBits('10 10 12$%_.0'); diff --git a/types/bitwise/buffer/and.d.ts b/types/bitwise/buffer/and.d.ts new file mode 100644 index 0000000000..c4789600c3 --- /dev/null +++ b/types/bitwise/buffer/and.d.ts @@ -0,0 +1,7 @@ +/// + +export default function and( + buffer1: Buffer, + buffer2: Buffer, + isLooping?: boolean +): Buffer; diff --git a/types/bitwise/buffer/create.d.ts b/types/bitwise/buffer/create.d.ts new file mode 100644 index 0000000000..3c67301d97 --- /dev/null +++ b/types/bitwise/buffer/create.d.ts @@ -0,0 +1,3 @@ +/// + +export default function create(bits: ReadonlyArray): Buffer; diff --git a/types/bitwise/buffer/index.d.ts b/types/bitwise/buffer/index.d.ts new file mode 100644 index 0000000000..a109aecb73 --- /dev/null +++ b/types/bitwise/buffer/index.d.ts @@ -0,0 +1,31 @@ +import bufferAnd from './and'; +import bufferCreate from './create'; +import bufferModify from './modify'; +import bufferNand from './nand'; +import bufferNor from './nor'; +import bufferNot from './not'; +import bufferOr from './or'; +import bufferRead from './read'; +import bufferReadCInt from './read-c-int'; +import bufferReadInt from './read-int'; +import bufferReadUInt from './read-u-int'; +import bufferXnor from './xnor'; +import bufferXor from './xor'; + +declare namespace buffer { + const and: typeof bufferAnd; + const create: typeof bufferCreate; + const modify: typeof bufferModify; + const nand: typeof bufferNand; + const nor: typeof bufferNor; + const not: typeof bufferNot; + const or: typeof bufferOr; + const read: typeof bufferRead; + const readCInt: typeof bufferReadCInt; + const readInt: typeof bufferReadInt; + const readUInt: typeof bufferReadUInt; + const xnor: typeof bufferXnor; + const xor: typeof bufferXor; +} + +export default buffer; diff --git a/types/bitwise/buffer/modify.d.ts b/types/bitwise/buffer/modify.d.ts new file mode 100644 index 0000000000..1d242cfd79 --- /dev/null +++ b/types/bitwise/buffer/modify.d.ts @@ -0,0 +1,7 @@ +/// + +export default function modify( + buffer: Buffer, + newBits: ReadonlyArray, + bitOffset?: number +): void; diff --git a/types/bitwise/buffer/nand.d.ts b/types/bitwise/buffer/nand.d.ts new file mode 100644 index 0000000000..f887d7f82a --- /dev/null +++ b/types/bitwise/buffer/nand.d.ts @@ -0,0 +1,7 @@ +/// + +export default function nand( + buffer1: Buffer, + buffer2: Buffer, + isLooping?: boolean +): Buffer; diff --git a/types/bitwise/buffer/nor.d.ts b/types/bitwise/buffer/nor.d.ts new file mode 100644 index 0000000000..7d285abce0 --- /dev/null +++ b/types/bitwise/buffer/nor.d.ts @@ -0,0 +1,7 @@ +/// + +export default function nor( + buffer1: Buffer, + buffer2: Buffer, + isLooping: boolean +): Buffer; diff --git a/types/bitwise/buffer/not.d.ts b/types/bitwise/buffer/not.d.ts new file mode 100644 index 0000000000..8dd6e56434 --- /dev/null +++ b/types/bitwise/buffer/not.d.ts @@ -0,0 +1,3 @@ +/// + +export default function not(buffer: Buffer): Buffer; diff --git a/types/bitwise/buffer/or.d.ts b/types/bitwise/buffer/or.d.ts new file mode 100644 index 0000000000..1f06097215 --- /dev/null +++ b/types/bitwise/buffer/or.d.ts @@ -0,0 +1,7 @@ +/// + +export default function or( + buffer1: Buffer, + buffer2: Buffer, + isLooping?: boolean +): Buffer; diff --git a/types/bitwise/buffer/read-c-int.d.ts b/types/bitwise/buffer/read-c-int.d.ts new file mode 100644 index 0000000000..d3d1caca3c --- /dev/null +++ b/types/bitwise/buffer/read-c-int.d.ts @@ -0,0 +1,7 @@ +/// + +export default function readCInt( + buffer: Buffer, + bitOffset?: number, + bitLength?: number +): number; diff --git a/types/bitwise/buffer/read-int.d.ts b/types/bitwise/buffer/read-int.d.ts new file mode 100644 index 0000000000..3bb3f65a58 --- /dev/null +++ b/types/bitwise/buffer/read-int.d.ts @@ -0,0 +1,7 @@ +/// + +export default function readInt( + buffer: Buffer, + bitOffset?: number, + bitLength?: number +): number; diff --git a/types/bitwise/buffer/read-u-int.d.ts b/types/bitwise/buffer/read-u-int.d.ts new file mode 100644 index 0000000000..5e5eec4b07 --- /dev/null +++ b/types/bitwise/buffer/read-u-int.d.ts @@ -0,0 +1,7 @@ +/// + +export default function readUInt( + buffer: Buffer, + bitOffset?: number, + bitLength?: number +): number; diff --git a/types/bitwise/buffer/read.d.ts b/types/bitwise/buffer/read.d.ts new file mode 100644 index 0000000000..b5e5f18f58 --- /dev/null +++ b/types/bitwise/buffer/read.d.ts @@ -0,0 +1,7 @@ +/// + +export default function read( + buffer: Buffer, + bitOffset?: number, + bitLength?: number +): ReadonlyArray; diff --git a/types/bitwise/buffer/xnor.d.ts b/types/bitwise/buffer/xnor.d.ts new file mode 100644 index 0000000000..4cfd64dc88 --- /dev/null +++ b/types/bitwise/buffer/xnor.d.ts @@ -0,0 +1,7 @@ +/// + +export default function xnor( + buffer1: Buffer, + buffer2: Buffer, + isLooping?: boolean +): Buffer; diff --git a/types/bitwise/buffer/xor.d.ts b/types/bitwise/buffer/xor.d.ts new file mode 100644 index 0000000000..61ce88f10a --- /dev/null +++ b/types/bitwise/buffer/xor.d.ts @@ -0,0 +1,7 @@ +/// + +export default function xor( + buffer1: Buffer, + buffer2: Buffer, + isLooping?: boolean +): Buffer; diff --git a/types/bitwise/byte/index.d.ts b/types/bitwise/byte/index.d.ts new file mode 100644 index 0000000000..f2e3c21d42 --- /dev/null +++ b/types/bitwise/byte/index.d.ts @@ -0,0 +1,9 @@ +import byteRead from './read'; +import byteWrite from './write'; + +declare namespace byte { + const read: typeof byteRead; + const write: typeof byteWrite; +} + +export default byte; diff --git a/types/bitwise/byte/read.d.ts b/types/bitwise/byte/read.d.ts new file mode 100644 index 0000000000..10fc79106e --- /dev/null +++ b/types/bitwise/byte/read.d.ts @@ -0,0 +1 @@ +export default function read(byte: number): ReadonlyArray; diff --git a/types/bitwise/byte/write.d.ts b/types/bitwise/byte/write.d.ts new file mode 100644 index 0000000000..be485032da --- /dev/null +++ b/types/bitwise/byte/write.d.ts @@ -0,0 +1 @@ +export default function write(bits: ReadonlyArray): number; diff --git a/types/bitwise/index.d.ts b/types/bitwise/index.d.ts new file mode 100644 index 0000000000..4e1ae86896 --- /dev/null +++ b/types/bitwise/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for bitwise 1.5 +// Project: https://github.com/dodekeract/bitwise +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import bitwiseBits from './bits'; +import bitwiseBuffer from './buffer'; +import bitwiseByte from './byte'; +import bitwiseInteger from './integer'; +import bitwiseNibble from './nibble'; +import bitwiseString from './string'; + +declare namespace bitwise { + const bits: typeof bitwiseBits; + const buffer: typeof bitwiseBuffer; + const byte: typeof bitwiseByte; + const integer: typeof bitwiseInteger; + const nibble: typeof bitwiseNibble; + const string: typeof bitwiseString; +} + +export default bitwise; diff --git a/types/bitwise/integer/get-bit.d.ts b/types/bitwise/integer/get-bit.d.ts new file mode 100644 index 0000000000..ced50ff35c --- /dev/null +++ b/types/bitwise/integer/get-bit.d.ts @@ -0,0 +1 @@ +export default function getBit(number: number, position: number): number; diff --git a/types/bitwise/integer/index.d.ts b/types/bitwise/integer/index.d.ts new file mode 100644 index 0000000000..965726728b --- /dev/null +++ b/types/bitwise/integer/index.d.ts @@ -0,0 +1,11 @@ +import integerGetBit from './get-bit'; +import integerSetBit from './set-bit'; +import integerToggleBit from './toggle-bit'; + +declare namespace integer { + const getBit: typeof integerGetBit; + const setBit: typeof integerSetBit; + const toggleBit: typeof integerToggleBit; +} + +export default integer; diff --git a/types/bitwise/integer/set-bit.d.ts b/types/bitwise/integer/set-bit.d.ts new file mode 100644 index 0000000000..a6524c4079 --- /dev/null +++ b/types/bitwise/integer/set-bit.d.ts @@ -0,0 +1,5 @@ +export default function setBit( + number: number, + position: number, + value: number +): ReadonlyArray; diff --git a/types/bitwise/integer/toggle-bit.d.ts b/types/bitwise/integer/toggle-bit.d.ts new file mode 100644 index 0000000000..a3ea04da80 --- /dev/null +++ b/types/bitwise/integer/toggle-bit.d.ts @@ -0,0 +1,4 @@ +export default function toggleBit( + number: number, + position: number +): ReadonlyArray; diff --git a/types/bitwise/nibble/index.d.ts b/types/bitwise/nibble/index.d.ts new file mode 100644 index 0000000000..a18ed9ef6f --- /dev/null +++ b/types/bitwise/nibble/index.d.ts @@ -0,0 +1,9 @@ +import nibbleRead from './read'; +import nibbleWrite from './write'; + +declare namespace nibble { + const read: typeof nibbleRead; + const write: typeof nibbleWrite; +} + +export default nibble; diff --git a/types/bitwise/nibble/read.d.ts b/types/bitwise/nibble/read.d.ts new file mode 100644 index 0000000000..a1182a72dd --- /dev/null +++ b/types/bitwise/nibble/read.d.ts @@ -0,0 +1 @@ +export default function read(nibble: number): ReadonlyArray; diff --git a/types/bitwise/nibble/write.d.ts b/types/bitwise/nibble/write.d.ts new file mode 100644 index 0000000000..4e79f88571 --- /dev/null +++ b/types/bitwise/nibble/write.d.ts @@ -0,0 +1 @@ +export default function write(nibble: ReadonlyArray): number; diff --git a/types/bitwise/string/index.d.ts b/types/bitwise/string/index.d.ts new file mode 100644 index 0000000000..9100d0050b --- /dev/null +++ b/types/bitwise/string/index.d.ts @@ -0,0 +1,7 @@ +import stringToBits from './to-bits'; + +declare namespace string { + const toBits: typeof stringToBits; +} + +export default string; diff --git a/types/bitwise/string/to-bits.d.ts b/types/bitwise/string/to-bits.d.ts new file mode 100644 index 0000000000..4930f10f79 --- /dev/null +++ b/types/bitwise/string/to-bits.d.ts @@ -0,0 +1 @@ +export default function toBits(string: string): ReadonlyArray; diff --git a/types/bitwise/tsconfig.json b/types/bitwise/tsconfig.json new file mode 100644 index 0000000000..9956f50c76 --- /dev/null +++ b/types/bitwise/tsconfig.json @@ -0,0 +1,60 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bitwise-tests.ts", + "bits/and.d.ts", + "bits/index.d.ts", + "bits/nand.d.ts", + "bits/nor.d.ts", + "bits/not.d.ts", + "bits/or.d.ts", + "bits/reduce-and.d.ts", + "bits/reduce-nand.d.ts", + "bits/reduce-nor.d.ts", + "bits/reduce-or.d.ts", + "bits/reduce-xnor.d.ts", + "bits/reduce-xor.d.ts", + "bits/to-boolean.d.ts", + "bits/to-string.d.ts", + "bits/xnor.d.ts", + "bits/xor.d.ts", + "buffer/and.d.ts", + "buffer/create.d.ts", + "buffer/modify.d.ts", + "buffer/nand.d.ts", + "buffer/nor.d.ts", + "buffer/not.d.ts", + "buffer/or.d.ts", + "buffer/read-c-int.d.ts", + "buffer/read-int.d.ts", + "buffer/read-u-int.d.ts", + "buffer/read.d.ts", + "buffer/xnor.d.ts", + "buffer/xor.d.ts", + "byte/index.d.ts", + "byte/read.d.ts", + "byte/write.d.ts", + "integer/get-bit.d.ts", + "integer/index.d.ts", + "integer/set-bit.d.ts", + "integer/toggle-bit.d.ts", + "nibble/index.d.ts", + "nibble/read.d.ts", + "nibble/write.d.ts", + "string/index.d.ts", + "string/to-bits.d.ts" + ] +} diff --git a/types/bitwise/tslint.json b/types/bitwise/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/bitwise/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/buffer-xor/buffer-xor-tests.ts b/types/buffer-xor/buffer-xor-tests.ts new file mode 100644 index 0000000000..7c55514eaa --- /dev/null +++ b/types/buffer-xor/buffer-xor-tests.ts @@ -0,0 +1,4 @@ +import xor = require('buffer-xor'); + +// $ExpectType Buffer +xor(Buffer.from('a'), Buffer.from('b')); diff --git a/types/buffer-xor/index.d.ts b/types/buffer-xor/index.d.ts new file mode 100644 index 0000000000..5e98793266 --- /dev/null +++ b/types/buffer-xor/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for buffer-xor 2.0 +// Project: https://github.com/crypto-browserify/buffer-xor +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function xor(a: Buffer, b: Buffer): Buffer; + +export = xor; diff --git a/types/buffer-xor/tsconfig.json b/types/buffer-xor/tsconfig.json new file mode 100644 index 0000000000..adbeaec3b7 --- /dev/null +++ b/types/buffer-xor/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "buffer-xor-tests.ts" + ] +} diff --git a/types/buffer-xor/tslint.json b/types/buffer-xor/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/buffer-xor/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/cannon/index.d.ts b/types/cannon/index.d.ts index 56272a6b1f..6cf0043878 100644 --- a/types/cannon/index.d.ts +++ b/types/cannon/index.d.ts @@ -454,6 +454,13 @@ declare module CANNON { type?: number; linearDamping?: number; angularDamping?: number; + allowSleep?: boolean; + sleepSpeedLimit?: number; + sleepTimeLimit?: number; + collisionFilterGroup?: number; + collisionFilterMask?: number; + fixedRotation?: boolean; + shape?: Shape; } export class Body extends EventTarget { diff --git a/types/cesium/index.d.ts b/types/cesium/index.d.ts index 3ea9745ebd..398d05ad33 100644 --- a/types/cesium/index.d.ts +++ b/types/cesium/index.d.ts @@ -797,6 +797,22 @@ declare namespace Cesium { isLeapSecond: boolean; } + class HeadingPitchRoll { + heading: number; + pitch: number; + roll: number; + constructor(heading?: number, pitch?: number, roll?: number); + static clone(headingPitchRoll: HeadingPitchRoll, result?: HeadingPitchRoll): HeadingPitchRoll; + static equals(left: HeadingPitchRoll | null | undefined, right: HeadingPitchRoll | null | undefined): boolean; + static equalsEpsilon(left: HeadingPitchRoll | null | undefined, right: HeadingPitchRoll | null | undefined, relativeEpsilon: number, absoluteEpsilon?: number): boolean; + static fromDegrees(heading: number, pitch: number, roll: number, result?: HeadingPitchRoll): HeadingPitchRoll; + static fromQuaternion(quaternion: Quaternion, result?: HeadingPitchRoll): HeadingPitchRoll; + clone(result?: HeadingPitchRoll): HeadingPitchRoll; + equals(right: HeadingPitchRoll | null | undefined): boolean; + equalsEpsilon(right: HeadingPitchRoll | null | undefined, relativeEpsilon: number, absoluteEpsilon?: number): boolean; + toString(): string; + } + class HeightmapTerrainData { waterMask: Uint8Array | HTMLImageElement | HTMLCanvasElement; constructor(options: { @@ -959,6 +975,7 @@ declare namespace Cesium { static fromArray(array: number[], startingIndex?: number, result?: Matrix3): Matrix3; static fromColumnMajorArray(values: number[], result?: Matrix3): Matrix3; static fromRowMajorArray(values: number[], result?: Matrix3): Matrix3; + static fromHeadingPitchRoll(headingPitchRoll: HeadingPitchRoll, result?: Matrix3): Matrix3; static fromQuaternion(quaternion: Quaternion): Matrix3; static fromScale(scale: Cartesian3, result?: Matrix3): Matrix3; static fromUniformScale(scale: number, result?: Matrix3): Matrix3; @@ -1236,7 +1253,7 @@ declare namespace Cesium { toString(): string; static fromAxisAngle(axis: Cartesian3, angle: number, result?: Quaternion): Quaternion; static fromRotationMatrix(matrix: Matrix3, result?: Quaternion): Quaternion; - static fromHeadingPitchRoll(heading: number, pitch: number, roll: number, result: Quaternion): Quaternion; + static fromHeadingPitchRoll(headingPitchRoll: HeadingPitchRoll, result?: Quaternion): Quaternion; static pack(value: Quaternion, array: number[], startingIndex?: number): number[]; static unpack(array: number[], startingIndex?: number, result?: Quaternion): Quaternion; static convertPackedArrayForInterpolation(packedArray: number[], startingIndex?: number, lastIndex?: number, result?: number[]): void; @@ -4880,13 +4897,15 @@ declare namespace Cesium { function eastNorthUpToFixedFrame(origin: Cartesian3, ellipsoid?: Ellipsoid, result?: Matrix4): Matrix4; function northEastDownToFixedFrame(origin: Cartesian3, ellipsoid?: Ellipsoid, result?: Matrix4): Matrix4; function northUpEastToFixedFrame(origin: Cartesian3, ellipsoid?: Ellipsoid, result?: Matrix4): Matrix4; - function headingPitchRollToFixedFrame(origin: Cartesian3, heading: number, pitch: number, roll: number, ellipsoid?: Ellipsoid, result?: Matrix4): Matrix4; - function headingPitchRollQuaternion(origin: Cartesian3, heading: number, pitch: number, roll: number, ellipsoid?: Ellipsoid, result?: Quaternion): Quaternion; + function headingPitchRollToFixedFrame(origin: Cartesian3, headingPitchRoll: HeadingPitchRoll, ellipsoid?: Ellipsoid, fixedFrameTransform?: LocalFrameToFixedFrame, result?: Matrix4): Matrix4; + function headingPitchRollQuaternion(origin: Cartesian3, headingPitchRoll: HeadingPitchRoll, ellipsoid?: Ellipsoid, fixedFrameTransform?: LocalFrameToFixedFrame, + result?: Quaternion): Quaternion; function computeTemeToPseudoFixedMatrix(date: JulianDate, result?: Matrix3): Matrix3; function preloadIcrfFixed(timeInterval: TimeInterval): Promise; function computeIcrfToFixedMatrix(date: JulianDate, result?: Matrix3): Matrix3; function computeFixedToIcrfMatrix(date: JulianDate, result?: Matrix3): Matrix3; function pointToWindowCoordinates(modelViewProjectionMatrix: Matrix4, viewportTransformation: Matrix4, point: Cartesian3, result?: Cartesian2): Cartesian2; + type LocalFrameToFixedFrame = (origin: Cartesian3, ellipsoid?: Ellipsoid, result?: Matrix4) => Matrix4; } namespace TridiagonalSystemSolver { diff --git a/types/cesium/test/cesium-global.test.ts b/types/cesium/test/cesium-global.test.ts index 8974e56542..512f977344 100644 --- a/types/cesium/test/cesium-global.test.ts +++ b/types/cesium/test/cesium-global.test.ts @@ -46,3 +46,7 @@ const entity = new Cesium.Entity({ }) }); viewer.entities.add(entity); + +const hpr = new Cesium.HeadingPitchRoll(1.0, 2.2, 3.4); +const quat: Cesium.Quaternion = Cesium.Quaternion.fromHeadingPitchRoll(hpr); +const matrix: Cesium.Matrix3 = Cesium.Matrix3.fromHeadingPitchRoll(hpr); diff --git a/types/cesium/test/cesium-module.test.ts b/types/cesium/test/cesium-module.test.ts index 726daf7df2..2fe8f6cdb8 100644 --- a/types/cesium/test/cesium-module.test.ts +++ b/types/cesium/test/cesium-module.test.ts @@ -48,3 +48,7 @@ const entity = new Cesium.Entity({ }) }); viewer.entities.add(entity); + +const hpr = new Cesium.HeadingPitchRoll(1.0, 2.2, 3.4); +const quat: Cesium.Quaternion = Cesium.Quaternion.fromHeadingPitchRoll(hpr); +const matrix: Cesium.Matrix3 = Cesium.Matrix3.fromHeadingPitchRoll(hpr); diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 4e82fb9ff5..49027a2bea 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -8,7 +8,6 @@ // Joseph Page // Dan Manastireanu // Guillaume Rodriguez -// Sergey Rubanov // Simon Archer // Ken Elkabany // Slavik Nychkalo @@ -159,6 +158,8 @@ interface Model { tension: number; x: number; y: number; + base: number; + head: number; } declare namespace Chart { @@ -390,6 +391,8 @@ declare namespace Chart { easing?: string; onProgress?(chart: any): void; onComplete?(chart: any): void; + animateRotate?: boolean; + animateScale?: boolean; } interface ChartElementsOptions { diff --git a/types/chess.js/chess.js-tests.ts b/types/chess.js/chess.js-tests.ts new file mode 100644 index 0000000000..fb78bb5e3f --- /dev/null +++ b/types/chess.js/chess.js-tests.ts @@ -0,0 +1,202 @@ +import * as chessjs from "chess.js"; + +const fen = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1"; + +// --- constructors --- \\ + +// $ExpectType ChessInstance +chessjs.Chess(fen); + +// $ExpectType ChessInstance +const chess = new chessjs.Chess(); + +// $ExpectType "w" +chess.WHITE; + +// $ExpectType "b" +chess.BLACK; + +// $ExpectType "p" +chess.PAWN; + +// $ExpectType "n" +chess.KNIGHT; + +// $ExpectType "b" +chess.BISHOP; + +// $ExpectType "r" +chess.ROOK; + +// $ExpectType "q" +chess.QUEEN; + +// $ExpectType "k" +chess.KING; + +// tslint:disable-next-line:max-line-length +// $ExpectType ["a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8", "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7", "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6", "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5", "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4", "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1"] +chess.SQUARES; + +// $ExpectType { NORMAL: "n"; CAPTURE: "c"; BIG_PAWN: "b"; EP_CAPTURE: "e"; PROMOTION: "p"; KSIDE_CASTLE: "k"; QSIDE_CASTLE: "q"; } +chess.FLAGS; + +// $ExpectType void +chess.reset(); + +// $ExpectType boolean +chess.load(fen); + +// -- moves -- \\ + +// $ExpectType Move[] +chess.moves({ verbose: true }); + +// $ExpectType string[] +chess.moves({ verbose: false }); + +// $ExpectType Move[] +chess.moves({ square: "e2", verbose: true }); + +// $ExpectType string[] +chess.moves({ square: "e2", verbose: false }); + +// $ExpectType string[] +chess.moves({ square: "e2" }); + +// $ExpectType string[] +chess.moves({}); + +// $ExpectType string[] +chess.moves(); + +// $ExpectType boolean +chess.in_check(); + +// $ExpectType boolean +chess.in_checkmate(); + +// $ExpectType boolean +chess.in_stalemate(); + +// $ExpectType boolean +chess.in_draw(); + +// $ExpectType boolean +chess.insufficient_material(); + +// $ExpectType boolean +chess.in_threefold_repetition(); + +// $ExpectType boolean +chess.game_over(); + +// $ExpectType { valid: boolean; error_number: number; error: string; } +chess.validate_fen(fen); + +// $ExpectType string +chess.fen(); + +// --- pgn --- \\ + +// $ExpectType string +chess.pgn({ max_width: 80, newline_char: '\n' }); + +// $ExpectType string +chess.pgn({ max_width: 120 }); + +// $ExpectType string +chess.pgn({ newline_char: '\r\n' }); + +// $ExpectType string +chess.pgn({}); + +// $ExpectType string +const pgn = chess.pgn(); + +// --- load_pgn --- \\ + +// $ExpectType boolean +chess.load_pgn(pgn, { newline_char: '\n', sloppy: true }); + +// $ExpectType boolean +chess.load_pgn(pgn, { newline_char: '\r\n' }); + +// $ExpectType boolean +chess.load_pgn(pgn, { sloppy: true }); + +// $ExpectType boolean +chess.load_pgn(pgn, {}); + +// $ExpectType boolean +chess.load_pgn(pgn); + +// $ExpectType { [key: string]: string | undefined; } +chess.header('White', 'Morphy', 'Black', 'Anderssen', 'Date', '1858-??-??'); + +// $ExpectType string +chess.ascii(); + +// $ExpectType "w" | "b" +chess.turn(); + +// --- move --- \\ + +// $ExpectType Move | null +chess.move('e3'); + +// $ExpectType Move | null +chess.move('e3', {}); + +// $ExpectType Move | null +chess.move('e3', { sloppy: true }); + +// $ExpectType Move | null +chess.move('e3', { sloppy: false }); + +// $ExpectType Move | null +chess.move({ from: 'e2', to: 'e3' }); + +// $ExpectType Move | null +chess.move({ from: 'e2', to: 'e3', promotion: 'q' }); + +// $ExpectType Move | null +chess.move({ from: 'e2', to: 'e3' }); + +// $ExpectType Move | null +chess.move({ from: 'e2', to: 'e3', promotion: 'q' }); + +// $ExpectType Move | null +chess.undo(); + +// $ExpectType void +chess.clear(); + +// $ExpectType boolean +chess.put({ type: "p", color: "b" }, 'a5'); + +// $ExpectType Piece | null +chess.get("a5"); + +// $ExpectType Piece | null +chess.remove("a5"); + +// $ExpectType "light" | "dark" +chess.square_color("a5"); + +// $ExpectType "light" | "dark" | null +chess.square_color("invalid square string"); + +// --- history --- \\ + +// $ExpectType string[] +chess.history(); + +// $ExpectType string[] +chess.history({}); + +// $ExpectType string[] +chess.history({ verbose: false }); + +// $ExpectType Move[] +chess.history({ verbose: true }); diff --git a/types/chess.js/index.d.ts b/types/chess.js/index.d.ts new file mode 100644 index 0000000000..1e9e7aeca3 --- /dev/null +++ b/types/chess.js/index.d.ts @@ -0,0 +1,530 @@ +// Type definitions for chess.js 0.10 +// Project: https://github.com/jhlywa/chess.js +// Definitions by: Jacob Fischer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * One of the possible sqaures on a chess board in san format, + * e.g. "a8" to "h1". + */ +export type Square = + "a8" | "b8" | "c8" | "d8" | "e8" | "f8" | "g8" | "h8" | + "a7" | "b7" | "c7" | "d7" | "e7" | "f7" | "g7" | "h7" | + "a6" | "b6" | "c6" | "d6" | "e6" | "f6" | "g6" | "h6" | + "a5" | "b5" | "c5" | "d5" | "e5" | "f5" | "g5" | "h5" | + "a4" | "b4" | "c4" | "d4" | "e4" | "f4" | "g4" | "h4" | + "a3" | "b3" | "c3" | "d3" | "e3" | "f3" | "g3" | "h3" | + "a2" | "b2" | "c2" | "d2" | "e2" | "f2" | "g2" | "h2" | + "a1" | "b1" | "c1" | "d1" | "e1" | "f1" | "g1" | "h1" +; + +/** + * Partial data about a chess move including the from and to square, and if a + * promotion occured. + */ +export interface ShortMove { + /** + * The location the piece is moving from. + * Must be in san format, e.g "h8" + */ + from: Square; + + /** + * The location the piece is moving to. + * Must be in san format, e.g "a1" + */ + to: Square; + + /** + * If this move results in a promotion, this will have the unit promotion. + * - "n" for Knight + * - "b" for Bishop + * - "r" for Rook + * - "q" for Queen + */ + promotion?: "n" | "b" | "r" | "q"; +} + +/** + * The full data about a chess move + */ +export interface Move extends ShortMove { + /** + * The color of the piece that moved + * - "b" for Black + * - "w" for White + */ + color: "b" | "w"; + + /** Flags indicating what occurred, combined into one string */ + flags: string; + + /** + * The type of the piece that moved + * - "p" for Pawn + * - "n" for Knight + * - "b" for Bishop + * - "r" for Rook + * - "q" for Queen + * - "k" for King + */ + piece: "p" | "n" | "b" | "r" | "q" | "k"; + + /** The Standard Algebraic Notation (SAN) representation of the move */ + san: string; + + /** + * If an enemy piece was captured this is their type. + * - "p" for Pawn + * - "n" for Knight + * - "b" for Bishop + * - "r" for Rook + * - "q" for Queen + */ + captured?: "p" | "n" | "b" | "r" | "q"; +} + +export interface Piece { + /** + * The type of the piece to place + * - "p" for Pawn + * - "n" for Knight + * - "b" for Bishop + * - "r" for Rook + * - "q" for Queen + * - "k" for King + */ + type: "p" | "n" | "b" | "r" | "q" | "k"; + + /** + * The color of the piece + * - "b" for Black + * - "w" for White + */ + color: "b" | "w"; +} + +export interface ChessInstance { + /** The string that represents the White color side */ + readonly WHITE: "w"; + + /** The string that represents the Black color side */ + readonly BLACK: "b"; + + /** The string that represents a Pawn */ + readonly PAWN: "p"; + + /** The string that represents a Knight */ + readonly KNIGHT: "n"; + /** The string that represents a Bishop */ + readonly BISHOP: "b"; + + /** The string that represents a Rook */ + readonly ROOK: "r"; + + /** The string that represents a Queen */ + readonly QUEEN: "q"; + + /** The string that represents a King */ + readonly KING: "k"; + + /** A list of all the squares in the game, from "a1" to "h8" */ + readonly SQUARES: [ + "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8", + "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7", + "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6", + "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5", + "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4", + "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", + "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", + "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1" + ]; + + /** Flags used to build flag strings for moves */ + readonly FLAGS: { + /** a non-capture */ + NORMAL: "n", + /** a standard capture */ + CAPTURE: "c", + /** a pawn push of two squares */ + BIG_PAWN: "b", + /** an en passant capture */ + EP_CAPTURE: "e", + /** a promotion */ + PROMOTION: "p", + /** kingside castling */ + KSIDE_CASTLE: "k", + /** queenside castling */ + QSIDE_CASTLE: "q", + }; + + /** + * The board is cleared, and the FEN string is loaded. + * Returns true if the position was successfully loaded, otherwise false + * @param fen the fen formatted string to load + * @returns true if the position was successfully loaded, otherwise + * false + */ + load(fen: string): boolean; + + /** + * Reset the board to the initial starting position. + */ + reset(): void; + + /** + * Returns a list of legal moves from the current position. + * The function takes an optional parameter which controls the + * single-square move generation and verbosity. + * @param options an optional parameter which controls the single-square + * move generation and verbosity. + * @returns The list of all valid moves, either in SAN format, or as + * verbose objects. + */ + moves(options: { + /** Set to true to return verbose move objects instead of strings */ + verbose: true; + /** + * The string to test if it is a valid move, if it is not then an + * empty array is returned + */ + square?: string; + }): Move[]; + + /** + * Returns a list of legal moves from the current position. + * The function takes an optional parameter which controls the + * single-square move generation and verbosity. + * @param options an optional parameter which controls the single-square + * move generation and verbosity. + * @returns The list of all valid moves, either in SAN format, or as + * verbose objects. + */ + moves(options?: { + /** Set to true to return verbose move objects instead of strings */ + verbose?: false; + /** + * The string to test if it is a valid move, if it is not then an + * empty array is returned + */ + square?: string; + }): string[]; + + /** + * Returns a list of legal moves from the current position. + * The function takes an optional parameter which controls the + * single-square move generation and verbosity. + * @param options an optional parameter which controls the single-square + * move generation and verbosity. + * @returns The list of all valid moves, either in SAN format, or as + * verbose objects. + */ + moves(options?: { + /** Set to true to return verbose move objects instead of strings */ + verbose?: boolean; + /** + * The string to test if it is a valid move, if it is not then an + * empty array is returned + */ + square?: string; + }): string[] | Move[]; + + /** + * Returns true or false if the side to move is in check. + * @returns true or false if the side to move is in check. + */ + in_check(): boolean; + + /** + * Returns true or false if the side to move has been checkmated. + * @returns true or false if the side to move has been checkmated. + */ + in_checkmate(): boolean; + /** + * Returns true or false if the side to move has been stalemated. + * @returns true or false if the side to move has been stalemated. + */ + in_stalemate(): boolean; + + /** + * Returns true or false if the game is drawn (50-move rule or + * insufficient material). + * @returns true or false if the game is drawn (50-move rule or + * insufficient material). + */ + in_draw(): boolean; + + /** + * Returns true if the game is drawn due to insufficient material + * (K vs. K, K vs. KB, or K vs. KN); otherwise false. + * @returns True if the game is drawn due to insufficient material + * (K vs. K, K vs. KB, or K vs. KN); otherwise false. + */ + insufficient_material(): boolean; + + /** + * Returns true or false if the current board position has occurred three + * or more times. + * @returns true or false if the current board position has occurred three + * or more times. + */ + in_threefold_repetition(): boolean; + + /** + * Returns true if the game has ended via checkmate, stalemate, draw, + * threefold repetition, or insufficient material. + * Otherwise, returns false. + * @returns True if the game has ended via checkmate, stalemate, draw, + * threefold repetition, or insufficient material. Otherwise, returns + * false. + */ + game_over(): boolean; + + /** + * Returns a validation object specifying validity or the errors found + * within the FEN string. + * @param fen the fen formatted string to validate + */ + validate_fen(fen: string): { + /** Indicates if the fen is valid or not. */ + valid: boolean; + + /** + * If not valid, then this will a type of error used internally in + * chess.js. Otherwise 0. + */ + error_number: number; + + /** + * The string "No errors." if valid. Otherwise a string explaining why + * it is not valid. + */ + error: string; + }; + + /** + * Returns the FEN string for the current position. + * @returns the FEN string for the current position. + */ + fen(): string; + + /** + * Returns the game in PGN format. + * Options is an optional parameter which may include max width and/or a + * newline character settings. + * @param options optional object which may include max width and/or a + * newline character settings. + * @returns the current game state in PGN format. + */ + pgn(options?: { + /** the maximum width of a line */ + max_width?: number, + /** Specific newline character */ + newline_char?: string; + }): string; + + /** + * Load the moves of a game stored in Portable Game Notation. + * @param pgn the pgn should be a string in Portable Game Notation. + * @param options An optional object which may contain a string + * newline_char and a boolean sloppy. + * @returns The method will return true if the PGN was parsed successfully, + * otherwise false. + */ + load_pgn(pgn: string, options?: { + /** + * The newline_char is a string representation of a valid RegExp + * fragment and is used to process the PGN. + * It defaults to \r?\n. + * Special characters should not be pre-escaped, but any literal + * special characters should be escaped as is normal for a RegExp. + * Keep in mind that backslashes in JavaScript strings must + * themselves be escaped. + * Avoid using a newline_char that may occur elsewhere in a PGN, + * such as . or x, as this will result in unexpected behavior. + */ + newline_char?: string; + + /** + * The sloppy flag is a boolean that permits chess.js to parse moves in + * non-standard notations. + * See .move documentation for more information about non-SAN + * notations. + */ + sloppy?: boolean; + }): boolean; + + /** + * Allows header information to be added to PGN output. + * Any number of key/value pairs can be passed to .header(), with each + * first arg being treated as a header key, and each second as the value. + * @param args (optional) Header pairs to store in the header. + * @returns The current header information after storing any values. + */ + header(...args: string[]): { [key: string]: string | undefined }; + + /** + * Returns a string containing an ASCII diagram of the current position. + * @returns A string containing an ASCII diagram of the current position. + */ + ascii(): string; + + /** + * Returns the current side to move. + * @returns "b" if Black is the side to move, otherwise "w" for White. + */ + turn(): "b" | "w"; + + /** + * Attempts to make a move on the board, returning a move object if the + * move was legal, otherwise null. + * The .move function can be called two ways, by passing a string in + * Standard Algebraic Notation (SAN), + * Or by passing .move() a move object (only the 'to', 'from', and when + * necessary 'promotion', fields are needed). + * @param move Must be either a string in Standard Algebraic Notation + * (SAN), or a move object (only the 'to', 'from', and when necessary + * 'promotion', fields are needed) + * @param options An optional sloppy flag can be used to parse a variety of + * non-standard move notations: + * @returns The move as a full object is returned if the move was valid, + * and the chess board's state changes. + * If the move was invalid, null is returned and the state does not update. + */ + move(move: string | ShortMove, options?: { + /** + * An optional sloppy flag can be used to parse a variety of + * non-standard move notations. + */ + sloppy?: boolean; + }): Move | null; + + /** + * Take back the last half-move, returning a move object if successful, + * otherwise null. + * @returns the move object that was undone if successful, otherwise null. + */ + undo(): Move | null; + + /** + * Clears the board of all pieces. + */ + clear(): void; + + /** + * Place a piece on the square where piece is an object with the form + * { type: ..., color: ... }. + * put() will fail when passed an invalid piece or square, or when two + * or more kings of the same color are placed. + * @param piece the piece to put somewhere on the game board. + * @param square the square on the chess board to place the piece at. + * @returns true if the piece was successfully placed, otherwise, the + * board remains unchanged and false is returned. + */ + put(piece: Piece, square: Square): boolean; + + /** + * Returns the piece on the square + * @param square the square to get the piece on. + * @returns null if no piece is on that square, or it is not a valid + * square. Otherwise a piece object. + */ + get(square: Square): Piece | null; + + /** + * Remove and return the piece on square. + * @param square the square to remove the piece from, e.g. "b6" + * @returns null if no piece was removed, otherwise an object with the + * removed piece's type and color. + */ + remove(square: Square): Piece | null; + + // This is a debugging utility, and is not documented in their readme. + // So it is not included in these type definitions. + // perft(depth: number): number, + + /** + * Returns the color of the square ('light' or 'dark'). + * @param square the square to check if it is light or dark. + * @returns "light" if a light square, "dark" if a dark square, or null if + * not a valid square. + */ + square_color(square: Square): "light" | "dark"; + + /** + * Returns the color of the square ('light' or 'dark'). + * @param square the square to check if it is light or dark. + * @returns "light" if a light square, "dark" if a dark square, or null if + * not a valid square. + */ + square_color(square: string): "light" | "dark" | null; + + /** + * Returns a list containing the moves of the current game. + * Options is an optional parameter which may contain a 'verbose' flag. + * See .moves() for a description of the verbose move fields. + * @param options an optional parameter which may contain a 'verbose' flag. + * @returns a list of all moves of the current game. They will be strings + * if not passed the verbose flag. + */ + history(options?: { + /** + * Pass true if you want this function to output verbose objects + * instead of strings. + */ + verbose?: false; + }): string[]; + + /** + * Returns a list containing the moves of the current game. + * Options is an optional parameter which may contain a 'verbose' flag. + * See .moves() for a description of the verbose move fields. + * @param options an optional parameter which may contain a 'verbose' flag. + * @returns a list of all moves of the current game. They will be strings + * if not passed the verbose flag. + */ + history(options: { + /** + * Pass true if you want this function to output verbose objects + * instead of strings. + */ + verbose: true; + }): Move[]; + + /** + * Returns a list containing the moves of the current game. + * Options is an optional parameter which may contain a 'verbose' flag. + * See .moves() for a description of the verbose move fields. + * @param options an optional parameter which may contain a 'verbose' flag. + * @returns a list of all moves of the current game. They will be strings + * if not passed the verbose flag. + */ + history(options?: { + /** + * Pass true if you want this function to output verbose objects + * instead of strings. + */ + verbose?: boolean; + }): string[] | Move[]; +} + +/** + * The chess.js function that is used to build chess game instances. + * It can be used with or without `new` to build your instance. Both variants + * work the same. + */ +export const Chess: { + /** + * The Chess() constructor takes an optional parameter which specifies + * the board configuration in Forsyth-Edwards Notation. + * @param fen specifies the board configuration in Forsyth-Edwards Notation. + */ + (fen?: string): ChessInstance; + + /** + * The Chess() constructor takes an optional parameter which specifies + * the board configuration in Forsyth-Edwards Notation. + * @param fen specifies the board configuration in Forsyth-Edwards Notation. + */ + new (fen?: string): ChessInstance; +}; diff --git a/types/chess.js/tsconfig.json b/types/chess.js/tsconfig.json new file mode 100644 index 0000000000..3943fa51b6 --- /dev/null +++ b/types/chess.js/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", + "chess.js-tests.ts" + ] +} diff --git a/types/chess.js/tslint.json b/types/chess.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/chess.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chrome/chrome-cast/index.d.ts b/types/chrome/chrome-cast/index.d.ts index 29bfbebf81..440886031a 100644 --- a/types/chrome/chrome-cast/index.d.ts +++ b/types/chrome/chrome-cast/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Chrome Cast application development // Project: https://developers.google.com/cast/ // Definitions by: Thomas Stig Jacobsen +// Stefan Ullinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped //////////////////// @@ -194,7 +195,7 @@ declare namespace chrome.cast { errorCallback: (error: chrome.cast.Error) => void ): void - export interface ApiConfig { + export class ApiConfig { /** * @param {!chrome.cast.SessionRequest} sessionRequest * @param {function(!chrome.cast.Session)} sessionListener @@ -205,13 +206,13 @@ declare namespace chrome.cast { * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.ApiConfig */ - new( + constructor( sessionRequest: chrome.cast.SessionRequest, sessionListener: (session: chrome.cast.Session) => void, receiverListener: (receiverAvailability: chrome.cast.ReceiverAvailability) => void, autoJoinPolicy?: chrome.cast.AutoJoinPolicy, defaultActionPolicy?: chrome.cast.DefaultActionPolicy - ): ApiConfig; + ); sessionRequest: chrome.cast.SessionRequest; sessionListener: (session: chrome.cast.Session) => void; @@ -220,7 +221,7 @@ declare namespace chrome.cast { defaultActionPolicy: chrome.cast.DefaultActionPolicy; } - export interface Error { + export class Error { /** * @param {!chrome.cast.ErrorCode} code * @param {string=} opt_description @@ -228,11 +229,11 @@ declare namespace chrome.cast { * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Error */ - new( + constructor( code: chrome.cast.ErrorCode, description?: string, details?: Object - ): Error; + ); code: chrome.cast.ErrorCode; description?: string; @@ -253,22 +254,22 @@ declare namespace chrome.cast { width?: number; } - export interface SenderApplication { + export class SenderApplication { /** * @param {!chrome.cast.SenderPlatform} platform * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.SenderApplication */ - new( + constructor( platform: chrome.cast.SenderPlatform - ): SenderApplication; + ); platform: chrome.cast.SenderPlatform; url?: string; packageId?: string; } - export interface SessionRequest { + export class SessionRequest { /** * @param {string} appId * @param {!Array=} opt_capabilities @@ -276,11 +277,11 @@ declare namespace chrome.cast { * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.SessionRequest */ - new( + constructor( appId: string, capabilities?: Array, timeout?: number - ): SessionRequest; + ); appId: string; capabilities: Array; @@ -288,7 +289,7 @@ declare namespace chrome.cast { language?: string; } - export interface Session { + export class Session { /** * @param {string} sessionId * @param {string} appId @@ -298,13 +299,13 @@ declare namespace chrome.cast { * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Session */ - new( + constructor( sessionId: string, appId: string, displayName: string, appImages: Array, receiver: chrome.cast.Receiver - ): Session; + ); sessionId: string; appId: string; @@ -438,7 +439,7 @@ declare namespace chrome.cast { ): void } - export interface Receiver { + export class Receiver { /** * @param {string} label * @param {string} friendlyName @@ -447,12 +448,12 @@ declare namespace chrome.cast { * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Receiver */ - new( + constructor( label: string, friendlyName: string, capabilities?: Array, volume?: chrome.cast.Volume - ): Receiver; + ); label: string; friendlyName: string; @@ -462,33 +463,33 @@ declare namespace chrome.cast { displayStatus: chrome.cast.ReceiverDisplayStatus; } - export interface ReceiverDisplayStatus { + export class ReceiverDisplayStatus { /** * @param {string} statusText * @param {!Array} appImages * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.ReceiverDisplayStatus */ - new( + constructor( statusText: string, appImages: Array - ): ReceiverDisplayStatus; + ); statusText: string; appImages: Array; } - export interface Volume { + export class Volume { /** * @param {?number=} opt_level * @param {?boolean=} opt_muted * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Volume */ - new( + constructor( level?: number, muted?: boolean - ): Volume; + ); level?: number; muted?: boolean; @@ -574,15 +575,15 @@ declare namespace chrome.cast.media { ALL_AND_SHUFFLE = "REPEAT_ALL_AND_SHUFFLE" } - export interface QueueItem { + export class QueueItem { /** * @param {!chrome.cast.media.MediaInfo} mediaInfo * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueItem */ - new( + constructor( mediaInfo: chrome.cast.media.MediaInfo - ): QueueItem; + ); activeTrackIds: Array; autoplay: boolean; @@ -593,15 +594,15 @@ declare namespace chrome.cast.media { startTime: number; } - export interface QueueLoadRequest { + export class QueueLoadRequest { /** * @param {!Array} items * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueLoadRequest */ - new( + constructor( items: Array - ): QueueLoadRequest; + ); customData: Object; items: Array; @@ -609,59 +610,59 @@ declare namespace chrome.cast.media { startIndex: number; } - export interface QueueInsertItemsRequest { + export class QueueInsertItemsRequest { /** * @param {!Array} * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueInsertItemsRequest */ - new( + constructor( itemsToInsert: Array - ): QueueInsertItemsRequest; + ); customData: Object; insertBefore: number; items: Array; } - export interface QueueRemoveItemsRequest { + export class QueueRemoveItemsRequest { /** * @param {!Array} * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueRemoveItemsRequest */ - new( + constructor( itemIdsToRemove: Array - ): QueueRemoveItemsRequest; + ); customData: Object; itemIds: Array; } - export interface QueueReorderItemsRequest { + export class QueueReorderItemsRequest { /** * @param {!Array} * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueReorderItemsRequest */ - new( + constructor( itemIdsToReorder: Array - ): QueueReorderItemsRequest; + ); customData: Object; insertBefore: number; itemIds: Array; } - export interface QueueUpdateItemsRequest { + export class QueueUpdateItemsRequest { /** * @param {!Array} * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.QueueUpdateItemsRequest */ - new( + constructor( itemsToUpdate: Array - ): QueueUpdateItemsRequest; + ); customData: Object; item: Array; @@ -736,67 +737,67 @@ declare namespace chrome.cast.media { ITALIC = "ITALIC" } - export interface GetStatusRequest { + export class GetStatusRequest { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.GetStatusRequest */ - new(): GetStatusRequest; + constructor(); customData: Object; } - export interface PauseRequest { + export class PauseRequest { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.PauseRequest */ - new(): PauseRequest; + constructor(); customData: Object; } - export interface PlayRequest { + export class PlayRequest { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.PlayRequest */ - new(): PlayRequest; + constructor(); customData: Object; } - export interface SeekRequest { + export class SeekRequest { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.SeekRequest */ - new(): SeekRequest; + constructor(); currentTime: number; resumeState: chrome.cast.media.ResumeState; customData: Object; } - export interface StopRequest { + export class StopRequest { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.StopRequest */ - new(): StopRequest; + constructor(); customData: Object; } - export interface VolumeRequest { + export class VolumeRequest { /** * @param {!chrome.cast.Volume} volume * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.VolumeRequest */ - new( + constructor( volume: chrome.cast.Volume - ): VolumeRequest; + ); volume: chrome.cast.Volume; customData: Object; @@ -819,17 +820,17 @@ declare namespace chrome.cast.media { media: chrome.cast.media.MediaInfo; } - export interface EditTracksInfoRequest { + export class EditTracksInfoRequest { /** * @param {Array=} opt_activeTrackIds * @param {chrome.cast.media.TextTrackStyle=} opt_textTrackStyle * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.EditTracksInfoRequest */ - new( + constructor( activeTrackIds?: Array, textTrackStyle?: chrome.cast.media.TextTrackStyle - ): EditTracksInfoRequest; + ); activeTrackIds: Array; textTrackStyle: chrome.cast.media.TextTrackStyle; @@ -847,12 +848,12 @@ declare namespace chrome.cast.media { type: chrome.cast.media.MetadataType; } - export interface MovieMediaMetadata { + export class MovieMediaMetadata { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.MovieMediaMetadata */ - new(): MovieMediaMetadata; + constructor(); images: Array; metadataType: chrome.cast.media.MetadataType; @@ -866,12 +867,12 @@ declare namespace chrome.cast.media { type: chrome.cast.media.MetadataType; } - export interface TvShowMediaMetadata { + export class TvShowMediaMetadata { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.TvShowMediaMetadata */ - new(): TvShowMediaMetadata; + constructor(); metadataType: chrome.cast.media.MetadataType; seriesTitle: string; @@ -893,12 +894,12 @@ declare namespace chrome.cast.media { releaseYear: number; } - export interface MusicTrackMediaMetadata { + export class MusicTrackMediaMetadata { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.MusicTrackMediaMetadata */ - new(): MusicTrackMediaMetadata; + constructor(); metadataType: chrome.cast.media.MetadataType; albumName: string; @@ -920,12 +921,12 @@ declare namespace chrome.cast.media { releaseYear: number; } - export interface PhotoMediaMetadata { + export class PhotoMediaMetadata { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.PhotoMediaMetadata */ - new(): PhotoMediaMetadata; + constructor(); metadataType: chrome.cast.media.MetadataType; title: string; @@ -964,17 +965,17 @@ declare namespace chrome.cast.media { customData: Object; } - export interface Media { + export class Media { /** * @param {string} sessionId * @param {number} mediaSessionId * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.Media */ - new( + constructor( sessionId: string, mediaSessionId: number - ): Media; + ); activeTrackIds: Array; currentItemId: number; @@ -1210,17 +1211,17 @@ declare namespace chrome.cast.media { } - export interface Track { + export class Track { /** * @param {number} trackId * @param {!chrome.cast.media.TrackType} trackType * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.Track */ - new( + constructor( trackId: number, trackType: chrome.cast.media.TrackType - ): Track; + ); trackId: number; trackContentId: string; @@ -1232,12 +1233,12 @@ declare namespace chrome.cast.media { customData: Object; } - export interface TextTrackStyle { + export class TextTrackStyle { /** * @constructor * @see https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.TextTrackStyle */ - new(): TextTrackStyle; + constructor(); foregroundColor: string; backgroundColor: string; diff --git a/types/cleave.js/options/index.d.ts b/types/cleave.js/options/index.d.ts index 65d87d79e1..b1dc95920b 100644 --- a/types/cleave.js/options/index.d.ts +++ b/types/cleave.js/options/index.d.ts @@ -51,4 +51,5 @@ export interface CleaveOptions { noImmediatePrefix?: boolean; rawValueTrimPrefix?: boolean; uppercase?: boolean; + onValueChanged?(event: any): void; } diff --git a/types/commonmark/index.d.ts b/types/commonmark/index.d.ts index 01b9541efa..96bb2774c5 100644 --- a/types/commonmark/index.d.ts +++ b/types/commonmark/index.d.ts @@ -64,7 +64,7 @@ export class Node { /** * either Bullet or Ordered (or undefined). */ - listType: 'Bullet' | 'Ordered'; + listType: 'bullet' | 'ordered'; /** * true if list is tight */ diff --git a/types/compute-quantile/compute-quantile-tests.ts b/types/compute-quantile/compute-quantile-tests.ts new file mode 100644 index 0000000000..8a4c51ea3d --- /dev/null +++ b/types/compute-quantile/compute-quantile-tests.ts @@ -0,0 +1,13 @@ +import quantile = require('compute-quantile'); + +// $ExpectType number +quantile([1, 2, 3], 0.5); + +// $ExpectType number +quantile([1, 2, 3], 0.5, undefined); + +// $ExpectType number +quantile([1, 2, 3], 0.5, {}); + +// $ExpectType number +quantile([1, 2, 3], 0.5, { sorted: true }); diff --git a/types/compute-quantile/index.d.ts b/types/compute-quantile/index.d.ts new file mode 100644 index 0000000000..05d83b65f4 --- /dev/null +++ b/types/compute-quantile/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for compute-quantile 1.0 +// Project: https://github.com/compute-io/quantile +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Computes a quantile for a numeric array. + */ +declare function quantile(array: ArrayLike, quantile: number, options?: quantile.Options): number; + +declare namespace quantile { + interface Options { + /** + * If the input `array` is already sorted in `__ascending__` order, you can set the `sorted` option to `true`. + * + * @default + * false + */ + sorted?: boolean; + } +} + +export = quantile; diff --git a/types/compute-quantile/tsconfig.json b/types/compute-quantile/tsconfig.json new file mode 100644 index 0000000000..29d10580e3 --- /dev/null +++ b/types/compute-quantile/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", + "compute-quantile-tests.ts" + ] +} diff --git a/types/compute-quantile/tslint.json b/types/compute-quantile/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/compute-quantile/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/connect-mongo/index.d.ts b/types/connect-mongo/index.d.ts index ee110ab6b0..ea39a13f42 100644 --- a/types/connect-mongo/index.d.ts +++ b/types/connect-mongo/index.d.ts @@ -104,12 +104,12 @@ declare namespace connectMongo { } export class MongoStore extends session.Store { - get: (sid: string, callback: (err: any, session: Express.Session | null) => void) => void; - set: (sid: string, session: Express.Session, callback?: (err: any) => void) => void; + get: (sid: string, callback: (err: any, session: Express.SessionData | null) => void) => void; + set: (sid: string, session: Express.SessionData, callback?: (err: any) => void) => void; destroy: (sid: string, callback?: (err: any) => void) => void; length: (callback: (err: any, length: number) => void) => void; clear: (callback?: (err?: any) => void) => void; - touch: (sid: string, session: Express.Session, callback?: (err: any) => void) => void; + touch: (sid: string, session: Express.SessionData, callback?: (err: any) => void) => void; } } diff --git a/types/cookie-session/index.d.ts b/types/cookie-session/index.d.ts index a0b7a2e6b0..af48860396 100644 --- a/types/cookie-session/index.d.ts +++ b/types/cookie-session/index.d.ts @@ -15,7 +15,7 @@ declare namespace CookieSessionInterfaces { /** * The name of the cookie to set, defaults to session. */ - name: string; + name?: string; /** * The list of keys to use to sign & verify cookie values. Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation. @@ -47,6 +47,11 @@ declare namespace CookieSessionInterfaces { */ domain?: string; + /** + * a boolean or string indicating whether the cookie is a "same site" cookie (false by default). This can be set to 'strict', 'lax', or true (which maps to 'strict'). + */ + sameSite?: "strict" | "lax" | boolean; + /** * a boolean indicating whether the cookie is only to be sent over HTTPS (false by default for HTTP, true by default for HTTPS). */ diff --git a/types/create-subscription/create-subscription-tests.tsx b/types/create-subscription/create-subscription-tests.tsx index 891adc5ede..d1b3d3bda0 100644 --- a/types/create-subscription/create-subscription-tests.tsx +++ b/types/create-subscription/create-subscription-tests.tsx @@ -105,15 +105,7 @@ declare const wrongPromise: Promise; ; // $ExpectError -const MismatchSubscription = createSubscription({ - getCurrentValue: (a: number) => null, - subscribe: (a: string, callback) => (() => undefined) -}); +const MismatchSubscription = createSubscription({ getCurrentValue: (a: number) => null, subscribe: (a: string, callback) => (() => undefined) }); // $ExpectError -const NoUnsubscribe = createSubscription({ - getCurrentValue: (a: number) => a, - subscribe: (a: number, callback) => { - // oops, should've returned a callback here - } -}); +const NoUnsubscribe = createSubscription({ getCurrentValue: (a: number) => a, subscribe: (a: number, callback) => { /* oops, should've returned a callback here */ }}); diff --git a/types/credit-card-type/index.d.ts b/types/credit-card-type/index.d.ts index 8625e5e5f8..c4a98b4e10 100644 --- a/types/credit-card-type/index.d.ts +++ b/types/credit-card-type/index.d.ts @@ -1,31 +1,39 @@ -// Type definitions for Credit Card Type v5.0.0 +// Type definitions for Credit Card Type v7.0.0 // Project: https://github.com/braintree/credit-card-type // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 declare namespace creditCardType { - - type CardBrand = "american-express" | "diners-club" | "discover" | "jcb" | "maestro" | "master-card" | "unionpay" | "visa" + type CardBrand = + | "american-express" + | "diners-club" + | "discover" + | "jcb" + | "maestro" + | "mastercard" + | "unionpay" + | "visa"; interface CreditCardTypeInfo { - niceType?: string - type?: CardBrand - prefixPattern?: RegExp - exactPattern?: RegExp - gaps?: Array - lengths?: Array + niceType?: string; + type?: CardBrand; + prefixPattern?: RegExp; + exactPattern?: RegExp; + gaps?: Array; + lengths?: Array; code?: { - name?: string - size?: number - } + name?: string; + size?: number; + }; } interface CreditCardType { - (number: string): Array - getTypeInfo (type: string): CreditCardTypeInfo - types: { [type: string]: string } + (number: string): Array; + getTypeInfo(type: string): CreditCardTypeInfo; + types: { [type: string]: string }; } } -declare const creditCardType: creditCardType.CreditCardType -export = creditCardType +declare const creditCardType: creditCardType.CreditCardType; +export = creditCardType; diff --git a/types/d3.cloud.layout/d3.cloud.layout-tests.ts b/types/d3-cloud/d3-cloud-tests.ts similarity index 100% rename from types/d3.cloud.layout/d3.cloud.layout-tests.ts rename to types/d3-cloud/d3-cloud-tests.ts diff --git a/types/d3.cloud.layout/index.d.ts b/types/d3-cloud/index.d.ts similarity index 100% rename from types/d3.cloud.layout/index.d.ts rename to types/d3-cloud/index.d.ts diff --git a/types/d3.cloud.layout/tsconfig.json b/types/d3-cloud/tsconfig.json similarity index 94% rename from types/d3.cloud.layout/tsconfig.json rename to types/d3-cloud/tsconfig.json index ffb26214cc..d5f3d151b7 100644 --- a/types/d3.cloud.layout/tsconfig.json +++ b/types/d3-cloud/tsconfig.json @@ -24,6 +24,6 @@ }, "files": [ "index.d.ts", - "d3.cloud.layout-tests.ts" + "d3-cloud-tests.ts" ] } \ No newline at end of file diff --git a/types/d3.cloud.layout/tslint.json b/types/d3-cloud/tslint.json similarity index 100% rename from types/d3.cloud.layout/tslint.json rename to types/d3-cloud/tslint.json diff --git a/types/d3-delaunay/d3-delaunay-tests.ts b/types/d3-delaunay/d3-delaunay-tests.ts new file mode 100644 index 0000000000..7f3103f60e --- /dev/null +++ b/types/d3-delaunay/d3-delaunay-tests.ts @@ -0,0 +1,118 @@ +/** + * TypeScript definition tests for d3-delaunay module + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +import * as d3 from 'd3-delaunay'; + +// Test Delaunay class + +const constructedDelaunay = new d3.Delaunay([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); +const defaultDelaunayFromArray: d3.Delaunay<[number, number]> = d3.Delaunay.from([[0, 0], [1, 0], [0, 1], [1, 1]]); +const defaultDelaunayFromIterator = d3.Delaunay.from((function*() { + yield [0, 0]; + yield [1, 0]; + yield [0, 1]; + yield [1, 1]; +})()); +const customDelaunayFromArray = d3.Delaunay.from({length: 4}, (d, i) => i & 1, (d, i) => (i >> 1) & 1); +const customDelaunayFromIterator = d3.Delaunay.from((function*() { + yield {x: 0, y: 0}; + yield {x: 1, y: 0}; + yield {x: 0, y: 1}; + yield {x: 1, y: 1}; +})(), p => p.x, p => p.y); + +const {points, halfedges, hull, triangles} = defaultDelaunayFromArray; +for (let i = 0, l = points.length; i < l; i++) { + typeof(points[i]); +} +for (let i = 0, l = halfedges.length; i < l; i++) { + const j = halfedges[i]; + const ti = triangles[i]; + const tj = triangles[j]; + const pix = points[ti * 2]; + const piy = points[ti * 2 + 1]; + const pjx = points[tj * 2]; + const pjy = points[tj * 2 + 1]; +} +for (let n = hull.next; n !== hull; n = n.next) { + const i: number = n.i; + const x: number = n.x; + const y: number = n.y; + const t: number = n.t; + const next: d3.Delaunay.Node = n.next; + const prev: d3.Delaunay.Node = n.prev; + const removed: boolean = n.removed; +} +for (let i = 0, l = triangles.length; i < l; i++) { + const t0 = triangles[i * 3 + 0]; + const t1 = triangles[i * 3 + 1]; + const t2 = triangles[i * 3 + 2]; + const p0x = points[t0 * 2]; + const p0y = points[t0 * 2 + 1]; + const p1x = points[t1 * 2]; + const p1y = points[t1 * 2 + 1]; + const p2x = points[t2 * 2]; + const p2y = points[t2 * 2 + 1]; +} +const findClosest = defaultDelaunayFromArray.find(0.5, 0.5); +for (const neighbor of defaultDelaunayFromArray.neighbors(0)) { + typeof(neighbor); +} +const render: string = defaultDelaunayFromArray.render(); +const renderHull: string = defaultDelaunayFromArray.renderHull(); +const renderTriangle: string = defaultDelaunayFromArray.renderTriangle(0); +const renderPoints: string = defaultDelaunayFromArray.renderPoints(); +const renderPointsRadius: string = defaultDelaunayFromArray.renderPoints(void 0, 3); +for (const p of defaultDelaunayFromArray.hullPolygon()) { + const x = p[0]; + const y = p[1]; +} +for (const poly of defaultDelaunayFromArray.trianglePolygons()) { + for (const p of poly) { + const x = p[0]; + const y = p[1]; + } +} +for (const p of defaultDelaunayFromArray.trianglePolygon(0)) { + const x = p[0]; + const y = p[1]; +} + +// Test Voronoi class + +const v = defaultDelaunayFromArray.voronoi(); +const {circumcenters, vectors} = v; +const d: d3.Delaunay<[number, number]> = v.delaunay; +for (let i = 0, l = circumcenters.length; i < l; i++) { + const x: number = circumcenters[i * 2]; + const y: number = circumcenters[i * 2 + 1]; +} +for (let i = 0, l = vectors.length; i < l; i++) { + const vx: number = vectors[i * 4]; + const vy: number = vectors[i * 4 + 1]; + const wx: number = vectors[i * 4 + 2]; + const wy: number = vectors[i * 4 + 3]; +} +const xmin: number = v.xmin; +const ymin: number = v.ymin; +const xmax: number = v.xmax; +const ymax: number = v.ymax; +const contains: boolean = v.contains(0, 0.5, 0.5); +const vrender: string = v.render(); +const vrenderBounds: string = v.renderBounds(); +const renderCell: string = v.renderCell(0); +for (const poly of v.cellPolygons()) { + for (const p of poly) { + const x = p[0]; + const y = p[1]; + } +} +for (const p of v.cellPolygon(0)) { + const x = p[0]; + const y = p[1]; +} diff --git a/types/d3-delaunay/index.d.ts b/types/d3-delaunay/index.d.ts new file mode 100644 index 0000000000..c5d10e8aa3 --- /dev/null +++ b/types/d3-delaunay/index.d.ts @@ -0,0 +1,359 @@ +// Type definitions for d3-delaunay 4.1 +// Project: https://github.com/d3/d3-delaunay +// Definitions by: Bradley Odell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Delaunay triangulation + */ +export class Delaunay

{ + /** + * The coordinates of the points as an array [x0, y0, x1, y1, ...]. + * Typically, this is a Float64Array, however you can use any array-like type in the constructor. + */ + points: ArrayLike; + + /** + * The halfedge indices as an Int32Array [j0, j1, ...]. + * For each index 0 <= i < halfedges.length, there is a halfedge from triangle vertex j = halfedges[i] to triangle vertex i. + */ + halfedges: Int32Array; + + /** + * An arbitrary node on the convex hull. + * The convex hull is represented as a circular doubly-linked list of nodes. + */ + hull: Delaunay.Node; + + /** + * The triangle vertex indices as an Uint32Array [i0, j0, k0, i1, j1, k1, ...]. + * Each contiguous triplet of indices i, j, k forms a counterclockwise triangle. + * The coordinates of the triangle's points can be found by going through 'points'. + */ + triangles: Uint32Array; + + /** + * The incoming halfedge indexes as a Int32Array [e0, e1, e2, ...]. + * For each point i, inedges[i] is the halfedge index e of an incoming halfedge. + * For coincident points, the halfedge index is -1; for points on the convex hull, the incoming halfedge is on the convex hull; for other points, the choice of incoming halfedge is arbitrary. + */ + inedges: Int32Array; + + /** + * The outgoing halfedge indexes as a Int32Array [e0, e1, e2, ...]. + * For each point i on the convex hull, outedges[i] is the halfedge index e of the corresponding outgoing halfedge; for other points, the halfedge index is -1. + */ + outedges: Int32Array; + + /** + * Returns the Delaunay triangulation for the given flat array [x0, y0, x1, y1, …] of points. + */ + constructor(points: ArrayLike); + + /** + * Returns the Delaunay triangulation for the given array or iterable of points where each point is an array in the form: [x, y]. + */ + static from(points: ArrayLike|Iterable): Delaunay; + + /** + * Returns the Delaunay triangulation for the given array or iterable of points. + * Otherwise, the getX and getY functions are invoked for each point in order, and must return the respective x- and y-coordinate for each point. + * If that is specified, the functions getX and getY are invoked with that as this. + * (See Array.from for reference.) + */ + static from

(points: ArrayLike

|Iterable

, + getX: Delaunay.GetCoordinate|Iterable

>, + getY: Delaunay.GetCoordinate|Iterable

>, + that?: any): Delaunay

; + + /** + * Returns the index of the input point that is closest to the specified point ⟨x, y⟩. + * The search is started at the specified point i. If i is not specified, it defaults to zero. + */ + find(x: number, y: number, i?: number): number; + + /** + * Returns an iterable over the indexes of the neighboring points to the specified point i. + * The iterable is empty if i is a coincident point. + */ + neighbors(i: number): IterableIterator; + + /** + * Returns the closed polygon [[x0, y0], [x1, y1], ..., [x0, y0]] representing the convex hull. + */ + hullPolygon(): Delaunay.Polygon; + + /** + * Returns the closed polygon [[x0, y0], [x1, y1], [x2, y2], [x0, y0]] representing the triangle i. + */ + trianglePolygon(i: number): Delaunay.Triangle; + + /** + * Returns an iterable over the polygons for each triangle, in order. + */ + trianglePolygons(): IterableIterator; + + /** + * Renders the edges of the Delaunay triangulation to an SVG path string. + */ + render(): string; + + /** + * Renders the edges of the Delaunay triangulation to the specified context. + * The specified context must implement the context.moveTo and context.lineTo methods from the CanvasPathMethods API. + */ + render(context: Delaunay.MoveContext & Delaunay.LineContext): void; + + /** + * Renders the convex hull of the Delaunay triangulation to an SVG path string. + */ + renderHull(): string; + + /** + * Renders the convex hull of the Delaunay triangulation to the specified context. + * The specified context must implement the context.moveTo and context.lineTo methods from the CanvasPathMethods API. + */ + renderHull(context: Delaunay.MoveContext & Delaunay.LineContext): void; + + /** + * Renders triangle i of the Delaunay triangulation to an SVG path string. + */ + renderTriangle(i: number): string; + + /** + * Renders triangle i of the Delaunay triangulation to the specified context. + * The specified context must implement the context.moveTo, context.lineTo and context.closePath methods from the CanvasPathMethods API. + */ + renderTriangle(i: number, context: Delaunay.MoveContext & Delaunay.LineContext & Delaunay.ClosableContext): void; + + /** + * Renders the input points of the Delaunay triangulation to an SVG path string as circles with radius 2. + */ + renderPoints(): string; + + /** + * Renders the input points of the Delaunay triangulation to an SVG path string as circles with the specified radius. + */ + renderPoints(context: undefined, radius: number): string; + + /** + * Renders the input points of the Delaunay triangulation to the specified context as circles with the specified radius. + * If radius is not specified, it defaults to 2. + * The specified context must implement the context.moveTo and context.arc methods from the CanvasPathMethods API. + */ + renderPoints(context: Delaunay.MoveContext & Delaunay.ArcContext, radius?: number): void; + + /** + * Returns the Voronoi diagram for the associated points. + * When rendering, the diagram will be clipped to the specified bounds = [xmin, ymin, xmax, ymax]. + * If bounds is not specified, it defaults to [0, 0, 960, 500]. + * See To Infinity and Back Again for an interactive explanation of Voronoi cell clipping. + */ + voronoi(bounds?: Delaunay.Bounds): Voronoi

; +} + +export namespace Delaunay { + /** + * A point represented as an array tuple [x, y]. + */ + type Point = number[]; + + /** + * A closed polygon [[x0, y0], [x1, y1], [x2, y2], [x0, y0]] representing a triangle. + */ + type Triangle = Point[]; + + /** + * A closed polygon [[x0, y0], [x1, y1], ..., [x0, y0]]. + */ + type Polygon = Point[]; + + /** + * A rectangular area [x, y, width, height]. + */ + type Bounds = number[]; + + /** + * A function to extract a x- or y-coordinate from the specified point. + */ + type GetCoordinate = (point: P, i: number, points: PS) => number; + + /** + * A point node on a convex hull (represented as a circular linked list). + */ + interface Node { + /** + * The index of the associated point. + */ + i: number; + + /** + * The x-coordinate of the associated point. + */ + x: number; + + /** + * The y-coordinate of the associated point. + */ + y: number; + + /** + * The index of the (incoming or outgoing?) associated halfedge. + */ + t: number; + + /** + * The previous node on the hull. + */ + prev: Node; + + /** + * The next node on the hull. + */ + next: Node; + + /** + * Whether the node has been removed from the linked list. + */ + removed: boolean; + } + + /** + * An interface for the rect() method of the CanvasPathMethods API. + */ + interface RectContext { + /** + * rect() method of the CanvasPathMethods API. + */ + rect(x: number, y: number, width: number, height: number): void; + } + + /** + * An interface for the moveTo() method of the CanvasPathMethods API. + */ + interface MoveContext { + /** + * moveTo() method of the CanvasPathMethods API. + */ + moveTo(x: number, y: number): void; + } + + /** + * An interface for the lineTo() method of the CanvasPathMethods API. + */ + interface LineContext { + /** + * lineTo() method of the CanvasPathMethods API. + */ + lineTo(x: number, y: number): void; + } + + /** + * An interface for the arc() method of the CanvasPathMethods API. + */ + interface ArcContext { + /** + * arc() method of the CanvasPathMethods API. + */ + arc(x: number, y: number, radius: number, + startAngle: number, endAngle: number, + counterclockwise?: boolean): void; + } + + /** + * An interface for the closePath() method of the CanvasPathMethods API. + */ + interface ClosableContext { + /** + * closePath() method of the CanvasPathMethods API. + */ + closePath(): void; + } +} + +/** + * Voronoi regions + */ +export class Voronoi

{ + /** + * The Voronoi diagram’s associated Delaunay triangulation. + */ + delaunay: Delaunay

; + + /** + * The circumcenters of the Delaunay triangles [cx0, cy0, cx1, cy1, ...]. + * Each contiguous pair of coordinates cx, cy is the circumcenter for the corresponding triangle. + * These circumcenters form the coordinates of the Voronoi cell polygons. + */ + circumcenters: Float64Array; + + /** + * An array [vx0, vy0, wx0, wy0, ...] where each non-zero quadruple describes an open (infinite) cell + * on the outer hull, giving the directions of two open half-lines. + */ + vectors: Float64Array; + + /** + * The bounds of the viewport [xmin, ymin, xmax, ymax] for rendering the Voronoi diagram. + * These values only affect the rendering methods (voronoi.render, voronoi.renderBounds, cell.render). + */ + xmin: number; + ymin: number; + xmax: number; + ymax: number; + + /** + * Internally used to implement Delaunay#voronoi. + */ + constructor(delaunay: Delaunay

, bounds: Delaunay.Bounds); + + /** + * Returns true if the cell with the specified index i contains the specified point ⟨x, y⟩. + * (This method is not affected by the associated Voronoi diagram’s viewport bounds.) + */ + contains(i: number, x: number, y: number): boolean; + + /** + * Returns the convex, closed polygon [[x0, y0], [x1, y1], ..., [x0, y0]] representing the cell for the specified point i. + */ + cellPolygon(i: number): Delaunay.Polygon; + + /** + * Returns an iterable over the polygons for each cell, in order. + */ + cellPolygons(): IterableIterator; + + /** + * Renders the mesh of Voronoi cells to an SVG path string. + */ + render(): string; + + /** + * Renders the mesh of Voronoi cells to the specified context. + * The specified context must implement the context.moveTo and context.lineTo methods from the CanvasPathMethods API. + */ + render(context: Delaunay.MoveContext & Delaunay.LineContext): void; + + /** + * Renders the viewport extent to an SVG path string. + */ + renderBounds(): string; + + /** + * Renders the viewport extent to the specified context. + * The specified context must implement the context.rect method from the CanvasPathMethods API. + * Equivalent to context.rect(voronoi.xmin, voronoi.ymin, voronoi.xmax - voronoi.xmin, voronoi.ymax - voronoi.ymin). + */ + renderBounds(context: Delaunay.RectContext): void; + + /** + * Renders the cell with the specified index i to an SVG path string. + */ + renderCell(i: number): string; + + /** + * Renders the cell with the specified index i to the specified context. + * The specified context must implement the context.moveTo, context.lineTo, and context.closePath methods from the CanvasPathMethods API. + */ + renderCell(i: number, context: Delaunay.MoveContext & Delaunay.LineContext & Delaunay.ClosableContext): void; +} diff --git a/types/d3-delaunay/tsconfig.json b/types/d3-delaunay/tsconfig.json new file mode 100644 index 0000000000..ab2a753d44 --- /dev/null +++ b/types/d3-delaunay/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3-delaunay-tests.ts" + ] +} \ No newline at end of file diff --git a/types/d3-delaunay/tslint.json b/types/d3-delaunay/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/d3-delaunay/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/d3-hexbin/d3-hexbin-tests.ts b/types/d3-hexbin/d3-hexbin-tests.ts index 0082ae075d..bef57a94c4 100644 --- a/types/d3-hexbin/d3-hexbin-tests.ts +++ b/types/d3-hexbin/d3-hexbin-tests.ts @@ -104,8 +104,8 @@ interface Point { } { - // hexbin.hexagon(radius) uses the current bin radius if radius is null - let path: string = d3Hexbin.hexbin().hexagon(null); + // hexbin.hexagon(radius) uses the current bin radius if radius is undefined + let path: string = d3Hexbin.hexbin().hexagon(); path = d3Hexbin.hexbin().hexagon(undefined); } @@ -146,6 +146,13 @@ interface Point { .mesh(); } +{ + // hexbin.size() + let size: [number, number] = [100, 100]; + d3Hexbin.hexbin().size(size); + size = d3Hexbin.hexbin().size(); +} + { let hb: d3Hexbin.Hexbin; let bins: Array>; diff --git a/types/d3-hexbin/index.d.ts b/types/d3-hexbin/index.d.ts index 5fa53e6145..616ca7186c 100644 --- a/types/d3-hexbin/index.d.ts +++ b/types/d3-hexbin/index.d.ts @@ -1,12 +1,22 @@ // Type definitions for D3JS d3-hexbin module 0.2 // Project: https://github.com/d3/d3-hexbin/ -// Definitions by: UNCOVER TRUTH Inc. , Tom Wanzek +// Definitions by: UNCOVER TRUTH Inc. +// Tom Wanzek +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -// Last module patch version validated against: 0.2.1 +// Last module patch version validated against: 0.2.2 export interface HexbinBin extends Array { + /** + * The x-coordinate of the center of the associated bin’s hexagon. + */ x: number; + + /** + * The y-coordinate of the center of the associated bin’s hexagon. + */ y: number; } @@ -15,7 +25,7 @@ export interface Hexbin { * Bins the specified array of points, returning an array of hexagonal bins. * For each point in the specified points array, the x- and y-accessors are * invoked to compute the x- and y-coordinates of the point, which is then - * used to determine which hexagonal bin to add the point. + * used to assign the point to a hexagonal bin. * If either the x- or y-coordinate is NaN, the point is ignored and will * not be in any of the returned bins. */ @@ -47,49 +57,34 @@ export interface Hexbin { mesh(): string; /** - * If x is specified, sets the x-coordinate accessor to the specified - * function and returns this hexbin generator. + * Sets the x-coordinate accessor to the specified function and returns this hexbin generator. * * The x-coordinate accessor is used by hexbin to compute the x-coordinate * of each point. The default value assumes each point is specified as * a two-element array of numbers [x, y]. */ - x(x: (d: T) => number): Hexbin; + x(x: (d: T) => number): this; /** - * If x is not specified, returns the current x-coordinate accessor, - * - * which defaults to: - * - * function x(d) { - * return d[0]; - * } + * Returns the current x-coordinate accessor, which defaults to: `x(d) => d[0]`. * * The x-coordinate accessor is used by hexbin to compute the x-coordinate * of each point. The default value assumes each point is specified as * a two-element array of numbers [x, y]. - * */ x(): (d: T) => number; /** - * If y is specified, sets the y-coordinate accessor to the specified - * function and returns this hexbin generator. + * Sets the y-coordinate accessor to the specified function and returns this hexbin generator. * * The y-coordinate accessor is used by hexbin to compute the y-coordinate * of each point. The default value assumes each point is specified as * a two-element array of numbers [x, y]. */ - y(y: (d: T) => number): Hexbin; + y(y: (d: T) => number): this; /** - * If y is not specified, returns the current y-coordinate accessor, - * - * which defaults to: - * - * function y(d) { - * return d[1]; - * } + * Returns the current y-coordinate accessor, which defaults to: `y(d) => d[1]`. * * The y-coordinate accessor is used by hexbin to compute the y-coordinate * of each point. The default value assumes each point is specified as @@ -98,18 +93,16 @@ export interface Hexbin { y(): (d: T) => number; /** - * If radius is specified, sets the radius of the hexagon to - * the specified number. + * Sets the radius of the hexagon to the specified number. * * The hexagons are pointy-topped (rather than flat-topped); * the width of each hexagon is radius × 2 × sin(π / 3) * and the height of each hexagon radius × 3 / 2. */ - radius(radius: number): Hexbin; + radius(radius: number): this; /** - * If radius is not specified, returns the current radius, - * which defaults to 1. + * Returns the current radius, which defaults to 1. * * The hexagons are pointy-topped (rather than flat-topped); * the width of each hexagon is radius × 2 × sin(π / 3) @@ -118,23 +111,42 @@ export interface Hexbin { radius(): number; /** - * If extent is specified, sets the hexbin generator’s extent to the - * specified bounds [[x0, y0], [x1, y1]] and returns the hexbin generator. + * Sets the hexbin generator’s extent to the specified bounds + * `[[x0, y0], [x1, y1]]` and returns the hexbin generator. */ - extent(extent: [[number, number], [number, number]]): Hexbin; + extent(extent: [[number, number], [number, number]]): this; /** - * If extent is not specified, returns the generator’s current - * extent [[x0, y0], [x1, y1]], where x0 and y0 are the lower bounds and - * x1 and y1 are the upper bounds. + * Returns the generator’s current extent `[[x0, y0], [x1, y1]]`, + * where `x0` and `y0` are the lower bounds and `x1` and `y1` are the upper bounds. * - * The extent defaults to [[0, 0], [1, 1]]. + * The extent defaults to `[[0, 0], [1, 1]]`. */ extent(): [[number, number], [number, number]]; + + /** + * Sets the extent to the specified bounds `[[0, 0], [dx, dy]]` and returns the hexbin generator. + * + * This is a convenience method for setting the extent. + */ + size(size: [number, number]): this; + + /** + * Returns the generator’s current size `[x1 - x0, y1 - y0]`, + * where `x0` and `y0` are the lower bounds and `x1` and `y1` are the upper bounds. + * + * The size defaults to [1, 1]. + */ + size(): [number, number]; } /** - * Constructs a new default hexbin generator. + * Creates a new hexbin generator with default radius, extent, x- and y- accessors. + * The x- and y-accessors may have to be set to correspond to the data type provided + * by the generic. + * + * The generic refers to the type of the data for the corresponding element. + * Without specifying a generic the layout is assumed to be based on data represented + * by a two-dimensional coordinate `[number, number]` for x- and y-coordinate, respectively. */ -export function hexbin(): Hexbin<[number, number]>; -export function hexbin(): Hexbin; +export function hexbin(): Hexbin; diff --git a/types/d3-hexbin/tsconfig.json b/types/d3-hexbin/tsconfig.json index 773221263b..2ac8e0c3ff 100644 --- a/types/d3-hexbin/tsconfig.json +++ b/types/d3-hexbin/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/d3-queue/d3-queue-tests.ts b/types/d3-queue/d3-queue-tests.ts index 08c195d9bd..064e1a5b61 100644 --- a/types/d3-queue/d3-queue-tests.ts +++ b/types/d3-queue/d3-queue-tests.ts @@ -73,7 +73,7 @@ qWithResults = d3Queue.queue() .defer(getFileStats, './yetanotherworkingpath/file2.json') .awaitAll((error, fileStats) => { if (error) throw error; - console.log(fileStats[0], fileStats[1]); + console.log(fileStats![0], fileStats![1]); }); // Abort Deferred Tasks ============================================== @@ -83,11 +83,11 @@ function requestDataFromInterWeb(url: string, callback: (error: any | null, data } qWithResults = d3Queue.queue() - .defer(requestDataFromInterWeb, 'http://www.google.com:81') - .defer(requestDataFromInterWeb, 'http://www.google.com:81') + .defer(requestDataFromInterWeb, 'http://www.example.org:81') + .defer(requestDataFromInterWeb, 'http://www.example.org:81') .awaitAll((error, results) => { if (error) throw error; - console.log(results[0], results[1]); + console.log(results![0], results![1]); }); qWithResults.abort(); diff --git a/types/d3-queue/index.d.ts b/types/d3-queue/index.d.ts index 5ad38d8d74..094a62ab03 100644 --- a/types/d3-queue/index.d.ts +++ b/types/d3-queue/index.d.ts @@ -1,9 +1,12 @@ // Type definitions for D3JS d3-queue module 3.0 // Project: https://github.com/d3/d3-queue/ -// 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: 3.0.2 +// Last module patch version validated against: 3.0.7 /** * A d3-queue queue object as returned by queue(...) @@ -12,36 +15,42 @@ export interface Queue { /** * Adds the specified asynchronous task callback to the queue, with any optional arguments. * - * @param task Task to be executed.The task is a function that will be called when the task should start. It is passed the - * specified optional arguments and an additional callback as the last argument; + * @param task Task to be executed.The task is a function that will be called when the task should start. + * It is passed the specified optional arguments and an additional callback as the last argument; * the callback must be invoked by the task when it finishes. * The task must invoke the callback with two arguments: the error, if any, and the result of the task. * To return multiple results from a single callback, wrap the results in an object or array. - * @param args Additional, optional arguments to be passed into deferred task on invocation + * @param args Additional, optional arguments to be passed into deferred task on invocation. + * @throws If called after an `await`, will throw an `Error`. */ defer(task: (...args: any[]) => void, ...args: any[]): this; + /** * Aborts any active tasks, invoking each active task’s task.abort function, if any. * Also prevents any new tasks from starting, and immediately invokes the queue.await or * queue.awaitAll callback with an error indicating that the queue was aborted. */ abort(): this; + /** * Sets the callback to be invoked when all deferred tasks have finished (individual result arguments). * - * @param callback Callback function to be executed, when error occurred or all deferred tasks - * have completed. The first argument to the callback is the first error that occurred, or null if no error occurred. - * If an error occurred, there are no additional arguments to the callback. Otherwise, - * the callback is passed each result as an additional argument. + * @param callback Callback function to be executed, when error occurred or all deferred tasks have completed. + * The first argument to the callback is the first error that occurred, or null if no error occurred. + * If an error occurred, there are no additional arguments to the callback. + * Otherwise, the callback is passed each result as an additional argument. + * @throws If called several times or after `awaitAll`, will throw an `Error`. */ await(callback: (error: any | null, ...results: any[]) => void): this; + /** * Sets the callback to be invoked when all deferred tasks have finished (results array). * - * @param callback Callback function to be executed, when error occurred or all deferred tasks - * have completed. The first argument to the callback is the first error that occurred, - * or null if no error occurred. If an error occurred, there are no additional arguments to the callback. + * @param callback Callback function to be executed, when error occurred or all deferred tasks have completed. + * The first argument to the callback is the first error that occurred, or null if no error occurred. + * If an error occurred, there are no additional arguments to the callback. * Otherwise, the callback is also passed an array of results as the second argument. + * @throws If called several times or after `await`, will throw an `Error`. */ awaitAll(callback: (error: any | null, results?: any[]) => void): this; } @@ -53,5 +62,6 @@ export interface Queue { * when loading resources in a web browser. * * @param concurrency Maximum number of deferred tasks to execute concurrently. + * @throws If `concurrency` is negative or zero, will throw an `Error`. */ export function queue(concurrency?: number): Queue; diff --git a/types/d3-queue/tsconfig.json b/types/d3-queue/tsconfig.json index 72f00c11e5..251d3912b3 100644 --- a/types/d3-queue/tsconfig.json +++ b/types/d3-queue/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/d3-request/d3-request-tests.ts b/types/d3-request/d3-request-tests.ts index 8b2130240a..e2208481d8 100644 --- a/types/d3-request/d3-request-tests.ts +++ b/types/d3-request/d3-request-tests.ts @@ -36,13 +36,13 @@ interface ResponseDatumPOST { success: boolean; } -let listenerXhr: (this: d3Request.Request, xhr: XMLHttpRequest) => void; +let listenerXhr: ((this: d3Request.Request, xhr: XMLHttpRequest) => void) | undefined; -let listenerProgress: (this: d3Request.Request, progEvent: ProgressEvent) => void; +let listenerProgress: ((this: d3Request.Request, progEvent: ProgressEvent) => void) | undefined; -let listenerError: (this: d3Request.Request, error: any) => void; +let listenerError: ((this: d3Request.Request, error: any) => void) | undefined; -let listenerResult: (this: d3Request.Request, result: ResponseDatumGET[]) => void; +let listenerResult: ((this: d3Request.Request, result: ResponseDatumGET[]) => void) | undefined; // ------------------------------------------------------------------------------- // Generic Request @@ -108,7 +108,7 @@ const r7: d3Request.Request = request.header('Accept-Encoding', null); // Mime Type ------------------------------------------------------------------- // get -let mimeType: string = request.mimeType(); +let mimeType: string | null = request.mimeType(); // set const r8: d3Request.Request = request.mimeType('application/json'); // remove @@ -162,11 +162,12 @@ r10 = r10.on('load', function(result: ResponseDatumGET[]) { // do something; }); -// r10 = r10.on('load', function(result: number) { // fails, wrong argument type for callback -// const that: d3Request.Request = this; -// const res: number = result; -// // do something; -// }); +// $ExpectError +r10 = r10.on('load', function(result: number) { // fails, wrong argument type for callback + const that: d3Request.Request = this; + const res: number = result; + // do something; +}); listenerResult = r10.on('load'); @@ -191,9 +192,10 @@ listenerError = r10.on('error.foo'); // Password --------------------------------------------------------------------- // get -const password: string = request.password(); +const password: string | null = request.password(); // set const r11: d3Request.Request = request.password('MyPassword'); +const r25: d3Request.Request = request.password(null); // Post ------------------------------------------------------------------------- @@ -238,11 +240,11 @@ const r16: d3Request.Request = d3Request.request(url) // ResponseType ----------------------------------------------------------------- // get -const responseType: string = d3Request.request(url) +const responseType: XMLHttpRequestResponseType | undefined = d3Request.request(url) .responseType(); // set const r17: d3Request.Request = d3Request.request(url) - .responseType('application/json'); + .responseType('json'); // Send ------------------------------------------------------------------------ @@ -259,7 +261,7 @@ const r20: d3Request.Request = d3Request.request(url) .response(xhr2Listing) .send('GET', (error, response) => { if (!error) { - const r: ResponseDatumGET[] = response; + const r: ResponseDatumGET[] | null = response; console.log(r); } }); @@ -269,7 +271,7 @@ const r21: d3Request.Request = d3Request.request(url) .response(xhr2Listing) .send('GET', { kind: 'Listing' }, (error, response) => { if (!error) { - const r: ResponseDatumGET[] = response; + const r: ResponseDatumGET[] | null = response; console.log(r); } }); @@ -286,9 +288,10 @@ const r22: d3Request.Request = d3Request.request(url) // User---------------------------------------------------------------------------- // get -const user: string = request.user(); +const user: string | null = request.user(); // set const r23: d3Request.Request = request.user('User'); +const r24: d3Request.Request = request.user(null); // ------------------------------------------------------------------------------- // HTML Request @@ -360,8 +363,8 @@ const csvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.csv, Alex Ford , Boris Yankov , Tom Wanzek +// Definitions by: Hugues Stefanski +// Alex Ford +// Boris Yankov +// Tom Wanzek +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -// Last module patch version validated against: 1.0.2 +// Last module patch version validated against: 1.0.6 import { DSVParsedArray, DSVRowString, DSVRowAny } from 'd3-dsv'; export interface Request { + /** + * Aborts this request, if it is currently in-flight, and returns this request instance. + * See XMLHttpRequest’s abort. + */ abort(): this; + /** + * Equivalent to `request.send` with the GET method: `request.send("GET")`. + */ get(): this; + /** + * Equivalent to `request.send` with the GET method: `request.send("GET", data)`. + */ get(data: RequestData): this; + /** + * Equivalent to `request.send` with the GET method: `request.send("GET", callback)`. + */ get(callback: (error: any, d: ResponseData) => void): this; + /** + * Equivalent to `request.send` with the GET method: `request.send("GET", data, callback)`. + */ get(data: RequestData, callback: (error: any, d: ResponseData) => void): this; + /** + * Returns the current value of the request header with the specified name. + * Header names are case-insensitive. + */ header(name: string): string; + /** + * Sets the request header with the specified name to the specified value and returns this request instance. + * If value is null, removes the request header with the specified name instead. + * Header names are case-insensitive. + * + * Request headers can only be modified before the request is sent. + * Therefore, you cannot pass a callback to the request constructor if you wish to specify a header; + * use `request.get` or similar instead. + */ header(name: string, value: string | null): this; + /** + * Returns the current mime type, which defaults to null. + */ mimeType(): string | null; + /** + * Sets the request mime type to the specified value and returns this request instance. + * If type is null, clears the current mime type (if any) instead. + * + * The mime type is used to both set the "Accept" request header and for `overrideMimeType`, where supported. + * + * The request mime type can only be modified before the request is sent. + * Therefore, you cannot pass a callback to the request constructor if you wish to override the mime type; + * use `request.get` or similar instead. + */ mimeType(value: string | null): this; - on(type: 'beforesend'): (this: this, xhr: XMLHttpRequest) => void; - on(type: 'progress'): (this: this, progressEvent: ProgressEvent) => void; - on(type: 'error'): (this: this, error: any) => void; - on(type: 'load'): (this: this, data: ResponseData) => void; - on(type: string): (this: this, data: any) => void; + /** + * Returns the currently-assigned listener for the "beforesend" type, if any. + */ + on(type: 'beforesend'): ((this: this, xhr: XMLHttpRequest) => void) | undefined; + /** + * Returns the currently-assigned listener for the "progress" type, if any. + */ + on(type: 'progress'): ((this: this, progressEvent: ProgressEvent) => void) | undefined; + /** + * Returns the currently-assigned listener for the "error" type, if any. + */ + on(type: 'error'): ((this: this, error: any) => void) | undefined; + /** + * Returns the currently-assigned listener for the "load" type, if any. + */ + on(type: 'load'): ((this: this, data: ResponseData) => void) | undefined; + /** + * Returns the currently-assigned listener for the specified type, if any. + */ + on(type: string): ((this: this, data: any) => void) | undefined; + + /** + * Removes the current event listener for the specified type, if any. + */ on(type: string, listener: null): this; + + /** + * Sets the event listener for the "beforesend" type, + * to allow custom headers and the like to be set before the request is sent, + * and returns this request instance. + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `beforesend.foo`. See d3-dispatch for details. + */ on(type: 'beforesend', listener: (this: this, xhr: XMLHttpRequest) => void): this; + /** + * Sets the event listener for the "progress" type, + * to monitor the progress of the request, + * and returns this request instance. + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `progress.foo`. See d3-dispatch for details. + */ on(type: 'progress', listener: (this: this, progressEvent: ProgressEvent) => void): this; + /** + * Sets the event listener for the "error" type, + * when the request completes unsuccessfully; this includes 4xx and 5xx response codes, + * and returns this request instance. + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `error.foo`. See d3-dispatch for details. + */ on(type: 'error', listener: (this: this, error: any) => void): this; + /** + * Sets the event listener for the "load" type, + * when the request completes successfully, + * and returns this request instance. + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `load.foo`. See d3-dispatch for details. + */ on(type: 'load', listener: (this: this, data: ResponseData) => void): this; + /** + * Sets the event listener for the specified type, + * and returns this request instance. + * + * The type must be one of the following: "beforesend", "progress", "load", "error". + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `load.foo`. See d3-dispatch for details. + */ on(type: string, listener: (this: this, data: any) => void): this; + /** + * Returns the current password, which defaults to null. + */ password(): string | null; - password(value: string): this; + /** + * Sets the password for authentication to the specified string and returns this request instance. + */ + password(value: string | null): this; + /** + * Equivalent to `request.send` with the POST method: `request.send("POST")`. + */ post(): this; + /** + * Equivalent to `request.send` with the POST method: `request.send("POST", data)`. + */ post(data: RequestData): this; + /** + * Equivalent to `request.send` with the POST method: `request.send("POST", callback)`. + */ post(callback: (this: this, error: any, d: ResponseData) => void): this; + /** + * Equivalent to `request.send` with the POST method: `request.send("POST", data, callback)`. + */ post(data: RequestData, callback: (this: this, error: any, d: ResponseData) => void): this; + /** + * Sets the response value function to the specified function and returns this request instance. + * The response value function is used to map the response XMLHttpRequest object to a useful data value. + * See the convenience methods `json` and `text` for examples. + */ response(callback: (this: this, response: XMLHttpRequest) => ResponseData): this; - responseType(): string | null; - responseType(value: string): this; + /** + * Returns the current response type, which defaults to `` (the empty string). + */ + responseType(): XMLHttpRequestResponseType | undefined; + /** + * Sets the response type attribute of the request and returns this request instance. Typical values are: `` (the empty string), `arraybuffer`, `blob`, `document`, and `text`. + */ + responseType(value: XMLHttpRequestResponseType): this; + /** + * Issues this request using the specified method (such as GET or POST). + * + * The listeners "load" and "error" should be registered via `request.on`. + */ send(method: string): this; + /** + * Issues this request using the specified method (such as GET or POST), posting the specified data in the request body, and returns this request instance. + * + * The listeners "load" and "error" should be registered via `request.on`. + */ send(method: string, data: RequestData): this; + /** + * Issues this request using the specified method (such as GET or POST) and returns this request instance. + * The callback will be invoked asynchronously when the request succeeds or fails. + * The callback is invoked with two arguments: the error, if any, and the response value. + * The response value is undefined if an error occurs. + */ send(method: string, callback: (this: this, error: any | null, d: ResponseData | null) => void): this; + /** + * Issues this request using the specified method (such as GET or POST), posting the specified data in the request body, and returns this request instance. + * The callback will be invoked asynchronously when the request succeeds or fails. + * The callback is invoked with two arguments: the error, if any, and the response value. + * The response value is undefined if an error occurs. + */ send(method: string, data: RequestData, callback: (this: this, error: any | null, d: ResponseData | null) => void): this; + /** + * Returns the current response timeout, which defaults to 0. + */ timeout(): number; + /** + * Sets the timeout attribute of the request to the specified number of milliseconds and returns this request instance. + */ timeout(value: number): this; + /** + * Returns the current user name, which defaults to null. + */ user(): string | null; - user(value: string): this; + /** + * Sets the user name for authentication to the specified string and returns this request instance. + */ + user(value: string | null): this; } export interface DsvRequest extends Request { row(value: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow): DsvRequest; } +/** + * Returns a new request for the CSV file at the specified url with the default mime type `text/csv`. + */ export function csv(url: string): DsvRequest; +/** + * Returns a new request for the CSV file at the specified url with the default mime type `text/csv`. + * And send a GET request. + */ export function csv(url: string, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void): DsvRequest; +/** + * Returns a new request for the CSV file at the specified url with the default mime type `text/csv`. + * And send a GET request. + * Use a row conversion function to map and filter row objects to a more-specific representation; see `dsv.parse` for details. + */ export function csv( url: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void ): DsvRequest; +/** + * Returns a new request for the HTML file at the specified url with the default mime type `text/html`. The HTML file is returned as a document fragment. + */ export function html(url: string): Request; +/** + * Returns a new request for the HTML file at the specified url with the default mime type `text/html`. The HTML file is returned as a document fragment. + * And send a GET request. + */ export function html(url: string, callback: (this: Request, error: any, d: DocumentFragment) => void): Request; +/** + * Returns a new request to get the JSON file at the specified url with the default mime type `application/json`. + */ export function json(url: string): Request; +/** + * Returns a new request to get the JSON file at the specified url with the default mime type `application/json`. + * And send a GET request. + */ export function json(url: string, callback: (this: Request, error: any, d: ParsedObject) => void): Request; +/** + * Returns a new request for specified url. The returned request is not yet sent and can be further configured. + * + * See `d3.json`, `d3.csv`, `d3.tsv`, `d3.text`, `d3.html` and `d3.xml` for content-specific convenience constructors. + */ export function request(url: string): Request; +/** + * Returns a new request for specified url. It is equivalent to calling `request.get` immediately after construction: `d3.request(url).get(callback)`. + * And send a GET request. + * + * If you wish to specify a request header or a mime type, you must not specify a callback to the constructor. + * Use `request.header` or `request.mimeType` followed by `request.get` instead. + * + * See `d3.json`, `d3.csv`, `d3.tsv`, `d3.text`, `d3.html` and `d3.xml` for content-specific convenience constructors. + */ export function request(url: string, callback: (this: Request, error: any, d: XMLHttpRequest) => void): Request; +/** + * Returns a new request to get the text file at the specified url with the default mime type `text/plain`. + */ export function text(url: string): Request; +/** + * Returns a new request to get the text file at the specified url with the default mime type `text/plain`. + * And send a GET request. + */ export function text(url: string, callback: (this: Request, error: any, d: string) => void): Request; +/** + * Returns a new request for a TSV file at the specified url with the default mime type `text/tab-separated-values`. + */ export function tsv(url: string): DsvRequest; +/** + * Returns a new request for a TSV file at the specified url with the default mime type `text/tab-separated-values`. + * And send a GET request. + */ export function tsv(url: string, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void): DsvRequest; +/** + * Returns a new request for a TSV file at the specified url with the default mime type `text/tab-separated-values`. + * And send a GET request. + * Use a row conversion function to map and filter row objects to a more-specific representation; see `dsv.parse` for details. + */ export function tsv( url: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void ): DsvRequest; +/** + * Returns a new request to get the XML file at the specified url with the default mime type `application/xml`. + */ export function xml(url: string): Request; +/** + * Returns a new request to get the XML file at the specified url with the default mime type `application/xml`. + * And send a GET request. + */ export function xml(url: string, callback: (this: Request, error: any, d: any) => void): Request; diff --git a/types/d3-request/tsconfig.json b/types/d3-request/tsconfig.json index a52d00ffaa..9ba2eb33f3 100644 --- a/types/d3-request/tsconfig.json +++ b/types/d3-request/tsconfig.json @@ -6,8 +6,8 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ diff --git a/types/d3-request/tslint.json b/types/d3-request/tslint.json index a965459d61..1aeb60bae1 100644 --- a/types/d3-request/tslint.json +++ b/types/d3-request/tslint.json @@ -3,9 +3,7 @@ "rules": { // TODOs "no-any-union": false, - "no-this-assignment": false, "no-unnecessary-generics": false, - "unified-signatures": false, - "max-line-length": [false, 145] + "unified-signatures": false } } diff --git a/types/d3-voronoi/d3-voronoi-tests.ts b/types/d3-voronoi/d3-voronoi-tests.ts index 434055dc4d..cc516d0adb 100644 --- a/types/d3-voronoi/d3-voronoi-tests.ts +++ b/types/d3-voronoi/d3-voronoi-tests.ts @@ -12,8 +12,8 @@ import * as d3Voronoi from 'd3-voronoi'; // Preparatory Steps // --------------------------------------------------------------------- -let extent: [[number, number], [number, number]]; -let size: [number, number]; +let extent: [[number, number], [number, number]] | null; +let size: [number, number] | null; let coordinates: [number, number]; let num: number; @@ -38,9 +38,11 @@ let numberAccessor: (d: VoronoiTestDatum) => number; let edges: Array>; let edge: d3Voronoi.VoronoiEdge; -let cells: Array>; +let cells: Array | null>; let cell: d3Voronoi.VoronoiCell; +let cellOrNull: d3Voronoi.VoronoiCell | null; let site: d3Voronoi.VoronoiSite; +let siteOrNull: d3Voronoi.VoronoiSite | null; let polygons: Array>; let polygon: d3Voronoi.VoronoiPolygon; @@ -57,18 +59,20 @@ let link: d3Voronoi.VoronoiLink; // VoronoiPoint ------------------------------------------------------- -let point: d3Voronoi.VoronoiPoint; +declare let point: d3Voronoi.VoronoiPoint; point[0] = 10; // x-coordinate point[1] = 10; // y-coordinate point = [10, 10]; -// point = [10]; // fails, second element for y-coordinate missing -// point = ['a', 'b']; // fails, wrong element type +// $ExpectError +point = [10]; // fails, second element for y-coordinate missing +// $ExpectError +point = ['a', 'b']; // fails, wrong element type // VoronoiPointPair --------------------------------------------------- -let pointPair: d3Voronoi.VoronoiPointPair; +declare let pointPair: d3Voronoi.VoronoiPointPair; pointPair[0][0] = 10; // x-coordinate of first point pointPair[0][1] = 10; // y-coordinate of first point @@ -77,10 +81,14 @@ pointPair[1][1] = 10; // y-coordinate of second point pointPair = [[10, 10], [50, 50]]; -// pointPair = [[10, 10]]; // fails, second point coordinates missing -// pointPair = [[10, 10], [50]]; // fails, one element is not of type [number, number] -// pointPair = [[10], [50, 50]]; // fails, one element is not of type [number, number] -// pointPair = [['a', 10], [50, 50]]; // fails, one element is not of type [number, number] +// $ExpectError +pointPair = [[10, 10]]; // fails, second point coordinates missing +// $ExpectError +pointPair = [[10, 10], [50]]; // fails, one element is not of type [number, number] +// $ExpectError +pointPair = [[10], [50, 50]]; // fails, one element is not of type [number, number] +// $ExpectError +pointPair = [['a', 10], [50, 50]]; // fails, one element is not of type [number, number] // VoronoiPolygon ------------------------------------------------------- @@ -173,13 +181,14 @@ coordinates = edge[0]; // source point coordinates coordinates = edge[1]; // source point coordinates site = edge.left; -site = edge.right; +siteOrNull = edge.right; // cells() VoronoiCell ================================================= cells = voronoiDiagram.cells; -cell = cells[0]; +cellOrNull = cells[0]; +cell = cells[0]!; site = cell.site; @@ -237,4 +246,5 @@ nearestSite = voronoiDiagram.find(10, 50); nearestSite = voronoiDiagram.find(10, 50, 20); // wrong data type -// const wrongSiteDataType: d3Voronoi.VoronoiSite<[number, number]> | null; = voronoiDiagram.find(10, 50); // fails, due to data type mismatch +// $ExpectError +const wrongSiteDataType: d3Voronoi.VoronoiSite<[number, number]> | null = voronoiDiagram.find(10, 50); // fails, due to data type mismatch diff --git a/types/d3-voronoi/index.d.ts b/types/d3-voronoi/index.d.ts index c3dc03c9de..7dfb79cf66 100644 --- a/types/d3-voronoi/index.d.ts +++ b/types/d3-voronoi/index.d.ts @@ -1,9 +1,13 @@ // Type definitions for D3JS d3-voronoi module 1.1 // Project: https://github.com/d3/d3-voronoi/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -// Last module patch version validated against: 1.1.0 +// Last module patch version validated against: 1.1.4 // -------------------------------------------------------------------------- // Shared Type Definitions and Interfaces @@ -61,6 +65,7 @@ export interface VoronoiSite extends VoronoiPoint { * The Voronoi Site’s index, corresponding to the associated input point. */ index: number; + /** * The input data corresponding to this site. */ @@ -78,6 +83,7 @@ export interface VoronoiCell { * The Voronoi Site of the cell’s associated input point. */ site: VoronoiSite; + /** * An array of indexes into diagram.edges representing the cell’s polygon. */ @@ -95,8 +101,9 @@ export interface VoronoiEdge extends VoronoiPointPair { * The Voronoi site on the left side of the edge. */ left: VoronoiSite; + /** - * The Voronoi site on the right side of the edge. null for a clipped border edge. + * The Voronoi site on the right side of the edge; `null` for a clipped border edge. */ right: VoronoiSite | null; } @@ -112,6 +119,7 @@ export interface VoronoiLink { * The source node, an element in data. */ source: T; + /** * The target node, an element in data. */ @@ -137,6 +145,7 @@ export interface VoronoiLayout { x(): (d: T) => number; /** * Set the x-coordinate accessor and return the layout. + * * @param x An accessor function which takes a data element as input and return a * numeric value for the x-coordinate. */ @@ -149,6 +158,7 @@ export interface VoronoiLayout { y(): (d: T) => number; /** * Set the y-coordinate accessor and return the layout. + * * @param y An accessor function which takes a data element as input and return a * numeric value for the y-coordinate. */ @@ -207,6 +217,7 @@ export interface VoronoiLayout { * @param data Array of data points. */ polygons(data: T[]): Array>; + /** * Return the Delaunay triangulation of the specified data array as an array of triangles. * Each triangle is a three-element array of elements from data. @@ -214,6 +225,7 @@ export interface VoronoiLayout { * @param data Array of data points. */ triangles(data: T[]): Array>; + /** * Return the Delaunay triangulation of the specified data array as an array of links. * Each link has source and target attributes referring to elements in data. @@ -233,10 +245,12 @@ export interface VoronoiDiagram { * Array of Voronoi Edges */ edges: Array>; + /** * Array of Voronoi Cells, one per input point; a cell may be null for a coincident point. */ cells: Array | null>; + /** * Return an array of polygons clipped to the extent, one for each cell in the diagram. * Each polygon is represented as an array of points [x, y] where x and y are the point coordinates, @@ -282,18 +296,13 @@ export interface VoronoiDiagram { // voronoi Export // -------------------------------------------------------------------------- -/** - * Creates a new Voronoi layout with default x- and y- accessors and a null extent. - * - * Without specifying a generic the layout is assumed to be based on data represented - * by a two-dimensional coordinate [number, number] for x- and y-coordinate, respectively. - */ -export function voronoi(): VoronoiLayout<[number, number]>; /** * Creates a new Voronoi layout with default x- and y- accessors and a null extent. * x- and y-accessors may have to be set to correspond to the data type provided by the * generic. * * The generic refers to the type of the data for the corresponding element. + * Without specifying a generic the layout is assumed to be based on data represented + * by a two-dimensional coordinate `[number, number]` for x- and y-coordinate, respectively. */ -export function voronoi(): VoronoiLayout; +export function voronoi(): VoronoiLayout; diff --git a/types/d3-voronoi/tsconfig.json b/types/d3-voronoi/tsconfig.json index ada834dec3..5fba11f4e4 100644 --- a/types/d3-voronoi/tsconfig.json +++ b/types/d3-voronoi/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/dat.gui/index.d.ts b/types/dat.gui/index.d.ts index 5c20fd51fe..a7fe6a4e3a 100644 --- a/types/dat.gui/index.d.ts +++ b/types/dat.gui/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for dat.GUI 0.7 +// Type definitions for dat.GUI 0.7.2 // Project: https://github.com/dataarts/dat.gui -// Definitions by: Satoru Kimura , ZongJing Lu , Richard Roylance +// Definitions by: Satoru Kimura , ZongJing Lu , Richard Roylance , Nahuel Scotti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace dat; @@ -95,12 +95,12 @@ export class GUIController { destroy(): void; // Controller - onChange: (value?: any) => void; - onFinishChange: (value?: any) => void; + onChange: (value?: any) => GUIController; + onFinishChange: (value?: any) => GUIController; setValue(value: any): GUIController; getValue(): any; - updateDisplay(): void; + updateDisplay(): GUIController; isModified(): boolean; // NumberController diff --git a/types/delaunator/delaunator-tests.ts b/types/delaunator/delaunator-tests.ts index 1d50e0273a..6310448c83 100644 --- a/types/delaunator/delaunator-tests.ts +++ b/types/delaunator/delaunator-tests.ts @@ -1,9 +1,12 @@ import * as Delaunator from 'delaunator'; -import { Points, GetPoint } from 'delaunator'; + +// Zipped points [x0, y0, x1, y1, ...] +const zippedPoints = [168, 180, 168, 178, 168, 179, 168, 181, 168, 183, 167, 183, 167, 184]; +const zipped = new Delaunator(zippedPoints); // Default [x, y] -const points: Points = [[168, 180], [168, 178], [168, 179], [168, 181], [168, 183], [167, 183], [167, 184]]; -const d = new Delaunator(points); +const defaultPoints = [[168, 180], [168, 178], [168, 179], [168, 181], [168, 183], [167, 183], [167, 184]]; +const d = Delaunator.from(defaultPoints); // Custom getX & getY interface CustomPoint { @@ -15,17 +18,18 @@ const customPoints = [{x: 168, y: 180}, {x: 168, y: 178}, {x: 168, y: 179}, {x: const getX = (point: CustomPoint) => point.x; const getY = (point: CustomPoint) => point.y; -new Delaunator(customPoints, point => point.x, point => point.y); -new Delaunator(customPoints, getX, getY); +Delaunator.from(customPoints, point => point.x, point => point.y); +Delaunator.from(customPoints, getX, getY); // To get the coordinates of all triangles, use: const triangles = d.triangles; const halfedges = d.halfedges; +const hull = d.hull; const coordinates: number[][][] = []; for (let i = 0; i < triangles.length; i += 3) { coordinates.push([ - points[triangles[i]], - points[triangles[i + 1]], - points[triangles[i + 2]] + defaultPoints[triangles[i]], + defaultPoints[triangles[i + 1]], + defaultPoints[triangles[i + 2]] ]); } diff --git a/types/delaunator/index.d.ts b/types/delaunator/index.d.ts index 5761fec4a8..c717feec95 100644 --- a/types/delaunator/index.d.ts +++ b/types/delaunator/index.d.ts @@ -1,13 +1,14 @@ -// Type definitions for delaunator 1.0 +// Type definitions for delaunator 2.0 // Project: https://github.com/mapbox/delaunator#readme // Definitions by: Denis Carriere +// Bradley Odell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class Delaunator { +declare class Delaunator

{ /** - * A flat Int32Array array of triangle vertex indices (each group of three numbers forms a triangle). All triangles are directed counterclockwise. + * A flat Uint32Array array of triangle vertex indices (each group of three numbers forms a triangle). All triangles are directed counterclockwise. */ - triangles: Int32Array; + triangles: Uint32Array; /** * A flat Int32Array array of triangle half-edge indices that allows you to traverse the triangulation. @@ -19,17 +20,36 @@ declare class Delaunator { halfedges: Int32Array; /** - * Constructs a delaunay triangulation object given an array of points ([x, y] by default). Duplicate points are skipped. + * A circular doubly-linked list that holds a convex hull of the delaunay triangulation. */ - constructor(points: Delaunator.Points); - constructor(points: T[], getX: Delaunator.GetPoint, getY: Delaunator.GetPoint); + hull: Delaunator.Node; + + /** + * Constructs a delaunay triangulation object given a typed array of point coordinates of the form: [x0, y0, x1, y1, ...]. + */ + constructor(points: ArrayLike); + + /** + * Constructs a delaunay triangulation object given an array of points (e.g. [x, y]). Duplicate points are skipped. + */ + static from(points: ArrayLike>): Delaunator>; + + /** + * Constructs a delaunay triangulation object given an array of custom points. Duplicate points are skipped. + */ + static from

(points: ArrayLike

, getX: (point: P) => number, getY: (point: P) => number): Delaunator

; } declare namespace Delaunator { - type Point = number[]; - type Points = Point[]; - type Triangles = Int32Array; - type HalfEdges = Int32Array; - type GetPoint = (point: T) => number; + interface Node { + i: number; + x: number; + y: number; + t: number; + prev: Node|null; + next: Node|null; + removed: boolean; + } } + export = Delaunator; diff --git a/types/delaunator/tslint.json b/types/delaunator/tslint.json index f2ffe2445b..b4b47a0378 100644 --- a/types/delaunator/tslint.json +++ b/types/delaunator/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-duplicate-imports": false - } + "extends": "dtslint/dt.json" } diff --git a/types/delay/delay-tests.ts b/types/delay/delay-tests.ts deleted file mode 100644 index 9714bfd86d..0000000000 --- a/types/delay/delay-tests.ts +++ /dev/null @@ -1,47 +0,0 @@ -import delay = require('delay'); - -delay(200) - .then(() => { - }); - -let str: string; -let num: number; -Promise.resolve(delay(100)) - .then(() => { - }); - -Promise.resolve("foo") - .then(delay(100)) - .then(result => { - str = result; - }); - -Promise.resolve('foo') - .then(delay(100, 10)) - .then(result => { - num = result; - }); - -Promise.resolve('foo') - .then(delay.reject(100)) - .then(x => 10) - .catch(err => { - }); - -Promise.resolve('foo') - .then(delay.reject(100, 'bar')) - .then(x => 10) - .catch(err => { - }); - -(async () => { - const delaying = delay(1000); - delaying.cancel(); - try { - await delaying; - } catch (err) { - // `err` is an instance of `delay.CancelError` - } -})(); - -throw new delay.CancelError('bar'); diff --git a/types/delay/index.d.ts b/types/delay/index.d.ts deleted file mode 100644 index 0ec894f1e1..0000000000 --- a/types/delay/index.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Type definitions for delay 2.0 -// Project: https://github.com/sindresorhus/delay#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -export = delay; - -declare function delay(ms: number): delay.PDelayedPassThroughThunk; -declare function delay(ms: number, value: T): delay.PDelayedThunk; - -declare namespace delay { - function reject(ms: number, rejectionValue?: any): PDelayedThunk; - - class CancelError extends Error { - readonly name: 'CancelError'; - constructor(message?: string); - } - - type PDelayedThunk = ((value: any) => DelayedPromiseLike) & DelayedPromiseLike; - - type PDelayedPassThroughThunk = ((value: TValue) => DelayedPromiseLike) & DelayedPromiseLike; - - interface DelayedPromiseLike { - then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onrejected?: ((reason: any) => TResult2 | PromiseLike) | null): Promise; - catch(onrejected?: ((reason: any) => TResult | PromiseLike) | null): Promise; - cancel(): void; - } -} diff --git a/types/delay/tslint.json b/types/delay/tslint.json deleted file mode 100644 index bf610ae17f..0000000000 --- a/types/delay/tslint.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - // TODO - "await-promise": false, - "no-unnecessary-generics": false - } -} diff --git a/types/delete-empty/delete-empty-tests.ts b/types/delete-empty/delete-empty-tests.ts new file mode 100644 index 0000000000..88d6691e3b --- /dev/null +++ b/types/delete-empty/delete-empty-tests.ts @@ -0,0 +1,12 @@ +import * as deleteEmpty from 'delete-empty'; + +deleteEmpty('foo').then(f => f[0].toLowerCase()); +deleteEmpty('foo', (err, f) => { + if (err) { + err.message; + } else { + f[0].toLowerCase(); + } +}); + +deleteEmpty.sync('foo')[0].toLowerCase(); diff --git a/types/delete-empty/index.d.ts b/types/delete-empty/index.d.ts new file mode 100644 index 0000000000..fbaf2d8029 --- /dev/null +++ b/types/delete-empty/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for delete-empty 2.0 +// Project: https://github.com/jonschlinkert/delete-empty +// Definitions by: Alorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function deleteEmpty(dir: string): Promise; +declare function deleteEmpty(dir: string, cb: (err: Error | undefined | null, deleted: string[]) => void): void; + +declare namespace deleteEmpty { + function sync(dir: string): string[]; +} + +export = deleteEmpty; diff --git a/types/delete-empty/tsconfig.json b/types/delete-empty/tsconfig.json new file mode 100644 index 0000000000..3a10f6082b --- /dev/null +++ b/types/delete-empty/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", + "delete-empty-tests.ts" + ] +} diff --git a/types/delete-empty/tslint.json b/types/delete-empty/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/delete-empty/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dialogflow/index.d.ts b/types/dialogflow/index.d.ts index 6a3faa8618..c421c47f68 100644 --- a/types/dialogflow/index.d.ts +++ b/types/dialogflow/index.d.ts @@ -562,6 +562,12 @@ export interface QueryResult { outputContexts: Context[]; intent: Intent; intentDetectionConfidence: number; + sentimentAnalysisResult?: { + queryTextSentiment: { + magnitude: number; + score: number; + }; + }; diagnosticInfo: any; } diff --git a/types/dplayer/dplayer-tests.ts b/types/dplayer/dplayer-tests.ts new file mode 100644 index 0000000000..92a3e984b3 --- /dev/null +++ b/types/dplayer/dplayer-tests.ts @@ -0,0 +1,18 @@ +import DPlayer from 'dplayer'; + +const dp = new DPlayer({ + container: document.querySelector('#dplayer'), + screenshot: true, + video: { + url: 'demo.mp4', + pic: 'demo.jpg', + thumbnails: 'thumbnails.jpg' + }, + subtitle: { + url: 'webvtt.vtt' + }, + danmaku: { + id: 'demo', + api: 'https://api.prprpr.me/dplayer3/' + } +}); diff --git a/types/dplayer/index.d.ts b/types/dplayer/index.d.ts new file mode 100644 index 0000000000..a8fbd9e162 --- /dev/null +++ b/types/dplayer/index.d.ts @@ -0,0 +1,160 @@ +// Type definitions for dplayer 1.24 +// Project: https://github.com/DIYgod/DPlayer#readme +// Definitions by: Guanyunhan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export type Lang = 'en' | 'zh-cn' | 'zh-tw'; +export type Preload = 'none' | 'metadata' | 'auto'; +export type VideoType = 'auto' | 'hls' | 'flv' | 'dash' | 'webtorrent' | 'normal'; +export type SubTitleType = 'webvtt' | 'ass'; +export type DirectionType = 'top' | 'right' | 'bottom'; + +export enum DPlayerEvents { + abort = 'abort', + canplay = 'canplay', + canplaythrough = 'canplaythrough', + durationchange = 'durationchange', + emptied = 'emptied', + ended = 'ended', + error = 'error', + loadeddata = 'loadeddata', + loadedmetadata = 'loadedmetadata', + loadstart = 'loadstart', + mozaudioavailable = 'mozaudioavailable', + pause = 'pause', + play = 'play', + playing = 'playing', + progress = 'progress', + ratechange = 'ratechange', + seeked = 'seeked', + seeking = 'seeking', + stalled = 'stalled', + suspend = 'suspend', + timeupdate = 'timeupdate', + volumechange = 'volumechange', + waiting = 'waiting', + screenshot = 'screenshot', + thumbnails_show = 'thumbnails_show', + thumbnails_hide = 'thumbnails_hide', + danmaku_show = 'danmaku_show', + danmaku_hide = 'danmaku_hide', + danmaku_clear = 'danmaku_clear', + danmaku_loaded = 'danmaku_loaded', + danmaku_send = 'danmaku_send', + danmaku_opacity = 'danmaku_opacity', + contextmenu_show = 'contextmenu_show', + contextmenu_hide = 'contextmenu_hide', + notice_show = 'notice_show', + notice_hide = 'notice_hide', + quality_start = 'quality_start', + quality_end = 'quality_end', + destroy = 'destroy', + resize = 'resize', + fullscreen = 'fullscreen', + fullscreen_cancel = 'fullscreen_cancel', + subtitle_show = 'subtitle_show', + subtitle_hide = 'subtitle_hide', + subtitle_change = 'subtitle_change' +} + +export interface DPlayerOptions { + [key: string]: any; + + container: HTMLElement | null; + live?: boolean; + autoplay?: boolean; + theme?: string; + loop?: boolean; + lang?: Lang | string; + screenshot?: boolean; + hotkey?: boolean; + preload?: Preload; + logo?: string; + volume?: number; + mutex?: boolean; + video?: DPlayerVideo; + subtitle?: DPlayerSubTitle; + danmaku?: DPlayerDanmaku; + contextmenu?: DPlayerContextMenuItem[]; + highlight?: DPlayerHighLightItem[]; + apiBackend?: DPlayerAPIBackend; +} + +export interface DPlayerDanmakuItem { + text: string; + color: string; + type: DirectionType; +} + +export interface DPlayerContextMenuItem { + text: string; + link?: string; + click?: () => void; +} + +export interface DPlayerHighLightItem { + text: string; + time: number; +} + +export interface DPlayerVideo { + url: string; + pic?: string; + thumbnails?: string; + type?: VideoType | string; + customType?: any; +} + +export interface DPlayerSubTitle { + url: string; + type?: SubTitleType; + fontSize?: string; + bottom?: string; + color?: string; +} + +export interface DPlayerDanmaku { + id: string; + api: string; + token?: string; + maximum?: string; + addition?: string[]; + user?: string; + bottom?: string; + unlimited?: boolean; +} + +export interface DPlayerAPIBackend { + read(endpoint: any, callback: () => void): void; + + send(endpoint: any, danmakuData: DPlayerDanmakuItem, callback: () => void): void; +} + +export default class DPlayer { + events: any; + + constructor(options: DPlayerOptions); + + play(): void; + + pause(): void; + + seek(time: number): void; + + toggle(): void; + + on(event: DPlayerEvents, handler: () => void): void; + + switchVideo(video: DPlayerVideo, danmaku: DPlayerDanmaku): void; + + notice(text: string, time: number, opacity: number): void; + + switchQuality(index: number): void; + + destroy(): void; + + speed(rate: number): void; + + volume(percentage: number, nostorage: boolean, nonotice: boolean): void; +} diff --git a/types/dplayer/tsconfig.json b/types/dplayer/tsconfig.json new file mode 100644 index 0000000000..c98e26d06c --- /dev/null +++ b/types/dplayer/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es5", "es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "strictFunctionTypes": false, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "allowSyntheticDefaultImports": true + }, + "files": [ + "index.d.ts", + "dplayer-tests.ts" + ] +} diff --git a/types/dplayer/tslint.json b/types/dplayer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dplayer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 06cb8f55f2..aea132cb3d 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -8,6 +8,7 @@ // Willis Plummer // Santiago Vilar // Ulf Schwekendiek +// Pablo Varela // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -950,6 +951,7 @@ import Editor = Draft.Component.Base.DraftEditor; import EditorProps = Draft.Component.Base.DraftEditorProps; import EditorBlock = Draft.Component.Components.DraftEditorBlock; import EditorState = Draft.Model.ImmutableData.EditorState; +import EditorChangeType = Draft.Model.ImmutableData.EditorChangeType; import CompositeDecorator = Draft.Model.Decorators.CompositeDraftDecorator; import Entity = Draft.Model.Entity.DraftEntity; @@ -999,6 +1001,7 @@ export { EditorProps, EditorBlock, EditorState, + EditorChangeType, CompositeDecorator, Entity, diff --git a/types/ej.web.all/ej.web.all-tests.ts b/types/ej.web.all/ej.web.all-tests.ts index 58faf8c7f4..628fab8754 100644 --- a/types/ej.web.all/ej.web.all-tests.ts +++ b/types/ej.web.all/ej.web.all-tests.ts @@ -206,7 +206,7 @@ module ChartComponent { }, visible: true }, - border : { width: 2 } + border : {width: 2} }, series: [ @@ -494,6 +494,7 @@ function createLabel(options : any) { } + module DialogComponent { $(function () { var dialogInstance = new ej.Dialog($("#basicDialog"), { @@ -683,7 +684,7 @@ module GridComponent { -var columns = ["Vegie-spread", "Tofuaa", "Alice Mutton", "Konbu", "Fl�temysost"] +var columns = ["Vegie-spread", "Tofuaa", "Alice Mutton", "Konbu", "Fløtemysost"] var itemSource: any[] = []; for (var i = 0; i < columns.length; i++) { for (var j = 0; j < 6; j++) { @@ -839,7 +840,7 @@ var world_map= { "type": "Feature", "properties": { "admin": "Switzerland", "name": "Switzerland", "continent": "Europe" }, "geometry": { "type": "Polygon", "coordinates": [[[9.594226108446346, 47.525058091820256], [9.632931756232974, 47.347601223329974], [9.479969516649019, 47.102809963563367], [9.932448357796657, 46.920728054382948], [10.442701450246627, 46.893546250997424], [10.36337812667861, 46.483571275409851], [9.922836541390378, 46.314899400409182], [9.182881707403054, 46.440214748716976], [8.966305779667804, 46.036931871111186], [8.489952426801322, 46.005150865251672], [8.316629672894377, 46.163642483090847], [7.755992058959832, 45.824490057959302], [7.273850945676655, 45.776947740250769], [6.843592970414504, 45.991146552100595], [6.500099724970424, 46.429672756529428], [6.022609490593537, 46.272989813820466], [6.037388950229, 46.725778713561859], [6.768713820023605, 47.287708238303686], [6.736571079138058, 47.541801255882838], [7.192202182655505, 47.449765529971003], [7.466759067422228, 47.620581976911794], [8.31730146651415, 47.613579820336255], [8.522611932009765, 47.830827541691285], [9.594226108446346, 47.525058091820256]]] } }, { "type": "Feature", "properties": { "admin": "Chile", "name": "Chile", "continent": "South America" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-68.634010227583147, -52.636370458874353], [-68.633349999999879, -54.8695], [-67.56244, -54.87001], [-66.95992, -54.89681], [-67.291029999999878, -55.30124], [-68.148629999999841, -55.61183], [-68.639990810811796, -55.580017999086877], [-69.2321, -55.49906], [-69.95809, -55.19843], [-71.00568, -55.05383], [-72.2639, -54.49514], [-73.2852, -53.957519999999874], [-74.66253, -52.83749], [-73.8381, -53.04743], [-72.43418, -53.7154], [-71.10773, -54.07433], [-70.591779999999787, -53.61583], [-70.26748, -52.93123], [-69.345649999999878, -52.5183], [-68.634010227583147, -52.636370458874353]]], [[[-68.219913092711224, -21.49434661223183], [-67.828179897722634, -22.872918796482178], [-67.106673550063604, -22.735924574476392], [-66.985233934177629, -22.986348565362825], [-67.328442959244128, -24.025303236590908], [-68.417652960876111, -24.518554782816874], [-68.386001146097342, -26.185016371365229], [-68.594799770772667, -26.50690886811126], [-68.295541551370391, -26.899339694935787], [-69.001234910748266, -27.521213881136127], [-69.656130337183143, -28.459141127233686], [-70.013550381129861, -29.367922865518544], [-69.919008348251921, -30.336339206668306], [-70.535068935819439, -31.365010267870279], [-70.074399380153622, -33.09120981214803], [-69.814776984319209, -33.273886000299839], [-69.817309129501453, -34.193571465798279], [-70.388049485949082, -35.169687595359441], [-70.364769253201658, -36.005088799789931], [-71.121880662709771, -36.65812387466233], [-71.118625047475419, -37.576827487947192], [-70.814664272734703, -38.552995293940732], [-71.413516608349042, -38.916022230791107], [-71.680761277946445, -39.808164157878061], [-71.915734015577542, -40.832339369470716], [-71.746803758415453, -42.051386407235988], [-72.148898078078517, -42.254888197601375], [-71.915423956983901, -43.408564548517404], [-71.464056159130493, -43.787611179378324], [-71.793622606071935, -44.207172133156099], [-71.329800788036195, -44.407521661151677], [-71.222778896759721, -44.784242852559409], [-71.659315558545316, -44.973688653341434], [-71.552009446891233, -45.560732924177117], [-71.917258470330196, -46.884838148791786], [-72.44735531278026, -47.738532810253517], [-72.331160854771937, -48.244238376661819], [-72.648247443314929, -48.878618259476774], [-73.415435757120022, -49.318436374712952], [-73.328050910114456, -50.378785088909865], [-72.975746832964617, -50.741450290734299], [-72.309973517532342, -50.677009779666342], [-72.329403856074023, -51.425956312872394], [-71.914803839796321, -52.009022305865912], [-69.498362189396076, -52.142760912637236], [-68.571545376241332, -52.299443855346247], [-69.461284349226617, -52.291950772663924], [-69.94277950710611, -52.537930590373243], [-70.8451016913545, -52.899200528525711], [-71.006332160105217, -53.833252042201345], [-71.429794684520928, -53.856454760300373], [-72.557942877884855, -53.531410001184447], [-73.702756720662862, -52.835069268607249], [-73.702756720662862, -52.835070076051487], [-74.946763475225154, -52.262753588419017], [-75.260026007778507, -51.62935475037321], [-74.976632453089806, -51.043395684615675], [-75.47975419788348, -50.378371677451547], [-75.608015102831942, -48.673772881871784], [-75.182769741502128, -47.711919447623153], [-74.126580980104677, -46.939253431995084], [-75.644395311165439, -46.647643324572016], [-74.69215369332305, -45.76397633238097], [-74.351709357384252, -44.10304412208788], [-73.240356004515192, -44.454960625995611], [-72.717803921179765, -42.383355808278985], [-73.388899909138232, -42.117532240569567], [-73.701335618774834, -43.365776462579738], [-74.33194312203257, -43.224958184584395], [-74.017957119427152, -41.794812920906828], [-73.677099372029943, -39.942212823243111], [-73.217592536090663, -39.258688653318508], [-73.505559455037044, -38.282882582351064], [-73.588060879191076, -37.156284681956016], [-73.166717088499283, -37.123780206044351], [-72.553136969681717, -35.508840020491022], [-71.861732143832555, -33.909092706031522], [-71.438450486929895, -32.418899428030819], [-71.668720669222424, -30.920644626592516], [-71.370082567007714, -30.095682061484997], [-71.48989437527645, -28.861442152625909], [-70.905123867461569, -27.640379734001193], [-70.724953986275963, -25.705924167587209], [-70.403965827095035, -23.628996677344542], [-70.091245897080668, -21.393319187101223], [-70.164419725205974, -19.756468194256183], [-70.372572394477714, -18.347975355708879], [-69.858443569605797, -18.092693780187027], [-69.590423753523979, -17.580011895419286], [-69.100246955019401, -18.260125420812653], [-68.966818406841824, -18.981683444904089], [-68.442225104430918, -19.405068454671419], [-68.757167121033703, -20.37265797290447], [-68.219913092711224, -21.49434661223183]]]] } }, { "type": "Feature", "properties": { "admin": "China", "name": "China", "continent": "Asia" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[110.339187860151526, 18.678395087147603], [109.475209588663702, 18.19770091396861], [108.655207961056135, 18.507681993071397], [108.626217482540426, 19.367887885001974], [109.119055617308007, 19.821038519769385], [110.211598748822837, 20.101253973872073], [110.786550734502228, 20.077534491450077], [111.01005130416462, 19.695929877190732], [110.570646600386794, 19.255879218009305], [110.339187860151526, 18.678395087147603]]], [[[127.657407261262378, 49.760270494172929], [129.397817824420429, 49.440600084015429], [130.58229332898236, 48.729687404976112], [130.987281528853828, 47.790132351261391], [132.506671991099495, 47.788969631534876], [133.373595819228001, 48.183441677434914], [135.026311476786702, 48.478229885443902], [134.500813836810607, 47.578439846377833], [134.112362095272601, 47.212467352886719], [133.76964399631288, 46.116926988299056], [133.097126906466428, 45.14406647397216], [131.883454217659562, 45.32116160743643], [131.025212030156069, 44.967953192721573], [131.288555129115537, 44.111519680348252], [131.144687941614848, 42.929989732426932], [130.633866408409801, 42.903014634770543], [130.640015903852429, 42.39500946712527], [129.994267205933227, 42.985386867843793], [129.596668735879462, 42.424981797854592], [128.05221520397231, 41.994284572917984], [128.208433058790717, 41.466771552082534], [127.343782993683021, 41.503151760415953], [126.869083286649854, 41.816569322266155], [126.18204511932943, 41.107336127276362], [125.079941847840587, 40.569823716792449], [124.265624627785314, 39.928493353834135], [122.86757042856101, 39.637787583976255], [122.131387974130917, 39.170451768544623], [121.054554478032856, 38.89747101496291], [121.585994907722466, 39.360853583324136], [121.376757033372641, 39.750261338859524], [122.168595005381007, 40.422442531896046], [121.640358514493528, 40.946389878903304], [120.768628778161954, 40.593388169917596], [119.639602085449056, 39.898055935214209], [119.023463983233015, 39.252333075511096], [118.042748651197897, 39.204273993479674], [117.532702264477052, 38.73763580988409], [118.05969852098967, 38.061475531561051], [118.878149855628351, 37.897325344385898], [118.911636183753501, 37.448463853498723], [119.702802362142037, 37.156388658185072], [120.823457472823648, 37.870427761377968], [121.711258579597938, 37.481123358707165], [122.357937453298462, 37.454484157860684], [122.519994744965814, 36.930614325501828], [121.104163853033029, 36.651329047180432], [120.63700890511457, 36.111439520811125], [119.66456180224607, 35.609790554337728], [119.151208123858567, 34.909859117160458], [120.227524855633717, 34.360331936168613], [120.620369093916565, 33.37672272392512], [121.229014113450219, 32.460318711877186], [121.908145786630044, 31.692174384074683], [121.891919386890336, 30.949351508095098], [121.264257440273298, 30.676267401648712], [121.503519321784722, 30.14291494396425], [122.092113885589086, 29.832520453403156], [121.93842817595305, 29.018022365834803], [121.684438511238469, 28.225512600206677], [121.125661248866436, 28.135673122667178], [120.395473260582307, 27.053206895449385], [119.585496860839555, 25.740780544532605], [118.656871372554519, 24.547390855400234], [117.281606479970833, 23.624501451099714], [115.890735304835118, 22.782873236578094], [114.763827345846209, 22.668074042241663], [114.152546828265656, 22.223760077396204], [113.806779819800752, 22.548339748621423], [113.241077915501592, 22.051367499270462], [111.843592157032447, 21.550493679281512], [110.78546552942413, 21.39714386645533], [110.444039341271662, 20.34103261970639], [109.88986128137357, 20.282457383703441], [109.627655063924635, 21.008227037026725], [109.864488153118316, 21.395050970947516], [108.522812941524421, 21.715212307211821], [108.050180291782979, 21.552379869060101], [107.043420037872636, 21.8118989120299], [106.567273390735352, 22.21820486092474], [106.725403273548466, 22.794267889898375], [105.811247186305209, 22.976892401617899], [105.329209425886631, 23.352063300056976], [104.476858351664475, 22.819150092046918], [103.504514601660503, 22.703756618739217], [102.706992222100155, 22.708795070887696], [102.170435825613552, 22.464753119389336], [101.652017856861576, 22.318198757409554], [101.803119744882906, 21.174366766845051], [101.27002566936001, 21.201651923095167], [101.180005324307558, 21.436572984294052], [101.150032993578236, 21.849984442629015], [100.416537713627349, 21.558839423096654], [99.983489211021549, 21.742936713136451], [99.240898878987196, 22.118314317304559], [99.53199222208741, 22.949038804612591], [98.898749220782804, 23.142722072842581], [98.66026248575578, 24.063286037690002], [97.604719679762027, 23.897404690033049], [97.724609002679131, 25.083637193293036], [98.671838006589212, 25.91870250091349], [98.712093947344556, 26.743535874940243], [98.682690057370507, 27.508812160750658], [98.246230910233351, 27.747221381129172], [97.91198774616943, 28.335945136014367], [97.327113885490007, 28.261582749946339], [96.248833449287829, 28.411030992134467], [96.586590610747521, 28.830979519154361], [96.117678664131006, 29.452802028922513], [95.404802280664626, 29.031716620392157], [94.565990431702929, 29.27743805593996], [93.413347609432662, 28.640629380807233], [92.503118931043616, 27.896876329046442], [91.696656528696693, 27.771741848251615], [91.258853794319876, 28.040614325466343], [90.730513950567797, 28.064953925075738], [90.015828891971182, 28.296438503527177], [89.475810174521158, 28.042758897406365], [88.814248488320573, 27.299315904239389], [88.730325962278528, 28.086864732367552], [88.120440708369941, 27.876541652939572], [86.954517043000635, 27.974261786403524], [85.823319940131526, 28.203575954698742], [85.011638218123053, 28.642773952747369], [84.23457970575015, 28.839893703724691], [83.89899295444674, 29.320226141877633], [83.337115106137176, 29.463731594352193], [82.327512648450877, 30.115268052688204], [81.525804477874786, 30.422716986608659], [81.111256138029276, 30.183480943313402], [79.721366815107118, 30.882714748654728], [78.738894484374001, 31.515906073527045], [78.458446486326025, 32.61816437431272], [79.176128777995544, 32.483779812137747], [79.208891636068543, 32.994394639613738], [78.811086460285722, 33.506198025032397], [78.912268914713209, 34.321936346975768], [77.83745079947461, 35.494009507787794], [76.192848341785705, 35.89840342868785], [75.896897414050173, 36.666806138651872], [75.158027785140987, 37.133030910789152], [74.980002475895404, 37.419990139305888], [74.829985792952144, 37.990007025701445], [74.864815708316783, 38.378846340481587], [74.25751427602269, 38.606506862943476], [73.928852166646394, 38.505815334622717], [73.675379266254836, 39.431236884105566], [73.960013055318427, 39.660008449861714], [73.822243686828315, 39.893973497063136], [74.776862420556043, 40.366425279291619], [75.467827996730719, 40.56207225194867], [76.526368035797432, 40.427946071935132], [76.90448449087711, 41.066485907549648], [78.187196893226044, 41.185315863604799], [78.543660923175253, 41.582242540038713], [80.119430373051401, 42.12394074153822], [80.259990268885318, 42.34999929459908], [80.180150180994374, 42.920067857426844], [80.866206496101213, 43.180362046881008], [79.966106398441426, 44.917516994804622], [81.947070753918084, 45.317027492853143], [82.458925815769035, 45.539649563166499], [83.180483839860543, 47.330031236350735], [85.164290399113213, 47.000955715516099], [85.720483839870667, 47.452969468773077], [85.76823286330837, 48.455750637396896], [86.59877648310335, 48.549181626980605], [87.359970330762692, 49.214980780629148], [87.751264276076668, 49.297197984405464], [88.013832228551678, 48.599462795600594], [88.854297723346747, 48.069081732773007], [90.280825636763893, 47.693549099307901], [90.970809360724957, 46.88814606382293], [90.585768263718307, 45.719716091487491], [90.945539585334316, 45.286073309910243], [92.133890822318222, 45.115075995456429], [93.480733677141316, 44.97547211362], [94.688928664125356, 44.352331854828456], [95.306875441471504, 44.241330878265458], [95.762454868556688, 43.319449164394619], [96.349395786527808, 42.725635280928643], [97.451757440177971, 42.74888967546007], [99.515817498779995, 42.524691473961688], [100.845865513108279, 42.663804429691417], [101.833040399179936, 42.51487295182627], [103.312278273534787, 41.907468166667613], [104.522281935649005, 41.90834666601662], [104.964993931093431, 41.597409572916334], [106.129315627061658, 42.134327704428891], [107.744772576937976, 42.481515814781908], [109.243595819131428, 42.519446316084149], [110.412103306115299, 42.871233628911014], [111.129682244920218, 43.406834011400171], [111.82958784388137, 43.743118394539486], [111.667737257943202, 44.073175767587706], [111.348376906379428, 44.457441718110047], [111.87330610560025, 45.102079372735112], [112.436062453258842, 45.01164561622425], [113.463906691544196, 44.808893134127111], [114.46033165899604, 45.339816799493875], [115.985096470200133, 45.727235012386004], [116.717868280098855, 46.38820241961524], [117.421701287914246, 46.67273285581421], [118.874325799638711, 46.805412095723646], [119.663269891438745, 46.692679958678944], [119.772823927897562, 47.048058783550132], [118.866574334794947, 47.747060044946195], [118.064142694166719, 48.06673045510373], [117.295507440257438, 47.697709052107385], [116.308952671373234, 47.853410142602812], [115.742837355615734, 47.726544501326273], [115.485282017073018, 48.135382595403442], [116.191802199367601, 49.134598090199056], [116.67880089728618, 49.888531399121398], [117.879244419426371, 49.510983384796944], [119.288460728025839, 50.142882798862033], [119.279365675942358, 50.582907619827282], [120.182049595216924, 51.64356639261802], [120.738191359541972, 51.964115302124547], [120.725789015791975, 52.516226304730814], [120.177088657716865, 52.753886216841195], [121.003084751470226, 53.251401068731226], [122.245747918792858, 53.431725979213681], [123.571506789240843, 53.458804429734627], [125.068211297710434, 53.161044826868832], [125.946348911646169, 52.792798570356936], [126.564399041856959, 51.784255479532689], [126.939156528837657, 51.353894151405896], [127.287455682484904, 50.739797268265434], [127.657407261262378, 49.760270494172929]]]] } }, - { "type": "Feature", "properties": { "admin": "Ivory Coast", "name": "C�te d'Ivoire", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[-2.856125047202397, 4.994475816259508], [-3.311084357100071, 4.984295559098014], [-4.008819545904941, 5.179813340674314], [-4.64991736491791, 5.168263658057084], [-5.834496222344525, 4.993700669775135], [-6.528769090185845, 4.705087795425015], [-7.518941209330434, 4.338288479017307], [-7.712159389669749, 4.364565944837721], [-7.63536821128403, 5.188159084489455], [-7.53971513511176, 5.313345241716517], [-7.570152553731686, 5.707352199725903], [-7.993692592795879, 6.126189683451541], [-8.311347622094017, 6.193033148621081], [-8.602880214868618, 6.467564195171659], [-8.385451626000572, 6.911800645368742], [-8.485445522485348, 7.395207831243068], [-8.439298468448696, 7.686042792181736], [-8.280703497744936, 7.687179673692156], [-8.221792364932197, 8.123328762235571], [-8.299048631208562, 8.316443589710302], [-8.203498907900878, 8.455453192575446], [-7.832100389019186, 8.575704250518625], [-8.079113735374348, 9.376223863152033], [-8.309616461612249, 9.789531968622439], [-8.22933712404682, 10.129020290563897], [-8.029943610048617, 10.206534939001711], [-7.89958980959237, 10.297382106970824], [-7.622759161804808, 10.147236232946792], [-6.850506557635057, 10.138993841996237], [-6.666460944027547, 10.430810655148447], [-6.493965013037267, 10.411302801958268], [-6.205222947606429, 10.524060777219132], [-6.050452032892266, 10.096360785355442], [-5.816926235365286, 10.222554633012191], [-5.404341599946973, 10.370736802609144], [-4.954653286143098, 10.152713934769732], [-4.779883592131966, 9.821984768101741], [-4.330246954760383, 9.610834865757139], [-3.980449184576684, 9.862344061721698], [-3.511898972986272, 9.900326239456216], [-2.827496303712706, 9.642460842319775], [-2.56218950032624, 8.219627793811481], [-2.983584967450326, 7.379704901555511], [-3.244370083011261, 6.2504715031135], [-2.810701463217839, 5.389051215024109], [-2.856125047202397, 4.994475816259508]]] } }, + { "type": "Feature", "properties": { "admin": "Ivory Coast", "name": "Côte d'Ivoire", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[-2.856125047202397, 4.994475816259508], [-3.311084357100071, 4.984295559098014], [-4.008819545904941, 5.179813340674314], [-4.64991736491791, 5.168263658057084], [-5.834496222344525, 4.993700669775135], [-6.528769090185845, 4.705087795425015], [-7.518941209330434, 4.338288479017307], [-7.712159389669749, 4.364565944837721], [-7.63536821128403, 5.188159084489455], [-7.53971513511176, 5.313345241716517], [-7.570152553731686, 5.707352199725903], [-7.993692592795879, 6.126189683451541], [-8.311347622094017, 6.193033148621081], [-8.602880214868618, 6.467564195171659], [-8.385451626000572, 6.911800645368742], [-8.485445522485348, 7.395207831243068], [-8.439298468448696, 7.686042792181736], [-8.280703497744936, 7.687179673692156], [-8.221792364932197, 8.123328762235571], [-8.299048631208562, 8.316443589710302], [-8.203498907900878, 8.455453192575446], [-7.832100389019186, 8.575704250518625], [-8.079113735374348, 9.376223863152033], [-8.309616461612249, 9.789531968622439], [-8.22933712404682, 10.129020290563897], [-8.029943610048617, 10.206534939001711], [-7.89958980959237, 10.297382106970824], [-7.622759161804808, 10.147236232946792], [-6.850506557635057, 10.138993841996237], [-6.666460944027547, 10.430810655148447], [-6.493965013037267, 10.411302801958268], [-6.205222947606429, 10.524060777219132], [-6.050452032892266, 10.096360785355442], [-5.816926235365286, 10.222554633012191], [-5.404341599946973, 10.370736802609144], [-4.954653286143098, 10.152713934769732], [-4.779883592131966, 9.821984768101741], [-4.330246954760383, 9.610834865757139], [-3.980449184576684, 9.862344061721698], [-3.511898972986272, 9.900326239456216], [-2.827496303712706, 9.642460842319775], [-2.56218950032624, 8.219627793811481], [-2.983584967450326, 7.379704901555511], [-3.244370083011261, 6.2504715031135], [-2.810701463217839, 5.389051215024109], [-2.856125047202397, 4.994475816259508]]] } }, { "type": "Feature", "properties": { "admin": "Cameroon", "name": "Cameroon", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[13.07582238124675, 2.267097072759014], [12.951333855855605, 2.321615708826939], [12.359380323952218, 2.19281220133945], [11.751665480199787, 2.326757513839993], [11.276449008843711, 2.261050930180871], [9.649158155972627, 2.283866075037735], [9.795195753629455, 3.073404445809117], [9.404366896205998, 3.734526882335202], [8.948115675501068, 3.904128933117135], [8.744923943729416, 4.352215277519959], [8.488815545290889, 4.495617377129917], [8.500287713259693, 4.771982937026847], [8.757532993208626, 5.47966583904791], [9.233162876023043, 6.444490668153334], [9.522705926154398, 6.453482367372116], [10.118276808318255, 7.038769639509879], [10.497375115611417, 7.055357774275562], [11.058787876030349, 6.644426784690593], [11.745774366918509, 6.981382961449753], [11.839308709366801, 7.397042344589434], [12.063946160539556, 7.799808457872301], [12.218872104550597, 8.305824082874322], [12.753671502339214, 8.717762762888993], [12.955467970438971, 9.417771714714702], [13.1675997249971, 9.64062632897341], [13.308676385153914, 10.160362046748926], [13.572949659894558, 10.798565985553564], [14.415378859116682, 11.572368882692071], [14.468192172918974, 11.90475169519341], [14.57717776862253, 12.085360826053501], [14.181336297266792, 12.483656927943112], [14.213530714584634, 12.802035427293344], [14.495787387762842, 12.859396267137326], [14.893385857816522, 12.219047756392582], [14.960151808337598, 11.555574042197222], [14.923564894274955, 10.891325181517471], [15.467872755605269, 9.982336737503429], [14.909353875394713, 9.99212942142273], [14.627200555081057, 9.920919297724536], [14.171466098699025, 10.021378282099928], [13.954218377344002, 9.549494940626685], [14.544466586981766, 8.965861314322266], [14.979995558337688, 8.796104234243471], [15.120865512765331, 8.382150173369423], [15.436091749745765, 7.692812404811971], [15.279460483469107, 7.421924546737968], [14.776545444404572, 6.408498033062044], [14.536560092841111, 6.22695872642069], [14.459407179429345, 5.451760565610299], [14.558935988023501, 5.03059764243153], [14.478372430080466, 4.732605495620446], [14.950953403389658, 4.21038930909492], [15.036219516671249, 3.851367295747123], [15.405395948964379, 3.335300604664339], [15.862732374747479, 3.013537298998982], [15.907380812247649, 2.557389431158612], [16.01285241055535, 2.267639675298084], [15.940918816805061, 1.727672634280295], [15.14634199388524, 1.964014797367184], [14.337812534246577, 2.22787466064949], [13.07582238124675, 2.267097072759014]]] } }, { "type": "Feature", "properties": { "admin": "Democratic Republic of the Congo", "name": "Dem. Rep. Congo", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[30.833859897593801, 3.50916596111034], [30.773346795380036, 2.339883327642127], [31.174149204235807, 2.204465236821263], [30.852670118948048, 1.849396470543809], [30.468507521290292, 1.58380544677972], [30.086153598762703, 1.062312730306288], [29.875778842902488, 0.597379868976304], [29.819503208136634, -0.205310153813372], [29.587837762172164, -0.58740569417948], [29.579466180140876, -1.341313164885626], [29.29188683443661, -1.620055840667987], [29.254834832483336, -2.215109958508911], [29.117478875451546, -2.292211195488384], [29.02492638521678, -2.839257907730157], [29.276383904749046, -3.293907159034063], [29.339997592900342, -4.499983412294092], [29.519986606572925, -5.419978936386313], [29.41999271008816, -5.939998874539432], [29.620032179490003, -6.520015150583424], [30.199996779101692, -7.079980970898161], [30.740015496551781, -8.340007419470913], [30.34608605319081, -8.238256524288216], [29.002912225060467, -8.40703175215347], [28.734866570762495, -8.526559340044576], [28.449871046672818, -9.164918308146083], [28.673681674928922, -9.605924981324931], [28.496069777141763, -10.789883721564044], [28.372253045370421, -11.793646742401389], [28.642417433392346, -11.971568698782312], [29.341547885869087, -12.36074391037241], [29.616001417771223, -12.178894545137307], [29.699613885219485, -13.257226657771827], [28.934285922976834, -13.248958428605132], [28.52356163912102, -12.698604424696679], [28.15510867687998, -12.272480564017894], [27.38879886242378, -12.132747491100663], [27.164419793412456, -11.608748467661071], [26.55308759939961, -11.924439792532125], [25.752309604604726, -11.784965101776356], [25.418118116973197, -11.330935967659958], [24.783169793402948, -11.238693536018962], [24.314516228947948, -11.262826429899269], [24.257155389103982, -10.951992689663655], [23.912215203555714, -10.926826267137512], [23.456790805767433, -10.867863457892481], [22.837345411884733, -11.017621758674329], [22.402798292742371, -10.99307545333569], [22.155268182064304, -11.084801120653768], [22.208753289486388, -9.894796237836507], [21.87518191904234, -9.523707777548564], [21.801801385187897, -8.908706556842978], [21.949130893652036, -8.305900974158275], [21.746455926203303, -7.920084730667147], [21.728110792739695, -7.2908724910813], [20.514748162526498, -7.299605808138629], [20.601822950938292, -6.93931772219968], [20.091621534920645, -6.943090101756993], [20.037723016040214, -7.116361179231644], [19.417502475673157, -7.155428562044297], [19.166613396896107, -7.738183688999753], [19.016751743249664, -7.988245944860132], [18.464175652752683, -7.847014255406442], [18.134221632569048, -7.98767750410492], [17.472970004962232, -8.068551120641699], [17.089995965247166, -7.545688978712525], [16.860190870845198, -7.222297865429984], [16.573179965896141, -6.622644545115087], [16.326528354567042, -5.877470391466267], [13.375597364971892, -5.864241224799548], [13.02486941900696, -5.984388929878157], [12.735171339578695, -5.965682061388497], [12.322431674863507, -6.100092461779658], [12.182336866920249, -5.789930515163837], [12.436688266660866, -5.684303887559245], [12.468004184629734, -5.248361504745003], [12.631611769265788, -4.991271254092935], [12.995517205465173, -4.781103203961883], [13.258240187237044, -4.882957452009165], [13.600234816144676, -4.500138441590969], [14.144956088933295, -4.510008640158715], [14.209034864975219, -4.793092136253597], [14.582603794013179, -4.970238946150139], [15.170991652088441, -4.3435071753143], [15.753540073314749, -3.855164890156096], [16.006289503654298, -3.535132744972528], [15.972803175529149, -2.712392266453612], [16.407091912510051, -1.740927015798682], [16.86530683764212, -1.225816338713287], [17.523716261472853, -0.743830254726987], [17.638644646889983, -0.424831638189246], [17.663552687254676, -0.058083998213817], [17.826540154703245, 0.288923244626105], [17.774191928791563, 0.855658677571085], [17.89883548347958, 1.741831976728278], [18.09427575040743, 2.365721543788055], [18.39379235197114, 2.90044342692822], [18.453065219809925, 3.504385891123348], [18.542982211997778, 4.201785183118317], [18.932312452884755, 4.709506130385973], [19.467783644293146, 5.031527818212779], [20.290679152108932, 4.691677761245287], [20.927591180106273, 4.322785549329736], [21.659122755630019, 4.224341945813719], [22.405123732195531, 4.02916006104732], [22.704123569436284, 4.633050848810156], [22.841479526468103, 4.710126247573483], [23.297213982850135, 4.609693101414221], [24.41053104014625, 5.108784084489129], [24.805028924262409, 4.897246608902349], [25.128833449003274, 4.927244777847789], [25.278798455514302, 5.170408229997191], [25.650455356557465, 5.256087754737123], [26.402760857862535, 5.150874538590869], [27.044065382604703, 5.127852688004835], [27.374226108517483, 5.233944403500059], [27.979977247842807, 4.408413397637373], [28.428993768026906, 4.287154649264493], [28.696677687298795, 4.455077215996936], [29.159078403446497, 4.38926727947323], [29.715995314256013, 4.600804755060024], [29.953500197069467, 4.173699042167683], [30.833859897593801, 3.50916596111034]]] } }, { "type": "Feature", "properties": { "admin": "Republic of Congo", "name": "Congo", "continent": "Africa" }, "geometry": { "type": "Polygon", "coordinates": [[[12.995517205465173, -4.781103203961883], [12.620759718484491, -4.438023369976135], [12.318607618873923, -4.606230157086187], [11.914963006242086, -5.037986748884789], [11.093772820691923, -3.978826592630546], [11.855121697648114, -3.42687061932105], [11.478038771214299, -2.765618991714241], [11.820963575903189, -2.514161472181982], [12.495702752338159, -2.391688327650242], [12.575284458067639, -1.948511244315134], [13.109618767965626, -2.428740329603513], [13.992407260807706, -2.470804945489099], [14.299210239324564, -1.998275648612213], [14.425455763413593, -1.333406670744971], [14.316418491277741, -0.552627455247048], [13.843320753645653, 0.038757635901149], [14.276265903386953, 1.196929836426619], [14.026668735417214, 1.395677395021153], [13.282631463278816, 1.31418366129688], [13.003113641012074, 1.830896307783319], [13.07582238124675, 2.267097072759014], [14.337812534246577, 2.22787466064949], [15.14634199388524, 1.964014797367184], [15.940918816805061, 1.727672634280295], [16.01285241055535, 2.267639675298084], [16.537058139724135, 3.198254706226278], [17.133042433346297, 3.728196519379451], [17.809900343505259, 3.560196437998569], [18.453065219809925, 3.504385891123348], [18.39379235197114, 2.90044342692822], [18.09427575040743, 2.365721543788055], [17.89883548347958, 1.741831976728278], [17.774191928791563, 0.855658677571085], [17.826540154703245, 0.288923244626105], [17.663552687254676, -0.058083998213817], [17.638644646889983, -0.424831638189246], [17.523716261472853, -0.743830254726987], [16.86530683764212, -1.225816338713287], [16.407091912510051, -1.740927015798682], [15.972803175529149, -2.712392266453612], [16.006289503654298, -3.535132744972528], [15.753540073314749, -3.855164890156096], [15.170991652088441, -4.3435071753143], [14.582603794013179, -4.970238946150139], [14.209034864975219, -4.793092136253597], [14.144956088933295, -4.510008640158715], [13.600234816144676, -4.500138441590969], [13.258240187237044, -4.882957452009165], [12.995517205465173, -4.781103203961883]]] } }, @@ -1055,6 +1056,7 @@ module MenuComponent { } + module NavigationDrawerComponent { $(function () { var navigationdrawerInstance = new ej.NavigationDrawer($("#navpane"), { @@ -1657,7 +1659,6 @@ module RadialMenuComponent { }); } - function bold(e: any) { rteObj = rteEle.data("ejRTE"); @@ -1694,6 +1695,7 @@ function redo(e: any) { } + module RadialSliderComponent { $(function () { var radialsliderInstance = new ej.RadialSlider($("#radialSlider"), { @@ -2577,6 +2579,7 @@ function onClick(args:any) { } + module RotatorComponent { $(function () { var rotatorInstance = new ej.Rotator($("#sliderContent"), { @@ -2921,6 +2924,7 @@ module piesparkline4 { + module SplitterComponent { $(function () { var splitterInstance = new ej.Splitter($("#outterSpliter"), { @@ -3123,6 +3127,7 @@ module EditorComponent { } + module TileViewComponent { $(function () { var tile1 = new ej.Tile($("#tile1"), { @@ -3380,7 +3385,6 @@ module TreeViewComponent { - module UploadboxComponent { $(function () { diff --git a/types/ej.web.all/index.d.ts b/types/ej.web.all/index.d.ts index 7584d0ba4c..0c891b2eae 100644 --- a/types/ej.web.all/index.d.ts +++ b/types/ej.web.all/index.d.ts @@ -8,7 +8,7 @@ /*! * filename: ej.web.all.d.ts -* version : 16.2.0.41 +* version : 16.2.0.50 * Copyright Syncfusion Inc. 2001 - 2018. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing @@ -4994,7 +4994,7 @@ declare namespace ej { enableThumbnailCompress?: boolean; /** Allows specified type of files only to display in FileExplorer control. - * @Default {.} + * @Default {* . *} */ fileTypes?: string; @@ -15861,6 +15861,19 @@ declare namespace ej { toolbarData?: any; } + export interface SwimlaneSettingsHeader { + + /** Gets or sets a value that indicates to render the Kanban with specified swimlane header text. + * @Default {null} + */ + text?: string; + + /** Gets or sets a value that indicates to render the Kanban with specified swimlane header key. + * @Default {null} + */ + key?: string; + } + export interface SwimlaneSettingsUnassignedGroup { /** To enable or disable unassigned category change with swim lane key values. @@ -15886,6 +15899,16 @@ declare namespace ej { */ allowDragAndDrop?: boolean; + /** To enable or disable empty swimlane on Kanban board. It is used to shown empty swimlane when no data's present on headers key mapping value. + * @Default {false} + */ + showEmptySwimlane?: boolean; + + /** Gets or sets an object that indicates to render the swimlane rows with specified swimlane headers. + * @Default {[]} + */ + headers?: SwimlaneSettingsHeader[]; + /** Customize the settings for unassigned category of swim lane. * @Default {Object} */ @@ -16880,9 +16903,10 @@ declare namespace ej { /** This method helps to insert/paste the content at the current cursor (caret) position or the selected content to be replaced with our text by passing the value as parameter to the * pasteContent method in the Editor. + * @param {string} paste content * @returns {void} */ - pasteContent(): void; + pasteContent(html: string): void; /** Refreshes the RTE control. * @returns {void} @@ -23382,6 +23406,13 @@ declare namespace ej { */ refreshContent(templateRefresh?: boolean): void; + /** Refresh the grid contents with updated server Data, using XMLHttpRequest. Url Path should be provided in Grid datasource otherwise it refreshes with local data without + * XMLHttpRequest. + * @param {any} optionalData to the server + * @returns {void} + */ + refreshData(additionalParameters?: any): void; + /** Refresh the template of the grid * @returns {void} */ @@ -36252,6 +36283,10 @@ declare namespace ej { */ rowSelecting?(e: RowSelectingEventArgs): void; + /** Triggered after splitter resizing action in Gantt + */ + splitterResized?(e: SplitterResizedEventArgs): void; + /** Triggered when taskbar item is clicked in Gantt. */ taskbarClick?(e: TaskbarClickEventArgs): void; @@ -36852,6 +36887,33 @@ declare namespace ej { previousGridRow?: any; } + export interface SplitterResizedEventArgs { + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the value based on current splitter position. + */ + currentSplitterPosition?: string; + + /** To set custom position for splitter after resize action. + */ + customSplitterPosition?: string; + + /** Returns the value to differentiate whether splitter resizing is performed either by manual resizing or by method + */ + isOnResize?: boolean; + + /** To differentiate `customSplitterPosition` value was index or position. + */ + isSplitterIndex?: boolean; + + /** Returns the previous splitter position + */ + prevSplitterPosition?: string; + } + export interface TaskbarClickEventArgs { /** Returns currently clicked row data @@ -37455,8 +37517,14 @@ declare namespace ej { ///Enables the next time span icon in toolbar NextTimeSpan, + ///Enables the critical path icon in toolbar + CriticalPath, + ///Enables the excel export toolbar icon - ExcelExport + ExcelExport, + + ///Enables the pdf export toolbar icon + PdfExport } @@ -37688,6 +37756,10 @@ declare namespace ej { /** Fires when click the View Report Button. */ viewReportClick?(e: ViewReportClickEventArgs): void; + + /** This event will be triggered on rendering the Report Viewer toolbar. + */ + toolbarRendering?(e: ToolbarRenderingEventArgs): void; } export interface DestroyEventArgs { @@ -37826,6 +37898,9 @@ declare namespace ej { type?: string; } + export interface ToolbarRenderingEventArgs { + } + export interface DataSource { /** Gets or sets the name of the data source. @@ -40076,7 +40151,7 @@ declare namespace ej { editMode?: ej.TreeGrid.EditMode|string; /** Specifies the position where the new row has to be added. - * @Default {top} + * @Default {ej.TreeGrid.RowPosition.Top} */ rowPosition?: ej.TreeGrid.RowPosition|string; @@ -40140,7 +40215,7 @@ declare namespace ej { /** Gets or sets a value that indicates the maximum number of filter choices that can be showed in the excel styled filter menu. * @Default {1000} */ - maxFilterChoice?: number; + maxFilterChoices?: number; } export interface PageSettings { @@ -40307,6 +40382,10 @@ declare namespace ej { export interface SummaryRowsSummaryColumn { + /** Specifies the custom summary calculate function or text. + */ + customSummaryValue?: string; + /** Specifies summary column used to perform the summary calculation. */ dataMember?: string; @@ -40380,11 +40459,11 @@ declare namespace ej { ///At load time column are rendered with given width value, while resizing the column only current column width is changed FixedColumns, - ///At load time columns are stretched with control width,while resizing the column, current column width updated based on next column - Normal, + ///At load time columns are stretched with control width, while resizing the column, current column width adjusted based on next column + NextColumn, - ///In this mode columns are stretched with control width in load time and on resizing action. - NextColumn + ///In this mode columns are stretched with control width in load time and on resizing action current column width was adjusted with all columns. + Normal } @@ -40600,7 +40679,10 @@ declare namespace ej { TrueCount, ///Displays the false count value for boolean summary columns - FalseCount + FalseCount, + + ///Displays the value from custom summary function + Custom } @@ -40634,7 +40716,10 @@ declare namespace ej { ExcelExport, ///Enables the printing icon in toolbar - Print + Print, + + ///Enables the search textbox in toolbar + Search } } @@ -43154,9 +43239,10 @@ declare namespace ej { * @param {string} Specifies the context menu type in which the item to be inserted. * @param {any[]} Pass the items to be inserted * @param {string} Specifies the type of operation to be performed + * @param {number} Specifies the item index * @returns {void} */ - addItem(target: string, itemColl: any[], operation: string): void; + addItem(target: string, itemColl: any[], operation: string, itemIdx: number): void; /** This method is used to change data source in the context menu. * @param {string} Specifies the context menu type to bind the data source. @@ -53707,6 +53793,34 @@ declare namespace ej.datavisualization { RoundedRectangle, //string Image, + //string + Triangle, + //string + Diamond, + //string + Trapezoid, + //string + Pentagon, + //string + Wedge, + //string + Star, + //string + HorizontalLine, + //string + Verticalline, + //string + Cross, + //string + Uparrow, + //string + Downarrow, + //string + Leftarrow, + //string + Rightarrow, + //string + InvertedTriangle, } } namespace CircularGauge { @@ -62232,6 +62346,12 @@ declare namespace ej.datavisualization { */ allowSnapping?: boolean; + /** It allows to show the value between the particular periods (i.e) from 1st January to 31st February and so on. The default value is true. If we set the property as false, it allows + * to show the value between the particular periods.(i.e) from 1st January to 31st January and so on. + * @Default {true} + */ + allowNextValue?: boolean; + /** Options for customizing the color, opacity and width of the chart border. */ border?: Border; @@ -62805,6 +62925,11 @@ declare namespace ej.datavisualization { */ labelPlacement?: ej.datavisualization.RangeNavigator.LabelPlacement|string; + /** Specifies to hide the labels when it intersects with each other. + * @Default {none} + */ + labelIntersectAction?: ej.datavisualization.RangeNavigator.LabelIntersectAction|string; + /** Specifies the position of the labels in higher level * @Default {top} */ @@ -62921,6 +63046,11 @@ declare namespace ej.datavisualization { */ labelPlacement?: ej.datavisualization.RangeNavigator.LabelPlacement|string; + /** Specifies to hide the labels when it intersects with each other. + * @Default {none} + */ + labelIntersectAction?: ej.datavisualization.RangeNavigator.LabelIntersectAction|string; + /** Specifies the position of the labels in lower level.See Position * @Default {bottom} */ @@ -63435,6 +63565,14 @@ declare namespace ej.datavisualization { Outside, } } + namespace RangeNavigator { + enum LabelIntersectAction { + //string + None, + //string + Hide, + } + } namespace RangeNavigator { enum Position { //string @@ -64868,7 +65006,7 @@ declare namespace ej.datavisualization { */ zoom(level: number, isAnimate: boolean): void; - /** Method to reload the shape marker with updated values. + /** Method to reload the specified layer based on layer and sublayer index value. * @returns {void} */ refreshLayer(): void; @@ -65025,6 +65163,10 @@ declare namespace ej.datavisualization { /** Triggers after refreshing the map items. */ refreshed?(e: RefreshedEventArgs): void; + + /** Fires before rendering the data labels. This event is triggered for each data label in the layers. You can use this event to add custom text in data labels. + */ + displayTextRendering?(e: DisplayTextRenderingEventArgs): void; } export interface MarkerSelectedEventArgs { @@ -65206,6 +65348,26 @@ declare namespace ej.datavisualization { originalEvent?: any; } + export interface DisplayTextRenderingEventArgs { + + /** text - Text displayed in data label. You can add custom text to the data label locationX - X-coordinate of data label location locationY - Y-coordinate of data label + * location + */ + data?: any; + + /** Set this option to true to cancel the event. + */ + cancel?: boolean; + + /** Instance of the map model object. + */ + model?: any; + + /** Name of the event + */ + type?: string; + } + export interface ZoomSettings { /** Specifies animation duration for map shapes while zooming. @@ -65360,6 +65522,39 @@ declare namespace ej.datavisualization { valuePath?: string; } + export interface LayersLabelSettingsFont { + + /** Font family of the data label. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style of the data label. + * @Default {normal.} + */ + fontStyle?: ej.datavisualization.Map.FontStyle|string; + + /** NameType DescriptionRegularstring Specifies the font weight as regular.BoldstringSpecifies the font weight as bold.LighterstringSpecifies the font weight as lighter. + * @Default {regular. See} + */ + fontWeight?: ej.datavisualization.Map.FontWeight|string; + + /** Opacity of the text. + * @Default {1} + */ + opacity?: number; + + /** Font color of the data label text. + * @Default {null} + */ + color?: string; + + /** Font size of the data label. + * @Default {12px} + */ + size?: string; + } + export interface LayersLabelSettings { /** enable or disable the enableSmartLabel property @@ -65386,6 +65581,10 @@ declare namespace ej.datavisualization { * @Default {fixed} */ smartLabelSize?: ej.datavisualization.Map.LabelSize|string; + + /** Options for customizing the data label font. + */ + font?: LayersLabelSettingsFont; } export interface LayersLegendSettings { @@ -66222,6 +66421,24 @@ declare namespace ej.datavisualization { Default, } } + namespace Map { + enum FontStyle { + //string + Normal, + //string + Italic, + } + } + namespace Map { + enum FontWeight { + //string + Regular, + //string + Bold, + //string + Lighter, + } + } namespace Map { enum GeometryType { //specifies the geographic view of map @@ -70516,6 +70733,11 @@ declare namespace ej.datavisualization { */ gradient?: NodesGradient; + /** defines the node border with a smooth transition from one color to another color. + * @Default {null} + */ + borderGradient?: any; + /** Defines the header of a swimlane/lane * @Default {{ text: Title, fontSize: 11 }} */ @@ -72093,8 +72315,8 @@ declare namespace ej.datavisualization { Parallel, //Used to set Event Trigger as Conditional Conditional, - //Used to set Event Trigger as Termination - Termination, + //Used to set Event Trigger as Terminate + Terminate, //Used to set Event Trigger as Cancel Cancel, } diff --git a/types/electron-load-devtool/electron-load-devtool-tests.ts b/types/electron-load-devtool/electron-load-devtool-tests.ts new file mode 100644 index 0000000000..5c41673adc --- /dev/null +++ b/types/electron-load-devtool/electron-load-devtool-tests.ts @@ -0,0 +1,20 @@ +import loadDevtool from 'electron-load-devtool'; + +loadDevtool(loadDevtool.REDUX_DEVTOOLS); +loadDevtool(loadDevtool.EMBER_INSPECTOR); +loadDevtool(loadDevtool.REACT_DEVELOPER_TOOLS); +loadDevtool(loadDevtool.BACKBONE_DEBUGGER); +loadDevtool(loadDevtool.JQUERY_DEBUGGER); +loadDevtool(loadDevtool.ANGULARJS_BATARANG); +loadDevtool(loadDevtool.VUEJS_DEVTOOLS); +loadDevtool('another-devtools-id'); + +loadDevtool(loadDevtool.REDUX_DEVTOOLS, { + enabled: false +}); + +loadDevtool(loadDevtool.REDUX_DEVTOOLS, { + name: 'chromium', + profile: 'another-profile-name', + version: '1.2.3' +}); diff --git a/types/electron-load-devtool/index.d.ts b/types/electron-load-devtool/index.d.ts new file mode 100644 index 0000000000..6e8379fdf6 --- /dev/null +++ b/types/electron-load-devtool/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for electron-load-devtool 1.0 +// Project: https://github.com/akameco/electron-load-devtool#readme +// Definitions by: prince +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface ElectronLoadDevtool { + (devtoolId: string, options?: ElectronLoadDevtoolOptions): void; + REDUX_DEVTOOLS: string; + EMBER_INSPECTOR: string; + REACT_DEVELOPER_TOOLS: string; + BACKBONE_DEBUGGER: string; + JQUERY_DEBUGGER: string; + ANGULARJS_BATARANG: string; + VUEJS_DEVTOOLS: string; +} + +interface ElectronLoadDevtoolOptions { + enabled?: boolean; + name?: string; + profile?: string; + version?: string; +} + +declare const electronLoadDevtool: ElectronLoadDevtool; + +export default electronLoadDevtool; diff --git a/types/electron-load-devtool/tsconfig.json b/types/electron-load-devtool/tsconfig.json new file mode 100644 index 0000000000..4de2349ea8 --- /dev/null +++ b/types/electron-load-devtool/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", + "electron-load-devtool-tests.ts" + ] +} diff --git a/types/electron-load-devtool/tslint.json b/types/electron-load-devtool/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/electron-load-devtool/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/elementtree/elementtree-tests.ts b/types/elementtree/elementtree-tests.ts new file mode 100644 index 0000000000..630a17f6c6 --- /dev/null +++ b/types/elementtree/elementtree-tests.ts @@ -0,0 +1,56 @@ +import * as et from 'elementtree'; + +// Example 1 +// https://github.com/racker/node-elementtree#example-1--creating-an-xml-document + +const XML = et.XML; +const ElementTree = et.ElementTree; +const element = et.Element; +const subElement = et.SubElement; + +const root = element('entry'); +root.set('xmlns', 'http://www.w3.org/2005/Atom'); + +const tenantId = subElement(root, 'TenantId'); +tenantId.text = '12345'; + +const serviceName = subElement(root, 'ServiceName'); +serviceName.text = 'MaaS'; + +const resourceId = subElement(root, 'ResourceID'); +resourceId.text = 'enAAAA'; + +const usageId = subElement(root, 'UsageID'); +usageId.text = '550e8400-e29b-41d4-a716-446655440000'; + +const eventType = subElement(root, 'EventType'); +eventType.text = 'create'; + +const category = subElement(root, 'category'); +category.set('term', 'monitoring.entity.create'); + +const dataCenter = subElement(root, 'DataCenter'); +dataCenter.text = 'global'; + +const region = subElement(root, 'Region'); +region.text = 'global'; + +const startTime = subElement(root, 'StartTime'); +startTime.text = new Date(); + +const resourceName = subElement(root, 'ResourceName'); +resourceName.text = 'entity'; + +const etree1 = new ElementTree(root); +const xml = etree1.write({ xml_declaration: false }); + +// Example 2 +// https://github.com/racker/node-elementtree#example-2--parsing-an-xml-document + +const data = ''; +const etree2 = et.parse(data); + +etree2.findall('./entry/TenantId').length; // 2 +etree2.findtext('./entry/ServiceName'); // MaaS +etree2.findall('./entry/category')[0].get('term'); // monitoring.entity.create +etree2.findall('*/category/[@term="monitoring.entity.update"]').length; // 1 diff --git a/types/elementtree/index.d.ts b/types/elementtree/index.d.ts new file mode 100644 index 0000000000..8019797b4a --- /dev/null +++ b/types/elementtree/index.d.ts @@ -0,0 +1,88 @@ +// Type definitions for elementtree 0.1 +// Project: https://github.com/racker/node-elementtree +// Definitions by: Daniel Imhoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ElementTreeWriteOptions { + default_namespace?: string; + encoding?: string; // default is 'utf-8' + indent?: number; + method?: 'xml' | 'text'; // default is 'xml' + xml_declaration?: boolean; // on by default +} + +export class ElementTree { + constructor(element: Element); + + getroot(): Element; + _setroot(element: Element): void; + + parse(source: string): Element; + find(path: string): Element | null; + findtext(path: string): ElementText | undefined; + findall(path: string): Element[]; + write(options?: ElementTreeWriteOptions): string; +} + +export interface Attributes { + [key: string]: string | undefined; +} + +export type ElementTag = typeof Comment | typeof CData | typeof ProcessingInstruction | string; + +export type ElementText = { toString(): string; } | string; + +export interface Element { + tag: ElementTag; + attrib: Attributes; + text: ElementText | null; + tail: string | null; + + toString(): string; + makeelement(tag: ElementTag, attrib?: Attributes): Element; + len(): number; + + getItem(index: number): Element | undefined; + setItem(index: number, element: Element): void; + delItem(index: number): void; + getSlice(start: number, stop: number): Element[]; + setSlice(start: number, stop: number, elements: ReadonlyArray): void; + delSlice(start: number, stop: number): void; + + append(element: Element): void; + extend(elements: ReadonlyArray): void; + insert(index: number, element: Element): void; + remove(element: Element): void; + getchildren(): Element[]; + + find(path: string): Element | null; + findtext(path: string): ElementText | undefined; + findall(path: string): Element[]; + + clear(): void; + + get(k: string): string | undefined; + set(k: string, v?: string): string; + keys(): string[]; + items(): Array<[string, string]>; +} + +export class QName { + text: string; + + constructor(text_or_uri: string, tag?: string); + toString(): string; +} + +// special tags +export function CData(text?: ElementText): Element; +export function Comment(text?: ElementText): Element; +export function ProcessingInstruction(target: ElementText, text?: ElementText): Element; + +export function XML(data: string): Element; +export function Element(ElementTag: string, attrib?: Attributes): Element; +export function SubElement(parent: Element, ElementTag: string, attrib?: Attributes): Element; + +export function parse(source: string): ElementTree; +export function register_namespace(prefix: string, uri: string): void; +export function tostring(element: Element, options: ElementTreeWriteOptions): string; diff --git a/types/elementtree/tsconfig.json b/types/elementtree/tsconfig.json new file mode 100644 index 0000000000..9f9991fb4e --- /dev/null +++ b/types/elementtree/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", + "elementtree-tests.ts" + ] +} diff --git a/types/elementtree/tslint.json b/types/elementtree/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/elementtree/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/elliptic/elliptic-tests.ts b/types/elliptic/elliptic-tests.ts new file mode 100644 index 0000000000..d587be5e8d --- /dev/null +++ b/types/elliptic/elliptic-tests.ts @@ -0,0 +1,47 @@ +import elliptic = require('elliptic'); + +const ec = new elliptic.ec('secp256k1'); + +// Generate keys +const key = ec.genKeyPair(); + +// Sign the message's hash (input must be an array, or a hex-string) +const msgHash = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +const signature = key.sign(msgHash); + +// Export DER encoded signature in Array +const derSign = signature.toDER(); + +// Verify signature +console.log(key.verify(msgHash, derSign)); + +// CHECK WITH NO PRIVATE KEY + +const pubPoint = key.getPublic(); +const x = pubPoint.getX(); +const y = pubPoint.getY(); + +// Public Key MUST be either: +// 1) '04' + hex string of x + hex string of y; or +// 2) object with two hex string properties (x and y); or +// 3) object with two buffer properties (x and y) +const pub = pubPoint.encode('hex'); // case 1 +const aPub = { x: x.toString('hex'), y: y.toString('hex') }; // case 2 +const bPub = { x: x.toBuffer(), y: y.toBuffer() }; // case 3 +const cPub = { x: x.toArrayLike(Buffer), y: y.toArrayLike(Buffer) }; // case 3 + +// Import public key +const newKey = ec.keyFromPublic(pub, 'hex'); + +// Signature MUST be either: +// 1) DER-encoded signature as hex-string; or +// 2) DER-encoded signature as buffer; or +// 3) object with two hex-string properties (r and s); or +// 4) object with two buffer properties (r and s) + +// const signature = '3046022100...'; // case 1 +// const signature = new Buffer('...'); // case 2 +// const signature = { r: 'b1fc...', s: '9c42...' }; // case 3 + +// Verify signature +console.log(key.verify(msgHash, signature)); diff --git a/types/elliptic/index.d.ts b/types/elliptic/index.d.ts new file mode 100644 index 0000000000..f819d17497 --- /dev/null +++ b/types/elliptic/index.d.ts @@ -0,0 +1,158 @@ +// Type definitions for elliptic 6.4 +// Project: https://github.com/indutny/elliptic +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import BN = require('bn.js'); + +// incomplete typings +export const utils: any; +export const rand: any; +export const eddsa: any; + +export type BNInput = string | BN | number | Buffer | number[]; + +export const version: number; + +export namespace curve { + class BaseCurve { + constructor(type: string, conf: BaseCurve.BaseCurveOptions) + p: BN; + type: string; + red: any; // ? + zero: any; // ? + one: any; // ? + two: any; // ? + n: BN | undefined | null; + g: any; // ? + redN: any; // ? + decodePoint(bytes: any, enc: string): any; // ? + } + + namespace BaseCurve { + class BasePoint { + constructor(curve: any, type: string); + curve: any; + type: string; + precomputed: PrecomputedValues | null; + encode(enc: string, compact: boolean): BN; + encodeCompressed(enc: string): BN; + validate(): boolean; + precompute(power: number): BasePoint; + dblp(k: any): any; // ? + } + + interface BaseCurveOptions { + p: number | string | number[] | Buffer | BN; + prime?: BN | string; + n?: number | BN | Buffer; + g?: any; // ? + gRed?: any; // ? + } + + interface PrecomputedValues { + doubles: any; // ? + naf: any; // ? + beta: any; // ? + } + } +} + +export namespace curves { + class PresetCurve { + constructor(options: PresetCurve.Options) + type: string; + g: any; // ? + n: BN | undefined | null; + hash: any; // ? + } + + namespace PresetCurve { + interface Options { + type: string; + prime: string | null; + p: string; + a: string; + b: string; + n: string; + hash: any; + gRed: boolean; + g: any; // ? + beta?: string; + lambda?: string; + basis?: any; // ? + } + } +} + +export class ec { + constructor(options: string | curves.PresetCurve) + curve: any; + n: BN | undefined | null; + nh: any; + g: any; + hash: any; + + keyPair(options: ec.KeyPairOptions): ec.KeyPair; + keyFromPrivate(priv: Buffer | ec.KeyPair, enc?: string): ec.KeyPair; + keyFromPublic(pub: Buffer | ec.KeyPair, enc?: string): ec.KeyPair; + genKeyPair(options?: ec.GenKeyPairOptions): ec.KeyPair; + sign(msg: BNInput, key: Buffer | ec.KeyPair, enc: string, options?: ec.SignOptions): ec.Signature; + sign(msg: BNInput, key: Buffer | ec.KeyPair, options?: ec.SignOptions): ec.Signature; + verify(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, key: Buffer | ec.KeyPair, enc?: string): boolean; + recoverPubKey(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, j: number, enc?: string): any; + getKeyRecoveryParam(e: Error | undefined, signature: ec.Signature | ec.SignatureOptions, Q: BN, enc?: string): number; +} + +export namespace ec { + interface GenKeyPairOptions { + pers: any; + entropy: any; + persEnc?: string; + entropyEnc?: string; + } + + interface SignOptions { + pers: any; + persEnc?: string; + canonical?: boolean; + k?: BN; + } + + class KeyPair { + static fromPublic(ec: ec, pub: Buffer | KeyPair, enc?: string): KeyPair; + static fromPrivate(ec: ec, priv: Buffer | KeyPair, enc?: string): KeyPair; + constructor(ec: ec, options: KeyPairOptions) + ec: ec; + validate(): { readonly result: boolean, readonly reason: string }; + getPublic(compact: boolean, enc?: string): any; // ? + getPublic(enc?: string): any; // ? + getPrivate(enc?: 'hex'): Buffer | BN | string; + derive(pub: any): any; // ? + sign(msg: BNInput, enc: string, options?: SignOptions): Signature; + sign(msg: BNInput, options?: SignOptions): Signature; + verify(msg: BNInput, signature: Signature | SignatureOptions): boolean; + inspect(): string; + } + + class Signature { + constructor(options: SignatureOptions | Signature, enc?: string) + r: BN; + s: BN; + recoveryParam: number | null; + toDER(enc?: string | null): any; // ? + } + + interface SignatureOptions { + r: number; + s: number; + recoveryParam?: number; + } + + interface KeyPairOptions { + priv?: Buffer; + privEnc?: string; + pub?: Buffer; + pubEnc?: string; + } +} diff --git a/types/elliptic/tsconfig.json b/types/elliptic/tsconfig.json new file mode 100644 index 0000000000..505cd03374 --- /dev/null +++ b/types/elliptic/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", + "elliptic-tests.ts" + ] +} diff --git a/types/elliptic/tslint.json b/types/elliptic/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/elliptic/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts index b071662326..b038a7f62b 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for ember-data 2.14 +// Type definitions for ember-data 3.0 // Project: https://github.com/emberjs/data // Definitions by: Derek Wickern // Mike North // Chris Krycho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 declare module 'ember-data' { import Ember from 'ember'; diff --git a/types/ember-data/v2/adapter.d.ts b/types/ember-data/v2/adapter.d.ts new file mode 100644 index 0000000000..e7d126b345 --- /dev/null +++ b/types/ember-data/v2/adapter.d.ts @@ -0,0 +1,4 @@ +import { DS } from "ember-data"; + +export default DS.Adapter; +export { AdapterRegistry } from 'ember-data'; diff --git a/types/ember-data/v2/adapters/errors.d.ts b/types/ember-data/v2/adapters/errors.d.ts new file mode 100644 index 0000000000..bd7e1dd65a --- /dev/null +++ b/types/ember-data/v2/adapters/errors.d.ts @@ -0,0 +1,13 @@ +import DS from 'ember-data'; + +declare const AdapterError: typeof DS.AdapterError; +declare const InvalidError: typeof DS.InvalidError; +declare const UnauthorizedError: typeof DS.UnauthorizedError; +declare const ForbiddenError: typeof DS.ForbiddenError; +declare const NotFoundError: typeof DS.NotFoundError; +declare const ConflictError: typeof DS.ConflictError; +declare const ServerError: typeof DS.ServerError; +declare const TimeoutError: typeof DS.TimeoutError; +declare const AbortError: typeof DS.AbortError; +declare const errorsHashToArray: typeof DS.errorsHashToArray; +declare const errorsArrayToHash: typeof DS.errorsArrayToHash; diff --git a/types/ember-data/v2/adapters/json-api.d.ts b/types/ember-data/v2/adapters/json-api.d.ts new file mode 100644 index 0000000000..4296b32eec --- /dev/null +++ b/types/ember-data/v2/adapters/json-api.d.ts @@ -0,0 +1,2 @@ +import DS from 'ember-data'; +export default DS.JSONAPIAdapter; diff --git a/types/ember-data/v2/adapters/rest.d.ts b/types/ember-data/v2/adapters/rest.d.ts new file mode 100644 index 0000000000..c7dd3824ae --- /dev/null +++ b/types/ember-data/v2/adapters/rest.d.ts @@ -0,0 +1,2 @@ +import DS from 'ember-data'; +export default DS.RESTAdapter; diff --git a/types/ember-data/v2/attr.d.ts b/types/ember-data/v2/attr.d.ts new file mode 100644 index 0000000000..2ecdea2d7e --- /dev/null +++ b/types/ember-data/v2/attr.d.ts @@ -0,0 +1,2 @@ +import DS from 'ember-data'; +export default DS.attr; diff --git a/types/ember-data/v2/index.d.ts b/types/ember-data/v2/index.d.ts new file mode 100644 index 0000000000..dccf63e890 --- /dev/null +++ b/types/ember-data/v2/index.d.ts @@ -0,0 +1,2121 @@ +// Type definitions for ember-data 2.14 +// Project: https://github.com/emberjs/data +// Definitions by: Derek Wickern +// Mike North +// Chris Krycho +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Ember from 'ember'; +import RSVP from 'rsvp'; + +export interface ModelRegistry {} +export interface AdapterRegistry {} +export interface SerializerRegistry {} +export interface TransformRegistry { + 'string': string; + 'boolean': boolean; + 'number': number; + 'date': Date; +} + +type AttributesFor = keyof Model; // TODO: filter to attr properties only (TS 2.8) +type RelationshipsFor = keyof Model; // TODO: filter to hasMany/belongsTo properties only (TS 2.8) + +export interface ChangedAttributes { + [key: string]: [any, any] | undefined; +} +interface AttributeMeta { + type: keyof TransformRegistry; + options: object; + name: AttributesFor; + parentType: Model; + isAttribute: true; +} +interface RelationshipMeta { + key: RelationshipsFor; + kind: 'belongsTo' | 'hasMany'; + type: keyof ModelRegistry; + options: object; + name: string; + parentType: Model; + isRelationship: true; +} + +export namespace DS { + /** + * Convert an hash of errors into an array with errors in JSON-API format. + */ + function errorsHashToArray(errors: {}): any[]; + /** + * Convert an array of errors in JSON-API format into an object. + */ + function errorsArrayToHash(errors: any[]): {}; + + interface RelationshipOptions { + async?: boolean; + inverse?: RelationshipsFor | null; + polymorphic?: boolean; + } + + interface Sync { async: false; } + interface Async { async?: true; } + + /** + * `DS.belongsTo` is used to define One-To-One and One-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function belongsTo( + modelName: K, + options: RelationshipOptions & Sync + ): Ember.ComputedProperty; + function belongsTo( + modelName: K, + options?: RelationshipOptions & Async + ): Ember.ComputedProperty, ModelRegistry[K]>; + /** + * `DS.hasMany` is used to define One-To-Many and Many-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function hasMany( + type: K, + options: RelationshipOptions & Sync + ): Ember.ComputedProperty>; + function hasMany( + type: K, + options?: RelationshipOptions & Async + ): Ember.ComputedProperty, Ember.Array>; + /** + * This method normalizes a modelName into the format Ember Data uses + * internally. + */ + function normalizeModelName(modelName: K): string; + const VERSION: string; + + interface AttrOptions { + defaultValue?: T | (() => T); + allowNull?: boolean; // TODO: restrict to boolean transform (TS 2.8) + } + + /** + * `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). + * By default, attributes are passed through as-is, however you can specify an + * optional type to have the value automatically transformed. + * Ember Data ships with four basic transform types: `string`, `number`, + * `boolean` and `date`. You can define your own transforms by subclassing + * [DS.Transform](/api/data/classes/DS.Transform.html). + */ + function attr( + type: K, + options?: AttrOptions + ): Ember.ComputedProperty; + function attr(options?: AttrOptions): Ember.ComputedProperty; + /** + * WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 + * ## Using BuildURLMixin + * To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. + * The default behaviour is designed for RESTAdapter. + * ### Example + * ```javascript + * export default DS.Adapter.extend(BuildURLMixin, { + * findRecord: function(store, type, id, snapshot) { + * var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); + * return this.ajax(url, 'GET'); + * } + * }); + * ``` + * ### Attributes + * The `host` and `namespace` attributes will be used if defined, and are optional. + */ + class BuildURLMixin { + /** + * Builds a URL for a given type and optional ID. + */ + buildURL( + modelName?: K, + id?: string | any[] | {} | null, + snapshot?: Snapshot | any[] | null, + requestType?: string, + query?: {} + ): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll( + modelName: K, + snapshot: SnapshotRecordArray + ): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: K): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: K): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany( + ids: any[], + modelName: K, + snapshots: any[] + ): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: K, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: K): string; + } + /** + * A `DS.AdapterError` is used by an adapter to signal that an error occurred + * during a request to an external API. It indicates a generic error, and + * subclasses are used to indicate specific error states. The following + * subclasses are provided: + */ + class AdapterError extends Ember.Object {} + /** + * A `DS.InvalidError` is used by an adapter to signal the external API + * was unable to process a request because the content was not + * semantically correct or meaningful per the API. Usually this means a + * record failed some form of server side validation. When a promise + * from an adapter is rejected with a `DS.InvalidError` the record will + * transition to the `invalid` state and the errors will be set to the + * `errors` property on the record. + */ + class InvalidError extends AdapterError { + constructor(errors: any[]); + } + /** + * A `DS.TimeoutError` is used by an adapter to signal that a request + * to the external API has timed out. I.e. no response was received from + * the external API within an allowed time period. + */ + class TimeoutError extends AdapterError {} + /** + * A `DS.AbortError` is used by an adapter to signal that a request to + * the external API was aborted. For example, this can occur if the user + * navigates away from the current page after a request to the external API + * has been initiated but before a response has been received. + */ + class AbortError extends AdapterError {} + /** + * A `DS.UnauthorizedError` equates to a HTTP `401 Unauthorized` response + * status. It is used by an adapter to signal that a request to the external + * API was rejected because authorization is required and has failed or has not + * yet been provided. + */ + class UnauthorizedError extends AdapterError {} + /** + * A `DS.ForbiddenError` equates to a HTTP `403 Forbidden` response status. + * It is used by an adapter to signal that a request to the external API was + * valid but the server is refusing to respond to it. If authorization was + * provided and is valid, then the authenticated user does not have the + * necessary permissions for the request. + */ + class ForbiddenError extends AdapterError {} + /** + * A `DS.NotFoundError` equates to a HTTP `404 Not Found` response status. + * It is used by an adapter to signal that a request to the external API + * was rejected because the resource could not be found on the API. + */ + class NotFoundError extends AdapterError {} + /** + * A `DS.ConflictError` equates to a HTTP `409 Conflict` response status. + * It is used by an adapter to indicate that the request could not be processed + * because of a conflict in the request. An example scenario would be when + * creating a record with a client generated id but that id is already known + * to the external API. + */ + class ConflictError extends AdapterError {} + /** + * A `DS.ServerError` equates to a HTTP `500 Internal Server Error` response + * status. It is used by the adapter to indicate that a request has failed + * because of an error in the external API. + */ + class ServerError extends AdapterError {} + /** + * Holds validation errors for a given record, organized by attribute names. + */ + interface Errors extends Ember.Enumerable, Ember.Evented {} + class Errors extends Ember.Object { + /** + * DEPRECATED: + * Register with target handler + */ + registerHandlers( + target: {}, + becameInvalid: Function, + becameValid: Function + ): any; + /** + * Returns errors for a given attribute + */ + errorsFor(attribute: string): any[]; + /** + * An array containing all of the error messages for this + * record. This is useful for displaying all errors to the user. + */ + messages: Ember.ComputedProperty; + /** + * Total number of errors. + */ + length: Ember.ComputedProperty; + isEmpty: Ember.ComputedProperty; + /** + * DEPRECATED: + * Adds error messages to a given attribute and sends + * `becameInvalid` event to the record. + */ + add(attribute: string, messages: any[] | string): any; + /** + * DEPRECATED: + * Removes all error messages from the given attribute and sends + * `becameValid` event to the record if there no more errors left. + */ + remove(attribute: string): any; + /** + * DEPRECATED: + * Removes all error messages and sends `becameValid` event + * to the record. + */ + clear(): any; + /** + * Checks if there is error messages for the given attribute. + */ + has(attribute: string): boolean; + } + /** + * The model class that all Ember Data records descend from. + * This is the public API of Ember Data models. If you are using Ember Data + * in your application, this is the class you should use. + * If you are working on Ember Data internals, you most likely want to be dealing + * with `InternalModel` + */ + class Model extends Ember.Object { + /** + * If this property is `true` the record is in the `empty` + * state. Empty is the first state all records enter after they have + * been created. Most records created by the store will quickly + * transition to the `loading` state if data needs to be fetched from + * the server or the `created` state if the record is created on the + * client. A record can also enter the empty state if the adapter is + * unable to locate the record. + */ + isEmpty: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loading` state. A + * record enters this state when the store asks the adapter for its + * data. It remains in this state until the adapter provides the + * requested data. + */ + isLoading: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loaded` state. A + * record enters this state when its data is populated. Most of a + * record's lifecycle is spent inside substates of the `loaded` + * state. + */ + isLoaded: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `dirty` state. The + * record has local changes that have not yet been saved by the + * adapter. This includes records that have been created (but not yet + * saved) or deleted. + */ + hasDirtyAttributes: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `saving` state. A + * record enters the saving state when `save` is called, but the + * adapter has not yet acknowledged that the changes have been + * persisted to the backend. + */ + isSaving: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `deleted` state + * and has been marked for deletion. When `isDeleted` is true and + * `hasDirtyAttributes` is true, the record is deleted locally but the deletion + * was not yet persisted. When `isSaving` is true, the change is + * in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the + * change has persisted. + */ + isDeleted: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `new` state. A + * record will be in the `new` state when it has been created on the + * client and the adapter has not yet report that it was successfully + * saved. + */ + isNew: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `valid` state. + */ + isValid: Ember.ComputedProperty; + /** + * If the record is in the dirty state this property will report what + * kind of change has caused it to move into the dirty + * state. Possible values are: + */ + dirtyType: Ember.ComputedProperty; + /** + * If `true` the adapter reported that it was unable to save local + * changes to the backend for any reason other than a server-side + * validation error. + */ + isError: boolean; + /** + * If `true` the store is attempting to reload the record from the adapter. + */ + isReloading: boolean; + /** + * All ember models have an id property. This is an identifier + * managed by an external source. These are always coerced to be + * strings before being used internally. Note when declaring the + * attributes for a model it is an error to declare an id + * attribute. + */ + id: string; + /** + * When the record is in the `invalid` state this object will contain + * any errors returned by the adapter. When present the errors hash + * contains keys corresponding to the invalid property names + * and values which are arrays of Javascript objects with two keys: + */ + errors: Ember.ComputedProperty; + /** + * This property holds the `DS.AdapterError` object with which + * last adapter operation was rejected. + */ + adapterError: AdapterError; + /** + * Create a JSON representation of the record, using the serialization + * strategy of the store's adapter. + */ + serialize(options?: { includeId?: boolean }): {}; + /** + * Use [DS.JSONSerializer](DS.JSONSerializer.html) to + * get the JSON representation of a record. + */ + toJSON(options: {}): {}; + /** + * Fired when the record is ready to be interacted with, + * that is either loaded from the server or created locally. + */ + ready(): void; + /** + * Fired when the record is loaded from the server. + */ + didLoad(): void; + /** + * Fired when the record is updated. + */ + didUpdate(): void; + /** + * Fired when a new record is commited to the server. + */ + didCreate(): void; + /** + * Fired when the record is deleted. + */ + didDelete(): void; + /** + * Fired when the record becomes invalid. + */ + becameInvalid(): void; + /** + * Fired when the record enters the error state. + */ + becameError(): void; + /** + * Fired when the record is rolled back. + */ + rolledBack(): void; + /** + * Marks the record as deleted but does not save it. You must call + * `save` afterwards if you want to persist it. You might use this + * method if you want to allow the user to still `rollbackAttributes()` + * after a delete was made. + */ + deleteRecord(): any; + /** + * Same as `deleteRecord`, but saves the record immediately. + */ + destroyRecord(options?: {}): RSVP.Promise; + /** + * Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(): any; + /** + * Returns an object, whose keys are changed properties, and value is + * an [oldProp, newProp] array. + */ + changedAttributes(): ChangedAttributes; + /** + * If the model `hasDirtyAttributes` this function will discard any unsaved + * changes. If the model `isNew` it will be removed from the store. + */ + rollbackAttributes(): any; + /** + * Save the record and persist any changes to the record to an + * external source via the adapter. + */ + save(options?: {}): RSVP.Promise; + /** + * Reload the record from the adapter. + */ + reload(): RSVP.Promise; + /** + * Get the reference for the specified belongsTo relationship. + */ + belongsTo(name: RelationshipsFor): BelongsToReference; + /** + * Get the reference for the specified hasMany relationship. + */ + hasMany(name: RelationshipsFor): HasManyReference; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + eachRelationship(callback: (name: string, details: RelationshipMeta) => void, binding?: any): any; + /** + * Represents the model's class name as a string. This can be used to look up the model's class name through + * `DS.Store`'s modelFor method. + */ + static modelName: keyof ModelRegistry; + /** + * For a given relationship name, returns the model type of the relationship. + */ + static typeForRelationship(name: K, store: Store): ModelRegistry[K]; + /** + * Find the relationship which is the inverse of the one asked for. + */ + static inverseFor(name: K, store: Store): {}; + /** + * The model's relationships as a map, keyed on the type of the + * relationship. The value of each entry is an array containing a descriptor + * for each relationship with that type, describing the name of the relationship + * as well as the type. + */ + static relationships: Ember.ComputedProperty; + /** + * A hash containing lists of the model's relationships, grouped + * by the relationship kind. For example, given a model with this + * definition: + */ + static relationshipNames: Ember.ComputedProperty<{}>; + /** + * An array of types directly related to a model. Each type will be + * included once, regardless of the number of relationships it has with + * the model. + */ + static relatedTypes: Ember.ComputedProperty< + Ember.NativeArray + >; + /** + * A map whose keys are the relationships of a model and whose values are + * relationship descriptors. + */ + static relationshipsByName: Ember.ComputedProperty; + /** + * A map whose keys are the fields of the model and whose values are strings + * describing the kind of the field. A model's fields are the union of all of its + * attributes and relationships. + */ + static fields: Ember.ComputedProperty; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + static eachRelationship(callback: (name: string, details: RelationshipMeta) => void, binding?: any): any; + /** + * Given a callback, iterates over each of the types related to a model, + * invoking the callback with the related type's class. Each type will be + * returned just once, regardless of how many different relationships it has + * with a model. + */ + static eachRelatedType(callback: Function, binding: any): any; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are the meta object for the + * property. + */ + static attributes: Ember.ComputedProperty; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are type of transformation + * applied to each attribute. This map does not include any + * attributes that do not have an transformation type. + */ + static transformedAttributes: Ember.ComputedProperty; + /** + * Iterates through the attributes of the model, calling the passed function on each + * attribute. + */ + static eachAttribute(callback: Function, binding: {}): any; + /** + * Iterates through the transformedAttributes of the model, calling + * the passed function on each attribute. Note the callback will not be + * called for any attributes that do not have an transformation type. + */ + static eachTransformedAttribute( + callback: Function, + binding: {} + ): any; + /** + * Discards any unsaved changes to the given attribute. This feature is not enabled by default. You must enable `ds-rollback-attribute` and be running a canary build. + */ + rollbackAttribute(): any; + /** + * This Ember.js hook allows an object to be notified when a property + * is defined. + */ + didDefineProperty( + proto: {}, + key: string, + value: Ember.ComputedProperty + ): any; + } + /** + * ### State + */ + class RootState {} + /** + * Represents an ordered list of records whose order and membership is + * determined by the adapter. For example, a query sent to the adapter + * may trigger a search on the server, whose results would be loaded + * into an instance of the `AdapterPopulatedRecordArray`. + */ + class AdapterPopulatedRecordArray extends RecordArray {} + /** + * Represents a list of records whose membership is determined by the + * store. As records are created, loaded, or modified, the store + * evaluates them to determine if they should be part of the record + * array. + */ + class FilteredRecordArray extends RecordArray { + /** + * The filterFunction is a function used to test records from the store to + * determine if they should be part of the record array. + */ + filterFunction(record: Model): boolean; + } + /** + * A record array is an array that contains records of a certain modelName. The record + * array materializes records as needed when they are retrieved for the first + * time. You should not create record arrays yourself. Instead, an instance of + * `DS.RecordArray` or its subclasses will be returned by your application's store + * in response to queries. + */ + interface RecordArray extends Ember.ArrayProxy, Ember.Evented {} + class RecordArray { + /** + * The flag to signal a `RecordArray` is finished loading data. + */ + isLoaded: boolean; + /** + * The flag to signal a `RecordArray` is currently loading data. + */ + isUpdating: boolean; + /** + * The modelClass represented by this record array. + */ + type: Ember.ComputedProperty; + /** + * Used to get the latest version of all of the records in this array + * from the adapter. + */ + update(): any; + /** + * Saves all of the records in the `RecordArray`. + */ + save(): PromiseArray; + } + /** + * A BelongsToReference is a low level API that allows users and + * addon author to perform meta-operations on a belongs-to + * relationship. + */ + class BelongsToReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The `id` of the record that this reference refers to. Together, the + * `type()` and `id()` methods form a composite key for the identity + * map. This can be used to access the id of an async relationship + * without triggering a fetch that would normally happen if you + * attempted to use `record.get('relationship.id')`. + */ + id(): string; + /** + * The link Ember Data will use to fetch or reload this belongs-to + * relationship. + */ + link(): string; + /** + * The meta data for the belongs-to relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the conanical value of this + * relationship on the backend. + */ + push(objectOrPromise: {} | RSVP.Promise): RSVP.Promise; + /** + * `value()` synchronously returns the current value of the belongs-to + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(objectOrPromise: {} | RSVP.Promise): Model; + /** + * Loads a record in a belongs to relationship if it is not already + * loaded. If the relationship is already loaded this method does not + * trigger a new load. + */ + load(): RSVP.Promise; + /** + * Triggers a reload of the value in this relationship. If the + * remoteType is `"link"` Ember Data will use the relationship link to + * reload the relationship. Otherwise it will reload the record by its + * id. + */ + reload(): RSVP.Promise; + } + /** + * A HasManyReference is a low level API that allows users and addon + * author to perform meta-operations on a has-many relationship. + */ + class HasManyReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The link Ember Data will use to fetch or reload this has-many + * relationship. + */ + link(): string; + /** + * `ids()` returns an array of the record ids in this relationship. + */ + ids(): any[]; + /** + * The meta data for the has-many relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the canonical value of this + * relationship on the backend. + */ + push(objectOrPromise: T[] | RSVP.Promise): ManyArray; + /** + * `value()` synchronously returns the current value of the has-many + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(): ManyArray; + /** + * Loads the relationship if it is not already loaded. If the + * relationship is already loaded this method does not trigger a new + * load. + */ + load(): RSVP.Promise; + /** + * Reloads this has-many relationship. + */ + reload(): RSVP.Promise; + } + /** + * An RecordReference is a low level API that allows users and + * addon author to perform meta-operations on a record. + */ + class RecordReference { + /** + * The `id` of the record that this reference refers to. + */ + id(): string; + /** + * How the reference will be looked up when it is loaded: Currently + * this always return `identity` to signifying that a record will be + * loaded by the `type` and `id`. + */ + remoteType(): string; + /** + * This API allows you to provide a reference with new data. The + * simplest usage of this API is similar to `store.push`: you provide a + * normalized hash of data and the object represented by the reference + * will update. + */ + push(payload: RSVP.Promise | {}): PromiseObject & T; + /** + * If the entity referred to by the reference is already loaded, it is + * present as `reference.value`. Otherwise the value returned by this function + * is `null`. + */ + value(): T | null; + /** + * Triggers a fetch for the backing entity based on its `remoteType` + * (see `remoteType` definitions per reference type). + */ + load(): PromiseObject & T; + /** + * Reloads the record if it is already loaded. If the record is not + * loaded it will load the record via `store.findRecord` + */ + reload(): PromiseObject & T; + } + /** + * A `ManyArray` is a `MutableArray` that represents the contents of a has-many + * relationship. + */ + interface ManyArray extends Ember.MutableArray {} + class ManyArray extends Ember.Object.extend( + Ember.MutableArray as {}, + Ember.Evented + ) { + /** + * The loading state of this array + */ + isLoaded: boolean; + /** + * Metadata associated with the request for async hasMany relationships. + */ + meta: {}; + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseArray; + /** + * Saves all of the records in the `ManyArray`. + */ + save(): PromiseArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + /** + * A `PromiseArray` is an object that acts like both an `Ember.Array` + * and a promise. When the promise is resolved the resulting value + * will be set to the `PromiseArray`'s `content` property. This makes + * it easy to create data bindings with the `PromiseArray` that will be + * updated when the promise resolves. + */ + interface PromiseArray + extends Ember.ArrayProxy, + Ember.PromiseProxyMixin> {} + class PromiseArray {} + /** + * A `PromiseObject` is an object that acts like both an `Ember.Object` + * and a promise. When the promise is resolved, then the resulting value + * will be set to the `PromiseObject`'s `content` property. This makes + * it easy to create data bindings with the `PromiseObject` that will + * be updated when the promise resolves. + */ + interface PromiseObject + extends Ember.ObjectProxy, + Ember.PromiseProxyMixin {} + class PromiseObject {} + /** + * A PromiseManyArray is a PromiseArray that also proxies certain method calls + * to the underlying manyArray. + * Right now we proxy: + */ + class PromiseManyArray extends PromiseArray { + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseManyArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + class SnapshotRecordArray { + /** + * Number of records in the array + */ + length: number; + /** + * Meta objects for the record array. + */ + meta: {}; + /** + * A hash of adapter options passed into the store method for this request. + */ + adapterOptions: {}; + /** + * The relationships to include for this request. + */ + include: string | any[]; + /** + * The type of the underlying records for the snapshots in the array, as a DS.Model + */ + type: ModelRegistry[K]; + /** + * Get snapshots of the underlying record array + */ + snapshots(): any[]; + } + class Snapshot { + /** + * The underlying record for this snapshot. Can be used to access methods and + * properties defined on the record. + */ + record: ModelRegistry[K]; + /** + * The id of the snapshot's underlying record + */ + id: string; + /** + * A hash of adapter options + */ + adapterOptions: {}; + /** + * The name of the type of the underlying record for this snapshot, as a string. + */ + modelName: K; + /** + * The type of the underlying record for this snapshot, as a DS.Model. + */ + type: ModelRegistry[K]; + /** + * Returns the value of an attribute. + */ + attr>(keyName: L): ModelRegistry[K][L]; + /** + * Returns all attributes and their corresponding values. + */ + attributes(): { [L in keyof ModelRegistry[K]]: ModelRegistry[K][L] }; + /** + * Returns all changed attributes and their old and new values. + */ + changedAttributes(): Partial<{ [L in keyof ModelRegistry[K]]: ModelRegistry[K][L] }>; + /** + * Returns the current value of a belongsTo relationship. + */ + belongsTo>( + keyName: L, + options?: {} + ): Snapshot['record'][L] | string | null | undefined; + /** + * Returns the current value of a hasMany relationship. + */ + hasMany>( + keyName: L, + options?: { ids: false } + ): Array['record'][L]> | undefined; + hasMany>( + keyName: L, + options: { ids: true } + ): string[] | undefined; + /** + * Iterates through all the attributes of the model, calling the passed + * function on each attribute. + */ + eachAttribute(callback: (key: keyof M, meta: AttributeMeta) => void, binding?: {}): any; + /** + * Iterates through all the relationships of the model, calling the passed + * function on each relationship. + */ + eachRelationship(callback: (key: keyof M, meta: RelationshipMeta) => void, binding?: {}): any; + /** + * Serializes the snapshot using the serializer for the model. + */ + serialize(options: {}): {}; + } + + /** + * The store contains all of the data for records loaded from the server. + * It is also responsible for creating instances of `DS.Model` that wrap + * the individual data for a record, so that they can be bound to in your + * Handlebars templates. + */ + class Store { + /** + * The default adapter to use to communicate to a backend server or + * other persistence layer. This will be overridden by an application + * adapter if present. + */ + adapter: string; + /** + * Create a new record in the current store. The properties passed + * to this method are set on the newly created record. + */ + createRecord( + modelName: K, + inputProperties?: {} + ): ModelRegistry[K]; + /** + * For symmetry, a record can be deleted via the store. + */ + deleteRecord(record: Model): void; + /** + * For symmetry, a record can be unloaded via the store. + * This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(record: Model): void; + /** + * This method returns a record for a given type and id combination. + */ + findRecord( + modelName: K, + id: string | number, + options?: {} + ): PromiseObject & ModelRegistry[K]; + /** + * Get the reference for the specified record. + */ + getReference( + modelName: K, + id: string | number + ): RecordReference; + /** + * Get a record by a given type and ID without triggering a fetch. + */ + peekRecord( + modelName: K, + id: string | number + ): ModelRegistry[K] | null; + /** + * This method returns true if a record for a given modelName and id is already + * loaded in the store. Use this function to know beforehand if a findRecord() + * will result in a request or that it will be a cache hit. + */ + hasRecordForId( + modelName: K, + id: string | number + ): boolean; + /** + * This method delegates a query to the adapter. This is the one place where + * adapter-level semantics are exposed to the application. + */ + query( + modelName: K, + query: any + ): AdapterPopulatedRecordArray & PromiseArray; + /** + * This method makes a request for one record, where the `id` is not known + * beforehand (if the `id` is known, use [`findRecord`](#method_findRecord) + * instead). + */ + queryRecord( + modelName: K, + query: any + ): RSVP.Promise; + /** + * `findAll` asks the adapter's `findAll` method to find the records for the + * given type, and returns a promise which will resolve with all records of + * this type present in the store, even if the adapter only returns a subset + * of them. + */ + findAll( + modelName: K, + options?: { + reload?: boolean; + backgroundReload?: boolean; + include?: string; + adapterOptions?: any; + } + ): PromiseArray; + /** + * This method returns a filtered array that contains all of the + * known records for a given type in the store. + */ + peekAll(modelName: K): RecordArray; + /** + * This method unloads all records in the store. + * It schedules unloading to happen during the next run loop. + */ + unloadAll(modelName: K): void; + /** + * DEPRECATED: + * This method has been deprecated and is an alias for store.hasRecordForId, which should + * be used instead. + */ + recordIsLoaded(modelName: K, id: string): boolean; + /** + * Returns the model class for the particular `modelName`. + */ + modelFor(modelName: K): ModelRegistry[K]; + /** + * Push some data for a given type into the store. + */ + push(data: {}): Model | any[]; + /** + * Push some raw data into the store. + */ + pushPayload(modelName: K, inputPayload: {}): any; + pushPayload(inputPayload: {}): any; + /** + * `normalize` converts a json payload into the normalized form that + * [push](#method_push) expects. + */ + normalize(modelName: K, payload: {}): {}; + /** + * Returns an instance of the adapter for a given type. For + * example, `adapterFor('person')` will return an instance of + * `App.PersonAdapter`. + */ + adapterFor(modelName: K): AdapterRegistry[K]; + /** + * Returns an instance of the serializer for a given type. For + * example, `serializerFor('person')` will return an instance of + * `App.PersonSerializer`. + */ + serializerFor(modelName: K): SerializerRegistry[K]; + } + /** + * The `JSONAPIAdapter` is the default adapter used by Ember Data. It + * is responsible for transforming the store's requests into HTTP + * requests that follow the [JSON API](http://jsonapi.org/format/) + * format. + */ + class JSONAPIAdapter extends RESTAdapter { + /** + * By default the JSONAPIAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + } + /** + * The REST adapter allows your store to communicate with an HTTP server by + * transmitting JSON via XHR. Most Ember.js apps that consume a JSON API + * should use the REST adapter. + */ + class RESTAdapter extends Adapter implements BuildURLMixin { + /** + * Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. + */ + ajax( + url: string, + type: string, + options?: object + ): RSVP.Promise; + /** + * Generate ajax options + */ + ajaxOptions(url: string, type: string, options?: object): object; + /** + * By default, the RESTAdapter will send the query params sorted alphabetically to the + * server. + */ + sortQueryParams(obj: {}): {}; + /** + * By default the RESTAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + /** + * Endpoint paths can be prefixed with a `namespace` by setting the namespace + * property on the adapter: + */ + namespace: string; + /** + * An adapter can target other hosts by setting the `host` property. + */ + host: string; + /** + * Some APIs require HTTP headers, e.g. to provide an API + * key. Arbitrary headers can be set as key/value pairs on the + * `RESTAdapter`'s `headers` object and Ember Data will send them + * along with each ajax request. For dynamic headers see [headers + * customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). + */ + headers: {}; + /** + * Called by the store in order to fetch the JSON for a given + * type and ID. + */ + findRecord( + store: Store, + type: ModelRegistry[K], + id: string, + snapshot: Snapshot + ): RSVP.Promise; + /** + * Called by the store in order to fetch a JSON array for all + * of the records for a given type. + */ + findAll( + store: Store, + type: ModelRegistry[K], + sinceToken: string, + snapshotRecordArray: SnapshotRecordArray + ): RSVP.Promise; + /** + * Called by the store in order to fetch a JSON array for + * the records that match a particular query. + */ + query(store: Store, type: ModelRegistry[K], query: {}): RSVP.Promise; + /** + * Called by the store in order to fetch a JSON object for + * the record that matches a particular query. + */ + queryRecord( + store: Store, + type: ModelRegistry[K], + query: {} + ): RSVP.Promise; + /** + * Called by the store in order to fetch several records together if `coalesceFindRequests` is true + */ + findMany( + store: Store, + type: ModelRegistry[K], + ids: any[], + snapshots: any[] + ): RSVP.Promise; + /** + * Called by the store in order to fetch a JSON array for + * the unloaded records in a has-many relationship that were originally + * specified as a URL (inside of `links`). + */ + findHasMany( + store: Store, + snapshot: Snapshot, + url: string, + relationship: {} + ): RSVP.Promise; + /** + * Called by the store in order to fetch the JSON for the unloaded record in a + * belongs-to relationship that was originally specified as a URL (inside of + * `links`). + */ + findBelongsTo( + store: Store, + snapshot: Snapshot, + url: string + ): RSVP.Promise; + /** + * Called by the store when a newly created record is + * saved via the `save` method on a model record instance. + */ + createRecord( + store: Store, + type: ModelRegistry[K], + snapshot: Snapshot + ): RSVP.Promise; + /** + * Called by the store when an existing record is saved + * via the `save` method on a model record instance. + */ + updateRecord( + store: Store, + type: ModelRegistry[K], + snapshot: Snapshot + ): RSVP.Promise; + /** + * Called by the store when a record is deleted. + */ + deleteRecord( + store: Store, + type: ModelRegistry[K], + snapshot: Snapshot + ): RSVP.Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * Takes an ajax response, and returns the json payload or an error. + */ + handleResponse( + status: number, + headers: {}, + payload: {}, + requestData: {} + ): {}; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is a success. + */ + isSuccess(status: number, headers: {}, payload: {}): boolean; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is an invalid error. + */ + isInvalid(status: number, headers: {}, payload: {}): boolean; + /** + * Get the data (body or query params) for a request. + */ + dataForRequest(params: {}): {}; + /** + * Get the HTTP method for a request. + */ + methodForRequest(params: {}): string; + /** + * Get the URL for a request. + */ + urlForRequest(params: {}): string; + /** + * Get the headers for a request. + */ + headersForRequest(params: {}): {}; + /** + * Builds a URL for a given type and optional ID. + */ + buildURL( + modelName?: K, + id?: string | any[] | {} | null, + snapshot?: Snapshot | any[] | null, + requestType?: string, + query?: {} + ): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll( + modelName: K, + snapshot: SnapshotRecordArray + ): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: K): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: K): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany( + ids: any[], + modelName: K, + snapshots: any[] + ): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: K, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord( + id: string, + modelName: K, + snapshot: Snapshot + ): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: K): string; + } + /** + * ## Using Embedded Records + */ + class EmbeddedRecordsMixin { + /** + * Normalize the record and recursively normalize/extract all the embedded records + * while pushing them into the store as they are encountered + */ + normalize(typeClass: Model, hash: {}, prop: string): {}; + /** + * Serialize `belongsTo` relationship when it is configured as an embedded object. + */ + serializeBelongsTo( + snapshot: Snapshot, + json: {}, + relationship: {} + ): any; + /** + * Serializes `hasMany` relationships when it is configured as embedded objects. + */ + serializeHasMany( + snapshot: Snapshot, + json: {}, + relationship: {} + ): any; + /** + * When serializing an embedded record, modify the property (in the json payload) + * that refers to the parent record (foreign key for relationship). + */ + removeEmbeddedForeignKey( + snapshot: Snapshot, + embeddedSnapshot: Snapshot, + relationship: {}, + json: {} + ): any; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONAPISerializer extends JSONSerializer { + pushPayload(store: Store, payload: {}): any; + /** + * Dasherizes and singularizes the model name in the payload to match + * the format Ember Data uses internally for the model name. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Converts the model name to a pluralized version of the model name. + */ + payloadKeyFromModelName(modelName: K): string; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as the word separator in the JSON + * attribute keys. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as word separators in + * relationship properties. + */ + keyForRelationship( + key: string, + typeClass: string, + method: string + ): string; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelName: K): string; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONSerializer extends Serializer { + /** + * The `primaryKey` is used when serializing and deserializing + * data. Ember Data always uses the `id` property to store the id of + * the record. The external source may not always follow this + * convention. In these cases it is useful to override the + * `primaryKey` property to match the `primaryKey` of your external + * store. + */ + primaryKey: string; + /** + * The `attrs` object can be used to declare a simple mapping between + * property names on `DS.Model` records and payload keys in the + * serialized JSON object representing the record. An object with the + * property `key` can also be used to designate the attribute's key on + * the response payload. + */ + attrs: {}; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeFindRecordResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeQueryRecordResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeFindAllResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeFindBelongsToResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeFindHasManyResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeFindManyResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeQueryResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeCreateRecordResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeDeleteRecordResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeUpdateRecordResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeSaveResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeSingleResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + normalizeArrayResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(typeClass: Model, hash: {}): {}; + /** + * Returns the resource's ID. + */ + extractId(modelClass: {}, resourceHash: {}): string; + /** + * Returns the resource's attributes formatted as a JSON-API "attributes object". + */ + extractAttributes(modelClass: {}, resourceHash: {}): {}; + /** + * Returns a relationship formatted as a JSON-API "relationship object". + */ + extractRelationship( + relationshipModelName: {}, + relationshipHash: {} + ): {}; + /** + * Returns a polymorphic relationship formatted as a JSON-API "relationship object". + */ + extractPolymorphicRelationship( + relationshipModelName: {}, + relationshipHash: {}, + relationshipOptions: {} + ): {}; + /** + * Returns the resource's relationships formatted as a JSON-API "relationships object". + */ + extractRelationships(modelClass: {}, resourceHash: {}): {}; + modelNameFromPayloadKey(key: string): string; + /** + * Check if the given hasMany relationship should be serialized + */ + shouldSerializeHasMany( + snapshot: Snapshot, + key: string, + relationshipType: string + ): boolean; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize how a serialized record is added to the complete + * JSON hash to be sent to the server. By default the JSON Serializer does not namespace + * the payload and just sends the raw serialized JSON object. + * If your server expects namespaced keys, you should consider using the RESTSerializer. + * Otherwise you can override this method to customize how the record is added to the hash. + * The hash property should be modified by reference. + */ + serializeIntoHash( + hash: {}, + typeClass: ModelRegistry[K], + snapshot: Snapshot, + options?: {} + ): any; + /** + * `serializeAttribute` can be used to customize how `DS.attr` + * properties are serialized + */ + serializeAttribute( + snapshot: Snapshot, + json: {}, + key: string, + attribute: {} + ): any; + /** + * `serializeBelongsTo` can be used to customize how `DS.belongsTo` + * properties are serialized. + */ + serializeBelongsTo( + snapshot: Snapshot, + json: {}, + relationship: {} + ): any; + /** + * `serializeHasMany` can be used to customize how `DS.hasMany` + * properties are serialized. + */ + serializeHasMany( + snapshot: Snapshot, + json: {}, + relationship: {} + ): any; + /** + * You can use this method to customize how polymorphic objects are + * serialized. Objects are considered to be polymorphic if + * `{ polymorphic: true }` is pass as the second argument to the + * `DS.belongsTo` function. + */ + serializePolymorphicType( + snapshot: Snapshot, + json: {}, + relationship: {} + ): any; + /** + * `extractMeta` is used to deserialize any meta information in the + * adapter payload. By default Ember Data expects meta information to + * be located on the `meta` property of the payload object. + */ + extractMeta(store: Store, modelClass: Model, payload: {}): any; + /** + * `extractErrors` is used to extract model errors when a call + * to `DS.Model#save` fails with an `InvalidError`. By default + * Ember Data expects error information to be located on the `errors` + * property of the payload object. + */ + extractErrors( + store: Store, + typeClass: Model, + payload: {}, + id: string | number + ): {}; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. By default + * `JSONSerializer` does not provide an implementation of this method. + */ + keyForRelationship( + key: string, + typeClass: string, + method: string + ): string; + /** + * `keyForLink` can be used to define a custom key when deserializing link + * properties. + */ + keyForLink(key: string, kind: string): string; + modelNameFromPayloadType(type: string): string; + /** + * serializeId can be used to customize how id is serialized + * For example, your server may expect integer datatype of id + */ + serializeId(snapshot: Snapshot, json: {}, primaryKey: string): any; + } + /** + * Normally, applications will use the `RESTSerializer` by implementing + * the `normalize` method. + */ + class RESTSerializer extends JSONSerializer { + /** + * `keyForPolymorphicType` can be used to define a custom key when + * serializing and deserializing a polymorphic type. By default, the + * returned key is `${key}Type`. + */ + keyForPolymorphicType( + key: string, + typeClass: string, + method: string + ): string; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(modelClass: Model, resourceHash: {}, prop?: string): {}; + /** + * This method allows you to push a payload containing top-level + * collections of records organized per type. + */ + pushPayload(store: Store, payload: {}): any; + /** + * This method is used to convert each JSON root key in the payload + * into a modelName that it can use to look up the appropriate model for + * that part of the payload. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize the root keys serialized into the JSON. + * The hash property should be modified by reference (possibly using something like _.extend) + * By default the REST Serializer sends the modelName of a model, which is a camelized + * version of the name. + */ + serializeIntoHash( + hash: {}, + typeClass: Model, + snapshot: Snapshot, + options?: {} + ): any; + /** + * You can use `payloadKeyFromModelName` to override the root key for an outgoing + * request. By default, the RESTSerializer returns a camelized version of the + * model's name. + */ + payloadKeyFromModelName(modelName: K): string; + /** + * You can use this method to customize how polymorphic objects are serialized. + * By default the REST Serializer creates the key by appending `Type` to + * the attribute and value from the model's camelcased model name. + */ + serializePolymorphicType( + snapshot: Snapshot, + json: {}, + relationship: {} + ): any; + /** + * You can use this method to customize how a polymorphic relationship should + * be extracted. + */ + extractPolymorphicRelationship( + relationshipType: {}, + relationshipHash: {}, + relationshipOptions: {} + ): {}; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelName: K): string; + } + /** + * The `DS.BooleanTransform` class is used to serialize and deserialize + * boolean attributes on Ember Data record objects. This transform is + * used when `boolean` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class BooleanTransform extends Transform {} + /** + * The `DS.DateTransform` class is used to serialize and deserialize + * date attributes on Ember Data record objects. This transform is used + * when `date` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. It uses the [`ISO 8601`](https://en.wikipedia.org/wiki/ISO_8601) + * standard. + */ + class DateTransform extends Transform {} + /** + * The `DS.NumberTransform` class is used to serialize and deserialize + * numeric attributes on Ember Data record objects. This transform is + * used when `number` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class NumberTransform extends Transform {} + /** + * The `DS.StringTransform` class is used to serialize and deserialize + * string attributes on Ember Data record objects. This transform is + * used when `string` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class StringTransform extends Transform {} + /** + * The `DS.Transform` class is used to serialize and deserialize model + * attributes when they are saved or loaded from an + * adapter. Subclassing `DS.Transform` is useful for creating custom + * attributes. All subclasses of `DS.Transform` must implement a + * `serialize` and a `deserialize` method. + */ + class Transform extends Ember.Object { + /** + * When given a deserialized value from a record attribute this + * method must return the serialized value. + */ + serialize(deserialized: any, options: AttrOptions): any; + /** + * When given a serialize value from a JSON object this method must + * return the deserialized value for the record attribute. + */ + deserialize(serialized: any, options: AttrOptions): any; + } + /** + * An adapter is an object that receives requests from a store and + * translates them into the appropriate action to take against your + * persistence layer. The persistence layer is usually an HTTP API, but + * may be anything, such as the browser's local storage. Typically the + * adapter is not invoked directly instead its functionality is accessed + * through the `store`. + */ + class Adapter extends Ember.Object { + /** + * If you would like your adapter to use a custom serializer you can + * set the `defaultSerializer` property to be the name of the custom + * serializer. + */ + defaultSerializer: string; + /** + * The `findRecord()` method is invoked when the store is asked for a record that + * has not previously been loaded. In response to `findRecord()` being called, you + * should query your persistence layer for a record with the given ID. The `findRecord` + * method should return a promise that will resolve to a JavaScript object that will be + * normalized by the serializer. + */ + findRecord( + store: Store, + type: ModelRegistry[K], + id: string, + snapshot: Snapshot + ): RSVP.Promise; + /** + * The `findAll()` method is used to retrieve all records for a given type. + */ + findAll( + store: Store, + type: ModelRegistry[K], + sinceToken: string, + snapshotRecordArray: SnapshotRecordArray + ): RSVP.Promise; + /** + * This method is called when you call `query` on the store. + */ + query( + store: Store, + type: ModelRegistry[K], + query: {}, + recordArray: AdapterPopulatedRecordArray + ): RSVP.Promise; + /** + * The `queryRecord()` method is invoked when the store is asked for a single + * record through a query object. + */ + queryRecord( + store: Store, + type: ModelRegistry[K], + query: {} + ): RSVP.Promise; + /** + * If the globally unique IDs for your records should be generated on the client, + * implement the `generateIdForRecord()` method. This method will be invoked + * each time you create a new record, and the value returned from it will be + * assigned to the record's `primaryKey`. + */ + generateIdForRecord( + store: Store, + type: ModelRegistry[K], + inputProperties: {} + ): string | number; + /** + * Proxies to the serializer's `serialize` method. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * Implement this method in a subclass to handle the creation of + * new records. + */ + createRecord( + store: Store, + type: ModelRegistry[K], + snapshot: Snapshot + ): RSVP.Promise; + /** + * Implement this method in a subclass to handle the updating of + * a record. + */ + updateRecord( + store: Store, + type: ModelRegistry[K], + snapshot: Snapshot + ): RSVP.Promise; + /** + * Implement this method in a subclass to handle the deletion of + * a record. + */ + deleteRecord( + store: Store, + type: ModelRegistry[K], + snapshot: Snapshot + ): RSVP.Promise; + /** + * By default the store will try to coalesce all `fetchRecord` calls within the same runloop + * into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. + * You can opt out of this behaviour by either not implementing the findMany hook or by setting + * coalesceFindRequests to false. + */ + coalesceFindRequests: boolean; + /** + * The store will call `findMany` instead of multiple `findRecord` + * requests to find multiple records at once if coalesceFindRequests + * is true. + */ + findMany( + store: Store, + type: ModelRegistry[K], + ids: any[], + snapshots: any[] + ): RSVP.Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * This method is used by the store to determine if the store should + * reload a record from the adapter when a record is requested by + * `store.findRecord`. + */ + shouldReloadRecord(store: Store, snapshot: Snapshot): boolean; + /** + * This method is used by the store to determine if the store should + * reload all records from the adapter when records are requested by + * `store.findAll`. + */ + shouldReloadAll( + store: Store, + snapshotRecordArray: SnapshotRecordArray + ): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record after the `store.findRecord` method resolves a + * cached record. + */ + shouldBackgroundReloadRecord( + store: Store, + snapshot: Snapshot + ): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record array after the `store.findAll` method resolves + * with a cached record array. + */ + shouldBackgroundReloadAll( + store: Store, + snapshotRecordArray: SnapshotRecordArray + ): boolean; + } + /** + * `DS.Serializer` is an abstract base class that you should override in your + * application to customize it for your backend. The minimum set of methods + * that you should implement is: + */ + class Serializer extends Ember.Object { + /** + * The `store` property is the application's `store` that contains + * all records. It can be used to look up serializers for other model + * types that may be nested inside the payload response. + */ + store: Store; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse( + store: Store, + primaryModelClass: Model, + payload: {}, + id: string | number, + requestType: string + ): {}; + /** + * The `serialize` method is used when a record is saved in order to convert + * the record into the form that your external data source expects. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * The `normalize` method is used to convert a payload received from your + * external data source into the normalized form `store.push()` expects. You + * should override this method, munge the hash and return the normalized + * payload. + */ + normalize(typeClass: Model, hash: {}): {}; + } +} + +export default DS; + +declare module 'ember' { + namespace Ember { + /* + * The store is automatically injected into these objects + * + * https://github.com/emberjs/data/blob/05e95280e11c411177f2fbcb65fd83488d6a9d89/addon/setup-container.js#L71-L78 + */ + interface Route { + store: DS.Store; + } + interface Controller { + store: DS.Store; + } + interface DataAdapter { + store: DS.Store; + } + } + + // It is also available to inject anywhere +} + +declare module '@ember/service' { + interface Registry { + 'store': DS.Store; + } +} + +declare module 'ember-test-helpers' { + interface TestContext { + store: DS.Store; + } +} diff --git a/types/ember-data/v2/model.d.ts b/types/ember-data/v2/model.d.ts new file mode 100644 index 0000000000..026a70f534 --- /dev/null +++ b/types/ember-data/v2/model.d.ts @@ -0,0 +1,4 @@ +import { DS } from 'ember-data'; + +export default DS.Model; +export { ModelRegistry } from 'ember-data'; diff --git a/types/ember-data/v2/relationships.d.ts b/types/ember-data/v2/relationships.d.ts new file mode 100644 index 0000000000..033e07da29 --- /dev/null +++ b/types/ember-data/v2/relationships.d.ts @@ -0,0 +1,4 @@ +import DS from 'ember-data'; + +declare const hasMany: typeof DS.hasMany; +declare const belongsTo: typeof DS.belongsTo; diff --git a/types/ember-data/v2/serializer.d.ts b/types/ember-data/v2/serializer.d.ts new file mode 100644 index 0000000000..998f50c1a2 --- /dev/null +++ b/types/ember-data/v2/serializer.d.ts @@ -0,0 +1,4 @@ +import DS from 'ember-data'; + +export default DS.Serializer; +export { SerializerRegistry } from 'ember-data'; diff --git a/types/ember-data/v2/serializers/embedded-records-mixin.d.ts b/types/ember-data/v2/serializers/embedded-records-mixin.d.ts new file mode 100644 index 0000000000..209a3cd920 --- /dev/null +++ b/types/ember-data/v2/serializers/embedded-records-mixin.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.EmbeddedRecordsMixin; diff --git a/types/ember-data/v2/serializers/json-api.d.ts b/types/ember-data/v2/serializers/json-api.d.ts new file mode 100644 index 0000000000..3619a4aa2b --- /dev/null +++ b/types/ember-data/v2/serializers/json-api.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.JSONAPISerializer; diff --git a/types/ember-data/v2/serializers/json.d.ts b/types/ember-data/v2/serializers/json.d.ts new file mode 100644 index 0000000000..b1ddf2c768 --- /dev/null +++ b/types/ember-data/v2/serializers/json.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.JSONSerializer; diff --git a/types/ember-data/v2/serializers/rest.d.ts b/types/ember-data/v2/serializers/rest.d.ts new file mode 100644 index 0000000000..114c96ff7b --- /dev/null +++ b/types/ember-data/v2/serializers/rest.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.RESTSerializer; diff --git a/types/ember-data/v2/store.d.ts b/types/ember-data/v2/store.d.ts new file mode 100644 index 0000000000..e222f3c06f --- /dev/null +++ b/types/ember-data/v2/store.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.Store; diff --git a/types/ember-data/v2/test/adapter.ts b/types/ember-data/v2/test/adapter.ts new file mode 100644 index 0000000000..101ac3e42f --- /dev/null +++ b/types/ember-data/v2/test/adapter.ts @@ -0,0 +1,120 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +class Session extends Ember.Service {} +declare module '@ember/service' { + interface Registry { 'session': Session; } +} + +const JsonApi = DS.JSONAPIAdapter.extend({ + // Application specific overrides go here +}); + +const Customized = DS.JSONAPIAdapter.extend({ + host: 'https://api.example.com', + namespace: 'api/v1', + headers: { + 'API_KEY': 'secret key', + 'ANOTHER_HEADER': 'Some header value' + } +}); + +const AuthTokenHeader = DS.JSONAPIAdapter.extend({ + session: Ember.inject.service('session'), + headers: Ember.computed('session.authToken', function() { + return { + 'API_KEY': this.get('session.authToken'), + 'ANOTHER_HEADER': 'Some header value' + }; + }) +}); + +const UseAjax = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + return this.ajax(url, 'POST', { + param: 'foo' + }); + } +}); + +const UseAjaxOptions = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + const options = this.ajaxOptions(url, 'DELETE', { + foo: 'bar' + }); + return Ember.$.ajax(url, { + ...options + }); + } +}); + +const UseAjaxOptionsWithOptionalThirdParams = DS.JSONAPIAdapter.extend({ + query(store: DS.Store, type: string, query: object) { + const url = 'https://api.example.com/my-api'; + const options = this.ajaxOptions(url, 'DELETE'); + return Ember.$.ajax(url, { + ...options + }); + } +}); + +declare module 'ember-data' { + interface ModelRegistry { + 'rootModel': any; + 'super-user': any; + } +} + +// https://github.com/emberjs/data/blob/c9d8212c857ca78218ad98d11621819b38dba98f/tests/unit/adapters/build-url-mixin/build-url-test.js +const BuildURLAdapter = DS.RESTAdapter.extend({ + worksWithOnlyModelNameAndId() { + this.buildURL('rootModel', 1); + }, + + worksWithFindRecord() { + this.buildURL('super-user', 1, {} as any, 'findRecord'); + }, + + worksWithFindAll() { + this.buildURL('super-user', null, {} as any, 'findAll'); + }, + + worksWithQueryStub() { + this.buildURL('super-user', null, null, 'query', { limit: 10 }); + }, + + worksWithQueryRecord() { + this.buildURL('super-user', null, null, 'queryRecord', { companyId: 10 }); + }, + + worksWithFindMany() { + this.buildURL('super-user', [1, 2, 3], null, 'findMany'); + }, + + worksWithFindHasMany() { + this.buildURL('super-user', 1, {} as any, 'findHasMany'); + }, + + worksWithFindBelongsTo() { + this.buildURL('super-user', 1, {} as any, 'findBelongsTo'); + }, + + worksWithCreateRecord() { + this.buildURL('super-user', 1, {} as any, 'createRecord'); + }, + + worksWithUpdateRecord() { + this.buildURL('super-user', 1, {} as any, 'updateRecord'); + }, + + worksWithDeleteRecord() { + this.buildURL('super-user', 1, {} as any, 'deleteRecord'); + }, + + worksWithUnknownRequestType() { + this.buildURL('super-user', 1, null, 'unknown'); + this.buildURL('super-user', null, null, 'unknown'); + } +}); diff --git a/types/ember-data/v2/test/belongs-to.ts b/types/ember-data/v2/test/belongs-to.ts new file mode 100644 index 0000000000..31977c148c --- /dev/null +++ b/types/ember-data/v2/test/belongs-to.ts @@ -0,0 +1,29 @@ +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +declare const store: DS.Store; + +class Folder extends DS.Model { + name = DS.attr('string'); + children = DS.hasMany('folder', { inverse: 'parent' }); + parent = DS.belongsTo('folder', { inverse: 'children' }); +} + +declare module 'ember-data' { + interface ModelRegistry { + folder: Folder; + } +} + +const folder = Folder.create(); +assertType(folder.get('parent')); +assertType(folder.get('parent').get('name')); +folder.get('parent').then(parent => { + assertType(parent); + assertType(parent.get('name')); + folder.set('parent', parent); +}); + +folder.set('parent', folder); +folder.set('parent', folder.get('parent')); +folder.set('parent', store.findRecord('folder', 3)); diff --git a/types/ember-data/v2/test/error.ts b/types/ember-data/v2/test/error.ts new file mode 100644 index 0000000000..b8b65ca967 --- /dev/null +++ b/types/ember-data/v2/test/error.ts @@ -0,0 +1,106 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +const { AdapterError } = DS; + +// https://emberjs.com/api/ember-data/2.16/classes/DS.AdapterError +const MaintenanceError = DS.AdapterError.extend({ + message: 'Down for maintenance.', +}); +const maintenanceError = new MaintenanceError(); +assertType(maintenanceError); + +// https://emberjs.com/api/ember-data/2.16/classes/DS.InvalidError +const anInvalidError = new DS.InvalidError([ + { + detail: 'Must be unique', + source: { pointer: '/data/attributes/title' }, + }, + { + detail: 'Must not be blank', + source: { pointer: '/data/attributes/content' }, + }, +]); + +// https://emberjs.com/api/ember-data/2.16/classes/DS.TimeoutError +const { TimeoutError } = DS; +const timedOut = Ember.Route.extend({ + actions: { + error(error: any, transition: any) { + if (error instanceof TimeoutError) { + // alert the user + alert('Are you still connected to the internet?'); + return; + } + + // ...other error handling logic + }, + }, +}); + +// This is technically private, but publicly exposed for APIs to use. We just +// check that it is a proper subclass of `AdapterError`. +// https://emberjs.com/api/ember-data/2.16/classes/DS.AbortError +// https://github.com/emberjs/data/blob/v2.16.0/addon/-private/adapters/errors.js#L206-L216 +const { AbortError } = DS; +assertType(AbortError); + +// https://emberjs.com/api/ember-data/2.16/classes/DS.UnauthorizedError +const { UnauthorizedError } = DS; +assertType(UnauthorizedError); +const unauthorized = Ember.Route.extend({ + actions: { + error(error: any, transition: any) { + if (error instanceof UnauthorizedError) { + // go to the sign in route + this.transitionTo('login'); + return; + } + + // ...other error handling logic + }, + }, +}); + +// This is technically private, but publicly exposed for APIs to use. We just +// check that it is a proper subclass of `AdapterError`. +// https://emberjs.com/api/ember-data/2.16/classes/DS.ForbiddenError +// https://github.com/emberjs/data/blob/v2.16.0/addon/-private/adapters/errors.js#L253-L263 +const { ForbiddenError } = DS; +assertType(ForbiddenError); + +// https://emberjs.com/api/ember-data/2.16/classes/DS.NotFoundError +const { NotFoundError } = DS; +assertType(NotFoundError); +const notFound = Ember.Route.extend({ + model(params: { post_id: string }): any { + return this.get('store').findRecord('post', params.post_id); + }, + + actions: { + error(error: any, transition: any): any { + if (error instanceof NotFoundError) { + // redirect to a list of all posts instead + this.transitionTo('posts'); + } else { + // otherwise let the error bubble + return true; + } + }, + }, +}); + +// This is technically private, but publicly exposed for APIs to use. We just +// check that it is a proper subclass of `AdapterError`. +// https://emberjs.com/api/ember-data/2.16/classes/DS.ConflictError +// https://github.com/emberjs/data/blob/v2.16.0/addon/-private/adapters/errors.js#L303-L313 +const { ConflictError } = DS; +assertType(ConflictError); + +// This is technically private, but publicly exposed for APIs to use. We just +// check that it is a proper subclass of `AdapterError`. +// https://emberjs.com/api/ember-data/2.16/classes/DS.ServerError +// https://github.com/emberjs/data/blob/v2.16.0/addon/-private/adapters/errors.js#L315-L323 +const { ServerError } = DS; +assertType(ServerError); diff --git a/types/ember-data/v2/test/has-many.ts b/types/ember-data/v2/test/has-many.ts new file mode 100644 index 0000000000..480a6bd56d --- /dev/null +++ b/types/ember-data/v2/test/has-many.ts @@ -0,0 +1,61 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +class BlogComment extends DS.Model { + text = DS.attr('string'); +} + +declare module 'ember-data' { + interface ModelRegistry { + 'blog-comment': BlogComment; + } +} + +class BlogPost extends DS.Model { + title = DS.attr('string'); + commentsAsync = DS.hasMany('blog-comment'); + commentsSync = DS.hasMany('blog-comment', { async: false }); +} + +const blogPost = BlogPost.create(); + +assertType>(blogPost.get('commentsSync').reload()); +assertType(blogPost.get('commentsSync').createRecord()); + +const comment = blogPost.get('commentsSync').get('firstObject'); +assertType(comment); +if (comment) { + assertType(comment.get('text')); +} + +assertType>(blogPost.get('commentsAsync').reload()); +assertType(blogPost.get('commentsAsync').createRecord()); +assertType(blogPost.get('commentsAsync').get('firstObject')); + +const commentAsync = blogPost.get('commentsAsync').get('firstObject'); +assertType(commentAsync); +if (commentAsync) { + assertType(commentAsync.get('text')); +} +assertType(blogPost.get('commentsAsync').get('isFulfilled')); + +blogPost.get('commentsAsync').then(comments => { + assertType(comments.get('firstObject')); + assertType(comments.get('firstObject')!.get('text')); +}); + +blogPost.set('commentsAsync', blogPost.get('commentsAsync')); +blogPost.set('commentsAsync', Ember.A()); +blogPost.set('commentsAsync', Ember.A([ comment! ])); + +class PaymentMethod extends DS.Model {} +declare module 'ember-data' { + interface ModelRegistry { + 'payment-method': PaymentMethod; + } +} + +class Polymorphic extends DS.Model { + paymentMethods = DS.hasMany('payment-method', { polymorphic: true }); +} diff --git a/types/ember-data/v2/test/injections.ts b/types/ember-data/v2/test/injections.ts new file mode 100644 index 0000000000..3e32a2b805 --- /dev/null +++ b/types/ember-data/v2/test/injections.ts @@ -0,0 +1,30 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +class MyModel extends DS.Model {} + +declare module 'ember-data' { + interface ModelRegistry { + 'my-model': MyModel; + } +} + +Ember.Route.extend({ + model(): any { + return this.store.findAll('my-model'); + } +}); + +Ember.Controller.extend({ + actions: { + create(): any { + return this.store.createRecord('my-model'); + } + } +}); + +Ember.DataAdapter.extend({ + test() { + this.store.findRecord('my-model', 123); + } +}); diff --git a/types/ember-data/v2/test/lib/assert.ts b/types/ember-data/v2/test/lib/assert.ts new file mode 100644 index 0000000000..10094b9616 --- /dev/null +++ b/types/ember-data/v2/test/lib/assert.ts @@ -0,0 +1,2 @@ +/** Static assertion that `value` has type `T` */ +export declare function assertType(value: T): void; diff --git a/types/ember-data/v2/test/model.ts b/types/ember-data/v2/test/model.ts new file mode 100644 index 0000000000..2085daf90a --- /dev/null +++ b/types/ember-data/v2/test/model.ts @@ -0,0 +1,37 @@ +import Ember from 'ember'; +import DS, { ChangedAttributes } from 'ember-data'; +import { assertType } from "./lib/assert"; + +const Person = DS.Model.extend({ + firstName: DS.attr(), + lastName: DS.attr(), + title: DS.attr({ defaultValue: "The default" }), + title2: DS.attr({ defaultValue: () => "The default" }), + + fullName: Ember.computed('firstName', 'lastName', function() { + return `${this.get('firstName')} ${this.get('lastName')}`; + }) +}); + +const User = DS.Model.extend({ + username: DS.attr('string'), + email: DS.attr('string'), + verified: DS.attr('boolean', { defaultValue: false }), + canBeNull: DS.attr('boolean', { allowNull: true }), + createdAt: DS.attr('date', { + defaultValue() { return new Date(); } + }) +}); + +const user = User.create({ username: 'dwickern' }); +assertType(user.get('id')); +assertType(user.get('username')); +assertType(user.get('verified')); +assertType(user.get('createdAt')); + +user.serialize(); +user.serialize({ includeId: true }); +user.serialize({ includeId: true }); + +const attributes = user.changedAttributes(); +assertType(attributes); diff --git a/types/ember-data/v2/test/module-api.ts b/types/ember-data/v2/test/module-api.ts new file mode 100644 index 0000000000..3ef3f3a224 --- /dev/null +++ b/types/ember-data/v2/test/module-api.ts @@ -0,0 +1,91 @@ +/** + * Tests for the Ember-Data "module API" introduced in v2.3 + * @see https://www.emberjs.com/blog/2016/01/12/ember-data-2-3-released.html#toc_importing-modules + */ +import DS from 'ember-data'; +// Adapters +import Adapter from 'ember-data/adapter'; +import JSONAPIAdapter from 'ember-data/adapters/json-api'; +import RESTAdapter from 'ember-data/adapters/rest'; +// Serializers +import Serializer from 'ember-data/serializer'; +import RESTSerializer from 'ember-data/serializers/rest'; +import JSONSerializer from 'ember-data/serializers/json'; +import JSONAPISerializer from 'ember-data/serializers/json-api'; + +// Model +import Model from 'ember-data/model'; +// Model - attr +import attr from 'ember-data/attr'; +// Model - relationships +import { hasMany, belongsTo } from 'ember-data/relationships'; + +// Transforms +import BooleanTransform from 'ember-data/transforms/boolean'; +import StringTransform from 'ember-data/transforms/string'; +import NumberTransform from 'ember-data/transforms/number'; +import DateTransform from 'ember-data/transforms/date'; +import Transform from 'ember-data/transforms/transform'; + +// Store +import Store from 'ember-data/store'; + +// Errors +import * as EDErrors from 'ember-data/adapters/errors'; + +import { assertType } from "./lib/assert"; + +// ADAPTERS +// - identity +assertType(Adapter); +assertType(RESTAdapter); +assertType(JSONAPIAdapter); +// - inheritance +assertType(RESTAdapter); +assertType(JSONAPIAdapter); + +// SERIALIZERS +// - identity +assertType(Serializer); +assertType(RESTSerializer); +assertType(JSONSerializer); +assertType(JSONAPISerializer); +// - inheritance +assertType(JSONSerializer); +assertType(RESTSerializer); +assertType(JSONAPISerializer); + +// MODEL +// - identity +assertType(Model); +// - attributes +assertType(attr); +// - relationships +assertType(hasMany); +assertType(belongsTo); + +// TRANSFORMS +// - identity +assertType(BooleanTransform); +assertType(NumberTransform); +assertType(StringTransform); +assertType(DateTransform); +assertType(Transform); + +// STORE +// - identity +assertType(Store); + +// ERRORS +// - identity +assertType(EDErrors.AdapterError); +assertType(EDErrors.InvalidError); +assertType(EDErrors.UnauthorizedError); +assertType(EDErrors.ForbiddenError); +assertType(EDErrors.NotFoundError); +assertType(EDErrors.ConflictError); +assertType(EDErrors.ServerError); +assertType(EDErrors.TimeoutError); +assertType(EDErrors.AbortError); +assertType(EDErrors.errorsHashToArray); +assertType(EDErrors.errorsArrayToHash); diff --git a/types/ember-data/v2/test/record-reference.ts b/types/ember-data/v2/test/record-reference.ts new file mode 100644 index 0000000000..f5bf973402 --- /dev/null +++ b/types/ember-data/v2/test/record-reference.ts @@ -0,0 +1,44 @@ +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +declare const store: DS.Store; + +class User extends DS.Model { + username = DS.attr('string'); +} + +declare module 'ember-data' { + interface ModelRegistry { + user: User; + } +} + +let userRef = store.getReference('user', 1); + +// get the record of the reference (null if not yet available) +let user = userRef.value(); +if (user !== null) { + assertType(user); +} + +// get the identifier of the reference +if (userRef.remoteType() === 'id') { + let id = userRef.id(); + assertType(id); +} + +// load user (via store.find) +userRef.load().then(user => { + assertType(user); +}); + +// or trigger a reload +userRef.reload().then(user => { + assertType(user); +}); + +// provide data for reference +userRef.push({ id: 1, username: '@user' }).then(function(user) { + assertType(user); + userRef.value() === user; +}); diff --git a/types/ember-data/v2/test/relationships.ts b/types/ember-data/v2/test/relationships.ts new file mode 100644 index 0000000000..06795c0e26 --- /dev/null +++ b/types/ember-data/v2/test/relationships.ts @@ -0,0 +1,60 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +declare const store: DS.Store; + +const Person = DS.Model.extend({ + children: DS.hasMany('folder', { inverse: 'parent' }), + parent: DS.belongsTo('folder', { inverse: 'children' }) +}); + +const Polymorphic = DS.Model.extend({ + paymentMethods: DS.hasMany('payment-method', { polymorphic: true }) +}); + +Polymorphic.eachRelationship(() => ''); +Polymorphic.eachRelationship(() => '', {}); +Polymorphic.eachRelationship((n, meta) => { + let s: string = n; + let m: 'belongsTo' | 'hasMany' = meta.kind; +}); +let p = Polymorphic.create(); +p.eachRelationship(() => ''); +p.eachRelationship(() => '', {}); +p.eachRelationship((n, meta) => { + let s: string = n; + let m: 'belongsTo' | 'hasMany' = meta.kind; +}); + +class Comment extends DS.Model { + author = DS.attr('string'); +} + +class Series extends DS.Model { + title = DS.attr('string'); +} + +class RelationalPost extends DS.Model { + title = DS.attr('string'); + tag = DS.attr('string'); + comments = DS.hasMany('comment', { async: true }); + relatedPosts = DS.hasMany('post'); + series = DS.belongsTo('series'); +} + +declare module 'ember-data' { + interface ModelRegistry { + 'relational-post': RelationalPost; + comment: Comment; + series: Series; + } +} + +let blogPost = store.peekRecord('relational-post', 1); +blogPost!.get('comments').then((comments) => { + // now we can work with the comments + let author: string = comments.get('firstObject')!.get('author'); +}); + +blogPost!.hasMany('relatedPosts'); +blogPost!.belongsTo('series'); diff --git a/types/ember-data/v2/test/serializer.ts b/types/ember-data/v2/test/serializer.ts new file mode 100644 index 0000000000..b694b38b89 --- /dev/null +++ b/types/ember-data/v2/test/serializer.ts @@ -0,0 +1,95 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +const JsonApi = DS.JSONAPISerializer.extend({}); + +const Customized = DS.JSONAPISerializer.extend({ + serialize(snapshot: DS.Snapshot<'user'>, options: {}) { + const lookup = snapshot.belongsTo('username'); + let json: any = this._super(...Array.from(arguments)); + + json.data.attributes.cost = { + amount: json.data.attributes.amount, + currency: json.data.attributes.currency + }; + + return json; + }, + normalizeResponse(store: DS.Store, primaryModelClass: DS.Model, payload: any, id: string|number, requestType: string) { + payload.data.attributes.amount = payload.data.attributes.cost.amount; + payload.data.attributes.currency = payload.data.attributes.cost.currency; + + delete payload.data.attributes.cost; + + return this._super(...Array.from(arguments)); + } +}); + +const EmbeddedRecordMixin = DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { + attrs: { + author: { + serialize: false, + deserialize: 'records' + }, + comments: { + deserialize: 'records', + serialize: 'ids' + } + } +}); + +class Message extends DS.Model.extend({ + title: DS.attr(), + body: DS.attr(), + + author: DS.belongsTo('user'), + comments: DS.belongsTo('comment') +}) {} + +declare module 'ember-data' { + interface ModelRegistry { + 'message-for-serializer': Message; + } +} + +interface CustomSerializerOptions { + includeId: boolean; +} + +const SerializerUsingSnapshots = DS.RESTSerializer.extend({ + serialize(snapshot: DS.Snapshot<'message-for-serializer'>, options: CustomSerializerOptions) { + let json: any = { + POST_TTL: snapshot.attr('title'), + POST_BDY: snapshot.attr('body'), + POST_CMS: snapshot.hasMany('comments', { ids: true }) + }; + + if (options.includeId) { + json.POST_ID_ = snapshot.id; + } + + return json; + } +}); + +DS.Serializer.extend({ + serialize(snapshot: DS.Snapshot<'message-for-serializer'>, options: {}) { + let json: any = { + id: snapshot.id + }; + + snapshot.eachAttribute((key, attribute) => { + json[key] = snapshot.attr(key); + }); + + snapshot.eachRelationship((key, relationship) => { + if (relationship.kind === 'belongsTo') { + json[key] = snapshot.belongsTo(key, { id: true }); + } else if (relationship.kind === 'hasMany') { + json[key] = snapshot.hasMany(key, { ids: true }); + } + }); + + return json; + }, +}); diff --git a/types/ember-data/v2/test/store.ts b/types/ember-data/v2/test/store.ts new file mode 100644 index 0000000000..f512afd8a7 --- /dev/null +++ b/types/ember-data/v2/test/store.ts @@ -0,0 +1,205 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +declare const store: DS.Store; + +class PostComment extends DS.Model {} +class Post extends DS.Model { + title = DS.attr('string'); + comments = DS.hasMany('comment'); +} + +declare module 'ember-data' { + interface ModelRegistry { + 'post': Post; + 'post-comment': PostComment; + } +} + +let post = store.createRecord('post', { + title: 'Rails is Omakase', + body: 'Lorem ipsum', +}); + +post.save(); // => POST to '/posts' +post.save().then(saved => { + assertType(saved); +}); + +store.findRecord('post', 1).then(function(post) { + post.get('title'); // => "Rails is Omakase" + post.set('title', 'A new post'); + post.save(); // => PATCH to '/posts/1' +}); + +class User extends DS.Model { + username = DS.attr('string'); +} + +class Author extends User {} + +declare module 'ember-data' { + interface ModelRegistry { + 'user': User; + 'author': Author; + } +} + +store.queryRecord('user', {}).then(function(user) { + let username = user.get('username'); + console.log(`Currently logged in as ${username}`); +}); + +store.findAll('post'); // => GET /posts +store.findAll('author', { reload: true }).then(function(authors) { + authors.getEach('id'); // ['first', 'second'] +}); +store.findAll('post', { + adapterOptions: { subscribe: false }, +}); +store.findAll('post', { include: 'comments,comments.author' }); + +store.peekAll('post'); // => no network request + +if (store.hasRecordForId('post', 1)) { + let maybePost = store.peekRecord('post', 1); + if (maybePost) { + maybePost.get('id'); // 1 + } +} + +class Message extends DS.Model { + hasBeenSeen = DS.attr('boolean'); +} + +declare module 'ember-data' { + interface ModelRegistry { + message: Message; + } +} + +const messages = store.peekAll('message'); +messages.forEach(function(message) { + message.set('hasBeenSeen', true); +}); +messages.save(); + +const people = store.peekAll('user'); +people.get('isUpdating'); // false +people.update().then(function() { + people.get('isUpdating'); // false +}); +people.get('isUpdating'); // true + +const MyRoute = Ember.Route.extend({ + model(params: any): any { + return this.store.findRecord('post', params.post_id, { + include: 'comments,comments.author', + }); + }, +}); + +// Store is injectable via `inject` and resolves to `DS.Store`. +const SomeComponent = Ember.Component.extend({ + store: Ember.inject.service('store'), + + lookUpUsers() { + assertType(this.get('store').findRecord('user', 123)); + assertType>(this.get('store').findAll('user')); + } +}); + +const MyRouteAsync = Ember.Route.extend({ + async beforeModel(): Promise> { + const store = Ember.get(this, 'store'); + return await store.findAll('post-comment'); + }, + async model(): Promise { + const store = this.get('store'); + return await store.findRecord('post-comment', 1); + }, + async afterModel(): Promise> { + const post = await this.get('store').findRecord('post', 1); + return await post.get('comments'); + } +}); + +class MyRouteAsyncES6 extends Ember.Route { + async beforeModel(): Promise> { + return await this.store.findAll('post-comment'); + } + async model(): Promise { + return await this.store.findRecord('post-comment', 1); + } + async afterModel(): Promise> { + const post = await this.store.findRecord('post', 1); + return await post.get('comments'); + } +} + +// GET to /users?filter[email]=tomster@example.com +const tom = store + .query('user', { + filter: { + email: 'tomster@example.com', + }, + }) + .then(function(users) { + return users.get('firstObject'); + }); + +// GET /users?isAdmin=true +const admins = store.query('user', { isAdmin: true }); +admins.then(function() { + console.log(admins.get('length')); // 42 +}); +admins.update().then(function() { + admins.get('isUpdating'); // false + console.log(admins.get('length')); // 123 +}); + +store.push({ + data: [ + { + id: 1, + type: 'album', + attributes: { + title: 'Fewer Moving Parts', + artist: 'David Bazan', + songCount: 10, + }, + relationships: {}, + }, + { + id: 2, + type: 'album', + attributes: { + title: "Calgary b/w I Can't Make You Love Me/Nick Of Time", + artist: 'Bon Iver', + songCount: 2, + }, + relationships: {}, + }, + ], +}); + +class UserAdapter extends DS.Adapter { + thisAdapterOnlyMethod(): void {} +} +class UserSerializer extends DS.Serializer { + thisSerializerOnlyMethod(): void {} +} + +declare module 'ember-data' { + interface AdapterRegistry { + user: UserAdapter; + } + + interface SerializerRegistry { + user: UserSerializer; + } +} + +assertType(store.adapterFor('user')); +assertType(store.serializerFor('user')); diff --git a/types/ember-data/v2/test/transform.ts b/types/ember-data/v2/test/transform.ts new file mode 100644 index 0000000000..b76d40a73f --- /dev/null +++ b/types/ember-data/v2/test/transform.ts @@ -0,0 +1,16 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +class Point extends Ember.Object { + x: number; + y: number; +} + +const PointTransform = DS.Transform.extend({ + serialize(value: Point): number[] { + return [value.get('x'), value.get('y')]; + }, + deserialize(value: [ number, number ]): Point { + return Point.create({ x: value[0], y: value[1] }); + } +}); diff --git a/types/ember-data/v2/transform.d.ts b/types/ember-data/v2/transform.d.ts new file mode 100644 index 0000000000..b57b7cbe76 --- /dev/null +++ b/types/ember-data/v2/transform.d.ts @@ -0,0 +1,2 @@ +import DS from 'ember-data'; +export default DS.Transform; diff --git a/types/ember-data/v2/transforms/boolean.d.ts b/types/ember-data/v2/transforms/boolean.d.ts new file mode 100644 index 0000000000..0dd20d73f2 --- /dev/null +++ b/types/ember-data/v2/transforms/boolean.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.BooleanTransform; diff --git a/types/ember-data/v2/transforms/date.d.ts b/types/ember-data/v2/transforms/date.d.ts new file mode 100644 index 0000000000..54b5e05877 --- /dev/null +++ b/types/ember-data/v2/transforms/date.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.DateTransform; diff --git a/types/ember-data/v2/transforms/number.d.ts b/types/ember-data/v2/transforms/number.d.ts new file mode 100644 index 0000000000..e3342141c1 --- /dev/null +++ b/types/ember-data/v2/transforms/number.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.NumberTransform; diff --git a/types/ember-data/v2/transforms/string.d.ts b/types/ember-data/v2/transforms/string.d.ts new file mode 100644 index 0000000000..9b0d039208 --- /dev/null +++ b/types/ember-data/v2/transforms/string.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.StringTransform; diff --git a/types/ember-data/v2/transforms/transform.d.ts b/types/ember-data/v2/transforms/transform.d.ts new file mode 100644 index 0000000000..438d8e0de5 --- /dev/null +++ b/types/ember-data/v2/transforms/transform.d.ts @@ -0,0 +1,3 @@ +import DS from 'ember-data'; + +export default DS.Transform; diff --git a/types/ember-data/v2/tsconfig.json b/types/ember-data/v2/tsconfig.json new file mode 100644 index 0000000000..003157a332 --- /dev/null +++ b/types/ember-data/v2/tsconfig.json @@ -0,0 +1,61 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "ember": ["ember/v2"], + "ember-data": ["ember-data/v2"], + "ember-data/*": ["ember-data/v2/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "adapter.d.ts", + "serializer.d.ts", + "model.d.ts", + "attr.d.ts", + "relationships.d.ts", + "store.d.ts", + "transform.d.ts", + "adapters/errors.d.ts", + "adapters/rest.d.ts", + "adapters/json-api.d.ts", + "serializers/json-api.d.ts", + "serializers/json.d.ts", + "serializers/rest.d.ts", + "serializers/embedded-records-mixin.d.ts", + "transforms/transform.d.ts", + "transforms/date.d.ts", + "transforms/boolean.d.ts", + "transforms/string.d.ts", + "transforms/number.d.ts", + "test/lib/assert.ts", + "test/model.ts", + "test/module-api.ts", + "test/adapter.ts", + "test/serializer.ts", + "test/transform.ts", + "test/relationships.ts", + "test/store.ts", + "test/has-many.ts", + "test/belongs-to.ts", + "test/record-reference.ts", + "test/injections.ts", + "test/error.ts" + ] +} diff --git a/types/ember-data/v2/tslint.json b/types/ember-data/v2/tslint.json new file mode 100644 index 0000000000..70eef4d46e --- /dev/null +++ b/types/ember-data/v2/tslint.json @@ -0,0 +1,20 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false, + // Heavy use of Function type in this older package. + "ban-types": false, + "jsdoc-format": false, + "no-misused-new": false, + // not sure what this means + "no-single-declare-module": false, + "object-literal-key-quotes": false, + "only-arrow-functions": false, + "no-empty-interface": false, + "prefer-const": false, + "no-unnecessary-generics": false, + "no-declare-current-package": false, + "no-self-import": false, + "no-return-await": false // used in tests + } +} diff --git a/types/ember-feature-flags/index.d.ts b/types/ember-feature-flags/index.d.ts index 94b443afae..6f3f963919 100644 --- a/types/ember-feature-flags/index.d.ts +++ b/types/ember-feature-flags/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for ember-feature-flags 3.0 +// Type definitions for ember-feature-flags 4.0 // Project: https://github.com/kategengler/ember-feature-flags#readme // Definitions by: Frank Tan +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 import Ember from 'ember'; diff --git a/types/ember-feature-flags/v3/ember-feature-flags-tests.ts b/types/ember-feature-flags/v3/ember-feature-flags-tests.ts new file mode 100644 index 0000000000..bfcfaae62e --- /dev/null +++ b/types/ember-feature-flags/v3/ember-feature-flags-tests.ts @@ -0,0 +1,27 @@ +import Features from 'ember-feature-flags'; +import 'ember-feature-flags/tests/helpers/with-feature'; + +/** Static assertion that `value` has type `T` */ +// Disable tslint here b/c the generic is used to let us do a type coercion and +// validate that coercion works for the type value "passed into" the function. +// tslint:disable-next-line:no-unnecessary-generics +export declare function assertType(value: T): void; + +declare module 'ember-feature-flags' { + export default interface Features { + someFeature: boolean; + } +} + +// https://www.npmjs.com/package/ember-feature-flags#withfeature +declare var features: Features; +features.isEnabled('new-billing-plans'); // $ExpectType boolean +features.enable('newHomepage'); // $ExpectType void +features.disable('newHomepage'); // $ExpectType void +const setup = { + 'new-billing-plans': true, + 'new-homepage': false +}; +features.setup(setup); // $ExpectType void +withFeature('new-homepage'); // $ExpectType void +assertType(features.get('someFeature')); diff --git a/types/ember-feature-flags/v3/index.d.ts b/types/ember-feature-flags/v3/index.d.ts new file mode 100644 index 0000000000..a2b31f3303 --- /dev/null +++ b/types/ember-feature-flags/v3/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for ember-feature-flags 3.0 +// Project: https://github.com/kategengler/ember-feature-flags#readme +// Definitions by: Frank Tan +// Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Ember from 'ember'; + +// https://github.com/kategengler/ember-feature-flags/blob/v3.0.0/addon/services/features.js#L5 +export default interface Features extends Ember.Service { + setup(features: { [key: string]: boolean }): void; + enable(feature: string): void; + disable(feature: string): void; + isEnabled(feature: string): boolean; +} diff --git a/types/ember-feature-flags/v3/tests/helpers/with-feature.d.ts b/types/ember-feature-flags/v3/tests/helpers/with-feature.d.ts new file mode 100644 index 0000000000..ef735f7923 --- /dev/null +++ b/types/ember-feature-flags/v3/tests/helpers/with-feature.d.ts @@ -0,0 +1,3 @@ +// https://www.npmjs.com/package/ember-feature-flags#withfeature +// https://github.com/kategengler/ember-feature-flags/blob/v3.0.0/test-support/helpers/with-feature.js#L3 +declare function withFeature(name: string): void; diff --git a/types/ember-feature-flags/v3/tsconfig.json b/types/ember-feature-flags/v3/tsconfig.json new file mode 100644 index 0000000000..62622d02af --- /dev/null +++ b/types/ember-feature-flags/v3/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "ember": ["ember/v2"], + "ember-feature-flags": ["ember-feature-flags/v3"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "tests/helpers/with-feature.d.ts", + "ember-feature-flags-tests.ts" + ] +} diff --git a/types/ember-feature-flags/v3/tslint.json b/types/ember-feature-flags/v3/tslint.json new file mode 100644 index 0000000000..4c4fc86ace --- /dev/null +++ b/types/ember-feature-flags/v3/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false + } +} diff --git a/types/ember-mocha/index.d.ts b/types/ember-mocha/index.d.ts index 638edb8542..69d2202f04 100644 --- a/types/ember-mocha/index.d.ts +++ b/types/ember-mocha/index.d.ts @@ -2,8 +2,9 @@ // Project: https://github.com/emberjs/ember-mocha#readme // Definitions by: Derek Wickern // Simon Ihmig +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 import { TestContext, ModuleCallbacks } from "ember-test-helpers"; import Ember from 'ember'; diff --git a/types/ember-modal-dialog/index.d.ts b/types/ember-modal-dialog/index.d.ts index b9b356e988..19f4c5692c 100644 --- a/types/ember-modal-dialog/index.d.ts +++ b/types/ember-modal-dialog/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for ember-modal-dialog 2.4 +// Type definitions for ember-modal-dialog 3.0 // Project: https://github.com/yapplabs/ember-modal-dialog#readme // Definitions by: Frank Tan +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 declare module 'ember-modal-dialog/components/modal-dialog' { import Ember from 'ember'; diff --git a/types/ember-modal-dialog/v2/ember-modal-dialog-tests.ts b/types/ember-modal-dialog/v2/ember-modal-dialog-tests.ts new file mode 100644 index 0000000000..06ab7fd241 --- /dev/null +++ b/types/ember-modal-dialog/v2/ember-modal-dialog-tests.ts @@ -0,0 +1,27 @@ +import ModalDialog from 'ember-modal-dialog/components/modal-dialog'; + +class MyDialog extends ModalDialog { + // https://www.npmjs.com/package/ember-modal-dialog#configurable-properties + testProperties() { + this.hasOverlay; // $ExpectType boolean + this.translucentOverlay; // $ExpectType boolean + this.onClose(); + this.onClickOverlay(); + this.clickOutsideToClose; // $ExpectType boolean + this.renderInPlace; // $ExpectType boolean + this.overlayPosition; // $ExpectType "parent" | "sibling" + this.containerClass; // $ExpectType string + this.containerClassNames; // $ExpectType string[] + this.overlayClass; // $ExpectType string + this.overlayClassNames; // $ExpectType string[] + this.wrapperClass; // $ExpectType string + this.wrapperClassNames; // $ExpectType string[] + this.animatable; // $ExpectType boolean + } +} + +class MyOtherDialog extends ModalDialog.extend({ + testProperties() { + this.hasOverlay; // $ExpectType boolean + } +}) {} diff --git a/types/ember-modal-dialog/v2/index.d.ts b/types/ember-modal-dialog/v2/index.d.ts new file mode 100644 index 0000000000..60d1a17c1b --- /dev/null +++ b/types/ember-modal-dialog/v2/index.d.ts @@ -0,0 +1,94 @@ +// Type definitions for ember-modal-dialog 2.4 +// Project: https://github.com/yapplabs/ember-modal-dialog#readme +// Definitions by: Frank Tan +// Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare module 'ember-modal-dialog/components/modal-dialog' { + import Ember from 'ember'; + + // https://github.com/yapplabs/ember-modal-dialog/blob/v2.4.1/addon/components/modal-dialog.js#L28 + // https://www.npmjs.com/package/ember-modal-dialog#configurable-properties + export default class ModalDialog extends Ember.Component { + /** + * Toggles presence of overlay div in DOM + */ + hasOverlay: boolean; + /** + * Indicates translucence of overlay, toggles presence of translucent CSS + * selector + */ + translucentOverlay: boolean; + /** + * The action handler for the dialog's onClose action. This action triggers + * when the user clicks the modal overlay. + */ + onClose: () => void; + /** + * An action to be called when the overlay is clicked. If this action is + * specified, clicking the overlay will invoke it instead of onClose. + */ + onClickOverlay: () => void; + /** + * Indicates whether clicking outside a modal without an overlay should + * close the modal. Useful if your modal isn't the focus of interaction, and + * you want hover effects to still work outside the modal. + */ + clickOutsideToClose: boolean; + /** + * A boolean, when true renders the modal without wormholing or tethering, + * useful for including a modal in a style guide + */ + renderInPlace: boolean; + /** + * either 'parent' or 'sibling', to control whether the overlay div is + * rendered as a parent element of the container div or as a sibling to it + * (default: 'parent') + */ + overlayPosition: 'parent' | 'sibling'; + /** + * CSS class name(s) to append to container divs. Set this from template. + */ + containerClass: string; + /** + * CSS class names to append to container divs. This is a concatenated + * property, so it does not replace the default container class + * (default: 'ember-modal-dialog'. If you subclass this component, you may + * define this in your subclass.) + */ + containerClassNames: string[]; + /** + * CSS class name(s) to append to overlay divs. Set this from template. + */ + overlayClass: string; + /** + * CSS class names to append to overlay divs. This is a concatenated + * property, so it does not replace the default overlay class + * (default: 'ember-modal-overlay'. If you subclass this component, you may + * define this in your subclass.) + */ + overlayClassNames: string[]; + /** + * CSS class name(s) to append to wrapper divs. Set this from template. + */ + wrapperClass: string; + /** + * CSS class names to append to wrapper divs. This is a concatenated + * property, so it does not replace the default container class + * (default: 'ember-modal-wrapper'. If you subclass this component, you may + * define this in your subclass.) + */ + wrapperClassNames: string[]; + /** + * A boolean, when true makes modal animatable using liquid-fire + * (requires liquid-wormhole to be installed, and for tethering situations + * liquid-tether. Having these optional dependencies installed and NOT + * explicitly specifying animatable is deprecated in 2.x and is equivalent + * to animatable=false for backwards compatibility. As of 3.x, the implicit + * default will be animatable=true when the optional + * liquid-wormhole/liquid-tether dependency is present. + */ + animatable: boolean; + } +} diff --git a/types/ember-modal-dialog/v2/tsconfig.json b/types/ember-modal-dialog/v2/tsconfig.json new file mode 100644 index 0000000000..b26dfa6212 --- /dev/null +++ b/types/ember-modal-dialog/v2/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "ember-modal-dialog": ["ember-modal-dialog/v2"], + "ember": ["ember/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-modal-dialog-tests.ts" + ] +} diff --git a/types/ember-modal-dialog/v2/tslint.json b/types/ember-modal-dialog/v2/tslint.json new file mode 100644 index 0000000000..f55a9ded82 --- /dev/null +++ b/types/ember-modal-dialog/v2/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-single-declare-module": false, + "no-declare-current-package": false, + "strict-export-declare-modifiers": false + } +} diff --git a/types/ember-qunit/index.d.ts b/types/ember-qunit/index.d.ts index 5dbfb49401..ed8ac13916 100644 --- a/types/ember-qunit/index.d.ts +++ b/types/ember-qunit/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for ember-qunit 3.0 +// Type definitions for ember-qunit 3.4 // Project: https://github.com/emberjs/ember-qunit#readme // Definitions by: Derek Wickern +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 /// diff --git a/types/ember-qunit/v2/index.d.ts b/types/ember-qunit/v2/index.d.ts index 0edc5c837f..b60f73f7cc 100644 --- a/types/ember-qunit/v2/index.d.ts +++ b/types/ember-qunit/v2/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for ember-qunit 2.2 // Project: https://github.com/emberjs/ember-qunit#readme // Definitions by: Derek Wickern +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 diff --git a/types/ember-qunit/v2/tsconfig.json b/types/ember-qunit/v2/tsconfig.json index 1a71d59c4a..181f10f533 100644 --- a/types/ember-qunit/v2/tsconfig.json +++ b/types/ember-qunit/v2/tsconfig.json @@ -16,7 +16,9 @@ "paths": { "ember-qunit": [ "ember-qunit/v2" - ] + ], + "ember": ["ember/v2"], + "ember-test-helpers": ["ember-test-helpers/v0"] }, "types": [], "noEmit": true, @@ -26,4 +28,4 @@ "index.d.ts", "ember-qunit-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/ember-resolver/ember-resolver-tests.ts b/types/ember-resolver/ember-resolver-tests.ts index d22a0d31be..6973daeda0 100644 --- a/types/ember-resolver/ember-resolver-tests.ts +++ b/types/ember-resolver/ember-resolver-tests.ts @@ -1,5 +1,5 @@ -import Application from '@ember/application'; import EmberResolver from 'ember-resolver'; +import { Ember } from 'ember'; const MyResolver = EmberResolver.extend({ pluralizedTypes: { @@ -7,6 +7,6 @@ const MyResolver = EmberResolver.extend({ } }); -const App = Application.extend({ +const App = Ember.Application.extend({ Resolver: MyResolver }); diff --git a/types/ember-resolver/index.d.ts b/types/ember-resolver/index.d.ts index 7c9ac5b6d0..f2ede7fe32 100644 --- a/types/ember-resolver/index.d.ts +++ b/types/ember-resolver/index.d.ts @@ -1,14 +1,13 @@ -// Type definitions for ember-resolver 4.5 +// Type definitions for ember-resolver 5.0 // Project: https://github.com/ember-cli/ember-resolver#readme // Definitions by: Dan Freeman +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 -/// - -import Resolver from '@ember/application/resolver'; +import Ember from 'ember'; /** * An Ember `Resolver` implementation used by ember-cli. */ -export default class EmberResolver extends Resolver {} +export default class EmberResolver extends Ember.Resolver {} diff --git a/types/ember-resolver/v4/ember-resolver-tests.ts b/types/ember-resolver/v4/ember-resolver-tests.ts new file mode 100644 index 0000000000..db834b1985 --- /dev/null +++ b/types/ember-resolver/v4/ember-resolver-tests.ts @@ -0,0 +1,12 @@ +import Ember from 'ember'; +import EmberResolver from 'ember-resolver'; + +const MyResolver = EmberResolver.extend({ + pluralizedTypes: { + sheep: 'sheep' + } +}); + +const App = Ember.Application.extend({ + Resolver: MyResolver +}); diff --git a/types/ember-resolver/v4/index.d.ts b/types/ember-resolver/v4/index.d.ts new file mode 100644 index 0000000000..fd5359cff4 --- /dev/null +++ b/types/ember-resolver/v4/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for ember-resolver 4.5 +// Project: https://github.com/ember-cli/ember-resolver#readme +// Definitions by: Dan Freeman +// Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Ember from 'ember'; + +/** + * An Ember `Resolver` implementation used by ember-cli. + */ +export default class EmberResolver extends Ember.Resolver {} diff --git a/types/ember-resolver/v4/tsconfig.json b/types/ember-resolver/v4/tsconfig.json new file mode 100644 index 0000000000..2539233e16 --- /dev/null +++ b/types/ember-resolver/v4/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "ember": ["ember/v2"], + "ember-resolver": ["ember-resolver/v4"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-resolver-tests.ts" + ] +} diff --git a/types/ember-resolver/v4/tslint.json b/types/ember-resolver/v4/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ember-resolver/v4/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ember-test-helpers/index.d.ts b/types/ember-test-helpers/index.d.ts index c0d5947aba..e70e76e821 100644 --- a/types/ember-test-helpers/index.d.ts +++ b/types/ember-test-helpers/index.d.ts @@ -1,8 +1,17 @@ -// Type definitions for ember-test-helpers 0.7 +// Type definitions for ember-test-helpers 1.0 // Project: https://github.com/emberjs/ember-test-helpers#readme // Definitions by: Derek Wickern +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 + +// NOTE: These types apply to ember-test-helper v0.7. The major +// version had to be bumped for SemVer due to a breaking change +// in TypeScript 3.1 +// +// In the future, we'll use another versioning strategy that +// provides safety from breaking changes without bumping the major +// version number /// diff --git a/types/ember-test-helpers/v0/ember-test-helpers-tests.ts b/types/ember-test-helpers/v0/ember-test-helpers-tests.ts new file mode 100644 index 0000000000..705d0c76b1 --- /dev/null +++ b/types/ember-test-helpers/v0/ember-test-helpers-tests.ts @@ -0,0 +1,53 @@ +/// +import { ModuleCallbacks, TestContext, TestModule } from "ember-test-helpers"; +import wait from 'ember-test-helpers/wait'; +import hasEmberVersion from 'ember-test-helpers/has-ember-version'; + +import hbs from 'htmlbars-inline-precompile'; + +function moduleFor(name: string, description: string, callbacks: ModuleCallbacks) { + const module = new TestModule(name, description, callbacks); + + QUnit.module(module.name, { + beforeEach() { + module.setup(); + }, + afterEach() { + module.teardown(); + } + }); +} + +async function testWait() { + await wait(); +} + +if (hasEmberVersion(2, 10)) { + // ... +} + +// https://github.com/emberjs/ember-test-helpers/blob/f07e86914f2a3823c4cb6787307f9ba2bf447e68/tests/unit/setup-context-test.js +QUnit.test('it sets up this.owner', function(this: TestContext, assert: Assert) { + const { owner } = this; + assert.ok(owner, 'owner was setup'); + assert.equal(typeof owner.lookup, 'function', 'has expected lookup interface'); + + if (hasEmberVersion(2, 12)) { + assert.equal(typeof owner.factoryFor, 'function', 'has expected factory interface'); + } +}); + +QUnit.test('can pauseTest to be resumed "later"', async function(this: TestContext, assert: Assert) { + const promise = this.pauseTest(); + + this.resumeTest(); + + await promise; +}); + +// https://github.com/emberjs/ember-test-helpers/blob/fb4c8d4cd36b54728ce180227f865b1fa0162632/tests/unit/setup-rendering-context-test.js +QUnit.test('render exposes an `.element` property', async function(this: TestContext, assert: Assert) { + await this.render(hbs`

Hello!

`); + + assert.equal(this.element.textContent, 'Hello!'); +}); diff --git a/types/ember-test-helpers/v0/index.d.ts b/types/ember-test-helpers/v0/index.d.ts new file mode 100644 index 0000000000..c2c82ed6fe --- /dev/null +++ b/types/ember-test-helpers/v0/index.d.ts @@ -0,0 +1,100 @@ +// Type definitions for ember-test-helpers 0.7 +// Project: https://github.com/emberjs/ember-test-helpers#readme +// Definitions by: Derek Wickern +// Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +declare module 'ember-test-helpers' { + import Ember from 'ember'; + import { TemplateFactory } from 'htmlbars-inline-precompile'; + import RSVP from "rsvp"; + + interface ModuleCallbacks { + integration?: boolean; + unit?: boolean; + needs?: string[]; + + beforeSetup?(assert?: any): void; + setup?(assert?: any): void; + teardown?(assert?: any): void; + afterTeardown?(assert?: any): void; + + [key: string]: any; + } + + interface TestContext { + get(key: string): any; + getProperties(...keys: K[]): Pick; + set(key: string, value: V): V; + setProperties

(hash: P): P; + on(actionName: string, handler: (this: TestContext, ...args: any[]) => any): void; + send(actionName: string): void; + $: JQueryStatic; + subject(options?: {}): any; + render(template?: string | string[] | TemplateFactory): Promise; + clearRender(): void; + registry: Ember.Registry; + container: Ember.Container; + dispatcher: Ember.EventDispatcher; + application: Ember.Application; + register(fullName: string, factory: any): void; + factory(fullName: string): any; + inject: { + controller(name: string, options?: { as: string }): any; + service(name: string, options?: { as: string }): any; + }; + owner: Ember.ApplicationInstance & { + factoryFor(fullName: string, options?: {}): any; + }; + pauseTest(): Promise; + resumeTest(): void; + element: Element; + } + + class TestModule { + constructor(name: string, callbacks?: ModuleCallbacks); + constructor(name: string, description?: string, callbacks?: ModuleCallbacks); + + name: string; + subjectName: string; + description: string; + isIntegration: boolean; + callbacks: ModuleCallbacks; + context: TestContext; + resolver: Ember.Resolver; + + setup(assert?: any): RSVP.Promise; + teardown(assert?: any): RSVP.Promise; + getContext(): TestContext; + setContext(context: TestContext): void; + } + + class TestModuleForAcceptance extends TestModule {} + class TestModuleForIntegration extends TestModule {} + class TestModuleForComponent extends TestModule {} + class TestModuleForModel extends TestModule {} + + function getContext(): TestContext | undefined; + function setContext(context: TestContext): void; + function unsetContext(): void; + function setResolver(resolver: Ember.Resolver): void; +} + +declare module 'ember-test-helpers/wait' { + import RSVP from "rsvp"; + + interface WaitOptions { + waitForTimers?: boolean; + waitForAJAX?: boolean; + waitForWaiters?: boolean; + } + + export default function wait(options?: WaitOptions): RSVP.Promise; +} + +declare module 'ember-test-helpers/has-ember-version' { + export default function hasEmberVersion(major: number, minor: number): boolean; +} diff --git a/types/ember-test-helpers/v0/tsconfig.json b/types/ember-test-helpers/v0/tsconfig.json new file mode 100644 index 0000000000..8d5222187c --- /dev/null +++ b/types/ember-test-helpers/v0/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "ember": ["ember/v2"], + "ember-test-helpers": ["ember-test-helpers/v0"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember-test-helpers-tests.ts" + ] +} diff --git a/types/ember-test-helpers/v0/tslint.json b/types/ember-test-helpers/v0/tslint.json new file mode 100644 index 0000000000..659431c9ea --- /dev/null +++ b/types/ember-test-helpers/v0/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false, + "no-duplicate-imports": false, + "no-declare-current-package": false + } +} diff --git a/types/ember/-private-types/mixin.d.ts b/types/ember/-private-types/mixin.d.ts new file mode 100644 index 0000000000..30e81493ca --- /dev/null +++ b/types/ember/-private-types/mixin.d.ts @@ -0,0 +1,5 @@ +import Ember from 'ember'; +/** + * Ember.Object.extend(...) accepts any number of mixins or literals. + */ +declare type MixinOrLiteral = Ember.Mixin | T; diff --git a/types/ember/-private-types/object.d.ts b/types/ember/-private-types/object.d.ts new file mode 100644 index 0000000000..be7be68dee --- /dev/null +++ b/types/ember/-private-types/object.d.ts @@ -0,0 +1,28 @@ +/** + * Used to infer the type of ember classes of type `T`. + * + * Generally you would use `EmberClass.create()` instead of `new EmberClass()`. + * + * The single-arg constructor is required by the typescript compiler. + * The multi-arg constructor is included for better ergonomics. + * + * Implementation is carefully chosen for the reasons described in + * https://github.com/typed-ember/ember-typings/pull/29 + */ +export type EmberClassConstructor = (new (properties?: object) => T) & (new (...args: any[]) => T); + +/** + * Check that any arguments to `create()` match the type's properties. + * + * Accept any additional properties and add merge them into the instance. + */ +export type EmberInstanceArguments = Partial & { + [key: string]: any; +}; + +/** + * Accept any additional properties and add merge them into the prototype. + */ +export interface EmberClassArguments { + [key: string]: any; +} diff --git a/types/ember/-private-types/object/computed.d.ts b/types/ember/-private-types/object/computed.d.ts new file mode 100644 index 0000000000..2c540db04b --- /dev/null +++ b/types/ember/-private-types/object/computed.d.ts @@ -0,0 +1,34 @@ +import ComputedProperty from '@ember/object/computed'; +/** + * Deconstructs computed properties into the types which would be returned by `.get()`. + */ +export type UnwrapComputedPropertyGetter = + T extends ComputedProperty ? U : + T; +export type UnwrapComputedPropertyGetters = { + [P in keyof T]: UnwrapComputedPropertyGetter; +}; + +export type UnwrapComputedPropertySetter = + T extends ComputedProperty ? V : + T; +export type UnwrapComputedPropertySetters = { + [P in keyof T]: UnwrapComputedPropertySetter; +}; + +export type ComputedPropertyGetterFunction = (this: any, key: string) => T; +export type ComputedPropertySetterFunction = (this: any, key: string, newVal: T, oldVal: T) => T; + +export interface ComputedPropertyGetterObj { + get(this: any, key: string): T; +} + +export interface ComputedPropertySetterObj { + set(this: any, key: string, value: T): T; +} +export type ComputedPropertyObj = ComputedPropertyGetterObj | ComputedPropertySetterObj | (ComputedPropertyGetterObj & ComputedPropertySetterObj); + +export type ComputedPropertyGetter = ComputedPropertyGetterFunction | ComputedPropertyGetterObj; +export type ComputedPropertySetter = ComputedPropertySetterFunction | ComputedPropertySetterObj; + +export type ComputedPropertyCallback = ComputedPropertyGetterFunction | ComputedPropertyObj; diff --git a/types/ember/-private-types/utils.d.ts b/types/ember/-private-types/utils.d.ts new file mode 100644 index 0000000000..a9902c7a1d --- /dev/null +++ b/types/ember/-private-types/utils.d.ts @@ -0,0 +1,36 @@ +import { Ember } from "ember"; + +/** + * Map type `T` to a plain object hash with the identity mapping. + * + * Discards any additional object identity like the ability to `new()` up the class. + * The `new()` capability is added back later by merging `EmberClassConstructor` + * + * Implementation is carefully chosen for the reasons described in + * https://github.com/typed-ember/ember-typings/pull/29 + */ +export type Objectify = Readonly; +export type ExtractPropertyNamesOfType = { + [K in keyof T]: T[K] extends S ? K : never +}[keyof T]; +export type Fix = { [K in keyof T]: T[K] }; + +export type KeysOfType = keyof Pick; + +export interface TypeLookup { + string: string; + number: number; + boolean: boolean; + regexp: RegExp; + function: (...args: any[]) => any; + array: any[]; + error: Error; + filelist: FileList; + class: typeof Ember.Object; + instance: Ember.Object; + date: Date; + null: null; + undefined: undefined; +} diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 93babaa0a7..5b059a0ee4 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Ember.js 2.8 +// Type definitions for Ember.js 3.0 // Project: http://emberjs.com/ // Definitions by: Jed Mao // bttf @@ -8,13 +8,24 @@ // Martin Feckie // Alex LaFroscia // Mike North +// Bryan Crotaz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 /// /// declare module 'ember' { + import { + UnwrapComputedPropertySetters, + UnwrapComputedPropertySetter, + UnwrapComputedPropertyGetters, + UnwrapComputedPropertyGetter, + ComputedPropertyCallback + } from 'ember/-private-types/object/computed'; + import { Objectify, Fix, KeysOfType, TypeLookup } from 'ember/-private-types/utils'; + import { EmberClassArguments, EmberClassConstructor, EmberInstanceArguments } from 'ember/-private-types/object'; + // Capitalization is intentional: this makes it much easier to re-export RSVP on // the Ember namespace. import Rsvp from 'rsvp'; @@ -27,40 +38,25 @@ declare module 'ember' { // Get an alias to the global Array type to use in inner scope below. type GlobalArray = T[]; - /** - * Deconstructs computed properties into the types which would be returned by `.get()`. - */ - type ComputedPropertyGetters = { [K in keyof T]: Ember.ComputedProperty | ModuleComputed | T[K] }; - type ComputedPropertySetters = { [K in keyof T]: Ember.ComputedProperty | ModuleComputed | T[K] }; + // TODO: TypeScript 3.0 + // type FunctionArgs any> = F extends (...args: infer ARGS) => any ? ARGS : never; + type FunctionArgs = + F extends (a: infer A) => any + ? [A] + : F extends (a: infer A, b: infer B) => any + ? [A, B] + : F extends (a: infer A, b: infer B, c: infer C) => any + ? [A, B, C] + : F extends (a: infer A, b: infer B, c: infer C, d: infer D) => any + ? [A, B, C, D] + : F extends (a: infer A, b: infer B, c: infer C, d: infer D, e: infer E) => any + ? [A, B, C, D, E] + : never; - /** - * Check that any arguments to `create()` match the type's properties. - * - * Accept any additional properties and add merge them into the instance. - */ - type EmberInstanceArguments = Partial & { - [key: string]: any; - }; - - /** - * Accept any additional properties and add merge them into the prototype. - */ - interface EmberClassArguments { - [key: string]: any; - } - - /** - * Map type `T` to a plain object hash with the identity mapping. - * - * Discards any additional object identity like the ability to `new()` up the class. - * The `new()` capability is added back later by merging `EmberClassConstructor` - * - * Implementation is carefully chosen for the reasons described in - * https://github.com/typed-ember/ember-typings/pull/29 - */ - type Objectify = Readonly; - - type Fix = { [K in keyof T]: T[K] }; + type Mix = B & Pick>; + type Mix3 = Mix, C>; + type Mix4 = Mix3, C, D>; + type Mix5 = Mix4, C, D, E>; /** * Ember.Object.extend(...) accepts any number of mixins or literals. @@ -78,23 +74,6 @@ declare module 'ember' { * Implementation is carefully chosen for the reasons described in * https://github.com/typed-ember/ember-typings/pull/29 */ - type EmberClassConstructor = (new (properties?: object) => T) & (new (...args: any[]) => T); - - type ComputedPropertyGetterFunction = (this: any, key: string) => T; - - interface ComputedPropertyGet { - get(this: any, key: string): T; - } - - interface ComputedPropertySet { - set(this: any, key: string, value: T): T; - } - - type ComputedPropertyCallback = - | ComputedPropertyGetterFunction - | ComputedPropertyGet - | ComputedPropertySet - | (ComputedPropertyGet & ComputedPropertySet); interface ActionsHash { [index: string]: (...params: any[]) => any; @@ -117,7 +96,7 @@ declare module 'ember' { type ObserverMethod = | (keyof Target) - | ((this: Target, sender: Sender, key: keyof Sender, value: any, rev: number) => void); + | ((this: Target, sender: Sender, key: string, value: any, rev: number) => void); interface RenderOptions { into?: string; @@ -298,6 +277,17 @@ declare module 'ember' { interface ArrayPrototypeExtensions extends MutableArray, Observable, Copyable {} + interface StringPrototypeExtensions { + camelize(): string; + decamelize(): string; + classify(): string; + capitalize(): string; + loc(values?: string[]): string; + dasherize(): string; + underscore(): string; + w(): string[]; + } + /** * Given a fullName return a factory manager. */ @@ -485,6 +475,10 @@ declare module 'ember' { * object when the boot process is complete. */ boot(): Promise; + /** + * Create an ApplicationInstance for this Application. + */ + buildInstance(options?: object): ApplicationInstance; } /** The `ApplicationInstance` encapsulates all of the stateful aspects of a @@ -698,6 +692,10 @@ declare module 'ember' { This will force the cached result to be recomputed if the dependencies are modified. **/ class ComputedProperty { + // Necessary in order to avoid losing type information + // see: https://github.com/typed-ember/ember-cli-typescript/issues/246#issuecomment-414812013 + private ______getType: Get; + private ______setType: Set; /** * Call on a computed property to set it into non-cached mode. When in this * mode the computed property will not automatically cache the return value. @@ -741,7 +739,7 @@ declare module 'ember' { class ContainerDebugAdapter extends Object { resolver: Resolver; canCatalogEntriesByType(type: string): boolean; - catalogEntriesByType(type: string): any[]; + catalogEntriesByType(type: string): string[]; } /** * Additional methods for the Controller. @@ -833,36 +831,31 @@ declare module 'ember' { **/ toString(): string; - static create(this: EmberClassConstructor): Fix; + static create(this: Class): InstanceType; - static create>( - this: EmberClassConstructor>, - arg1: T1 & ThisType> - ): Fix; + static create>> + >(this: Class, + arg1: T1 & ThisType> + ): InstanceType & T1; - static create< - Instance, - Args, - T1 extends EmberInstanceArguments, - T2 extends EmberInstanceArguments - >( - this: EmberClassConstructor>, - arg1: T1 & ThisType>, - arg2: T2 & ThisType> - ): Fix; + static create>>, + T2 extends EmberInstanceArguments>> + >(this: Class, + arg1: T1 & ThisType>, + arg2: T2 & ThisType> + ): InstanceType & T1 & T2; - static create< - Instance, - Args, - T1 extends EmberInstanceArguments, - T2 extends EmberInstanceArguments, - T3 extends EmberInstanceArguments - >( - this: EmberClassConstructor>, - arg1: T1 & ThisType>, - arg2: T2 & ThisType>, - arg3: T3 & ThisType> - ): Fix; + static create>>, + T2 extends EmberInstanceArguments>>, + T3 extends EmberInstanceArguments>> + >(this: Class, + arg1: T1 & ThisType>, + arg2: T2 & ThisType>, + arg3: T3 & ThisType> + ): InstanceType & T1 & T2 & T3; static extend( this: Statics & EmberClassConstructor @@ -1011,32 +1004,54 @@ declare module 'ember' { * The container-debug-adapter which is used * to list all models. */ - containerDebugAdapter: any; + containerDebugAdapter: ContainerDebugAdapter; /** * Ember Data > v1.0.0-beta.18 * requires string model names to be passed * around instead of the actual factories. */ - acceptsModelName: any; + acceptsModelName: boolean; /** * Specifies how records can be filtered. * Records returned will need to have a `filterValues` * property with a key for every name in the returned array. */ - getFilters(): any[]; + getFilters(): DataAdapter.Column[]; /** * Fetch the model types and observe them for changes. */ - watchModelTypes(typesAdded: Function, typesUpdated: Function): Function; + watchModelTypes( + typesAdded: (types: DataAdapter.WrappedType[]) => void, + typesUpdated: (types: DataAdapter.WrappedType[]) => void + ): () => void; /** * Fetch the records of a given type and observe them for changes. */ watchRecords( modelName: string, - recordsAdded: Function, - recordsUpdated: Function, - recordsRemoved: Function - ): Function; + recordsAdded: (records: DataAdapter.WrappedRecord[]) => void, + recordsUpdated: (records: DataAdapter.WrappedRecord[]) => void, + recordsRemoved: (idx: number, count: number) => void + ): () => void; + } + namespace DataAdapter { + interface Column { + name: string; + desc: string; + } + interface WrappedRecord { + columnValues: object; + object: object; + } + interface WrappedType { + type: { + name: string; + count: number; + columns: Column[]; + object: typeof Object; + }; + release: () => void; + } } const Debug: { /** @@ -1045,14 +1060,14 @@ declare module 'ember' { * The following example demonstrates its usage by registering a handler that throws an error if the * message contains the word "should", otherwise defers to the default handler. */ - registerDeprecationHandler(handler: Function): any; + registerDeprecationHandler(handler: (message: string, options: { id: string, until: string }, next: () => void) => void): void; /** * Allows for runtime registration of handler functions that override the default warning behavior. * Warnings are invoked by calls made to [Ember.warn](http://emberjs.com/api/classes/Ember.html#method_warn). * The following example demonstrates its usage by registering a handler that does nothing overriding Ember's * default warning behavior. */ - registerWarnHandler(handler: Function): any; + registerWarnHandler(handler: (message: string, options: { id: string }, next: () => void) => void): void; }; /** * The DefaultResolver defines the default lookup rules to resolve @@ -1103,6 +1118,10 @@ declare module 'ember' { * Set this to provide an alternate class to `Ember.DefaultResolver` */ resolver: Resolver; + /** + * Create an EngineInstance for this Engine. + */ + buildInstance(options?: object): EngineInstance; } /** * The `EngineInstance` encapsulates all of the stateful aspects of a @@ -1677,29 +1696,31 @@ declare module 'ember' { /** * Retrieves the value of a property from the object. */ - get(this: ComputedPropertyGetters, key: K): T[K]; + get(key: K): UnwrapComputedPropertyGetter; /** * To get the values of multiple properties at once, call `getProperties` * with a list of strings or an array: */ - getProperties(this: ComputedPropertyGetters, list: K[]): Pick; - getProperties( - this: ComputedPropertyGetters, + getProperties(list: K[]): Pick< UnwrapComputedPropertyGetters, K>; + getProperties( ...list: K[] - ): Pick; + ): Pick< UnwrapComputedPropertyGetters, K>; /** * Sets the provided key or path to the value. */ - set(this: ComputedPropertySetters, key: K, value: T[K]): T[K]; + set(key: K, value: this[K]): this[K]; + set(key: keyof this, value: T): T; /** * Sets a list of properties at once. These properties are set inside * a single `beginPropertyChanges` and `endPropertyChanges` batch, so * observers will be buffered. */ - setProperties( - this: ComputedPropertySetters, - hash: Pick - ): Pick; + setProperties( + hash: Pick + ): Pick< UnwrapComputedPropertySetters, K>; + setProperties( + hash: {[KK in K]: any} + ): Pick< UnwrapComputedPropertySetters, K>; /** * Convenience method to call `propertyWillChange` and `propertyDidChange` in * succession. @@ -1735,11 +1756,10 @@ declare module 'ember' { * Retrieves the value of a property, or a default value in the case that the * property returns `undefined`. */ - getWithDefault( - this: ComputedPropertyGetters, + getWithDefault( key: K, - defaultValue: T[K] - ): T[K]; + defaultValue: UnwrapComputedPropertyGetter + ): UnwrapComputedPropertyGetter; /** * Set the value of a property to the current value plus some amount. */ @@ -1759,7 +1779,7 @@ declare module 'ember' { * without accidentally invoking it if it is intended to be * generated lazily. */ - cacheFor(this: ComputedPropertyGetters, key: K): T[K] | undefined; + cacheFor(key: K): UnwrapComputedPropertyGetter | undefined; } const Observable: Mixin; /** @@ -2417,9 +2437,9 @@ declare module 'ember' { function dasherize(str: string): string; function decamelize(str: string): string; function fmt(...args: string[]): string; - function htmlSafe(str: string): void; // TODO: @returns Handlebars.SafeStringStatic; + function htmlSafe(str: string): Handlebars.SafeString; function isHTMLSafe(str: string): boolean; - function loc(...args: string[]): string; + function loc(template: string, args?: string[]): string; function underscore(str: string): string; function w(str: string): string[]; } @@ -3019,20 +3039,20 @@ declare module 'ember' { /** * Run a function meant for debugging. */ - function runInDebug(func: () => void): any; + function runInDebug(func: () => any): void; /** * Display a warning with the provided message. */ - function warn(message: string, test: boolean, options: { id: string }): any; - function warn(message: string, options: { id: string }): any; + function warn(message: string, test: boolean, options: { id: string }): void; + function warn(message: string, options: { id: string }): void; /** * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options */ - function warn(message: string, test: boolean, options?: { id?: string }): any; + function warn(message: string, test: boolean, options?: { id?: string }): void; /** * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options */ - function warn(message: string, options?: { id?: string }): any; + function warn(message: string, options?: { id?: string }): void; /** * Global helper method to create a new binding. Just pass the root object * along with a `to` and `from` path to create and connect the binding. @@ -3046,9 +3066,9 @@ declare module 'ember' { * it to be created. */ function cacheFor( - obj: ComputedPropertyGetters, + obj: T, key: K - ): T[K] | undefined; + ): UnwrapComputedPropertyGetter | undefined; /** * Add an event listener */ @@ -3094,40 +3114,35 @@ declare module 'ember' { * To get multiple properties at once, call `Ember.getProperties` * with an object followed by a list of strings or an array: */ + function getProperties(obj: T, list: K[]): Pick, K>; // for dynamic K function getProperties( - obj: ComputedPropertyGetters, - list: K[] - ): Pick; - function getProperties(obj: T, list: K[]): Pick; // for dynamic K - function getProperties( - obj: ComputedPropertyGetters, + obj: T, ...list: K[] - ): Pick; - function getProperties(obj: T, ...list: K[]): Pick; // for dynamic K + ): Pick, K>; /** * A value is blank if it is empty or a whitespace string. */ - function isBlank(obj: any): boolean; + function isBlank(obj?: any): boolean; /** * Verifies that a value is `null` or an empty string, empty array, * or empty function. */ - function isEmpty(obj: any): boolean; + function isEmpty(obj?: any): boolean; /** * Returns true if the passed value is null or undefined. This avoids errors * from JSLint complaining about use of ==, which can be technically * confusing. */ - function isNone(obj: any): obj is null | undefined; + function isNone(obj?: any): obj is null | undefined; /** * A value is present if it not `isBlank`. */ - function isPresent(obj: any): boolean; + function isPresent(obj?: any): boolean; /** * Merge the contents of two objects together into the first object. * @deprecated Use Object.assign */ - function merge(original: T, updates: U): T & U; + function merge(original: T, updates: U): Mix; /** * Makes a method available via an additional name. */ @@ -3197,30 +3212,27 @@ declare module 'ember' { * the function will be invoked. If the property is not defined but the * object implements the `unknownProperty` method then that will be invoked. */ - function get(obj: ComputedPropertyGetters, key: K): T[K]; - function get(obj: T, key: K): T[K]; // for dynamic K + function get(obj: T, key: K): UnwrapComputedPropertyGetter; /** * Retrieves the value of a property from an Object, or a default value in the * case that the property returns `undefined`. */ function getWithDefault( - obj: ComputedPropertyGetters, + obj: T, key: K, - defaultValue: T[K] - ): T[K]; - function getWithDefault(obj: T, key: K, defaultValue: T[K]): T[K]; // for dynamic K + defaultValue: UnwrapComputedPropertyGetter + ): UnwrapComputedPropertyGetter; /** * Sets the value of a property on an object, respecting computed properties * and notifying observers and other listeners of the change. If the * property is not defined but the object implements the `setUnknownProperty` * method then that will be invoked as well. */ - function set( - obj: ComputedPropertySetters, + function set( + obj: T, key: K, - value: V - ): V; - function set(obj: T, key: K, value: V): V; // for dynamic K + value: UnwrapComputedPropertySetter + ): UnwrapComputedPropertyGetter; /** * Error-tolerant form of `Ember.set`. Will not blow up if any part of the * chain is `undefined`, `null`, or destroyed. @@ -3232,10 +3244,9 @@ declare module 'ember' { * observers will be buffered. */ function setProperties( - obj: ComputedPropertySetters, - hash: Pick - ): Pick; - function setProperties(obj: T, hash: Pick): Pick; // for dynamic K + obj: T, + hash: Pick, K> + ): Pick, K>; /** * Detects when a specific package of Ember (e.g. 'Ember.Application') * has fully loaded and is available for extension. @@ -3275,14 +3286,17 @@ declare module 'ember' { /** * Returns a consistent type for the passed object. */ + function typeOf(value: T): KeysOfType; + function typeOf(): 'undefined'; function typeOf(item: any): string; /** * Copy properties from a source object to a target object. * @deprecated Use Object.assign */ - function assign(target: T, source: U): T & U; - function assign(target: T, source1: U, source2: V): T & U & V; - function assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + function assign(target: T, source: U): Mix; + function assign(target: T, source1: U, source2: V): Mix3; + function assign(target: T, source1: U, source2: V, source3: W): Mix4; + /** * Polyfill for Object.create * @deprecated Use Object.create @@ -3309,7 +3323,14 @@ declare module 'ember' { * Checks to see if the `methodName` exists on the `obj`, * and if it does, invokes it with the arguments passed. */ - function tryInvoke(obj: any, methodName: string, args?: any[]): any; + function tryInvoke( + obj: T, + methodName: FNAME, + args: FunctionArgs): T[FNAME] extends ((...args: any[]) => any) + ? ReturnType + : undefined; + function tryInvoke(obj: T, methodName: FNAME): T[FNAME] extends (() => any) ? ReturnType : undefined; + function tryInvoke(obj: object, methodName: string, args?: any[]): undefined; /** * Forces the passed object to be part of an array. If the object is already * an array, it will return the object. Otherwise, it will add the object to @@ -3674,7 +3695,9 @@ declare module '@ember/object' { declare module '@ember/object/computed' { import Ember from 'ember'; - export default class ComputedProperty extends Ember.ComputedProperty { } + type ComputedProperty = Ember.ComputedProperty; + const ComputedProperty: typeof Ember.ComputedProperty; + export default ComputedProperty; export const alias: typeof Ember.computed.alias; export const and: typeof Ember.computed.and; export const bool: typeof Ember.computed.bool; @@ -3856,7 +3879,6 @@ declare module '@ember/string' { export const classify: typeof Ember.String.classify; export const dasherize: typeof Ember.String.dasherize; export const decamelize: typeof Ember.String.decamelize; - export const fmt: typeof Ember.String.fmt; export const htmlSafe: typeof Ember.String.htmlSafe; export const isHTMLSafe: typeof Ember.String.isHTMLSafe; export const loc: typeof Ember.String.loc; diff --git a/types/ember/test/access-modifier.ts b/types/ember/test/access-modifier.ts new file mode 100644 index 0000000000..38f5bd4602 --- /dev/null +++ b/types/ember/test/access-modifier.ts @@ -0,0 +1,27 @@ +/** + * Tests to ensure that access modifier keywords are appropriately + * respected and supported + */ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +class Foo extends Ember.Object { + hello() { return 'world'; } + protected bar() { return 'bar'; } + private baz() { return 'baz'; } +} +const f = new Foo(); +assertType(f.hello()); +// protected property should not be visible from outside of Foo +assertType(f.bar()); // $ExpectError +// private property should not be visible from outside of Foo +assertType(f.baz()); // $ExpectError + +class Foo2 extends Ember.Object.extend({ + bar: '' +}) { + hello() { return 'world'; } + // Cannot override with a mis-matched property type + protected bar() { return 'bar'; } // $ExpectError + private baz() { return 'baz'; } +} diff --git a/types/ember/test/application.ts b/types/ember/test/application.ts index d0fc2e9c44..fe4152c01a 100755 --- a/types/ember/test/application.ts +++ b/types/ember/test/application.ts @@ -33,3 +33,9 @@ let App2 = BaseApp.create({ mouseleave: null } }); + +let App3 = BaseApp.create(); + +let App3Instance1 = App3.buildInstance(); + +let App3Instance2 = App3.buildInstance({ foo: 'bar' }); diff --git a/types/ember/test/component.ts b/types/ember/test/component.ts index bcc314300d..13ab88cbbd 100755 --- a/types/ember/test/component.ts +++ b/types/ember/test/component.ts @@ -3,6 +3,9 @@ import Component from '@ember/component'; import Object, { computed } from '@ember/object'; import hbs from 'htmlbars-inline-precompile'; import { assertType } from "./lib/assert"; +import ComputedProperty from '@ember/object/computed'; +import { ExtractPropertyNamesOfType } from 'ember/-private-types/utils'; +import { UnwrapComputedPropertySetter } from 'ember/-private-types/object/computed'; Component.extend({ layout: hbs` diff --git a/types/ember/test/core-object.ts b/types/ember/test/core-object.ts new file mode 100644 index 0000000000..984f5eec12 --- /dev/null +++ b/types/ember/test/core-object.ts @@ -0,0 +1,198 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +/** Newable tests */ +const co1 = new Ember.CoreObject(); + +// TODO: Enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// co1.concatenatedProperties; // $ExpectType string[] +co1.isDestroyed; // $ExpectType boolean +co1.isDestroying; // $ExpectType boolean +co1.destroy(); // $ExpectType CoreObject +co1.toString(); // $ExpectType string + +/** .create tests */ +const co2 = Ember.CoreObject.create(); +// TODO: Enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// co2.concatenatedProperties; // $ExpectType string[] +co2.isDestroyed; // $ExpectType boolean +co2.isDestroying; // $ExpectType boolean +co2.destroy(); // $ExpectType CoreObject +co2.toString(); // $ExpectType string + +/** .create tests w/ initial instance data passed in */ +const co3 = Ember.CoreObject.create({ foo: '123', bar: 456 }); + +co3.foo; // $ExpectType string +co3.bar; // $ExpectType number + +/** .extend with a zero-argument .create() */ +const co4 = Ember.CoreObject.extend({ + foo: '123', + bar: 456, + baz(): [string, number] { + return [this.foo, this.bar]; + } +}).create(); + +co4.foo; // $ExpectType string +co4.bar; // $ExpectType number +co4.baz; // $ExpectType () => [string, number] + +/** .extend with inconsistent arguments passed into .create() */ +const class05 = Ember.CoreObject.extend({ + foo: '123' as (string | boolean), + bar: 456, + baz() { + return [this.foo, this.bar]; + } +}); +const c05 = class05.create({ foo: 99 }); // $ExpectError +const c05b = class05.create({ foo: true }); +const c05c = class05.create({ foo: 'abc' }); +assertType(c05b.foo); // $ExpectError +assertType(c05c.foo); // $ExpectError + +/** two .extend arguments with a zero-argument .create() */ +const co6 = Ember.CoreObject.extend({ + foo: '123', + bar: 456, + baz() { + return [this.foo, this.bar]; + }, + func1() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.foo; // $ExpectType string + // this does not include stuff from later extend args + this.bee; // $ExpectError + } +}, { + foo: 99, + bee: 'honey', + func2() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 + this.foo; // $ExpectType string & number + // this includes stuff from earlier extend-args + this.bar; // $ExpectType number + } +}).create(); + +// TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// assertType(co6.foo); // $ExpectError +assertType(co6.bar); // $ExpectType number +assertType<() => Array>(co6.baz); // $ExpectType () => (string | number)[] + +/** three .extend arguments with a zero-argument .create() */ +const co7 = Ember.CoreObject.extend({ + foo: '123', + bar: 456, + baz() { + return [this.foo, this.bar]; + }, + func1() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.foo; // $ExpectType string + // this does not include stuff from later extend args + this.bee; // $ExpectError + } +}, { + foo: 99, + bee: 'honey', + func2() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 + this.foo; // $ExpectType string & number + // this includes stuff from earlier extend-args + this.bar; // $ExpectType number + } +}, { + foo: '99', + money: 'in the banana stand', + func3() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.money; // $ExpectType string + // this includes stuff from earlier extend-args + this.bee; // $ExpectType string + this.bar; // $ExpectType number + } +}).create(); +// TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// assertType(co7.foo); // $ExpectError +assertType(co7.bar); // $ExpectType number +assertType(co7.money); // $ExpectType string +assertType<() => Array>(co7.baz); // $ExpectType () => (string | number)[] + +/** four .extend arguments with a zero-argument .create() */ +const co8 = Ember.CoreObject.extend({ + foo: '123', + bar: 456, + baz() { + return [this.foo, this.bar]; + }, + func1() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.foo; // $ExpectType string + // this does not include stuff from later extend args + this.bee; // $ExpectError + } +}, { + foo: 99, + bee: 'honey', + func2() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + // TODO: switch to "$ExpectType number" in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 + this.foo; // $ExpectType string & number + // this includes stuff from earlier extend-args + this.bar; // $ExpectType number + // this does not include stuff from later extend args + this.money; // $ExpectError + } +}, { + foo: '99', + money: 'in the banana stand', + func3() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.money; // $ExpectType string + // this includes stuff from earlier extend-args + this.bee; // $ExpectType string + this.bar; // $ExpectType number + // this does not include stuff from later extend args + this.neighborhood; // $ExpectError + } +}, { + foo: '99', + neighborhood: 'sudden valley', + func4() { + // this includes stuff from CoreObject + this.init; // $ExpectType () => void + // this includes stuff from this extend-arg + this.neighborhood; // $ExpectType string + // this includes stuff from earlier extend-args + this.bee; // $ExpectType string + this.bar; // $ExpectType number + this.money; // $ExpectType string + } +}).create(); + +// TODO: enable in TS 3.0 see: https://github.com/typed-ember/ember-cli-typescript/issues/291 +// assertType(co8.foo); // $ExpectError +assertType(co8.bar); // $ExpectType number +assertType(co8.money); // $ExpectType string +assertType<() => Array>(co8.baz); // $ExpectType () => (string | number)[] diff --git a/types/ember/test/create-negative.ts b/types/ember/test/create-negative.ts new file mode 100644 index 0000000000..234b737a6f --- /dev/null +++ b/types/ember/test/create-negative.ts @@ -0,0 +1,11 @@ +import { assertType } from './lib/assert'; +import Ember from 'ember'; +import { PersonWithNumberName, Person } from './create'; + +Person.create({ firstName: 99 }); // $ExpectError +Person.create({}, { firstName: 99 }); // $ExpectError +Person.create({}, {}, { firstName: 99 }); // $ExpectError + +const p4 = new PersonWithNumberName(); + +// assertType>(p4.fullName); // $ExpectError diff --git a/types/ember/test/create.ts b/types/ember/test/create.ts index 6dc61b80f6..fb32fc8166 100755 --- a/types/ember/test/create.ts +++ b/types/ember/test/create.ts @@ -1,7 +1,54 @@ import Ember from 'ember'; import { assertType } from './lib/assert'; +/** + * Zero-argument case + */ +const o = Ember.Object.create(); +// create returns an object +assertType(o); +// object returned by create type-checks as an instance of Ember.Object +assertType(o.isDestroyed); // from instance +assertType(o.isDestroying); // from instance +assertType<(key: string) => any>(o.get); // from prototype + +/** + * One-argument case + */ +const o1 = Ember.Object.create({x: 9, y: 'hello', z: false}); +assertType(o1.x); +assertType(o1.y); +o1.y; // $ExpectType string +o1.z; // $ExpectType boolean + const obj = Ember.Object.create({ a: 1 }, { b: 2 }, { c: 3 }); -assertType(obj.a); assertType(obj.b); +assertType(obj.a); assertType(obj.c); + +export class Person extends Ember.Object.extend({ + fullName: Ember.computed('firstName', 'lastName', function() { + return [this.firstName + this.lastName].join(' '); + }) +}) { + firstName: string; + lastName: string; + age: number; +} +const p = new Person(); + +assertType(p.firstName); +assertType>(p.fullName); +assertType(p.get('fullName')); + +const p2 = Person.create({ firstName: 'string' }); +const p2b = Person.create({}, { firstName: 'string' }); +const p2c = Person.create({}, {}, { firstName: 'string' }); + +export class PersonWithNumberName extends Person.extend({ + fullName: 6 +}) {} + +const p4 = new PersonWithNumberName(); +assertType(p4.firstName); +assertType(p4.fullName); diff --git a/types/ember/test/data-adapter.ts b/types/ember/test/data-adapter.ts new file mode 100644 index 0000000000..ea77b27e70 --- /dev/null +++ b/types/ember/test/data-adapter.ts @@ -0,0 +1,53 @@ +import Ember from 'ember'; + +const da = Ember.DataAdapter.create(); + +const filters = da.getFilters(); +filters.includes({ name: 'foo', desc: 'bar'}); // $ExpectType boolean +filters.includes({}); // $ExpectError + +filters[0].name; // $ExpectType string +filters[0].desc; // $ExpectType string + +da.watchModelTypes(// $ExpectType () => void + function added(wrappedTypes) { + wrappedTypes; + wrappedTypes[0].release; // $ExpectType () => void + wrappedTypes[0].type.columns[0].desc; // $ExpectType string + wrappedTypes[0].type.columns[0].name; // $ExpectType string + wrappedTypes[0].type.count; // $ExpectType number + wrappedTypes[0].type.name; // $ExpectType string + }, + function updated(wrappedTypes) { + wrappedTypes; + wrappedTypes[0].release; // $ExpectType () => void + wrappedTypes[0].type.columns[0].desc; // $ExpectType string + wrappedTypes[0].type.columns[0].name; // $ExpectType string + wrappedTypes[0].type.count; // $ExpectType number + wrappedTypes[0].type.name; // $ExpectType string + } +); +da.watchModelTypes(() => void); // $ExpectError + +da.watchRecords('house', // $ExpectType () => void + function added(records) { + records[0].object; // $ExpectType object + records[0].columnValues; // $ExpectType object + }, + function updated(records) { + records[0].object; // $ExpectType object + records[0].columnValues; // $ExpectType object + }, + function removed(idx, count) { + idx; // $ExpectType number + count; // $ExpectType number + } +); +da.watchRecords(() => void); // $ExpectError + +da.acceptsModelName; // $ExpectType boolean +da.containerDebugAdapter; // $ExpectType ContainerDebugAdapter + +const ca: Ember.ContainerDebugAdapter = da.containerDebugAdapter; +ca.canCatalogEntriesByType('controller'); // $ExpectType boolean +ca.catalogEntriesByType('controller'); // $ExpectType string[] diff --git a/types/ember/test/debug.ts b/types/ember/test/debug.ts new file mode 100644 index 0000000000..b3f4bb5f17 --- /dev/null +++ b/types/ember/test/debug.ts @@ -0,0 +1,53 @@ +import Ember from 'ember'; + +const { + runInDebug, + warn, + debug, + assert, + Debug: { registerDeprecationHandler, registerWarnHandler } +} = Ember; + +/** + * @ember/debug tests + */ +runInDebug(); // $ExpectError +let x = runInDebug(() => console.log('Should not show up in prod')); // $ExpectType void + +// Log a warning if we have more than 3 tomsters +const tomsterCount = 2; +warn('Too many tomsters!'); // $ExpectType void +warn('Too many tomsters!', tomsterCount <= 3); // $ExpectType void +warn('Too many tomsters!', tomsterCount <= 3, { // $ExpectType void + id: 'ember-debug.too-many-tomsters' +}); + +debug(); // $ExpectError +debug('Too many tomsters!'); // $ExpectType void +debug('Too many tomsters!', 'foo'); // $ExpectError + +// Test for truthiness +const str = 'hello'; +assert('Must pass a string', typeof str === 'string'); // $ExpectType void + +// Fail unconditionally +assert('This code path should never be run'); // $ExpectType void + +// next is not called, so no warnings get the default behavior +registerWarnHandler(); // $ExpectError +registerWarnHandler(() => {}); // $ExpectType void +registerWarnHandler((message, { id }, next) => { // $ExpectType void + message; // $ExpectType string + id; // $ExpectType string + next; // $ExpectType () => void +}); + +// next is not called, so no warnings get the default behavior +registerDeprecationHandler(); // $ExpectError +registerDeprecationHandler(() => {}); // $ExpectType void +registerDeprecationHandler((message, { id, until }, next) => { // $ExpectType void + message; // $ExpectType string + id; // $ExpectType string + until; // $ExpectType string + next; // $ExpectType () => void +}); diff --git a/types/ember/test/ember-tests.ts b/types/ember/test/ember-tests.ts index c049512eb0..c78cb282a2 100755 --- a/types/ember/test/ember-tests.ts +++ b/types/ember/test/ember-tests.ts @@ -168,3 +168,6 @@ const component1 = Ember.Component.extend(mix1, mix2, { lyft: Ember.inject.service(), cars: Ember.computed.readOnly('lyft.cars'), }); + +// make sure htmlSafe returns a SafeString +Ember.String.htmlSafe("hello"); // $ExpectType SafeString diff --git a/types/ember/test/engine.ts b/types/ember/test/engine.ts new file mode 100755 index 0000000000..508bd3be4d --- /dev/null +++ b/types/ember/test/engine.ts @@ -0,0 +1,41 @@ +import Ember from 'ember'; +import { assertType } from "./lib/assert"; + +let BaseEngine = Ember.Engine.extend({ + modulePrefix: 'my-engine' +}); + +BaseEngine.initializer({ + name: 'my-initializer', + initialize(engine) { + engine.register('foo:bar', Ember.Object.extend({ foo: 'bar' })); + } +}); + +BaseEngine.instanceInitializer({ + name: 'my-instance-initializer', + initialize(engine) { + engine.lookup('foo:bar').get('foo'); + } +}); + +let Engine1 = BaseEngine.create({ + rootElement: '#engine-one', + customEvents: { + paste: 'paste' + } +}); + +let Engine2 = BaseEngine.create({ + rootElement: '#engine-two', + customEvents: { + mouseenter: null, + mouseleave: null + } +}); + +let Engine3 = BaseEngine.create(); + +let Engine3Instance1 = Engine3.buildInstance(); + +let Engine3Instance2 = Engine3.buildInstance({ foo: 'bar' }); diff --git a/types/ember/test/lib/assert.ts b/types/ember/test/lib/assert.ts index d6748cd5bc..262d18bc2c 100755 --- a/types/ember/test/lib/assert.ts +++ b/types/ember/test/lib/assert.ts @@ -2,4 +2,4 @@ // Disable tslint here b/c the generic is used to let us do a type coercion and // validate that coercion works for the type value "passed into" the function. // tslint:disable-next-line:no-unnecessary-generics -export declare function assertType(value: T): void; +export declare function assertType(value: T): T; diff --git a/types/ember/test/object.ts b/types/ember/test/object.ts index e1eefb75e9..7446d5e3ef 100755 --- a/types/ember/test/object.ts +++ b/types/ember/test/object.ts @@ -25,3 +25,27 @@ class MyObject31 extends Ember.Object { super(properties); } } + +class Foo extends Ember.Object.extend({ + a: Ember.computed({ + get() { return ''; }, + set(key: string, newVal: string) { return ''; } + }) +}) { + b = 5; + baz() { + let y = this.b; // $ExpectType number + let z = this.a; // $ExpectType ComputedProperty + this.b = 10; + this.get('b').toFixed(4); // $ExpectType string + this.set('a', 'abc').split(','); // $ExpectType string[] + this.set('b', 10).toFixed(4); // $ExpectType string + + this.setProperties({ b: 11 }); + // this.setProperties({ b: '11' }); // $ExpectError + this.setProperties({ + a: 'def', + b: 11 + }); + } +} diff --git a/types/ember/test/private/computed-tests.ts b/types/ember/test/private/computed-tests.ts new file mode 100644 index 0000000000..a4c3e819f6 --- /dev/null +++ b/types/ember/test/private/computed-tests.ts @@ -0,0 +1,82 @@ +import { Ember } from "ember"; +import { computed } from "@ember/object"; +import { UnwrapComputedPropertySetters, UnwrapComputedPropertyGetters, UnwrapComputedPropertySetter, UnwrapComputedPropertyGetter } from "ember/-private-types/object/computed"; +import ComputedProperty from "@ember/object/computed"; +import { assertType } from "../lib/assert"; + +class Example1 extends Ember.Object.extend({ + firstName: '', + lastName: '', + allNames: computed('fullName', function() { + return [this.fullName]; + }), + fullName: computed('firstName', 'lastName', function() { + return `${this.firstName} ${this.lastName}`; + }) +}) { + allNames!: ComputedProperty; + fullName!: ComputedProperty; +} + +let unwrappedGetters1: UnwrapComputedPropertyGetters = {} as any; +unwrappedGetters1.firstName; // $ExpectType string +unwrappedGetters1.lastName; // $ExpectType string +unwrappedGetters1.fullName; // $ExpectType string +unwrappedGetters1.allNames; // $ExpectType string[] + +let unwrappedSetters1: UnwrapComputedPropertySetters = {} as any; +unwrappedSetters1.firstName; // $ExpectType string +unwrappedSetters1.lastName; // $ExpectType string +unwrappedSetters1.fullName; // $ExpectType string +unwrappedSetters1.allNames; // $ExpectType string[] + +class Example2 extends Ember.Object.extend({ + allNames: computed('fullName', function() { + return [this.fullName + '']; + }) , + fullName: computed('firstName', 'lastName', function() { + return `${this.firstName} ${this.lastName}`; + }) +}) { + firstName = ''; + lastName = ''; + foo() { + this.fullName; // $ExpectType ComputedProperty + this.allNames; // $ExpectType ComputedProperty + this.firstName; // $ExpectType string + this.lastName; // $ExpectType string + + this.get('fullName').split(','); // $ExpectType string[] + this.get('allNames')[0]; // $ExpectType string + this.get('firstName').split(','); // $ExpectType string[] + this.get('lastName').split(','); // $ExpectType string[] + } +} +let ex2 = new Example2(); + +let unwrappedGetters2: UnwrapComputedPropertyGetters = (ex2 as any) as UnwrapComputedPropertyGetters; +assertType(unwrappedGetters2.firstName); // $ExpectType string +assertType(unwrappedGetters2.lastName); // $ExpectType string +assertType(unwrappedGetters2.fullName); // $ExpectType string +assertType(unwrappedGetters2.allNames); // $ExpectType string[] + +let unwrappedSetters2: UnwrapComputedPropertySetters = null as any; +assertType(unwrappedSetters2.firstName); // $ExpectType string +assertType(unwrappedSetters2.lastName); // $ExpectType string +assertType(unwrappedSetters2.fullName); // $ExpectType string +assertType(unwrappedSetters2.allNames); // $ExpectType string[] + +ex2.fullName; // $ExpectType ComputedProperty +ex2.allNames; // $ExpectType ComputedProperty +ex2.firstName; // $ExpectType string + +type UnwStringSet = UnwrapComputedPropertySetter; // $ExpectType string +type UnwStringGet = UnwrapComputedPropertyGetter; // $ExpectType string +type UnwCpStringSet1 = UnwrapComputedPropertySetter>; // $ExpectType string +type UnwCpStringGet1 = UnwrapComputedPropertyGetter>; // $ExpectType string +type UnwCpStringSet2 = UnwrapComputedPropertySetter>; // $ExpectType string +type UnwCpStringGet2 = UnwrapComputedPropertyGetter>; // $ExpectType string +type UnwCpStringSet3 = UnwrapComputedPropertySetter>; // $ExpectType string +type UnwCpStringGet3 = UnwrapComputedPropertyGetter>; // $ExpectType number +type UnwCpStringSet4 = UnwrapComputedPropertySetter>; // $ExpectType number +type UnwCpStringGet4 = UnwrapComputedPropertyGetter>; // $ExpectType string diff --git a/types/ember/test/private/observable-tests.ts b/types/ember/test/private/observable-tests.ts new file mode 100644 index 0000000000..be3d4bd69f --- /dev/null +++ b/types/ember/test/private/observable-tests.ts @@ -0,0 +1,175 @@ +import Observable from "@ember/object/observable"; +import { UnwrapComputedPropertyGetter, UnwrapComputedPropertyGetters, UnwrapComputedPropertySetters, UnwrapComputedPropertySetter } from "ember/-private-types/object/computed"; +// tslint-disable-next-line +import { assertType } from "../lib/assert"; +import { Ember } from "ember"; +import { ExtractPropertyNamesOfType } from "ember/-private-types/utils"; + +class OtherThing { + observerOfDemo(target: DemoObservable, key: 'foo') {} +} + +class DemoObservable implements Observable { + foo: string; + isFoo = true; + bar: [boolean, boolean]; + baz?: number; + constructor() { + this.foo = 'hello'; + this.bar = [false, true]; + this.baz = 9; + this.addObserver('foo', this, 'fooDidChange'); + this.addObserver('foo', this, 'fooDidChangeProtected'); // $ExpectError + this.addObserver('foo', this, this.fooDidChange); + this.addObserver('foo', this, this.fooDidChangeProtected); + const ot = new OtherThing(); + this.addObserver('foo', ot, ot.observerOfDemo); + Ember.addObserver(this, 'foo', this, 'fooDidChange'); + Ember.addObserver(this, 'foo', this, 'fooDidChangeProtected'); // $ExpectError + Ember.addObserver(this, 'foo', this, this.fooDidChange); + Ember.addObserver(this, 'foo', this, this.fooDidChangeProtected); + this.removeObserver('foo', this, 'fooDidChange'); + this.removeObserver('foo', this, 'fooDidChangeProtected'); // $ExpectError + this.removeObserver('foo', this, this.fooDidChange); + this.removeObserver('foo', this, this.fooDidChangeProtected); + Ember.removeObserver(this, 'foo', this, 'fooDidChange'); + Ember.removeObserver(this, 'foo', this, 'fooDidChangeProtected'); // $ExpectError + Ember.removeObserver(this, 'foo', this, this.fooDidChange); + const lambda = () => { + this.fooDidChange(this, 'foo'); + }; + this.addObserver('foo', lambda); + this.addObserver('foo', (sender, key, value, rev) => { + assertType(sender); + assertType<'foo'>(key); + assertType(value); + assertType(rev); + }); + this.removeObserver('foo', lambda); + Ember.addObserver(this, 'foo', lambda); + Ember.removeObserver(this, 'foo', lambda); + } + + fooDidChange(obj: this, propName: 'foo') {} + protected fooDidChangeProtected(obj: this, propName: 'foo') {} + get(key: K): UnwrapComputedPropertyGetter { + throw new Error("Method not implemented."); + } + getProperties(list: K[]): Pick, K>; + getProperties(...list: K[]): Pick, K>; + getProperties(...rest: any[]): any { + throw new Error("Method not implemented."); + } + set(key: K, value: this[K]): this[K] { + throw new Error("Method not implemented."); + } + setProperties(hash: Pick): Pick< UnwrapComputedPropertySetters, K> { + throw new Error("Method not implemented."); + } + notifyPropertyChange(keyName: string): this { + throw new Error("Method not implemented."); + } + addObserver(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): void; + addObserver(key: K, method: keyof this | ((this: this, sender: this, key: K, value: this[K], rev: number) => void)): void; + addObserver(key: any, target: any, method?: any) { + throw new Error("Method not implemented."); + } + removeObserver(key: keyof this, target: Target, method: keyof Target | ((this: Target, sender: this, key: string, value: any, rev: number) => void)): void; + removeObserver(key: keyof this, method: keyof this | ((this: this, sender: this, key: string, value: any, rev: number) => void)): void; + removeObserver(key: any, target: any, method?: any): void { + throw new Error("Method not implemented."); + } + getWithDefault(key: K, defaultValue: UnwrapComputedPropertyGetter): UnwrapComputedPropertyGetter { + throw new Error("Method not implemented."); + } + incrementProperty(keyName: ExtractPropertyNamesOfType, increment?: number): number { + throw new Error("Method not implemented."); + } + decrementProperty(keyName: ExtractPropertyNamesOfType, decrement?: number): number { + throw new Error("Method not implemented."); + } + toggleProperty(keyName: ExtractPropertyNamesOfType): boolean { + throw new Error("Method not implemented."); + } + cacheFor(key: K): UnwrapComputedPropertyGetter | undefined { + throw new Error("Method not implemented."); + } +} +const o = new DemoObservable(); + +/** + * get + */ +assertType(o.get('foo')); // $ExpectType string +assertType<[boolean, boolean]>(o.get('bar')); // $ExpectType [boolean, boolean] +assertType(o.get('baz')); // $ExpectType number | undefined + +/** + * incrementProperty, decrementProperty + */ +assertType(o.incrementProperty('baz')); // $ExpectType number +assertType(o.decrementProperty('baz')); // $ExpectType number +assertType(o.incrementProperty('baz', 3)); // $ExpectType number +assertType(o.decrementProperty('baz', 12)); // $ExpectType number +// non-numeric property case +assertType(o.incrementProperty('bar')); // $ExpectError +assertType(o.decrementProperty('bar')); // $ExpectError +// empty case +assertType(o.incrementProperty()); // $ExpectError +assertType(o.decrementProperty()); // $ExpectError + +/** + * toggleProperty + */ +o.toggleProperty('isFoo'); // $ExpectType boolean +o.toggleProperty(); // $ExpectError + +/** + * getWithDefault + */ +assertType(o.getWithDefault('foo', 'zzz')); // $ExpectType string +assertType<[boolean, boolean]>(o.getWithDefault('bar', [false, false])); // $ExpectType [boolean, boolean] +assertType(o.getWithDefault('baz', 10)); // $ExpectType number | undefined +// improper arguments cases +assertType(o.getWithDefault('baz', '10')); // $ExpectError +assertType(o.getWithDefault('baz')); // $ExpectError +assertType(o.getWithDefault()); // $ExpectError + +/** + * getProperties + */ +// ('foo', 'bar') +assertType<{ foo: string, bar: [boolean, boolean] }>(o.getProperties('foo', 'bar')); // $ExpectType { foo: string; bar: [boolean, boolean]; } +// ['foo', 'bar'] +assertType<{ foo: string, bar: [boolean, boolean] }>(o.getProperties(['foo', 'bar'])); // $ExpectType { foo: string; bar: [boolean, boolean]; } +// empty cases +assertType<{}>(o.getProperties()); // $ExpectType {} +assertType<{}>(o.getProperties([])); // $ExpectType {} +// property that doesn't exist +assertType(o.getProperties('jeanShorts', 'foo')); // $ExpectError +assertType(o.getProperties(['foo', 'jeanShorts'])); // $ExpectError + +/** + * set + */ +assertType(o.set('foo', 'abc')); // $ExpectType string +assertType<[boolean, boolean]>(o.set('bar', [false, false])); // $ExpectType [boolean, boolean] +assertType(o.set('baz', undefined)); // $ExpectType number | undefined +assertType(o.set('baz', 10)); // $ExpectType number | undefined +// property that doesn't exist +assertType(o.set('jeanShorts', 10)); // $ExpectError + +/** + * setProperties + */ +assertType<{ foo: string, bar: [boolean, boolean] }>(o.setProperties({ foo: 'abc', bar: [true, true] })); // $ExpectType { foo: string; bar: [boolean, boolean]; } +// empty case +assertType<{}>(o.setProperties({})); // $ExpectType {} +// property that doesn't exist +assertType(o.setProperties({ jeanShorts: 'under the pants' })); // $ExpectError + +/** + * notifyPropertyChange + */ +assertType(o.notifyPropertyChange('foo')); // $ExpectType DemoObservable +assertType(o.notifyPropertyChange('jeanShorts')); // $ExpectError diff --git a/types/ember/test/reopen.ts b/types/ember/test/reopen.ts index 6c13ca4155..ee5ee04edc 100755 --- a/types/ember/test/reopen.ts +++ b/types/ember/test/reopen.ts @@ -29,6 +29,9 @@ assertType(Person2.species); let tom = Person2.create({ name: 'Tom Dale' }); + +let badTom = Person2.create({ name: 99 }); // $ExpectError + let yehuda = Person2.createPerson('Yehuda Katz'); tom.sayHello(); // "Hello. My name is Tom Dale" diff --git a/types/ember/test/string-ext.ts b/types/ember/test/string-ext.ts new file mode 100644 index 0000000000..e4ac77d5b4 --- /dev/null +++ b/types/ember/test/string-ext.ts @@ -0,0 +1,28 @@ +import Ember from 'ember'; + +declare global { + interface String extends Ember.StringPrototypeExtensions {} +} + +''.dasherize('foo'); // $ExpectError +''.dasherize(); // $ExpectType string + +''.camelize(); // $ExpectType string +''.camelize('blue man group'); // $ExpectError + +''.decamelize(); // $ExpectType string +''.decamelize('blue man group'); // $ExpectError + +''.underscore(); // $ExpectType string +''.underscore('blue man group'); // $ExpectError + +''.w(); // $ExpectType string[] + +''.classify(); // $ExpectType string +''.classify('blue man group'); // $ExpectError + +''.capitalize(); // $ExpectType string +''.capitalize('blue man group'); // $ExpectError + +''.loc(); // $ExpectType string +''.loc("_Hello World"); // $ExpectError diff --git a/types/ember/test/string.ts b/types/ember/test/string.ts new file mode 100644 index 0000000000..0543bd60d0 --- /dev/null +++ b/types/ember/test/string.ts @@ -0,0 +1,36 @@ +import Ember from 'ember'; + +const { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w } = Ember.String; + +dasherize(); // $ExpectError +dasherize('blue man group'); // $ExpectType string +dasherize('', ''); // $ExpectError + +camelize(); // $ExpectError +camelize('blue man group'); // $ExpectType string +camelize('', ''); // $ExpectError + +decamelize(); // $ExpectError +decamelize('blue man group'); // $ExpectType string +decamelize('', ''); // $ExpectError + +underscore(); // $ExpectError +underscore('blue man group'); // $ExpectType string +underscore('', ''); // $ExpectError + +w(); // $ExpectError +w('blue man group'); // $ExpectType string[] +w('', ''); // $ExpectError + +classify(); // $ExpectError +classify('blue man group'); // $ExpectType string +classify('', ''); // $ExpectError + +capitalize(); // $ExpectError +capitalize('blue man group'); // $ExpectType string +capitalize('', ''); // $ExpectError + +loc(); // $ExpectError +loc("_Hello World"); // $ExpectType string +// TODO - fix this case upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/281 +loc("_Hello %@ %@", ["John", "Smith"]); // $ExpectType string diff --git a/types/ember/test/techniques/properties-from-this.ts b/types/ember/test/techniques/properties-from-this.ts new file mode 100644 index 0000000000..eef58009c3 --- /dev/null +++ b/types/ember/test/techniques/properties-from-this.ts @@ -0,0 +1,62 @@ +/** + * These tests validate that the method of pulling property types off of this + * continues to work. We use this technique in the critical Observable interface + * that serves to implement a lot of Ember.CoreObject's functionality + */ + +class BoxedProperty { + __getType: Get; + __setType: Set; +} + +type UnboxGetProperty = T extends BoxedProperty ? V : T; +type UnboxSetProperty = T extends BoxedProperty ? V : T; + +class GetAndSet { + get(key: K): UnboxGetProperty { + return this[key] as any; + } + set(key: K, newVal: UnboxSetProperty): UnboxSetProperty { + const rawVal: UnboxSetProperty = this[key] as any; + if (rawVal instanceof BoxedProperty) { + rawVal.__setType = newVal; + } + this[key] = newVal as any; + return newVal; + } +} + +class Foo123 extends GetAndSet { + // tslint:disable-next-line:no-inferrable-types + a: number; + b: [boolean, boolean]; + c: string; + cpA!: BoxedProperty; + constructor() { + super(); + this.a = 1; + this.b = [true, false]; + this.c = 'hello'; + } +} + +let f = new Foo123(); + +f.get('a'); // $ExpectType number +f.set('a'); // $ExpectError +f.set('a', '1'); // $ExpectError +f.set('a', 1); // $ExpectType number + +f.get('b'); // $ExpectType [boolean, boolean] +f.set('b', 1); // $ExpectError +f.set('b', []); // $ExpectError +f.set('b', [true]); // $ExpectError +f.set('b', [false, true]); // $ExpectType [boolean, boolean] +f.set('b', [false, true, false]); // $ExpectError + +f.get('c'); // $ExpectType string +f.set('c', '1'); // $ExpectType string + +f.get('cpA'); // $ExpectType string +f.set('cpA', ['newValue']); // $ExpectError +f.set('cpA', 'newValue'); // $ExpectType string diff --git a/types/ember/test/utils.ts b/types/ember/test/utils.ts index d729d472b8..77b52ca218 100755 --- a/types/ember/test/utils.ts +++ b/types/ember/test/utils.ts @@ -2,6 +2,11 @@ import Ember from 'ember'; import * as utils from '@ember/utils'; import { assertType } from "./lib/assert"; +function testTypeOf() { + utils.typeOf(); // $ExpectType "undefined" + const str: string = utils.typeOf({}); +} + function testIsNoneType() { const maybeUndefined: string | undefined = 'not actually undefined'; if (utils.isNone(maybeUndefined)) { @@ -9,6 +14,31 @@ function testIsNoneType() { } const anotherString = maybeUndefined + 'another string'; + utils.isNone(); // $ExpectType boolean +} + +function testIsBlank() { + utils.isBlank(); // $ExpectType boolean + utils.isBlank(''); // $ExpectType boolean + utils.isBlank('', ''); // $ExpectError +} + +function testIsEmpty() { + utils.isEmpty(); // $ExpectType boolean + utils.isEmpty(''); // $ExpectType boolean + utils.isEmpty('', ''); // $ExpectError +} + +function testIsPresent() { + utils.isPresent(); // $ExpectType boolean + utils.isPresent(''); // $ExpectType boolean + utils.isPresent('', ''); // $ExpectError +} + +function testIsNone() { + utils.isNone(); // $ExpectType boolean + utils.isNone(''); // $ExpectType boolean + utils.isNone('', ''); // $ExpectError } function testMerge() { @@ -69,3 +99,78 @@ function testDefineProperty() { return `${this.firstName} ${this.lastName}`; })); } + +function testTryInvoke() { + class Foo { + hello() { return ['world']; } + add(x: number, y: string) { return x + parseInt(y, 10); } + apples(n: number) { return `${n} apples`; } + } + // zero-argument function + Ember.tryInvoke(new Foo(), 'hello'); // $ExpectType string[] + // one-argument function + Ember.tryInvoke(new Foo(), 'apples', [4]); // $ExpectType string + // multi-argument function with different types (reversed types negative test case below) + Ember.tryInvoke(new Foo(), 'add', [4, '3']); // $ExpectType number + + // Cases that should return undefined + // No args provided + Ember.tryInvoke(new Foo(), 'apples'); // $ExpectType undefined + // Function does not exist + Ember.tryInvoke(new Foo(), 'doesNotExist'); // $ExpectType undefined + // Empty args provided + Ember.tryInvoke(new Foo(), 'apples', []); // $ExpectType undefined + // Wrong args provided + Ember.tryInvoke(new Foo(), 'apples', ['']); // $ExpectType undefined + // Wrong arg types + Ember.tryInvoke(new Foo(), 'add', [4, 3]); // $ExpectType undefined + // Reversed arg types + Ember.tryInvoke(new Foo(), 'add', ['4', 3]); // $ExpectType undefined +} + +(function() { + /** typeOf */ + // TODO: more specific return type in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/259 + Ember.typeOf(); // $ExpectType "undefined" + Ember.typeOf(null); // $ExpectType "null" + Ember.typeOf(undefined); // $ExpectType "undefined" + Ember.typeOf('michael'); // $ExpectType "string" + // tslint:disable-next-line:no-construct + Ember.typeOf(new String('michael')); // $ExpectType "string" + Ember.typeOf(101); // $ExpectType "number" + // tslint:disable-next-line:no-construct + Ember.typeOf(new Number(101)); // $ExpectType "number" + Ember.typeOf(true); // $ExpectType "boolean" + // tslint:disable-next-line:no-construct + Ember.typeOf(new Boolean(true)); // $ExpectType "boolean" + Ember.typeOf(() => 4); // $ExpectType "function" + Ember.typeOf([1, 2, 90]); // $ExpectType "array" + Ember.typeOf(/abc/); // $ExpectType "regexp" + Ember.typeOf(new Date()); // $ExpectType "date" + Ember.typeOf(({} as any) as FileList); // $ExpectType "filelist" + Ember.typeOf(Ember.Object.extend()); // $ExpectType "class" + Ember.typeOf(Ember.Object.create()); // $ExpectType "instance" + Ember.typeOf(new Error('teamocil')); // $ExpectType "error" + Ember.typeOf((new Date()) as RegExp | Date); // "regexp" | "date" +})(); + +(function() { /* assign */ + Ember.assign({}, { a: 'b'}); + Ember.assign({}, { a: 'b'}).a; // $ExpectType string + Ember.assign({ a: 6 }, { a: 'b'}).a; // $ExpectType string + Ember.assign({ a: 6 }, {}).a; // $ExpectType number + Ember.assign({ b: 6 }, {}).a; // $ExpectError + Ember.assign({}, { b: 6 }, {}).b; // $ExpectType number + Ember.assign({ a: 'hello' }, { b: 6 }, {}).a; // $ExpectType string + Ember.assign({ a: 'hello' }, { b: 6 }, { a: true }).a; // $ExpectType boolean + Ember.assign({ a: 'hello' }, '', { a: true }).a; // $ExpectError + Ember.assign({ d: ['gobias industries'] }, { a: 'hello' }, { b: 6 }, { a: true }).d; // $ExpectType string[] +}()); + +(function() { /* merge */ + Ember.merge({}, { a: 'b'}); + Ember.merge({}, { a: 'b'}).a; // $ExpectType string + Ember.merge({ a: 6 }, { a: 'b'}).a; // $ExpectType string + Ember.merge({ a: 6 }, {}).a; // $ExpectType number + Ember.merge({ b: 6 }, {}).a; // $ExpectError +}()); diff --git a/types/ember/tsconfig.json b/types/ember/tsconfig.json index 676c107f72..a267c26dd5 100755 --- a/types/ember/tsconfig.json +++ b/types/ember/tsconfig.json @@ -20,36 +20,51 @@ }, "files": [ "index.d.ts", + "-private-types/utils.d.ts", + "-private-types/mixin.d.ts", + "-private-types/object.d.ts", + "-private-types/object/computed.d.ts", "test/lib/assert.ts", - "test/application.ts", + "test/private/computed-tests.ts", + "test/private/observable-tests.ts", + "test/techniques/properties-from-this.ts", + "test/access-modifier.ts", "test/application-instance.ts", - "test/engine-instance.ts", + "test/application.ts", + "test/array-ext.ts", + "test/array-proxy.ts", + "test/array.ts", + "test/component.ts", + "test/computed.ts", + "test/controller.ts", + "test/core-object.ts", + "test/create-negative.ts", + "test/create.ts", + "test/data-adapter.ts", + "test/debug.ts", + "test/detect-instance.ts", + "test/detect.ts", "test/ember-tests.ts", + "test/engine-instance.ts", + "test/engine.ts", "test/error.ts", "test/event.ts", "test/extend.ts", - "test/create.ts", + "test/function-ext.ts", + "test/helper.ts", + "test/inject.ts", + "test/mixin.ts", "test/object.ts", "test/observable.ts", - "test/mixin.ts", "test/reopen.ts", - "test/detect.ts", - "test/detect-instance.ts", - "test/array.ts", - "test/array-ext.ts", - "test/array-proxy.ts", - "test/helper.ts", - "test/computed.ts", - "test/component.ts", - "test/function-ext.ts", - "test/inject.ts", - "test/utils.ts", - "test/transition.ts", + "test/route.ts", "test/router.ts", "test/run.ts", + "test/string-ext.ts", + "test/string.ts", "test/test.ts", - "test/controller.ts", - "test/route.ts", + "test/transition.ts", + "test/utils.ts", "test/view-utils.ts" ] } diff --git a/types/ember/v2/index.d.ts b/types/ember/v2/index.d.ts new file mode 100755 index 0000000000..93babaa0a7 --- /dev/null +++ b/types/ember/v2/index.d.ts @@ -0,0 +1,3898 @@ +// Type definitions for Ember.js 2.8 +// Project: http://emberjs.com/ +// Definitions by: Jed Mao +// bttf +// Derek Wickern +// Chris Krycho +// Theron Cross +// Martin Feckie +// Alex LaFroscia +// Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// +/// + +declare module 'ember' { + // Capitalization is intentional: this makes it much easier to re-export RSVP on + // the Ember namespace. + import Rsvp from 'rsvp'; + import { TemplateFactory } from 'htmlbars-inline-precompile'; + + import { Registry as ServiceRegistry } from '@ember/service'; + import { Registry as ControllerRegistry } from '@ember/controller'; + import ModuleComputed from '@ember/object/computed'; + + // Get an alias to the global Array type to use in inner scope below. + type GlobalArray = T[]; + + /** + * Deconstructs computed properties into the types which would be returned by `.get()`. + */ + type ComputedPropertyGetters = { [K in keyof T]: Ember.ComputedProperty | ModuleComputed | T[K] }; + type ComputedPropertySetters = { [K in keyof T]: Ember.ComputedProperty | ModuleComputed | T[K] }; + + /** + * Check that any arguments to `create()` match the type's properties. + * + * Accept any additional properties and add merge them into the instance. + */ + type EmberInstanceArguments = Partial & { + [key: string]: any; + }; + + /** + * Accept any additional properties and add merge them into the prototype. + */ + interface EmberClassArguments { + [key: string]: any; + } + + /** + * Map type `T` to a plain object hash with the identity mapping. + * + * Discards any additional object identity like the ability to `new()` up the class. + * The `new()` capability is added back later by merging `EmberClassConstructor` + * + * Implementation is carefully chosen for the reasons described in + * https://github.com/typed-ember/ember-typings/pull/29 + */ + type Objectify = Readonly; + + type Fix = { [K in keyof T]: T[K] }; + + /** + * Ember.Object.extend(...) accepts any number of mixins or literals. + */ + type MixinOrLiteral = Ember.Mixin | T; + + /** + * Used to infer the type of ember classes of type `T`. + * + * Generally you would use `EmberClass.create()` instead of `new EmberClass()`. + * + * The single-arg constructor is required by the typescript compiler. + * The multi-arg constructor is included for better ergonomics. + * + * Implementation is carefully chosen for the reasons described in + * https://github.com/typed-ember/ember-typings/pull/29 + */ + type EmberClassConstructor = (new (properties?: object) => T) & (new (...args: any[]) => T); + + type ComputedPropertyGetterFunction = (this: any, key: string) => T; + + interface ComputedPropertyGet { + get(this: any, key: string): T; + } + + interface ComputedPropertySet { + set(this: any, key: string, value: T): T; + } + + type ComputedPropertyCallback = + | ComputedPropertyGetterFunction + | ComputedPropertyGet + | ComputedPropertySet + | (ComputedPropertyGet & ComputedPropertySet); + + interface ActionsHash { + [index: string]: (...params: any[]) => any; + } + + interface EmberRunTimer { + __ember_run_timer_brand__: any; + } + + type RunMethod = ((this: Target, ...args: any[]) => Ret) | keyof Target; + type EmberRunQueues = + | 'sync' + | 'actions' + | 'routerTransitions' + | 'render' + | 'afterRender' + | 'destroy'; + type QueryParamTypes = 'boolean' | 'number' | 'array' | 'string'; + type QueryParamScopeTypes = 'controller' | 'model'; + + type ObserverMethod = + | (keyof Target) + | ((this: Target, sender: Sender, key: keyof Sender, value: any, rev: number) => void); + + interface RenderOptions { + into?: string; + controller?: string; + model?: any; + outlet?: string; + view?: string; + } + + interface RouteQueryParam { + refreshModel?: boolean; + replace?: boolean; + as?: string; + } + + interface EventDispatcherEvents { + touchstart?: string | null; + touchmove?: string | null; + touchend?: string | null; + touchcancel?: string | null; + keydown?: string | null; + keyup?: string | null; + keypress?: string | null; + mousedown?: string | null; + mouseup?: string | null; + contextmenu?: string | null; + click?: string | null; + dblclick?: string | null; + mousemove?: string | null; + focusin?: string | null; + focusout?: string | null; + mouseenter?: string | null; + mouseleave?: string | null; + submit?: string | null; + input?: string | null; + change?: string | null; + dragstart?: string | null; + drag?: string | null; + dragenter?: string | null; + dragleave?: string | null; + dragover?: string | null; + drop?: string | null; + dragend?: string | null; + [event: string]: string | null | undefined; + } + + interface ViewMixin { + /** + * A list of properties of the view to apply as attributes. If the property + * is a string value, the value of that string will be applied as the value + * for an attribute of the property's name. + */ + attributeBindings: string[]; + /** + * Returns the current DOM element for the view. + */ + element: Element; + /** + * Returns a jQuery object for this view's element. If you pass in a selector + * string, this method will return a jQuery object, using the current element + * as its buffer. + */ + $: JQueryStatic; + /** + * The HTML `id` of the view's element in the DOM. You can provide this + * value yourself but it must be unique (just as in HTML): + */ + elementId: string; + /** + * Tag name for the view's outer element. The tag name is only used when an + * element is first created. If you change the `tagName` for an element, you + * must destroy and recreate the view element. + */ + tagName: string; + /** + * Renders the view again. This will work regardless of whether the + * view is already in the DOM or not. If the view is in the DOM, the + * rendering process will be deferred to give bindings a chance + * to synchronize. + */ + rerender(): void; + /** + * Called when a view is going to insert an element into the DOM. + */ + willInsertElement(): void; + /** + * Called when the element of the view has been inserted into the DOM. + * Override this function to do any set up that requires an element + * in the document body. + */ + didInsertElement(): void; + /** + * Called when the view is about to rerender, but before anything has + * been torn down. This is a good opportunity to tear down any manual + * observers you have installed based on the DOM state + */ + willClearRender(): void; + /** + * Called when the element of the view is going to be destroyed. Override + * this function to do any teardown that requires an element, like removing + * event listeners. + */ + willDestroyElement(): void; + } + const ViewMixin: Ember.Mixin; + + /** + Ember.CoreView is an abstract class that exists to give view-like behavior to both Ember's main + view class Ember.Component and other classes that don't need the full functionality of Ember.Component. + + Unless you have specific needs for CoreView, you will use Ember.Component in your applications. + **/ + class CoreView extends Ember.Object.extend(Ember.Evented, Ember.ActionHandler) {} + interface ActionSupport { + sendAction(action: string, ...params: any[]): void; + } + const ActionSupport: Ember.Mixin; + + interface ClassNamesSupport { + /** + A list of properties of the view to apply as class names. If the property is a string value, + the value of that string will be applied as a class name. + + If the value of the property is a Boolean, the name of that property is added as a dasherized + class name. + + If you would prefer to use a custom value instead of the dasherized property name, you can + pass a binding like this: `classNameBindings: ['isUrgent:urgent']` + + This list of properties is inherited from the component's superclasses as well. + */ + classNameBindings: string[]; + /** + * Standard CSS class names to apply to the view's outer element. This + * property automatically inherits any class names defined by the view's + * superclasses as well. + */ + classNames: string[]; + } + const ClassNamesSupport: Ember.Mixin; + + interface TriggerActionOptions { + action?: string; + target?: Ember.Object; + actionContext?: Ember.Object; + } + /** + Ember.TargetActionSupport is a mixin that can be included in a class to add a triggerAction method + with semantics similar to the Handlebars {{action}} helper. In normal Ember usage, the {{action}} + helper is usually the best choice. This mixin is most often useful when you are doing more + complex event handling in Components. + **/ + interface TargetActionSupport { + triggerAction(opts: TriggerActionOptions): boolean; + } + + export namespace Ember { + interface FunctionPrototypeExtensions { + /** + * The `property` extension of Javascript's Function prototype is available + * when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is + * `true`, which is the default. + */ + property(...args: string[]): ComputedProperty; + /** + * The `observes` extension of Javascript's Function prototype is available + * when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is + * true, which is the default. + */ + observes(...args: string[]): this; + /** + * The `on` extension of Javascript's Function prototype is available + * when `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Function` is + * true, which is the default. + */ + on(...args: string[]): this; + } + + interface ArrayPrototypeExtensions extends MutableArray, Observable, Copyable {} + + /** + * Given a fullName return a factory manager. + */ + interface _ContainerProxyMixin { + /** + * Returns an object that can be used to provide an owner to a + * manually created instance. + */ + ownerInjection(): {}; + /** + * Given a fullName return a corresponding instance. + */ + lookup(fullName: string, options?: {}): any; + /** + * Given a fullName return a corresponding factory. + */ + factoryFor(fullName: string, options?: {}): any; + } + const _ContainerProxyMixin: Mixin<_ContainerProxyMixin>; + + /** + * RegistryProxyMixin is used to provide public access to specific + * registry functionality. + */ + interface _RegistryProxyMixin { + /** + * Given a fullName return the corresponding factory. + */ + resolveRegistration(fullName: string): Function; + /** + * Registers a factory or value that can be used for dependency injection (with + * `inject`) or for service lookup. Each factory is registered with + * a full name including two parts: `type:name`. + */ + register(fullName: string, factory: any, options?: { singleton?: boolean, instantiate?: boolean }): any; + /** + * Unregister a factory. + */ + unregister(fullName: string): any; + /** + * Check if a factory is registered. + */ + hasRegistration(fullName: string): boolean; + /** + * Register an option for a particular factory. + */ + registerOption(fullName: string, optionName: string, options: {}): any; + /** + * Return a specific registered option for a particular factory. + */ + registeredOption(fullName: string, optionName: string): {}; + /** + * Register options for a particular factory. + */ + registerOptions(fullName: string, options: {}): any; + /** + * Return registered options for a particular factory. + */ + registeredOptions(fullName: string): {}; + /** + * Allow registering options for all factories of a type. + */ + registerOptionsForType(type: string, options: {}): any; + /** + * Return the registered options for all factories of a type. + */ + registeredOptionsForType(type: string): {}; + /** + * Define a dependency injection onto a specific factory or all factories + * of a type. + */ + inject(factoryNameOrType: string, property: string, injectionName: string): any; + } + const _RegistryProxyMixin: Mixin<_RegistryProxyMixin>; + /** + Ember.ActionHandler is available on some familiar classes including Ember.Route, + Ember.Component, and Ember.Controller. (Internally the mixin is used by Ember.CoreView, + Ember.ControllerMixin, and Ember.Route and available to the above classes through inheritance.) + **/ + interface ActionHandler { + /** + Triggers a named action on the ActionHandler. Any parameters supplied after the actionName + string will be passed as arguments to the action target function. + + If the ActionHandler has its target property set, actions may bubble to the target. + Bubbling happens when an actionName can not be found in the ActionHandler's actions + hash or if the action target function returns true. + **/ + send(actionName: string, ...args: any[]): void; + /** + The collection of functions, keyed by name, available on this ActionHandler as action targets. + **/ + actions: ActionsHash; + } + const ActionHandler: Ember.Mixin; + /** + An instance of Ember.Application is the starting point for every Ember application. It helps to + instantiate, initialize and coordinate the many objects that make up your app. + **/ + class Application extends Engine { + /** + Call advanceReadiness after any asynchronous setup logic has completed. + Each call to deferReadiness must be matched by a call to advanceReadiness + or the application will never become ready and routing will not begin. + **/ + advanceReadiness(): void; + /** + Use this to defer readiness until some condition is true. + + This allows you to perform asynchronous setup logic and defer + booting your application until the setup has finished. + + However, if the setup requires a loading UI, it might be better + to use the router for this purpose. + */ + deferReadiness(): void; + /** + defines an injection or typeInjection + **/ + inject(factoryNameOrType: string, property: string, injectionName: string): void; + /** + This injects the test helpers into the window's scope. If a function of the + same name has already been defined it will be cached (so that it can be reset + if the helper is removed with `unregisterHelper` or `removeTestHelpers`). + Any callbacks registered with `onInjectHelpers` will be called once the + helpers have been injected. + **/ + injectTestHelpers(): void; + /** + registers a factory for later injection + @param fullName type:name (e.g., 'model:user') + @param factory (e.g., App.Person) + **/ + register(fullName: string, factory: Function, options?: {}): void; + /** + This removes all helpers that have been registered, and resets and functions + that were overridden by the helpers. + **/ + removeTestHelpers(): void; + /** + Reset the application. This is typically used only in tests. + **/ + reset(): void; + /** + This hook defers the readiness of the application, so that you can start + the app when your tests are ready to run. It also sets the router's + location to 'none', so that the window's location will not be modified + (preventing both accidental leaking of state between tests and interference + with your testing framework). + **/ + setupForTesting(): void; + /** + The DOM events for which the event dispatcher should listen. + */ + customEvents: EventDispatcherEvents; + /** + The Ember.EventDispatcher responsible for delegating events to this application's views. + **/ + eventDispatcher: EventDispatcher; + /** + Set this to provide an alternate class to Ember.DefaultResolver + **/ + resolver: DefaultResolver; + /** + The root DOM element of the Application. This can be specified as an + element or a jQuery-compatible selector string. + + This is the element that will be passed to the Application's, eventDispatcher, + which sets up the listeners for event delegation. Every view in your application + should be a child of the element you specify here. + **/ + rootElement: HTMLElement | string; + /** + Called when the Application has become ready. + The call will be delayed until the DOM has become ready. + **/ + ready: Function; + /** + Application's router. + **/ + Router: Router; + registry: Registry; + /** + * Initialize the application and return a promise that resolves with the `Application` + * object when the boot process is complete. + */ + boot(): Promise; + } + /** + The `ApplicationInstance` encapsulates all of the stateful aspects of a + running `Application`. + **/ + class ApplicationInstance extends EngineInstance {} + /** + This module implements Observer-friendly Array-like behavior. This mixin is picked up by the + Array class as well as other controllers, etc. that want to appear to be arrays. + **/ + interface Array extends Enumerable { + /** + * __Required.__ You must implement this method to apply this mixin. + */ + length: number | ComputedProperty; + /** + * Returns the object at the given `index`. If the given `index` is negative + * or is greater or equal than the array length, returns `undefined`. + */ + objectAt(idx: number): T | undefined; + /** + * This returns the objects at the specified indexes, using `objectAt`. + */ + objectsAt(indexes: number[]): Ember.Array; + /** + * Returns a new array that is a slice of the receiver. This implementation + * uses the observable array methods to retrieve the objects for the new + * slice. + */ + slice(beginIndex?: number, endIndex?: number): T[]; + /** + * Returns the index of the given object's first occurrence. + * If no `startAt` argument is given, the starting location to + * search is 0. If it's negative, will count backward from + * the end of the array. Returns -1 if no match is found. + */ + indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns the index of the given object's last occurrence. + * If no `startAt` argument is given, the search starts from + * the last position. If it's negative, will count backward + * from the end of the array. Returns -1 if no match is found. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + /** + * Adds an array observer to the receiving array. The array observer object + * normally must implement two methods: + */ + addArrayObserver(target: {}, opts: {}): this; + /** + * Removes an array observer from the object if the observer is current + * registered. Calling this method multiple times with the same object will + * have no effect. + */ + removeArrayObserver(target: {}, opts: {}): this; + /** + * Becomes true whenever the array currently has observers watching changes + * on the array. + */ + hasArrayObservers: ComputedProperty; + /** + * If you are implementing an object that supports `Ember.Array`, call this + * method just before the array content changes to notify any observers and + * invalidate any related properties. Pass the starting index of the change + * as well as a delta of the amounts to change. + */ + arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): this; + /** + * If you are implementing an object that supports `Ember.Array`, call this + * method just after the array content changes to notify any observers and + * invalidate any related properties. Pass the starting index of the change + * as well as a delta of the amounts to change. + */ + arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): this; + /** + * Returns a special object that can be used to observe individual properties + * on the array. Just get an equivalent property on this object and it will + * return an enumerable that maps automatically to the named key on the + * member objects. + */ + '@each': ComputedProperty; + } + // Ember.Array rather than Array because the `array-type` lint rule doesn't realize the global is shadowed + const Array: Mixin>; + + /** + An ArrayProxy wraps any other object that implements Ember.Array and/or Ember.MutableArray, + forwarding all requests. This makes it very useful for a number of binding use cases or other cases + where being able to swap out the underlying array is useful. + **/ + interface ArrayProxy extends MutableArray {} + class ArrayProxy extends Object.extend(MutableArray as {}) { + content: NativeArray; + + /** + * Should actually retrieve the object at the specified index from the + * content. You can override this method in subclasses to transform the + * content item to something new. + */ + objectAtContent(idx: number): T | undefined; + } + /** + AutoLocation will select the best location option based off browser support with the priority order: history, hash, none. + **/ + class AutoLocation extends Object {} + /** + * Connects the properties of two objects so that whenever the value of one property changes, + * the other property will be changed also. + * + * @deprecated https://emberjs.com/deprecations/v2.x#toc_ember-binding + **/ + class Binding { + constructor(toPath: string, fromPath: string); + connect(obj: any): Binding; + copy(): Binding; + disconnect(): Binding; + from(path: string): Binding; + to(path: string | string[]): Binding; + toString(): string; + } + /** + The internal class used to create text inputs when the {{input}} helper is used + with type of checkbox. See Handlebars.helpers.input for usage details. + **/ + class Checkbox extends Component {} + /** + * Implements some standard methods for comparing objects. Add this mixin to + * any class you create that can compare its instances. + */ + interface Comparable { + compare(a: any, b: any): number; + } + const Comparable: Mixin; + /** + A view that is completely isolated. Property access in its templates go to the view object + and actions are targeted at the view object. There is no access to the surrounding context or + outer controller; all contextual information is passed in. + **/ + class Component extends CoreView.extend(ViewMixin, ActionSupport, ClassNamesSupport) { + // methods + readDOMAttr(name: string): string; + // properties + /** + * The WAI-ARIA role of the control represented by this view. For example, a button may have a + * role of type 'button', or a pane may have a role of type 'alertdialog'. This property is + * used by assistive software to help visually challenged users navigate rich web applications. + */ + ariaRole: string; + /** + * The HTML id of the component's element in the DOM. You can provide this value yourself but + * it must be unique (just as in HTML): + * + * If not manually set a default value will be provided by the framework. Once rendered an + * element's elementId is considered immutable and you should never change it. If you need + * to compute a dynamic value for the elementId, you should do this when the component or + * element is being instantiated: + */ + elementId: string; + /** + * If false, the view will appear hidden in DOM. + */ + isVisible: boolean; + /** + * A component may contain a layout. A layout is a regular template but supersedes the template + * property during rendering. It is the responsibility of the layout template to retrieve the + * template property from the component (or alternatively, call Handlebars.helpers.yield, + * {{yield}}) to render it in the correct location. This is useful for a component that has a + * shared wrapper, but which delegates the rendering of the contents of the wrapper to the + * template property on a subclass. + */ + layout: TemplateFactory | string; + /** + * Enables components to take a list of parameters as arguments. + */ + static positionalParams: string[] | string; + // events + /** + * Called when the attributes passed into the component have been updated. Called both during the + * initial render of a container and during a rerender. Can be used in place of an observer; code + * placed here will be executed every time any attribute updates. + */ + didReceiveAttrs(): void; + /** + * Called after a component has been rendered, both on initial render and in subsequent rerenders. + */ + didRender(): void; + /** + * Called when the component has updated and rerendered itself. Called only during a rerender, + * not during an initial render. + */ + didUpdate(): void; + /** + * Called when the attributes passed into the component have been changed. Called only during a + * rerender, not during an initial render. + */ + didUpdateAttrs(): void; + /** + * Called before a component has been rendered, both on initial render and in subsequent rerenders. + */ + willRender(): void; + /** + * Called when the component is about to update and rerender itself. Called only during a rerender, + * not during an initial render. + */ + willUpdate(): void; + } + /** + A computed property transforms an objects function into a property. + By default the function backing the computed property will only be called once and the result + will be cached. You can specify various properties that your computed property is dependent on. + This will force the cached result to be recomputed if the dependencies are modified. + **/ + class ComputedProperty { + /** + * Call on a computed property to set it into non-cached mode. When in this + * mode the computed property will not automatically cache the return value. + */ + volatile(): this; + /** + * Call on a computed property to set it into read-only mode. When in this + * mode the computed property will throw an error when set. + */ + readOnly(): this; + /** + * Sets the dependent keys on this computed property. Pass any number of + * arguments containing key paths that this computed property depends on. + */ + property(...path: string[]): this; + /** + * In some cases, you may want to annotate computed properties with additional + * metadata about how they function or what values they operate on. For example, + * computed property functions may close over variables that are then no longer + * available for introspection. + */ + meta(meta: {}): this; + meta(): {}; + } + /** + * A container used to instantiate and cache objects. + */ + class Container { + /** + * Given a fullName, return the corresponding factory. The consumer of the factory + * is responsible for the destruction of any factory instances, as there is no + * way for the container to ensure instances are destroyed when it itself is + * destroyed. + */ + factoryFor(fullName: string, options?: {}): any; + } + /** + The ContainerDebugAdapter helps the container and resolver interface + with tools that debug Ember such as the Ember Inspector for Chrome and Firefox. + **/ + class ContainerDebugAdapter extends Object { + resolver: Resolver; + canCatalogEntriesByType(type: string): boolean; + catalogEntriesByType(type: string): any[]; + } + /** + * Additional methods for the Controller. + */ + interface ControllerMixin extends ActionHandler { + replaceRoute(name: string, ...args: any[]): void; + transitionToRoute(name: string, ...args: any[]): void; + model: any; + queryParams: string | string[] | Array<{ [key: string]: { + type?: QueryParamTypes, + scope?: QueryParamScopeTypes, + as?: string + }}>; + target: Object; + } + const ControllerMixin: Ember.Mixin; + class Controller extends Object.extend(ControllerMixin) {} + /** + * Implements some standard methods for copying an object. Add this mixin to + * any object you create that can create a copy of itself. This mixin is + * added automatically to the built-in array. + */ + interface Copyable { + /** + * __Required.__ You must implement this method to apply this mixin. + */ + copy(deep: boolean): Copyable; + /** + * If the object implements `Ember.Freezable`, then this will return a new + * copy if the object is not frozen and the receiver if the object is frozen. + */ + frozenCopy(): Copyable; + } + const Copyable: Ember.Mixin; + class CoreObject { + /** + * As of Ember 3.1, CoreObject constructor takes initial object properties as an argument. + * See: https://github.com/emberjs/ember.js/commit/4709935854d4c29b0d2c054614d53fa2c55309b1 + **/ + constructor(properties?: object); + + _super(...args: any[]): any; + + /** + An overridable method called when objects are instantiated. By default, + does nothing unless it is overridden during class definition. + **/ + init(): void; + + /** + * Defines the properties that will be concatenated from the superclass (instead of overridden). + * @default null + */ + concatenatedProperties: any[]; + + /** + Destroyed object property flag. If this property is true the observers and bindings were + already removed by the effect of calling the destroy() method. + @default false + **/ + isDestroyed: boolean; + /** + Destruction scheduled flag. The destroy() method has been called. The object stays intact + until the end of the run loop at which point the isDestroyed flag is set. + @default false + **/ + isDestroying: boolean; + + /** + Destroys an object by setting the `isDestroyed` flag and removing its + metadata, which effectively destroys observers and bindings. + If you try to set a property on a destroyed object, an exception will be + raised. + Note that destruction is scheduled for the end of the run loop and does not + happen immediately. It will set an isDestroying flag immediately. + @return receiver + */ + destroy(): CoreObject; + + /** + Override to implement teardown. + */ + willDestroy(): void; + + /** + Returns a string representation which attempts to provide more information than Javascript's toString + typically does, in a generic way for all Ember objects (e.g., ""). + @return string representation + **/ + toString(): string; + + static create(this: EmberClassConstructor): Fix; + + static create>( + this: EmberClassConstructor>, + arg1: T1 & ThisType> + ): Fix; + + static create< + Instance, + Args, + T1 extends EmberInstanceArguments, + T2 extends EmberInstanceArguments + >( + this: EmberClassConstructor>, + arg1: T1 & ThisType>, + arg2: T2 & ThisType> + ): Fix; + + static create< + Instance, + Args, + T1 extends EmberInstanceArguments, + T2 extends EmberInstanceArguments, + T3 extends EmberInstanceArguments + >( + this: EmberClassConstructor>, + arg1: T1 & ThisType>, + arg2: T2 & ThisType>, + arg3: T3 & ThisType> + ): Fix; + + static extend( + this: Statics & EmberClassConstructor + ): Objectify & EmberClassConstructor; + + static extend( + this: Statics & EmberClassConstructor, + arg1: MixinOrLiteral & ThisType> + ): Objectify & EmberClassConstructor; + + static extend< + Statics, + Instance extends B1 & B2, + T1 extends EmberClassArguments, + B1, + T2 extends EmberClassArguments, + B2 + >( + this: Statics & EmberClassConstructor, + arg1: MixinOrLiteral & ThisType>, + arg2: MixinOrLiteral & ThisType> + ): Objectify & EmberClassConstructor; + + static extend< + Statics, + Instance extends B1 & B2 & B3, + T1 extends EmberClassArguments, + B1, + T2 extends EmberClassArguments, + B2, + T3 extends EmberClassArguments, + B3 + >( + this: Statics & EmberClassConstructor, + arg1: MixinOrLiteral & ThisType>, + arg2: MixinOrLiteral & ThisType>, + arg3: MixinOrLiteral & ThisType> + ): Objectify & EmberClassConstructor; + + static extend< + Statics, + Instance extends B1 & B2 & B3 & B4, + T1 extends EmberClassArguments, + B1, + T2 extends EmberClassArguments, + B2, + T3 extends EmberClassArguments, + B3, + T4 extends EmberClassArguments, + B4 + >( + this: Statics & EmberClassConstructor, + arg1: MixinOrLiteral & ThisType>, + arg2: MixinOrLiteral & ThisType>, + arg3: MixinOrLiteral & ThisType>, + arg4: MixinOrLiteral & ThisType> + ): Objectify & EmberClassConstructor; + + static reopen( + this: Statics & EmberClassConstructor + ): Objectify & EmberClassConstructor; + + static reopen( + this: Statics & EmberClassConstructor, + arg1: MixinOrLiteral & ThisType> + ): Objectify & EmberClassConstructor; + + static reopen< + Statics, + Instance extends B1 & B2, + T1 extends EmberClassArguments, + B1, + T2 extends EmberClassArguments, + B2 + >( + this: Statics & EmberClassConstructor, + arg1: MixinOrLiteral & ThisType>, + arg2: MixinOrLiteral & ThisType> + ): Objectify & EmberClassConstructor; + + static reopen< + Statics, + Instance extends B1 & B2 & B3, + T1 extends EmberClassArguments, + B1, + T2 extends EmberClassArguments, + B2, + T3 extends EmberClassArguments, + B3 + >( + this: Statics & EmberClassConstructor, + arg1: MixinOrLiteral & ThisType>, + arg2: MixinOrLiteral & ThisType>, + arg3: MixinOrLiteral & ThisType> + ): Objectify & EmberClassConstructor; + + static reopenClass(this: Statics): Statics; + + static reopenClass( + this: Statics, + arg1: T1 + ): Statics & T1; + + static reopenClass< + Statics, + T1 extends EmberClassArguments, + T2 extends EmberClassArguments + >(this: Statics, arg1: T1, arg2: T2): Statics & T1 & T2; + + static reopenClass< + Statics, + T1 extends EmberClassArguments, + T2 extends EmberClassArguments, + T3 extends EmberClassArguments + >(this: Statics, arg1: T1, arg2: T2, arg3: T3): Statics & T1 & T2 & T3; + + static detect( + this: Statics & EmberClassConstructor, + obj: any + ): obj is Objectify & EmberClassConstructor; + + static detectInstance( + this: EmberClassConstructor, + obj: any + ): obj is Instance; + + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + } + /** + * The `DataAdapter` helps a data persistence library + * interface with tools that debug Ember such as Chrome and Firefox. + */ + class DataAdapter extends Object { + /** + * The container-debug-adapter which is used + * to list all models. + */ + containerDebugAdapter: any; + /** + * Ember Data > v1.0.0-beta.18 + * requires string model names to be passed + * around instead of the actual factories. + */ + acceptsModelName: any; + /** + * Specifies how records can be filtered. + * Records returned will need to have a `filterValues` + * property with a key for every name in the returned array. + */ + getFilters(): any[]; + /** + * Fetch the model types and observe them for changes. + */ + watchModelTypes(typesAdded: Function, typesUpdated: Function): Function; + /** + * Fetch the records of a given type and observe them for changes. + */ + watchRecords( + modelName: string, + recordsAdded: Function, + recordsUpdated: Function, + recordsRemoved: Function + ): Function; + } + const Debug: { + /** + * Allows for runtime registration of handler functions that override the default deprecation behavior. + * Deprecations are invoked by calls to [Ember.deprecate](http://emberjs.com/api/classes/Ember.html#method_deprecate). + * The following example demonstrates its usage by registering a handler that throws an error if the + * message contains the word "should", otherwise defers to the default handler. + */ + registerDeprecationHandler(handler: Function): any; + /** + * Allows for runtime registration of handler functions that override the default warning behavior. + * Warnings are invoked by calls made to [Ember.warn](http://emberjs.com/api/classes/Ember.html#method_warn). + * The following example demonstrates its usage by registering a handler that does nothing overriding Ember's + * default warning behavior. + */ + registerWarnHandler(handler: Function): any; + }; + /** + * The DefaultResolver defines the default lookup rules to resolve + * container lookups before consulting the container for registered + * items: + */ + class DefaultResolver extends Resolver { + /** + * This method is called via the container's resolver method. + * It parses the provided `fullName` and then looks up and + * returns the appropriate template or class. + */ + resolve(fullName: string): {}; + /** + * This will be set to the Application instance when it is + * created. + */ + namespace: Application; + } + interface Initializer { + name: string; + before?: string[]; + after?: string[]; + initialize(application: T): void; + } + /** + * The `Engine` class contains core functionality for both applications and + * engines. + */ + class Engine extends Namespace.extend(_RegistryProxyMixin) { + /** + * The goal of initializers should be to register dependencies and injections. + * This phase runs once. Because these initializers may load code, they are + * allowed to defer application readiness and advance it. If you need to access + * the container or store you should use an InstanceInitializer that will be run + * after all initializers and therefore after all code is loaded and the app is + * ready. + */ + static initializer(initializer: Initializer): void; + /** + * Instance initializers run after all initializers have run. Because + * instance initializers run after the app is fully set up. We have access + * to the store, container, and other items. However, these initializers run + * after code has loaded and are not allowed to defer readiness. + */ + static instanceInitializer(instanceInitializer: Initializer): void; + /** + * Set this to provide an alternate class to `Ember.DefaultResolver` + */ + resolver: Resolver; + } + /** + * The `EngineInstance` encapsulates all of the stateful aspects of a + * running `Engine`. + */ + class EngineInstance extends Ember.Object.extend( + _RegistryProxyMixin, + _ContainerProxyMixin + ) { + /** + * Unregister a factory. + */ + unregister(fullName: string): any; + + /** + * Initialize the `EngineInstance` and return a promise that resolves + * with the instance itself when the boot process is complete. + */ + boot(): Promise; + } + /** + * This mixin defines the common interface implemented by enumerable objects + * in Ember. Most of these methods follow the standard Array iteration + * API defined up to JavaScript 1.8 (excluding language-specific features that + * cannot be emulated in older versions of JavaScript). + */ + interface Enumerable { + /** + * Helper method returns the first object from a collection. This is usually + * used by bindings and other parts of the framework to extract a single + * object if the enumerable contains only one item. + */ + firstObject: ComputedProperty; + /** + * Helper method returns the last object from a collection. If your enumerable + * contains only one object, this method should always return that object. + * If your enumerable is empty, this method should return `undefined`. + */ + lastObject: ComputedProperty; + /** + * @deprecated Use `Enumerable#includes` instead. + */ + contains(obj: T): boolean; + /** + * Iterates through the enumerable, calling the passed function on each + * item. This method corresponds to the `forEach()` method defined in + * JavaScript 1.6. + */ + forEach: GlobalArray['forEach']; + /** + * Alias for `mapBy` + */ + getEach(key: string): any[]; + /** + * Sets the value on the named property for each member. This is more + * ergonomic than using other methods defined on this helper. If the object + * implements Ember.Observable, the value will be changed to `set(),` otherwise + * it will be set directly. `null` objects are skipped. + */ + setEach(key: string, value: any): any; + /** + * Maps all of the items in the enumeration to another value, returning + * a new array. This method corresponds to `map()` defined in JavaScript 1.6. + */ + map: GlobalArray['map']; + /** + * Similar to map, this specialized function returns the value of the named + * property on all items in the enumeration. + */ + mapBy(key: string): any[]; + /** + * Returns an array with all of the items in the enumeration that the passed + * function returns true for. This method corresponds to `filter()` defined in + * JavaScript 1.6. + */ + filter: GlobalArray['filter']; + /** + * Returns an array with all of the items in the enumeration where the passed + * function returns false. This method is the inverse of filter(). + */ + reject(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): NativeArray; + /** + * Returns an array with just the items with the matched property. You + * can pass an optional second argument with the target value. Otherwise + * this will match any property that evaluates to `true`. + */ + filterBy(key: string, value?: any): NativeArray; + /** + * Returns an array with the items that do not have truthy values for + * key. You can pass an optional second argument with the target value. Otherwise + * this will match any property that evaluates to false. + */ + rejectBy(key: string, value?: any): NativeArray; + /** + * Returns the first item in the array for which the callback returns true. + * This method works similar to the `filter()` method defined in JavaScript 1.6 + * except that it will stop working on the array once a match is found. + */ + find: GlobalArray['find']; + /** + * Returns the first item with a property matching the passed value. You + * can pass an optional second argument with the target value. Otherwise + * this will match any property that evaluates to `true`. + */ + findBy(key: string, value?: any): T | undefined; + /** + * Returns `true` if the passed function returns true for every item in the + * enumeration. This corresponds with the `every()` method in JavaScript 1.6. + */ + every: GlobalArray['every']; + /** + * Returns `true` if the passed property resolves to the value of the second + * argument for all items in the enumerable. This method is often simpler/faster + * than using a callback. + */ + isEvery(key: string, value?: any): boolean; + /** + * Returns `true` if the passed function returns true for any item in the + * enumeration. + */ + any(callback: (value: T, index: number, array: T[]) => boolean, target?: {}): boolean; + /** + * Returns `true` if the passed property resolves to the value of the second + * argument for any item in the enumerable. This method is often simpler/faster + * than using a callback. + */ + isAny(key: string, value?: any): boolean; + /** + * This will combine the values of the enumerator into a single value. It + * is a useful way to collect a summary value from an enumeration. This + * corresponds to the `reduce()` method defined in JavaScript 1.8. + */ + reduce: GlobalArray['reduce']; + /** + * Invokes the named method on every object in the receiver that + * implements it. This method corresponds to the implementation in + * Prototype 1.6. + */ + invoke(methodName: keyof T, ...args: any[]): any[]; + /** + * Simply converts the enumerable into a genuine array. The order is not + * guaranteed. Corresponds to the method implemented by Prototype. + */ + toArray(): T[]; + /** + * Returns a copy of the array with all `null` and `undefined` elements removed. + */ + compact(): NativeArray; + /** + * Returns a new enumerable that excludes the passed value. The default + * implementation returns an array regardless of the receiver type. + * If the receiver does not contain the value it returns the original enumerable. + */ + without(value: T): NativeArray; + /** + * Returns a new enumerable that contains only unique values. The default + * implementation returns an array regardless of the receiver type. + */ + uniq(): NativeArray; + /** + * Converts the enumerable into an array and sorts by the keys + * specified in the argument. + */ + sortBy(property: string): NativeArray; + /** + * Returns a new enumerable that contains only items containing a unique property value. + * The default implementation returns an array regardless of the receiver type. + */ + uniqBy(property: string): NativeArray; + /** + * Returns `true` if the passed object can be found in the enumerable. + */ + includes(searchElement: T, fromIndex?: number): boolean; + /** + * This is the handler for the special array content property. If you get + * this property, it will return this. If you set this property to a new + * array, it will replace the current content. + */ + '[]': ComputedProperty; + } + const Enumerable: Mixin>; + /** + A subclass of the JavaScript Error object for use in Ember. + **/ + const Error: ErrorConstructor; + /** + * `Ember.EventDispatcher` handles delegating browser events to their + * corresponding `Ember.Views.` For example, when you click on a view, + * `Ember.EventDispatcher` ensures that that view's `mouseDown` method gets + * called. + */ + class EventDispatcher extends Object { + /** + * The set of events names (and associated handler function names) to be setup + * and dispatched by the `EventDispatcher`. Modifications to this list can be done + * at setup time, generally via the `Ember.Application.customEvents` hash. + */ + events: EventDispatcherEvents; + } + /** + * This mixin allows for Ember objects to subscribe to and emit events. + */ + interface Evented { + /** + * Subscribes to a named event with given function. + */ + on( + name: string, + target: Target, + method: (this: Target, ...args: any[]) => void + ): this; + on(name: string, method: (...args: any[]) => void): this; + /** + * Subscribes a function to a named event and then cancels the subscription + * after the first time the event is triggered. It is good to use ``one`` when + * you only care about the first time an event has taken place. + */ + one( + name: string, + target: Target, + method: (this: Target, ...args: any[]) => void + ): this; + one(name: string, method: (...args: any[]) => void): this; + /** + * Triggers a named event for the object. Any additional arguments + * will be passed as parameters to the functions that are subscribed to the + * event. + */ + trigger(name: string, ...args: any[]): any; + /** + * Cancels subscription for given name, target, and method. + */ + off( + name: string, + target: Target, + method: (this: Target, ...args: any[]) => void + ): this; + off(name: string, method: (...args: any[]) => void): this; + /** + * Checks to see if object has any subscriptions for named event. + */ + has(name: string): boolean; + } + const Evented: Mixin; + /** + * The `Ember.Freezable` mixin implements some basic methods for marking an + * object as frozen. Once an object is frozen it should be read only. No changes + * may be made the internal state of the object. + * @deprecated Use `Object.freeze` instead. + */ + interface Freezable { + freeze(): Freezable; + isFrozen: boolean; + } + const Freezable: Mixin; + /** + * `Ember.HashLocation` implements the location API using the browser's + * hash. At present, it relies on a `hashchange` event existing in the + * browser. + */ + class HashLocation extends Object {} + /** + * Ember.HistoryLocation implements the location API using the browser's + * history.pushState API. + */ + class HistoryLocation extends Object {} + /** + * Ember Helpers are functions that can compute values, and are used in templates. + * For example, this code calls a helper named `format-currency`: + */ + class Helper extends Object { + /** + * In many cases, the ceremony of a full `Ember.Helper` class is not required. + * The `helper` method create pure-function helpers without instances. For + * example: + */ + static helper(helper: (params: any[], hash?: object) => any): Helper; + /** + * Override this function when writing a class-based helper. + */ + compute(params: any[], hash: object): any; + /** + * On a class-based helper, it may be useful to force a recomputation of that + * helpers value. This is akin to `rerender` on a component. + */ + recompute(): any; + } + /** + * The purpose of the Ember Instrumentation module is + * to provide efficient, general-purpose instrumentation + * for Ember. + */ + const Instrumentation: { + instrument(name: string, payload: any, callback: Function, binding: any): void; + reset(): void; + subscribe(pattern: string, object: any): void; + unsubscribe(subscriber: any): void; + }; + /** + * `Ember.LinkComponent` renders an element whose `click` event triggers a + * transition of the application's instance of `Ember.Router` to + * a supplied route by name. + */ + class LinkComponent extends Component { + /** + * Used to determine when this `LinkComponent` is active. + */ + currentWhen: any; + /** + * Sets the `title` attribute of the `LinkComponent`'s HTML element. + */ + title: string | null; + /** + * Sets the `rel` attribute of the `LinkComponent`'s HTML element. + */ + rel: string | null; + /** + * Sets the `tabindex` attribute of the `LinkComponent`'s HTML element. + */ + tabindex: string | null; + /** + * Sets the `target` attribute of the `LinkComponent`'s HTML element. + */ + target: string | null; + /** + * The CSS class to apply to `LinkComponent`'s element when its `active` + * property is `true`. + */ + activeClass: string; + /** + * Determines whether the `LinkComponent` will trigger routing via + * the `replaceWith` routing strategy. + */ + replace: boolean; + } + /** + * Ember.Location returns an instance of the correct implementation of + * the `location` API. + */ + const Location: { + /** + * This is deprecated in favor of using the container to lookup the location + * implementation as desired. + * @deprecated Use the container to lookup the location implementation that you need. + */ + create(options?: {}): any; + }; + /** + * Inside Ember-Metal, simply uses the methods from `imports.console`. + * Override this to provide more robust logging functionality. + */ + const Logger: { + /** + * If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace. + */ + assert(test: boolean, message?: string): void; + /** + * Logs the arguments to the console in blue text. + */ + debug(...args: any[]): void; + /** + * Prints the arguments to the console with an error icon, red text and a stack trace. + */ + error(...args: any[]): void; + /** + * Logs the arguments to the console. + */ + info(...args: any[]): void; + /** + * Logs the arguments to the console. + */ + log(...args: any[]): void; + /** + * Prints the arguments to the console with a warning icon. + */ + warn(...args: any[]): void; + }; + /** + * A Map stores values indexed by keys. Unlike JavaScript's + * default Objects, the keys of a Map can be any JavaScript + * object. + * @deprecated + */ + class Map { + copy(): Map; + static create(): Map; + forEach(callback: Function, self: any): void; + get(key: any): any; + has(key: any): boolean; + set(key: any, value: any): void; + length: number; + } + /** + * @deprecated + */ + class MapWithDefault extends Map { + copy(): MapWithDefault; + static create(): MapWithDefault; + } + /** + * The `Ember.Mixin` class allows you to create mixins, whose properties can be + * added to other classes. + */ + class Mixin { + /** + * Mixin needs to have *something* on its prototype, otherwise it's treated like an empty interface. + * It cannot be private, sadly. + */ + __ember_mixin__: never; + + static create( + args?: MixinOrLiteral & ThisType> + ): Mixin; + + static create( + arg1: MixinOrLiteral & ThisType>, + arg2: MixinOrLiteral & ThisType> + ): Mixin; + + static create( + arg1: MixinOrLiteral & ThisType>, + arg2: MixinOrLiteral & ThisType>, + arg3: MixinOrLiteral & ThisType> + ): Mixin; + + static create( + arg1: MixinOrLiteral & ThisType>, + arg2: MixinOrLiteral & ThisType>, + arg3: MixinOrLiteral & ThisType>, + arg4: MixinOrLiteral & ThisType> + ): Mixin; + } + /** + * This mixin defines the API for modifying array-like objects. These methods + * can be applied only to a collection that keeps its items in an ordered set. + * It builds upon the Array mixin and adds methods to modify the array. + * One concrete implementations of this class include ArrayProxy. + */ + interface MutableArray extends Array, MutableEnumerable { + /** + * __Required.__ You must implement this method to apply this mixin. + */ + replace(idx: number, amt: number, objects: any[]): any; + /** + * Remove all elements from the array. This is useful if you + * want to reuse an existing array without having to recreate it. + */ + clear(): this; + /** + * This will use the primitive `replace()` method to insert an object at the + * specified index. + */ + insertAt(idx: number, object: {}): this; + /** + * Remove an object at the specified index using the `replace()` primitive + * method. You can pass either a single index, or a start and a length. + */ + removeAt(start: number, len?: number): this; + /** + * Push the object onto the end of the array. Works just like `push()` but it + * is KVO-compliant. + */ + pushObject(obj: T): T; + /** + * Add the objects in the passed numerable to the end of the array. Defers + * notifying observers of the change until all objects are added. + */ + pushObjects(objects: Enumerable): this; + /** + * Pop object from array or nil if none are left. Works just like `pop()` but + * it is KVO-compliant. + */ + popObject(): T; + /** + * Shift an object from start of array or nil if none are left. Works just + * like `shift()` but it is KVO-compliant. + */ + shiftObject(): T; + /** + * Unshift an object to start of array. Works just like `unshift()` but it is + * KVO-compliant. + */ + unshiftObject(obj: T): T; + /** + * Adds the named objects to the beginning of the array. Defers notifying + * observers until all objects have been added. + */ + unshiftObjects(objects: Enumerable): this; + /** + * Reverse objects in the array. Works just like `reverse()` but it is + * KVO-compliant. + */ + reverseObjects(): this; + /** + * Replace all the receiver's content with content of the argument. + * If argument is an empty array receiver will be cleared. + */ + setObjects(objects: Ember.Array): this; + } + const MutableArray: Mixin>; + /** + * This mixin defines the API for modifying generic enumerables. These methods + * can be applied to an object regardless of whether it is ordered or + * unordered. + */ + interface MutableEnumerable extends Enumerable { + /** + * __Required.__ You must implement this method to apply this mixin. + */ + addObject(object: T): T; + /** + * Adds each object in the passed enumerable to the receiver. + */ + addObjects(objects: Enumerable): this; + /** + * __Required.__ You must implement this method to apply this mixin. + */ + removeObject(object: T): T; + /** + * Removes each object in the passed enumerable from the receiver. + */ + removeObjects(objects: Enumerable): this; + } + const MutableEnumerable: Mixin>; + /** + * A Namespace is an object usually used to contain other objects or methods + * such as an application or framework. Create a namespace anytime you want + * to define one of these new containers. + */ + class Namespace extends Object {} + /** + * The NativeArray mixin contains the properties needed to make the native + * Array support Ember.MutableArray and all of its dependent APIs. Unless you + * have `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Array` set to + * false, this will be applied automatically. Otherwise you can apply the mixin + * at anytime by calling `Ember.NativeArray.apply(Array.prototype)`. + */ + interface NativeArray extends GlobalArray, MutableArray, Observable, Copyable { + /** + * __Required.__ You must implement this method to apply this mixin. + */ + length: number; + } + const NativeArray: Mixin>; + /** + * Ember.NoneLocation does not interact with the browser. It is useful for + * testing, or when you need to manage state with your Router, but temporarily + * don't want it to muck with the URL (for example when you embed your + * application in a larger page). + */ + class NoneLocation extends Object {} + /** + * `Ember.Object` is the main base class for all Ember objects. It is a subclass + * of `Ember.CoreObject` with the `Ember.Observable` mixin applied. For details, + * see the documentation for each of these. + */ + class Object extends CoreObject.extend(Observable) {} + /** + * `Ember.ObjectProxy` forwards all properties not defined by the proxy itself + * to a proxied `content` object. + */ + class ObjectProxy extends Object { + /** + The object whose properties will be forwarded. + **/ + content: Object; + } + /** + * This mixin provides properties and property observing functionality, core features of the Ember object model. + */ + interface Observable { + /** + * Retrieves the value of a property from the object. + */ + get(this: ComputedPropertyGetters, key: K): T[K]; + /** + * To get the values of multiple properties at once, call `getProperties` + * with a list of strings or an array: + */ + getProperties(this: ComputedPropertyGetters, list: K[]): Pick; + getProperties( + this: ComputedPropertyGetters, + ...list: K[] + ): Pick; + /** + * Sets the provided key or path to the value. + */ + set(this: ComputedPropertySetters, key: K, value: T[K]): T[K]; + /** + * Sets a list of properties at once. These properties are set inside + * a single `beginPropertyChanges` and `endPropertyChanges` batch, so + * observers will be buffered. + */ + setProperties( + this: ComputedPropertySetters, + hash: Pick + ): Pick; + /** + * Convenience method to call `propertyWillChange` and `propertyDidChange` in + * succession. + */ + notifyPropertyChange(keyName: string): this; + /** + * Adds an observer on a property. + */ + addObserver( + key: keyof this, + target: Target, + method: ObserverMethod + ): void; + addObserver( + key: keyof this, + method: ObserverMethod + ): void; + /** + * Remove an observer you have previously registered on this object. Pass + * the same key, target, and method you passed to `addObserver()` and your + * target will no longer receive notifications. + */ + removeObserver( + key: keyof this, + target: Target, + method: ObserverMethod + ): any; + removeObserver( + key: keyof this, + method: ObserverMethod + ): any; + /** + * Retrieves the value of a property, or a default value in the case that the + * property returns `undefined`. + */ + getWithDefault( + this: ComputedPropertyGetters, + key: K, + defaultValue: T[K] + ): T[K]; + /** + * Set the value of a property to the current value plus some amount. + */ + incrementProperty(keyName: keyof this, increment?: number): number; + /** + * Set the value of a property to the current value minus some amount. + */ + decrementProperty(keyName: keyof this, decrement?: number): number; + /** + * Set the value of a boolean property to the opposite of its + * current value. + */ + toggleProperty(keyName: keyof this): boolean; + /** + * Returns the cached value of a computed property, if it exists. + * This allows you to inspect the value of a computed property + * without accidentally invoking it if it is intended to be + * generated lazily. + */ + cacheFor(this: ComputedPropertyGetters, key: K): T[K] | undefined; + } + const Observable: Mixin; + /** + * This class is used internally by Ember and Ember Data. + * Please do not use it at this time. We plan to clean it up + * and add many tests soon. + * @deprecated + */ + class OrderedSet { + add(obj: any): void; + clear(): void; + copy(): OrderedSet; + static create(): OrderedSet; + forEach(fn: Function, self: any): void; + has(obj: any): boolean; + isEmpty(): boolean; + toArray(): any[]; + } + /** + * A low level mixin making ObjectProxy promise-aware. + */ + interface PromiseProxyMixin extends RSVP.Promise { + /** + * If the proxied promise is rejected this will contain the reason + * provided. + */ + reason: any; + /** + * Once the proxied promise has settled this will become `false`. + */ + isPending: boolean; + /** + * Once the proxied promise has settled this will become `true`. + */ + isSettled: boolean; + /** + * Will become `true` if the proxied promise is rejected. + */ + isRejected: boolean; + /** + * Will become `true` if the proxied promise is fulfilled. + */ + isFulfilled: boolean; + /** + * The promise whose fulfillment value is being proxied by this object. + */ + promise: RSVP.Promise; + } + const PromiseProxyMixin: Mixin>; + /** + * A registry used to store factory and option information keyed + * by type. + */ + class Registry { + register( + fullName: string, + factory: EmberClassConstructor, + options?: { singleton?: boolean } + ): void; + } + class Resolver extends Ember.Object {} + /** + The `Ember.Route` class is used to define individual routes. Refer to + the [routing guide](http://emberjs.com/guides/routing/) for documentation. + */ + class Route extends Object.extend(ActionHandler, Evented) { + // methods + /** + This hook is called after this route's model has resolved. + It follows identical async/promise semantics to `beforeModel` + but is provided the route's resolved model in addition to + the `transition`, and is therefore suited to performing + logic that can only take place after the model has already + resolved. + */ + afterModel(resolvedModel: any, transition: Transition): any; + + /** + This hook is the first of the route entry validation hooks + called when an attempt is made to transition into a route + or one of its children. It is called before `model` and + `afterModel`, and is appropriate for cases when: + 1) A decision can be made to redirect elsewhere without + needing to resolve the model first. + 2) Any async operations need to occur first before the + model is attempted to be resolved. + This hook is provided the current `transition` attempt + as a parameter, which can be used to `.abort()` the transition, + save it for a later `.retry()`, or retrieve values set + on it from a previous hook. You can also just call + `this.transitionTo` to another route to implicitly + abort the `transition`. + You can return a promise from this hook to pause the + transition until the promise resolves (or rejects). This could + be useful, for instance, for retrieving async code from + the server that is required to enter a route. + */ + beforeModel(transition: Transition): any; + + /** + * Returns the controller for a particular route or name. + * The controller instance must already have been created, either through entering the + * associated route or using `generateController`. + */ + controllerFor(name: K): ControllerRegistry[K]; + + /** + * Disconnects a view that has been rendered into an outlet. + */ + disconnectOutlet(options: string | { outlet?: string; parentView?: string }): void; + + /** + * A hook you can implement to convert the URL into the model for + * this route. + */ + model(params: {}, transition: Transition): any; + + /** + * Returns the model of a parent (or any ancestor) route + * in a route hierarchy. During a transition, all routes + * must resolve a model object, and if a route + * needs access to a parent route's model in order to + * resolve a model (or just reuse the model from a parent), + * it can call `this.modelFor(theNameOfParentRoute)` to + * retrieve it. + */ + modelFor(name: string): {}; + + /** + * Retrieves parameters, for current route using the state.params + * variable and getQueryParamsFor, using the supplied routeName. + */ + paramsFor(name: string): {}; + + /** + * Refresh the model on this route and any child routes, firing the + * `beforeModel`, `model`, and `afterModel` hooks in a similar fashion + * to how routes are entered when transitioning in from other route. + * The current route params (e.g. `article_id`) will be passed in + * to the respective model hooks, and if a different model is returned, + * `setupController` and associated route hooks will re-fire as well. + * An example usage of this method is re-querying the server for the + * latest information using the same parameters as when the route + * was first entered. + * Note that this will cause `model` hooks to fire even on routes + * that were provided a model object when the route was initially + * entered. + */ + redirect(): Transition; + + /** + * Refresh the model on this route and any child routes, firing the + * `beforeModel`, `model`, and `afterModel` hooks in a similar fashion + * to how routes are entered when transitioning in from other route. + * The current route params (e.g. `article_id`) will be passed in + * to the respective model hooks, and if a different model is returned, + * `setupController` and associated route hooks will re-fire as well. + * An example usage of this method is re-querying the server for the + * latest information using the same parameters as when the route + * was first entered. + * Note that this will cause `model` hooks to fire even on routes + * that were provided a model object when the route was initially + * entered. + */ + refresh(): Transition; + + /** + * `render` is used to render a template into a region of another template + * (indicated by an `{{outlet}}`). `render` is used both during the entry + * phase of routing (via the `renderTemplate` hook) and later in response to + * user interaction. + */ + render(name: string, options?: RenderOptions): void; + + /** + * A hook you can use to render the template for the current route. + * This method is called with the controller for the current route and the + * model supplied by the `model` hook. By default, it renders the route's + * template, configured with the controller for the route. + * This method can be overridden to set up and render additional or + * alternative templates. + */ + renderTemplate(controller: Controller, model: {}): void; + + /** + * Transition into another route while replacing the current URL, if possible. + * This will replace the current history entry instead of adding a new one. + * Beside that, it is identical to `transitionTo` in all other respects. See + * 'transitionTo' for additional information regarding multiple models. + */ + replaceWith(name: string, ...args: any[]): Transition; + + /** + * A hook you can use to reset controller values either when the model + * changes or the route is exiting. + */ + resetController(controller: Controller, isExiting: boolean, transition: any): void; + + /** + * Sends an action to the router, which will delegate it to the currently active + * route hierarchy per the bubbling rules explained under actions. + */ + send(name: string, ...args: any[]): void; + + /** + * A hook you can implement to convert the route's model into parameters + * for the URL. + * + * The default `serialize` method will insert the model's `id` into the + * route's dynamic segment (in this case, `:post_id`) if the segment contains '_id'. + * If the route has multiple dynamic segments or does not contain '_id', `serialize` + * will return `Ember.getProperties(model, params)` + * This method is called when `transitionTo` is called with a context + * in order to populate the URL. + */ + serialize(model: {}, params: string[]): string | object; + + /** + * A hook you can use to setup the controller for the current route. + * This method is called with the controller for the current route and the + * model supplied by the `model` hook. + * By default, the `setupController` hook sets the `model` property of + * the controller to the `model`. + * If you implement the `setupController` hook in your Route, it will + * prevent this default behavior. If you want to preserve that behavior + * when implementing your `setupController` function, make sure to call + * `_super` + */ + setupController(controller: Controller, model: {}): void; + + /** + * Transition the application into another route. The route may + * be either a single route or route path + */ + transitionTo(name: string, ...object: any[]): Transition; + + /** + * The name of the view to use by default when rendering this routes template. + * When rendering a template, the route will, by default, determine the + * template and view to use from the name of the route itself. If you need to + * define a specific view, set this property. + * This is useful when multiple routes would benefit from using the same view + * because it doesn't require a custom `renderTemplate` method. + */ + transitionTo(name: string, ...object: any[]): Transition; + + // https://emberjs.com/api/ember/3.2/classes/Route/methods/intermediateTransitionTo?anchor=intermediateTransitionTo + /** + * Perform a synchronous transition into another route without attempting to resolve promises, + * update the URL, or abort any currently active asynchronous transitions + * (i.e. regular transitions caused by transitionTo or URL changes). + * + * @param name the name of the route or a URL + * @param object the model(s) or identifier(s) to be used while + * transitioning to the route. + * @returns the Transition object associated with this attempted transition + */ + intermediateTransitionTo(name: string, ...object: any[]): Transition; + + // properties + /** + * The controller associated with this route. + */ + controller: Controller; + + /** + * The name of the controller to associate with this route. + * By default, Ember will lookup a route's controller that matches the name + * of the route (i.e. `App.PostController` for `App.PostRoute`). However, + * if you would like to define a specific controller to use, you can do so + * using this property. + * This is useful in many ways, as the controller specified will be: + * * p assed to the `setupController` method. + * * used as the controller for the view being rendered by the route. + * * returned from a call to `controllerFor` for the route. + */ + controllerName: string; + + /** + * Configuration hash for this route's queryParams. + */ + queryParams: { [key: string]: RouteQueryParam }; + + /** + * The name of the route, dot-delimited + */ + routeName: string; + + /** + * The name of the template to use by default when rendering this routes + * template. + * This is similar with `viewName`, but is useful when you just want a custom + * template without a view. + */ + templateName: string; + + // events + /** + * This hook is executed when the router enters the route. It is not executed + * when the model for the route changes. + */ + activate(): void; + + /** + * This hook is executed when the router completely exits this route. It is + * not executed when the model for the route changes. + */ + deactivate(): void; + + /** + * The didTransition action is fired after a transition has successfully been + * completed. This occurs after the normal model hooks (beforeModel, model, + * afterModel, setupController) have resolved. The didTransition action has + * no arguments, however, it can be useful for tracking page views or resetting + * state on the controller. + */ + didTransition(): void; + + /** + * When attempting to transition into a route, any of the hooks may return a promise + * that rejects, at which point an error action will be fired on the partially-entered + * routes, allowing for per-route error handling logic, or shared error handling logic + * defined on a parent route. + */ + error(error: any, transition: Transition): void; + + /** + * The loading action is fired on the route when a route's model hook returns a + * promise that is not already resolved. The current Transition object is the first + * parameter and the route that triggered the loading event is the second parameter. + */ + loading(transition: Transition, route: Route): void; + + /** + * The willTransition action is fired at the beginning of any attempted transition + * with a Transition object as the sole argument. This action can be used for aborting, + * redirecting, or decorating the transition from the currently active routes. + */ + willTransition(transition: Transition): void; + } + /** + * The `Ember.Router` class manages the application state and URLs. Refer to + * the [routing guide](http://emberjs.com/guides/routing/) for documentation. + */ + class Router extends Object.extend(Evented) { + /** + * The `Router.map` function allows you to define mappings from URLs to routes + * in your application. These mappings are defined within the + * supplied callback function using `this.route`. + */ + static map(callback: (this: RouterDSL) => void): void; + /** + * The `location` property determines the type of URL's that your + * application will use. + */ + location: string; + /** + * Represents the URL of the root of the application, often '/'. This prefix is + * assumed on all routes defined on this router. + */ + rootURL: string; + /** + * Handles updating the paths and notifying any listeners of the URL + * change. + */ + didTransition(): any; + /** + * Handles notifying any listeners of an impending URL + * change. + */ + willTransition(): any; + /** + * Transition the application into another route. The route may + * be either a single route or route path: + */ + transitionTo(name: string, options?: {}): Transition; + transitionTo(name: string, ...models: any[]): Transition; + transitionTo(name: string, options: {}): Transition; + } + class RouterDSL { + constructor(name: string, options: object); + route(name: string, callback: (this: RouterDSL) => void): void; + route( + name: string, + options?: { path?: string; resetNamespace?: boolean }, + callback?: (this: RouterDSL) => void + ): void; + mount( + name: string, + options?: { + as?: string, + path?: string, + resetNamespace?: boolean, + engineInfo?: any + } + ): void; + } + class Service extends Object {} + /** + * The internal class used to create textarea element when the `{{textarea}}` + * helper is used. + */ + class TextArea extends Component.extend(TextSupport) {} + /** + * The internal class used to create text inputs when the `{{input}}` + * helper is used with `type` of `text`. + */ + class TextField extends Component.extend(TextSupport) { + /** + * The `value` attribute of the input element. As the user inputs text, this + * property is updated live. + */ + value: string; + /** + * The `type` attribute of the input element. + */ + type: string; + /** + * The `size` of the text field in characters. + */ + size: string; + /** + * The `pattern` attribute of input element. + */ + pattern: string; + /** + * The `min` attribute of input element used with `type="number"` or `type="range"`. + */ + min: string; + /** + * The `max` attribute of input element used with `type="number"` or `type="range"`. + */ + max: string; + } + /** + * `TextSupport` is a shared mixin used by both `Ember.TextField` and + * `Ember.TextArea`. `TextSupport` adds a number of methods that allow you to + * specify a controller action to invoke when a certain event is fired on your + * text field or textarea. The specifed controller action would get the current + * value of the field passed in as the only argument unless the value of + * the field is empty. In that case, the instance of the field itself is passed + * in as the only argument. + */ + interface TextSupport extends TargetActionSupport { + cancel(event: Function): void; + focusIn(event: Function): void; + focusOut(event: Function): void; + insertNewLine(event: Function): void; + keyPress(event: Function): void; + action: string; + bubbles: boolean; + onEvent: string; + } + const TextSupport: Ember.Mixin; + interface Transition { + /** + Aborts the Transition. Note you can also implicitly abort a transition + by initiating another transition while a previous one is underway. + */ + abort(): Transition; + /** + Retries a previously-aborted transition (making sure to abort the + transition if it's still active). Returns a new transition that + represents the new attempt to transition. + */ + retry(): Transition; + } + interface ViewTargetActionSupport { + target: any; + actionContext: any; + } + const ViewTargetActionSupport: Mixin; + const ViewUtils: { + isSimpleClick(event: Event): boolean; + }; + + // FYI - RSVP source comes from https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js + const RSVP: typeof Rsvp; + namespace RSVP { + type Promise = Rsvp.Promise; + } + + /** + * This is a container for an assortment of testing related functionality + */ + namespace Test { + /** + * `registerHelper` is used to register a test helper that will be injected + * when `App.injectTestHelpers` is called. + */ + function registerHelper( + name: string, + helperMethod: (app: Application, ...args: any[]) => any, + options?: object + ): any; + /** + * `registerAsyncHelper` is used to register an async test helper that will be injected + * when `App.injectTestHelpers` is called. + */ + function registerAsyncHelper( + name: string, + helperMethod: (app: Application, ...args: any[]) => any + ): void; + /** + * Remove a previously added helper method. + */ + function unregisterHelper(name: string): void; + /** + * Used to register callbacks to be fired whenever `App.injectTestHelpers` + * is called. + */ + function onInjectHelpers(callback: (app: Application) => void): void; + /** + * This returns a thenable tailored for testing. It catches failed + * `onSuccess` callbacks and invokes the `Ember.Test.adapter.exception` + * callback in the last chained then. + */ + function promise( + resolver: ( + resolve: (value?: T | PromiseLike) => void, + reject: (reason?: any) => void + ) => void, + label?: string + ): Ember.Test.Promise; + /** + * Replacement for `Ember.RSVP.resolve` + * The only difference is this uses + * an instance of `Ember.Test.Promise` + */ + function resolve(value?: T | PromiseLike, label?: string): Ember.Test.Promise; + /** + * This allows ember-testing to play nicely with other asynchronous + * events, such as an application that is waiting for a CSS3 + * transition or an IndexDB transaction. The waiter runs periodically + * after each async helper (i.e. `click`, `andThen`, `visit`, etc) has executed, + * until the returning result is truthy. After the waiters finish, the next async helper + * is executed and the process repeats. + */ + function registerWaiter(callback: () => boolean): any; + function registerWaiter( + context: Context, + callback: (this: Context) => boolean + ): any; + /** + * `unregisterWaiter` is used to unregister a callback that was + * registered with `registerWaiter`. + */ + function unregisterWaiter(callback: () => boolean): any; + function unregisterWaiter( + context: Context, + callback: (this: Context) => boolean + ): any; + /** + * Iterates through each registered test waiter, and invokes + * its callback. If any waiter returns false, this method will return + * true indicating that the waiters have not settled yet. + */ + function checkWaiters(): boolean; + /** + * Used to allow ember-testing to communicate with a specific testing + * framework. + */ + const adapter: Adapter; + /** + * The primary purpose of this class is to create hooks that can be implemented + * by an adapter for various test frameworks. + */ + class Adapter { + /** + * This callback will be called whenever an async operation is about to start. + */ + asyncStart(): any; + /** + * This callback will be called whenever an async operation has completed. + */ + asyncEnd(): any; + /** + * Override this method with your testing framework's false assertion. + * This function is called whenever an exception occurs causing the testing + * promise to fail. + */ + exception(error: string): any; + } + /** + * This class implements the methods defined by Ember.Test.Adapter for the + * QUnit testing framework. + */ + class QUnitAdapter extends Adapter {} + class Promise extends Rsvp.Promise { + constructor( + executor: ( + resolve: (value?: T | PromiseLike) => void, + reject: (reason?: any) => void + ) => void + ); + } + } + /** + * Namespace for injection helper methods. + */ + namespace inject { + /** + * Creates a property that lazily looks up another controller in the container. + * Can only be used when defining another controller. + */ + function controller(): ComputedProperty; + function controller( + name: K + ): ComputedProperty; + /** + * Creates a property that lazily looks up a service in the container. There + * are no restrictions as to what objects a service can be injected into. + */ + function service(): ComputedProperty; + function service( + name: K + ): ComputedProperty; + } + namespace ENV { + const EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; + const LOG_BINDINGS: boolean; + const LOG_STACKTRACE_ON_DEPRECATION: boolean; + const LOG_VERSION: boolean; + const MODEL_FACTORY_INJECTIONS: boolean; + const RAISE_ON_DEPRECATION: boolean; + } + namespace EXTEND_PROTOTYPES { + const Array: boolean; + const Function: boolean; + const String: boolean; + } + namespace Handlebars { + function compile(string: string): Function; + function compile(environment: any, options?: any, context?: any, asObject?: any): any; + function precompile(string: string, options: any): void; + class Compiler {} + class JavaScriptCompiler {} + function registerPartial(name: string, str: any): void; + function K(): any; + function createFrame(objec: any): any; + function Exception(message: string): void; + class SafeString { + constructor(str: string); + toString(): string; + } + function parse(string: string): any; + function print(ast: any): void; + const logger: typeof Ember.Logger; + function log(level: string, str: string): void; + } + namespace String { + function camelize(str: string): string; + function capitalize(str: string): string; + function classify(str: string): string; + function dasherize(str: string): string; + function decamelize(str: string): string; + function fmt(...args: string[]): string; + function htmlSafe(str: string): void; // TODO: @returns Handlebars.SafeStringStatic; + function isHTMLSafe(str: string): boolean; + function loc(...args: string[]): string; + function underscore(str: string): string; + function w(str: string): string[]; + } + const computed: { + (cb: ComputedPropertyCallback): ComputedProperty; + (k1: string, cb: ComputedPropertyCallback): ComputedProperty; + (k1: string, k2: string, cb: ComputedPropertyCallback): ComputedProperty; + ( + k1: string, + k2: string, + k3: string, + cb: ComputedPropertyCallback + ): ComputedProperty; + ( + k1: string, + k2: string, + k3: string, + k4: string, + cb: ComputedPropertyCallback + ): ComputedProperty; + ( + k1: string, + k2: string, + k3: string, + k4: string, + k5: string, + cb: ComputedPropertyCallback + ): ComputedProperty; + ( + k1: string, + k2: string, + k3: string, + k4: string, + k5: string, + k6: string, + cb: ComputedPropertyCallback + ): ComputedProperty; + ( + k1: string, + k2: string, + k3: string, + k4: string, + k5: string, + k6: string, + k7: string, + ...rest: any[] + ): ComputedProperty; + + /** + * A computed property that returns true if the value of the dependent + * property is null, an empty string, empty array, or empty function. + */ + empty(dependentKey: string): ComputedProperty; + /** + * A computed property that returns true if the value of the dependent + * property is NOT null, an empty string, empty array, or empty function. + */ + notEmpty(dependentKey: string): ComputedProperty; + /** + * A computed property that returns true if the value of the dependent + * property is null or undefined. This avoids errors from JSLint complaining + * about use of ==, which can be technically confusing. + */ + none(dependentKey: string): ComputedProperty; + /** + * A computed property that returns the inverse boolean value + * of the original value for the dependent property. + */ + not(dependentKey: string): ComputedProperty; + /** + * A computed property that converts the provided dependent property + * into a boolean value. + */ + bool(dependentKey: string): ComputedProperty; + /** + * A computed property which matches the original value for the + * dependent property against a given RegExp, returning `true` + * if the value matches the RegExp and `false` if it does not. + */ + match(dependentKey: string, regexp: RegExp): ComputedProperty; + /** + * A computed property that returns true if the provided dependent property + * is equal to the given value. + */ + equal(dependentKey: string, value: any): ComputedProperty; + /** + * A computed property that returns true if the provided dependent property + * is greater than the provided value. + */ + gt(dependentKey: string, value: number): ComputedProperty; + /** + * A computed property that returns true if the provided dependent property + * is greater than or equal to the provided value. + */ + gte(dependentKey: string, value: number): ComputedProperty; + /** + * A computed property that returns true if the provided dependent property + * is less than the provided value. + */ + lt(dependentKey: string, value: number): ComputedProperty; + /** + * A computed property that returns true if the provided dependent property + * is less than or equal to the provided value. + */ + lte(dependentKey: string, value: number): ComputedProperty; + /** + * A computed property that performs a logical `and` on the + * original values for the provided dependent properties. + */ + and(...dependentKeys: string[]): ComputedProperty; + /** + * A computed property which performs a logical `or` on the + * original values for the provided dependent properties. + */ + or(...dependentKeys: string[]): ComputedProperty; + /** + * Creates a new property that is an alias for another property + * on an object. Calls to `get` or `set` this property behave as + * though they were called on the original property. + */ + alias(dependentKey: string): ComputedProperty; + /** + * Where `computed.alias` aliases `get` and `set`, and allows for bidirectional + * data flow, `computed.oneWay` only provides an aliased `get`. The `set` will + * not mutate the upstream property, rather causes the current property to + * become the value set. This causes the downstream property to permanently + * diverge from the upstream property. + */ + oneWay(dependentKey: string): ComputedProperty; + /** + * This is a more semantically meaningful alias of `computed.oneWay`, + * whose name is somewhat ambiguous as to which direction the data flows. + */ + reads(dependentKey: string): ComputedProperty; + /** + * Where `computed.oneWay` provides oneWay bindings, `computed.readOnly` provides + * a readOnly one way binding. Very often when using `computed.oneWay` one does + * not also want changes to propagate back up, as they will replace the value. + */ + readOnly(dependentKey: string): ComputedProperty; + /** + * Creates a new property that is an alias for another property + * on an object. Calls to `get` or `set` this property behave as + * though they were called on the original property, but also + * print a deprecation warning. + */ + deprecatingAlias( + dependentKey: string, + options: { id: string; until: string } + ): ComputedProperty; + /** + * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options + */ + deprecatingAlias( + dependentKey: string, + options?: { id?: string; until?: string } + ): ComputedProperty; + /** + * A computed property that returns the sum of the values + * in the dependent array. + */ + sum(dependentKey: string): ComputedProperty; + /** + * A computed property that calculates the maximum value in the + * dependent array. This will return `-Infinity` when the dependent + * array is empty. + */ + max(dependentKey: string): ComputedProperty; + /** + * A computed property that calculates the minimum value in the + * dependent array. This will return `Infinity` when the dependent + * array is empty. + */ + min(dependentKey: string): ComputedProperty; + /** + * Returns an array mapped via the callback + */ + map( + dependentKey: string, + callback: (value: any, index: number, array: any[]) => U + ): ComputedProperty; + /** + * Returns an array mapped to the specified key. + */ + mapBy(dependentKey: string, propertyKey: string): ComputedProperty; + /** + * Filters the array by the callback. + */ + filter( + dependentKey: string, + callback: (value: any, index: number, array: any[]) => boolean + ): ComputedProperty; + /** + * Filters the array by the property and value + */ + filterBy( + dependentKey: string, + propertyKey: string, + value?: any + ): ComputedProperty; + /** + * A computed property which returns a new array with all the unique + * elements from one or more dependent arrays. + */ + uniq(propertyKey: string): ComputedProperty; + /** + * A computed property which returns a new array with all the unique + * elements from an array, with uniqueness determined by specific key. + */ + uniqBy(dependentKey: string, propertyKey: string): ComputedProperty; + /** + * A computed property which returns a new array with all the unique + * elements from one or more dependent arrays. + */ + union(...propertyKeys: string[]): ComputedProperty; + /** + * A computed property which returns a new array with all the elements + * two or more dependent arrays have in common. + */ + intersect(...propertyKeys: string[]): ComputedProperty; + /** + * A computed property which returns a new array with all the + * properties from the first dependent array that are not in the second + * dependent array. + */ + setDiff(setAProperty: string, setBProperty: string): ComputedProperty; + /** + * A computed property that returns the array of values + * for the provided dependent properties. + */ + collect(...dependentKeys: string[]): ComputedProperty; + /** + * A computed property which returns a new array with all the + * properties from the first dependent array sorted based on a property + * or sort function. + */ + sort( + itemsKey: string, + sortDefinition: string | ((itemA: any, itemB: any) => number) + ): ComputedProperty; + }; + const run: { + /** + * Runs the passed target and method inside of a RunLoop, ensuring any + * deferred actions including bindings and views updates are flushed at the + * end. + */ + (method: (...args: any[]) => Ret): Ret; + (target: Target, method: RunMethod): Ret; + /** + * If no run-loop is present, it creates a new one. If a run loop is + * present it will queue itself to run on the existing run-loops action + * queue. + */ + join(method: (...args: any[]) => Ret, ...args: any[]): Ret | undefined; + join( + target: Target, + method: RunMethod, + ...args: any[] + ): Ret | undefined; + /** + * Allows you to specify which context to call the specified function in while + * adding the execution of that function to the Ember run loop. This ability + * makes this method a great way to asynchronously integrate third-party libraries + * into your Ember application. + */ + bind( + target: Target, + method: RunMethod, + ...args: any[] + ): (...args: any[]) => Ret; + /** + * Begins a new RunLoop. Any deferred actions invoked after the begin will + * be buffered until you invoke a matching call to `run.end()`. This is + * a lower-level way to use a RunLoop instead of using `run()`. + */ + begin(): void; + /** + * Ends a RunLoop. This must be called sometime after you call + * `run.begin()` to flush any deferred actions. This is a lower-level way + * to use a RunLoop instead of using `run()`. + */ + end(): void; + /** + * Adds the passed target/method and any optional arguments to the named + * queue to be executed at the end of the RunLoop. If you have not already + * started a RunLoop when calling this method one will be started for you + * automatically. + */ + schedule( + queue: EmberRunQueues, + target: Target, + method: RunMethod, + ...args: any[] + ): EmberRunTimer; + schedule( + queue: EmberRunQueues, + method: (args: any[]) => any, + ...args: any[] + ): EmberRunTimer; + /** + * Invokes the passed target/method and optional arguments after a specified + * period of time. The last parameter of this method must always be a number + * of milliseconds. + */ + later(method: (...args: any[]) => any, wait: number): EmberRunTimer; + later(target: Target, method: RunMethod, wait: number): EmberRunTimer; + later( + target: Target, + method: RunMethod, + arg0: any, + wait: number + ): EmberRunTimer; + later( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + wait: number + ): EmberRunTimer; + later( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + wait: number + ): EmberRunTimer; + later( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + arg3: any, + wait: number + ): EmberRunTimer; + later( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + arg3: any, + arg4: any, + wait: number + ): EmberRunTimer; + later( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + arg3: any, + arg4: any, + arg5: any, + wait: number + ): EmberRunTimer; + /** + * Schedule a function to run one time during the current RunLoop. This is equivalent + * to calling `scheduleOnce` with the "actions" queue. + */ + once(target: Target, method: RunMethod, ...args: any[]): EmberRunTimer; + /** + * Schedules a function to run one time in a given queue of the current RunLoop. + * Calling this method with the same queue/target/method combination will have + * no effect (past the initial call). + */ + scheduleOnce( + queue: EmberRunQueues, + target: Target, + method: RunMethod, + ...args: any[] + ): EmberRunTimer; + /** + * Schedules an item to run from within a separate run loop, after + * control has been returned to the system. This is equivalent to calling + * `run.later` with a wait time of 1ms. + */ + next(target: Target, method: RunMethod, ...args: any[]): EmberRunTimer; + /** + * Cancels a scheduled item. Must be a value returned by `run.later()`, + * `run.once()`, `run.scheduleOnce()`, `run.next()`, `run.debounce()`, or + * `run.throttle()`. + */ + cancel(timer: EmberRunTimer): boolean; + /** + * Delay calling the target method until the debounce period has elapsed + * with no additional debounce calls. If `debounce` is called again before + * the specified time has elapsed, the timer is reset and the entire period + * must pass again before the target method is called. + */ + debounce( + method: (...args: any[]) => any, + wait: number, + immediate?: boolean + ): EmberRunTimer; + debounce( + target: Target, + method: RunMethod, + wait: number, + immediate?: boolean + ): EmberRunTimer; + debounce( + target: Target, + method: RunMethod, + arg0: any, + wait: number, + immediate?: boolean + ): EmberRunTimer; + debounce( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + wait: number, + immediate?: boolean + ): EmberRunTimer; + debounce( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + wait: number, + immediate?: boolean + ): EmberRunTimer; + debounce( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + arg3: any, + wait: number, + immediate?: boolean + ): EmberRunTimer; + debounce( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + arg3: any, + arg4: any, + wait: number, + immediate?: boolean + ): EmberRunTimer; + debounce( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + arg3: any, + arg4: any, + arg5: any, + wait: number, + immediate?: boolean + ): EmberRunTimer; + /** + * Ensure that the target method is never called more frequently than + * the specified spacing period. The target method is called immediately. + */ + throttle( + method: (...args: any[]) => any, + spacing: number, + immediate?: boolean + ): EmberRunTimer; + throttle( + target: Target, + method: RunMethod, + spacing: number, + immediate?: boolean + ): EmberRunTimer; + throttle( + target: Target, + method: RunMethod, + arg0: any, + spacing: number, + immediate?: boolean + ): EmberRunTimer; + throttle( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + spacing: number, + immediate?: boolean + ): EmberRunTimer; + throttle( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + spacing: number, + immediate?: boolean + ): EmberRunTimer; + throttle( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + arg3: any, + spacing: number, + immediate?: boolean + ): EmberRunTimer; + throttle( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + arg3: any, + arg4: any, + spacing: number, + immediate?: boolean + ): EmberRunTimer; + throttle( + target: Target, + method: RunMethod, + arg0: any, + arg1: any, + arg2: any, + arg3: any, + arg4: any, + arg5: any, + spacing: number, + immediate?: boolean + ): EmberRunTimer; + + queues: EmberRunQueues[]; + }; + const platform: { + defineProperty: boolean; + hasPropertyAccessors: boolean; + }; + + /** + * `getEngineParent` retrieves an engine instance's parent instance. + */ + function getEngineParent(engine: EngineInstance): EngineInstance; + /** + * Display a deprecation warning with the provided message and a stack trace + * (Chrome and Firefox only). + */ + function deprecate( + message: string, + test: boolean, + options: { id: string; until: string } + ): any; + /** + * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options + */ + function deprecate( + message: string, + test: boolean, + options?: { id?: string; until?: string } + ): any; + /** + * Define an assertion that will throw an exception if the condition is not met. + */ + function assert(desc: string, test?: boolean): void | never; + /** + * Display a debug notice. + */ + function debug(message: string): void; + /** + * NOTE: This is a low-level method used by other parts of the API. + * You almost never want to call this method directly. Instead you + * should use Ember.mixin() to define new properties. + */ + function defineProperty( + obj: object, + keyName: string, + desc?: PropertyDescriptor | ComputedProperty, + data?: any, + meta?: any + ): void; + /** + * Alias an old, deprecated method with its new counterpart. + */ + function deprecateFunc any)>( + message: string, + options: { id: string; until: string }, + func: Func + ): Func; + /** + * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options + */ + function deprecateFunc any)>( + message: string, + func: Func + ): Func; + /** + * Run a function meant for debugging. + */ + function runInDebug(func: () => void): any; + /** + * Display a warning with the provided message. + */ + function warn(message: string, test: boolean, options: { id: string }): any; + function warn(message: string, options: { id: string }): any; + /** + * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options + */ + function warn(message: string, test: boolean, options?: { id?: string }): any; + /** + * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options + */ + function warn(message: string, options?: { id?: string }): any; + /** + * Global helper method to create a new binding. Just pass the root object + * along with a `to` and `from` path to create and connect the binding. + * @deprecated https://emberjs.com/deprecations/v2.x#toc_ember-binding + */ + function bind(obj: {}, to: string, from: string): Binding; + /** + * Returns the cached value for a property, if one exists. + * This can be useful for peeking at the value of a computed + * property that is generated lazily, without accidentally causing + * it to be created. + */ + function cacheFor( + obj: ComputedPropertyGetters, + key: K + ): T[K] | undefined; + /** + * Add an event listener + */ + function addListener( + obj: Context, + key: keyof Context, + target: Target, + method: ObserverMethod, + once?: boolean + ): void; + function addListener( + obj: Context, + key: keyof Context, + method: ObserverMethod + ): void; + /** + * Remove an event listener + */ + function removeListener( + obj: Context, + key: keyof Context, + target: Target, + method: ObserverMethod + ): any; + function removeListener( + obj: Context, + key: keyof Context, + method: ObserverMethod + ): any; + /** + * Send an event. The execution of suspended listeners + * is skipped, and once listeners are removed. A listener without + * a target is executed on the passed object. If an array of actions + * is not passed, the actions stored on the passed object are invoked. + */ + function sendEvent(obj: any, eventName: string, params?: any[], actions?: any[]): boolean; + /** + * Define a property as a function that should be executed when + * a specified event or events are triggered. + */ + function on(eventNames: string, func: (...args: any[]) => void): (...args: any[]) => void; + /** + * To get multiple properties at once, call `Ember.getProperties` + * with an object followed by a list of strings or an array: + */ + function getProperties( + obj: ComputedPropertyGetters, + list: K[] + ): Pick; + function getProperties(obj: T, list: K[]): Pick; // for dynamic K + function getProperties( + obj: ComputedPropertyGetters, + ...list: K[] + ): Pick; + function getProperties(obj: T, ...list: K[]): Pick; // for dynamic K + /** + * A value is blank if it is empty or a whitespace string. + */ + function isBlank(obj: any): boolean; + /** + * Verifies that a value is `null` or an empty string, empty array, + * or empty function. + */ + function isEmpty(obj: any): boolean; + /** + * Returns true if the passed value is null or undefined. This avoids errors + * from JSLint complaining about use of ==, which can be technically + * confusing. + */ + function isNone(obj: any): obj is null | undefined; + /** + * A value is present if it not `isBlank`. + */ + function isPresent(obj: any): boolean; + /** + * Merge the contents of two objects together into the first object. + * @deprecated Use Object.assign + */ + function merge(original: T, updates: U): T & U; + /** + * Makes a method available via an additional name. + */ + function aliasMethod(methodName: string): ComputedProperty; + /** + * Specify a method that observes property changes. + */ + function observer(key1: string, func: (target: any, key: string) => void): void; + function observer( + key1: string, + key2: string, + func: (target: any, key: string) => void + ): void; + function observer( + key1: string, + key2: string, + key3: string, + func: (target: any, key: string) => void + ): void; + function observer( + key1: string, + key2: string, + key3: string, + key4: string, + func: (target: any, key: string) => void + ): void; + function observer( + key1: string, + key2: string, + key3: string, + key4: string, + key5: string, + func: (target: any, key: string) => void + ): void; + /** + * Adds an observer on a property. + */ + function addObserver( + obj: Context, + key: keyof Context, + target: Target, + method: ObserverMethod + ): void; + function addObserver( + obj: Context, + key: keyof Context, + method: ObserverMethod + ): void; + /** + * Remove an observer you have previously registered on this object. Pass + * the same key, target, and method you passed to `addObserver()` and your + * target will no longer receive notifications. + */ + function removeObserver( + obj: Context, + key: keyof Context, + target: Target, + method: ObserverMethod + ): any; + function removeObserver( + obj: Context, + key: keyof Context, + method: ObserverMethod + ): any; + /** + * Gets the value of a property on an object. If the property is computed, + * the function will be invoked. If the property is not defined but the + * object implements the `unknownProperty` method then that will be invoked. + */ + function get(obj: ComputedPropertyGetters, key: K): T[K]; + function get(obj: T, key: K): T[K]; // for dynamic K + /** + * Retrieves the value of a property from an Object, or a default value in the + * case that the property returns `undefined`. + */ + function getWithDefault( + obj: ComputedPropertyGetters, + key: K, + defaultValue: T[K] + ): T[K]; + function getWithDefault(obj: T, key: K, defaultValue: T[K]): T[K]; // for dynamic K + /** + * Sets the value of a property on an object, respecting computed properties + * and notifying observers and other listeners of the change. If the + * property is not defined but the object implements the `setUnknownProperty` + * method then that will be invoked as well. + */ + function set( + obj: ComputedPropertySetters, + key: K, + value: V + ): V; + function set(obj: T, key: K, value: V): V; // for dynamic K + /** + * Error-tolerant form of `Ember.set`. Will not blow up if any part of the + * chain is `undefined`, `null`, or destroyed. + */ + function trySet(root: object, path: string, value: any): any; + /** + * Set a list of properties on an object. These properties are set inside + * a single `beginPropertyChanges` and `endPropertyChanges` batch, so + * observers will be buffered. + */ + function setProperties( + obj: ComputedPropertySetters, + hash: Pick + ): Pick; + function setProperties(obj: T, hash: Pick): Pick; // for dynamic K + /** + * Detects when a specific package of Ember (e.g. 'Ember.Application') + * has fully loaded and is available for extension. + */ + function onLoad(name: string, callback: Function): any; + /** + * Called when an Ember.js package (e.g Ember.Application) has finished + * loading. Triggers any callbacks registered for this event. + */ + function runLoadHooks(name: string, object?: {}): any; + /** + * Creates an `Ember.NativeArray` from an Array like object. + * Does not modify the original object's contents. Ember.A is not needed if + * `EmberENV.EXTEND_PROTOTYPES` is `true` (the default value). However, + * it is recommended that you use Ember.A when creating addons for + * ember or when you can not guarantee that `EmberENV.EXTEND_PROTOTYPES` + * will be `true`. + */ + function A(arr?: T[]): NativeArray; + /** + * Compares two javascript values and returns: + */ + function compare(v: any, w: any): number; + /** + * Creates a shallow copy of the passed object. A deep copy of the object is + * returned if the optional `deep` argument is `true`. + */ + function copy(obj: any, deep?: boolean): any; + /** + * Compares two objects, returning true if they are equal. + */ + function isEqual(a: any, b: any): boolean; + /** + * Returns true if the passed object is an array or Array-like. + */ + function isArray(obj: any): obj is ArrayLike; + /** + * Returns a consistent type for the passed object. + */ + function typeOf(item: any): string; + /** + * Copy properties from a source object to a target object. + * @deprecated Use Object.assign + */ + function assign(target: T, source: U): T & U; + function assign(target: T, source1: U, source2: V): T & U & V; + function assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + /** + * Polyfill for Object.create + * @deprecated Use Object.create + */ + function create(o: object | null): any; + /** + * Polyfill for Object.keys + * @deprecated Use Object.keys + */ + function keys(o: any): string[]; + /** + * Returns a unique id for the object. If the object does not yet have a guid, + * one will be assigned to it. You can call this on any object, + * `Ember.Object`-based or not, but be aware that it will add a `_guid` + * property. + */ + function guidFor(obj: any): string; + /** + * Convenience method to inspect an object. This method will attempt to + * convert the object into a useful string description. + */ + function inspect(obj: any): string; + /** + * Checks to see if the `methodName` exists on the `obj`, + * and if it does, invokes it with the arguments passed. + */ + function tryInvoke(obj: any, methodName: string, args?: any[]): any; + /** + * Forces the passed object to be part of an array. If the object is already + * an array, it will return the object. Otherwise, it will add the object to + * an array. If obj is `null` or `undefined`, it will return an empty array. + */ + function makeArray(obj?: T[] | T | null): T[]; + /** + * Framework objects in an Ember application (components, services, routes, etc.) + * are created via a factory and dependency injection system. Each of these + * objects is the responsibility of an "owner", which handled its + * instantiation and manages its lifetime. + */ + function getOwner(object: any): any; + /** + * `setOwner` forces a new owner on a given object instance. This is primarily + * useful in some testing cases. + */ + function setOwner(object: any, owner: any): void; + /** + * A function may be assigned to `Ember.onerror` to be called when Ember + * internals encounter an error. This is useful for specialized error handling + * and reporting code. + */ + function onerror(error: Error): void; + /** + * An empty function useful for some operations. Always returns `this`. + * @deprecated https://emberjs.com/deprecations/v2.x/#toc_code-ember-k-code + */ + function K(this: This): This; + /** + * The semantic version + */ + const VERSION: string; + /** + * Alias for jQuery + */ + const $: JQueryStatic; + /** + * This property indicates whether or not this application is currently in + * testing mode. This is set when `setupForTesting` is called on the current + * application. + */ + const testing: boolean; + + const instrument: typeof Instrumentation.instrument; + + const reset: typeof Instrumentation.reset; + + const subscribe: typeof Instrumentation.subscribe; + + const unsubscribe: typeof Instrumentation.unsubscribe; + /** + * Expands `pattern`, invoking `callback` for each expansion. + */ + function expandProperties(pattern: string, callback: (expanded: string) => void): void; + } + + type RouteModel = object | string | number; + // https://emberjs.com/api/ember/2.18/classes/RouterService + /** + * The Router service is the public API that provides component/view layer access to the router. + */ + export class RouterService extends Ember.Service { + // + /** + Name of the current route. + This property represent the logical name of the route, + which is comma separated. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `index` when you visit `/` + * `about` when you visit `/about` + * `blog.index` when you visit `/blog` + * `blog.post` when you visit `/blog/some-post-id` + */ + readonly currentRouteName: string; + // + /** + Current URL for the application. + This property represent the URL path for this route. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `/` when you visit `/` + * `/about` when you visit `/about` + * `/blog` when you visit `/blog` + * `/blog/some-post-id` when you visit `/blog/some-post-id` + */ + readonly currentURL: string; + // + /** + * Determines whether a route is active. + * + * @param routeName the name of the route + * @param models the model(s) or identifier(s) to be used while + * transitioning to the route + * @param options optional hash with a queryParams property containing a + * mapping of query parameters + */ + isActive(routeName: string, options?: { queryParams: object }): boolean; + isActive(routeName: string, models: RouteModel, options?: { queryParams: object }): boolean; + isActive(routeName: string, modelsA: RouteModel, modelsB: RouteModel, options?: { queryParams: object }): boolean; + isActive(routeName: string, modelsA: RouteModel, modelsB: RouteModel, modelsC: RouteModel, options?: { queryParams: object }): boolean; + isActive(routeName: string, modelsA: RouteModel, modelsB: RouteModel, modelsC: RouteModel, modelsD: RouteModel, options?: { queryParams: object }): boolean; + + // https://emberjs.com/api/ember/2.18/classes/RouterService/methods/isActive?anchor=replaceWith + /** + * Transition into another route while replacing the current URL, if + * possible. The route may be either a single route or route path. + * + * @param routeNameOrUrl the name of the route or a URL + * @param models the model(s) or identifier(s) to be used while + * transitioning to the route. + * @param options optional hash with a queryParams property + * containing a mapping of query parameters + * @returns the Transition object associated with this attempted transition + */ + replaceWith(routeNameOrUrl: string, options?: { queryParams: object }): Ember.Transition; + replaceWith(routeNameOrUrl: string, models: RouteModel, options?: { queryParams: object }): Ember.Transition; + replaceWith(routeNameOrUrl: string, modelsA: RouteModel, modelsB: RouteModel, options?: { queryParams: object }): Ember.Transition; + replaceWith(routeNameOrUrl: string, modelsA: RouteModel, modelsB: RouteModel, modelsC: RouteModel, options?: { queryParams: object }): Ember.Transition; + replaceWith(routeNameOrUrl: string, modelsA: RouteModel, modelsB: RouteModel, modelsC: RouteModel, modelsD: RouteModel, options?: { queryParams: object }): Ember.Transition; + + // https://emberjs.com/api/ember/2.18/classes/RouterService/methods/isActive?anchor=transitionTo + /** + * Transition the application into another route. The route may be + * either a single route or route path + * + * @param routeNameOrUrl the name of the route or a URL + * @param models the model(s) or identifier(s) to be used while + * transitioning to the route. + * @param options optional hash with a queryParams property + * containing a mapping of query parameters + * @returns the Transition object associated with this attempted transition + */ + transitionTo(routeNameOrUrl: string, options?: { queryParam: object }): Ember.Transition; + transitionTo(routeNameOrUrl: string, models: RouteModel, options?: { queryParams: object }): Ember.Transition; + transitionTo(routeNameOrUrl: string, modelsA: RouteModel, modelsB: RouteModel, options?: { queryParams: object }): Ember.Transition; + transitionTo(routeNameOrUrl: string, modelsA: RouteModel, modelsB: RouteModel, modelsC: RouteModel, options?: { queryParams: object }): Ember.Transition; + transitionTo(routeNameOrUrl: string, modelsA: RouteModel, modelsB: RouteModel, modelsC: RouteModel, modelsD: RouteModel, options?: { queryParams: object }): Ember.Transition; + + // https://emberjs.com/api/ember/2.18/classes/RouterService/methods/isActive?anchor=urlFor + /** + * Generate a URL based on the supplied route name. + * + * @param routeName the name of the route or a URL + * @param models the model(s) or identifier(s) to be used while + * transitioning to the route. + * @param options optional hash with a queryParams property containing + * a mapping of query parameters + * @returns the string representing the generated URL + */ + urlFor(routeName: string, options?: { queryParams: object }): string; + urlFor(routeName: string, models: RouteModel, options?: { queryParams: object }): string; + urlFor(routeName: string, modelsA: RouteModel, modelsB: RouteModel, options?: { queryParams: object }): string; + urlFor(routeName: string, modelsA: RouteModel, modelsB: RouteModel, modelsC: RouteModel, options?: { queryParams: object }): string; + urlFor(routeName: string, modelsA: RouteModel, modelsB: RouteModel, modelsC: RouteModel, modelsD: RouteModel, options?: { queryParams: object }): string; + } + + module '@ember/service' { + interface Registry { + 'router': RouterService; + } + } + + export default Ember; +} + +declare module '@ember/application' { + import Ember from 'ember'; + export default class Application extends Ember.Application { } + export const getOwner: typeof Ember.getOwner; + export const onLoad: typeof Ember.onLoad; + export const runLoadHooks: typeof Ember.runLoadHooks; + export const setOwner: typeof Ember.setOwner; +} + +declare module '@ember/application/deprecations' { + import Ember from 'ember'; + export const deprecate: typeof Ember.deprecate; + export const deprecateFunc: typeof Ember.deprecateFunc; +} + +declare module '@ember/application/globals-resolver' { + import Ember from 'ember'; + export default class GlobalsResolver extends Ember.DefaultResolver { } +} + +declare module '@ember/application/instance' { + import Ember from 'ember'; + export default class ApplicationInstance extends Ember.ApplicationInstance { } +} + +declare module '@ember/application/resolver' { + import Ember from 'ember'; + export default class Resolver extends Ember.Resolver { } +} + +declare module '@ember/array' { + import Ember from 'ember'; + type EmberArray = Ember.Array; + const EmberArray: typeof Ember.Array; + export default EmberArray; + export const A: typeof Ember.A; + export const isArray: typeof Ember.isArray; + export const makeArray: typeof Ember.makeArray; +} + +declare module '@ember/array/mutable' { + import Ember from 'ember'; + type MutableArray = Ember.MutableArray; + const MutableArray: typeof Ember.MutableArray; + export default MutableArray; +} + +declare module '@ember/array/proxy' { + import Ember from 'ember'; + export default class ArrayProxy extends Ember.ArrayProxy { } +} + +declare module '@ember/component' { + import Ember from 'ember'; + export default class Component extends Ember.Component { } +} + +declare module '@ember/component/checkbox' { + import Ember from 'ember'; + export default class Checkbox extends Ember.Checkbox { } +} + +declare module '@ember/component/helper' { + import Ember from 'ember'; + export default class Helper extends Ember.Helper { } + /** + * In many cases, the ceremony of a full `Helper` class is not required. + * The `helper` method create pure-function helpers without instances. For + * example: + * ```app/helpers/format-currency.js + * import { helper } from '@ember/component/helper'; + * export default helper(function(params, hash) { + * let cents = params[0]; + * let currency = hash.currency; + * return `${currency}${cents * 0.01}`; + * }); + * ``` + */ + export function helper(helperFn: (params: any[], hash?: any) => any): any; +} + +declare module '@ember/component/text-area' { + import Ember from 'ember'; + export default class TextArea extends Ember.TextArea { } +} + +declare module '@ember/component/text-field' { + import Ember from 'ember'; + export default class TextField extends Ember.TextField { } +} + +declare module '@ember/controller' { + import Ember from 'ember'; + export default class Controller extends Ember.Controller { } + export const inject: typeof Ember.inject.controller; + + // A type registry for Ember `Controller`s. Meant to be declaration-merged + // so string lookups resolve to the correct type. + export interface Registry {} +} + +declare module '@ember/debug' { + import Ember from 'ember'; + export const assert: typeof Ember.assert; + export const debug: typeof Ember.debug; + export const inspect: typeof Ember.inspect; + export const registerDeprecationHandler: typeof Ember.Debug.registerDeprecationHandler; + export const registerWarnHandler: typeof Ember.Debug.registerWarnHandler; + export const runInDebug: typeof Ember.runInDebug; + export const warn: typeof Ember.warn; +} + +declare module '@ember/debug/container-debug-adapter' { + import Ember from 'ember'; + export default class ContainerDebugAdapter extends Ember.ContainerDebugAdapter { } +} + +declare module '@ember/debug/data-adapter' { + import Ember from 'ember'; + export default class DataAdapter extends Ember.DataAdapter { } +} + +declare module '@ember/engine' { + import Ember from 'ember'; + export default class Engine extends Ember.Engine { } + export const getEngineParent: typeof Ember.getEngineParent; +} + +declare module '@ember/engine/instance' { + import Ember from 'ember'; + export default class EngineInstance extends Ember.EngineInstance { } +} + +declare module '@ember/enumerable' { + import Ember from 'ember'; + type Enumerable = Ember.Enumerable; + const Enumerable: typeof Ember.Enumerable; + export default Enumerable; +} + +declare module '@ember/error' { + import Ember from 'ember'; + const Error: typeof Ember.Error; + export default Error; +} + +declare module '@ember/instrumentation' { + import Ember from 'ember'; + export const instrument: typeof Ember.instrument; + export const reset: typeof Ember.reset; + export const subscribe: typeof Ember.subscribe; + export const unsubscribe: typeof Ember.unsubscribe; +} + +declare module '@ember/map' { + import Ember from 'ember'; + export default class EmberMap extends Ember.Map { } +} + +declare module '@ember/map/with-default' { + import Ember from 'ember'; + export default class MapWithDefault extends Ember.MapWithDefault { } +} + +declare module '@ember/object' { + import Ember from 'ember'; + export default class EmberObject extends Ember.Object { } + export const aliasMethod: typeof Ember.aliasMethod; + export const computed: typeof Ember.computed; + export const defineProperty: typeof Ember.defineProperty; + export const get: typeof Ember.get; + export const getProperties: typeof Ember.getProperties; + export const getWithDefault: typeof Ember.getWithDefault; + export const observer: typeof Ember.observer; + export const set: typeof Ember.set; + export const setProperties: typeof Ember.setProperties; + export const trySet: typeof Ember.trySet; +} + +declare module '@ember/object/computed' { + import Ember from 'ember'; + export default class ComputedProperty extends Ember.ComputedProperty { } + export const alias: typeof Ember.computed.alias; + export const and: typeof Ember.computed.and; + export const bool: typeof Ember.computed.bool; + export const collect: typeof Ember.computed.collect; + export const deprecatingAlias: typeof Ember.computed.deprecatingAlias; + export const empty: typeof Ember.computed.empty; + export const equal: typeof Ember.computed.equal; + export const expandProperties: typeof Ember.expandProperties; + export const filter: typeof Ember.computed.filter; + export const filterBy: typeof Ember.computed.filterBy; + export const gt: typeof Ember.computed.gt; + export const gte: typeof Ember.computed.gte; + export const intersect: typeof Ember.computed.intersect; + export const lt: typeof Ember.computed.lt; + export const lte: typeof Ember.computed.lte; + export const map: typeof Ember.computed.map; + export const mapBy: typeof Ember.computed.mapBy; + export const match: typeof Ember.computed.match; + export const max: typeof Ember.computed.max; + export const min: typeof Ember.computed.min; + export const none: typeof Ember.computed.none; + export const not: typeof Ember.computed.not; + export const notEmpty: typeof Ember.computed.notEmpty; + export const oneWay: typeof Ember.computed.oneWay; + export const or: typeof Ember.computed.or; + export const readOnly: typeof Ember.computed.readOnly; + export const reads: typeof Ember.computed.reads; + export const setDiff: typeof Ember.computed.setDiff; + export const sort: typeof Ember.computed.sort; + export const sum: typeof Ember.computed.sum; + export const union: typeof Ember.computed.union; + export const uniq: typeof Ember.computed.uniq; + export const uniqBy: typeof Ember.computed.uniqBy; +} + +declare module '@ember/object/core' { + import Ember from 'ember'; + export default class CoreObject extends Ember.CoreObject { } +} + +declare module '@ember/object/evented' { + import Ember from 'ember'; + type Evented = Ember.Evented; + const Evented: typeof Ember.Evented; + export default Evented; + export const on: typeof Ember.on; +} + +declare module '@ember/object/events' { + import Ember from 'ember'; + export const addListener: typeof Ember.addListener; + export const removeListener: typeof Ember.removeListener; + export const sendEvent: typeof Ember.sendEvent; +} + +declare module '@ember/object/internals' { + import Ember from 'ember'; + export const cacheFor: typeof Ember.cacheFor; + export const copy: typeof Ember.copy; + export const guidFor: typeof Ember.guidFor; +} + +declare module '@ember/object/mixin' { + import Ember from 'ember'; + export default class Mixin extends Ember.Mixin {} +} + +declare module '@ember/object/observable' { + import Ember from 'ember'; + type Observable = Ember.Observable; + const Observable: typeof Ember.Observable; + export default Observable; +} + +declare module '@ember/object/observers' { + import Ember from 'ember'; + export const addObserver: typeof Ember.addObserver; + export const removeObserver: typeof Ember.removeObserver; +} + +declare module '@ember/object/promise-proxy-mixin' { + import Ember from 'ember'; + type PromiseProxyMixin = Ember.PromiseProxyMixin; + const PromiseProxyMixin: typeof Ember.PromiseProxyMixin; + export default PromiseProxyMixin; +} + +declare module '@ember/object/proxy' { + import Ember from 'ember'; + export default class ObjectProxy extends Ember.ObjectProxy { } +} + +declare module '@ember/polyfills' { + import Ember from 'ember'; + export const assign: typeof Ember.assign; + export const create: typeof Ember.create; + export const hasPropertyAccessors: typeof Ember.platform.hasPropertyAccessors; + export const keys: typeof Ember.keys; + export const merge: typeof Ember.merge; +} + +declare module '@ember/routing/auto-location' { + import Ember from 'ember'; + export default class AutoLocation extends Ember.AutoLocation { } +} + +declare module '@ember/routing/hash-location' { + import Ember from 'ember'; + export default class HashLocation extends Ember.HashLocation { } +} + +declare module '@ember/routing/history-location' { + import Ember from 'ember'; + export default class HistoryLocation extends Ember.HistoryLocation { } +} + +declare module '@ember/routing/link-component' { + import Ember from 'ember'; + export default class LinkComponent extends Ember.LinkComponent { } +} + +declare module '@ember/routing/location' { + import Ember from 'ember'; + const Location: typeof Ember.Location; + export default Location; +} + +declare module '@ember/routing/none-location' { + import Ember from 'ember'; + export default class NoneLocation extends Ember.NoneLocation { } +} + +declare module '@ember/routing/route' { + import Ember from 'ember'; + export default class Route extends Ember.Route { } +} + +declare module '@ember/routing/router' { + import Ember from 'ember'; + export default class EmberRouter extends Ember.Router { } +} + +declare module '@ember/routing/router-service' { + import { RouterService } from 'ember'; + export default class extends RouterService { } +} + +declare module '@ember/runloop' { + import Ember from 'ember'; + export const begin: typeof Ember.run.begin; + export const bind: typeof Ember.run.bind; + export const cancel: typeof Ember.run.cancel; + export const debounce: typeof Ember.run.debounce; + export const end: typeof Ember.run.end; + export const join: typeof Ember.run.join; + export const later: typeof Ember.run.later; + export const next: typeof Ember.run.next; + export const once: typeof Ember.run.once; + export const run: typeof Ember.run; + export const schedule: typeof Ember.run.schedule; + export const scheduleOnce: typeof Ember.run.scheduleOnce; + export const throttle: typeof Ember.run.throttle; +} + +declare module '@ember/service' { + import Ember from 'ember'; + export default class Service extends Ember.Service { } + export const inject: typeof Ember.inject.service; + + // A type registry for Ember `Service`s. Meant to be declaration-merged so + // string lookups resolve to the correct type. + interface Registry {} +} + +declare module '@ember/string' { + import Ember from 'ember'; + export const camelize: typeof Ember.String.camelize; + export const capitalize: typeof Ember.String.capitalize; + export const classify: typeof Ember.String.classify; + export const dasherize: typeof Ember.String.dasherize; + export const decamelize: typeof Ember.String.decamelize; + export const fmt: typeof Ember.String.fmt; + export const htmlSafe: typeof Ember.String.htmlSafe; + export const isHTMLSafe: typeof Ember.String.isHTMLSafe; + export const loc: typeof Ember.String.loc; + export const underscore: typeof Ember.String.underscore; + export const w: typeof Ember.String.w; +} + +declare module '@ember/test' { + import Ember from 'ember'; + export const registerAsyncHelper: typeof Ember.Test.registerAsyncHelper; + export const registerHelper: typeof Ember.Test.registerHelper; + export const registerWaiter: typeof Ember.Test.registerWaiter; + export const unregisterHelper: typeof Ember.Test.unregisterHelper; + export const unregisterWaiter: typeof Ember.Test.unregisterWaiter; +} + +declare module '@ember/test/adapter' { + import Ember from 'ember'; + export default class TestAdapter extends Ember.Test.Adapter { } +} + +declare module '@ember/utils' { + import Ember from 'ember'; + export const compare: typeof Ember.compare; + export const isBlank: typeof Ember.isBlank; + export const isEmpty: typeof Ember.isEmpty; + export const isEqual: typeof Ember.isEqual; + export const isNone: typeof Ember.isNone; + export const isPresent: typeof Ember.isPresent; + export const tryInvoke: typeof Ember.tryInvoke; + export const typeOf: typeof Ember.typeOf; +} + +declare module 'htmlbars-inline-precompile' { + interface TemplateFactory { + __htmlbars_inline_precompile_template_factory: any; + } + export default function hbs(tagged: TemplateStringsArray): TemplateFactory; +} diff --git a/types/ember/v2/test/application-instance.ts b/types/ember/v2/test/application-instance.ts new file mode 100644 index 0000000000..9ae22e5f26 --- /dev/null +++ b/types/ember/v2/test/application-instance.ts @@ -0,0 +1,29 @@ +import ApplicationInstance from '@ember/application/instance'; +import hbs from 'htmlbars-inline-precompile'; + +const appInstance = ApplicationInstance.create(); +appInstance.register('some:injection', class Foo {}); + +appInstance.register('some:injection', class Foo {}, { + singleton: true, +}); + +appInstance.register('some:injection', class Foo {}, { + instantiate: false, +}); + +appInstance.register('templates:foo/bar', hbs`

Hello World

`); + +appInstance.register('some:injection', class Foo {}, { + singleton: false, + instantiate: true, +}); + +appInstance.factoryFor('router:main'); +appInstance.lookup('route:basic'); + +appInstance.boot(); + +(async function() { + await appInstance.boot(); +}()); diff --git a/types/ember/v2/test/application.ts b/types/ember/v2/test/application.ts new file mode 100755 index 0000000000..d0fc2e9c44 --- /dev/null +++ b/types/ember/v2/test/application.ts @@ -0,0 +1,35 @@ +import Ember from 'ember'; +import { assertType } from "./lib/assert"; + +let BaseApp = Ember.Application.extend({ + modulePrefix: 'my-app' +}); + +BaseApp.initializer({ + name: 'my-initializer', + initialize(app) { + app.register('foo:bar', Ember.Object.extend({ foo: 'bar' })); + } +}); + +BaseApp.instanceInitializer({ + name: 'my-instance-initializer', + initialize(app) { + app.lookup('foo:bar').get('foo'); + } +}); + +let App1 = BaseApp.create({ + rootElement: '#app-one', + customEvents: { + paste: 'paste' + } +}); + +let App2 = BaseApp.create({ + rootElement: '#app-two', + customEvents: { + mouseenter: null, + mouseleave: null + } +}); diff --git a/types/ember/v2/test/array-ext.ts b/types/ember/v2/test/array-ext.ts new file mode 100755 index 0000000000..490fcd77e7 --- /dev/null +++ b/types/ember/v2/test/array-ext.ts @@ -0,0 +1,26 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +declare global { + interface Array extends Ember.ArrayPrototypeExtensions {} +} + +class Person extends Ember.Object { + name: string; +} + +const person = Person.create({ name: 'Joe' }); +const array = [person]; + +assertType(array.get('length')); +// This test must be disabled due to a breaking change in TS 3.1 +// see: https://github.com/Microsoft/TypeScript/issues/26120 +// https://github.com/typed-ember/ember-cli-typescript/issues/246 +// https://github.com/Microsoft/TypeScript/pull/26063 +// +// assertType(array.get('firstObject')); +assertType(array.mapBy('name')); +assertType(array.map(p => p.get('name'))); +assertType(array.sortBy('name')); +assertType(array.uniq()); +assertType(array.uniqBy('name')); diff --git a/types/ember/v2/test/array-proxy.ts b/types/ember/v2/test/array-proxy.ts new file mode 100644 index 0000000000..dceea7b847 --- /dev/null +++ b/types/ember/v2/test/array-proxy.ts @@ -0,0 +1,26 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +const pets = ['dog', 'cat', 'fish']; +const proxy = Ember.ArrayProxy.create({ content: Ember.A(pets) }); + +proxy.get('firstObject'); // 'dog' +proxy.set('content', Ember.A(['amoeba', 'paramecium'])); +proxy.get('firstObject'); // 'amoeba' + +const overridden = Ember.ArrayProxy.create({ + content: Ember.A(pets), + objectAtContent(idx: number): string { + return this.get('content').objectAt(idx)!.toUpperCase(); + } +}); + +overridden.get('firstObject'); // 'DOG' + +class MyNewProxy extends Ember.ArrayProxy { + isNew = true; +} + +let x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }) as MyNewProxy; +assertType(x.get('firstObject')); +assertType(x.isNew); diff --git a/types/ember/v2/test/array.ts b/types/ember/v2/test/array.ts new file mode 100755 index 0000000000..8416a4a9ec --- /dev/null +++ b/types/ember/v2/test/array.ts @@ -0,0 +1,48 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +type Person = typeof Person.prototype; +const Person = Ember.Object.extend({ + name: '', + isHappy: false +}); + +const people = Ember.A([ + Person.create({ name: 'Yehuda', isHappy: true }), + Person.create({ name: 'Majd', isHappy: false }), +]); + +assertType(people.get('length')); +assertType(people.get('lastObject')); +assertType(people.isAny('isHappy')); +assertType(people.isAny('isHappy', 'false')); +assertType>(people.filterBy('isHappy')); +assertType>(people.rejectBy('isHappy')); +assertType>(people.filter((person) => person.get('name') === 'Yehuda')); +assertType(people.get('[]')); +assertType(people.get('[]').get('firstObject')); + +assertType>(people.mapBy('isHappy')); +assertType(people.mapBy('name.length')); + +const last = people.get('lastObject'); +if (last) { + assertType(last.get('name')); +} + +const first = people.get('lastObject'); +if (first) { + assertType(first.get('isHappy')); +} + +const letters: Ember.Enumerable = Ember.A(['a', 'b', 'c']); +const codes: number[] = letters.map((item, index, enumerable) => { + assertType(item); + assertType(index); + return item.charCodeAt(0); +}); + +let value = '1,2,3'; +let filters = Ember.A(value.split(',')); +filters.push('4'); +filters.sort(); diff --git a/types/ember/v2/test/component.ts b/types/ember/v2/test/component.ts new file mode 100755 index 0000000000..bcc314300d --- /dev/null +++ b/types/ember/v2/test/component.ts @@ -0,0 +1,124 @@ +import Ember from 'ember'; +import Component from '@ember/component'; +import Object, { computed } from '@ember/object'; +import hbs from 'htmlbars-inline-precompile'; +import { assertType } from "./lib/assert"; + +Component.extend({ + layout: hbs` +
+ {{yield}} +
+ `, +}); + +Component.extend({ + layout: 'my-layout', +}); + +const MyComponent = Component.extend(); +assertType(Ember.get(MyComponent, 'positionalParams')); + +const component1 = Component.extend({ + actions: { + hello(name: string) { + console.log('Hello', name); + }, + }, +}); + +Component.extend({ + name: '', + hello(name: string) { + this.set('name', name); + }, +}); + +Component.extend({ + tagName: 'em', +}); + +Component.extend({ + classNames: ['my-class', 'my-other-class'], +}); + +Component.extend({ + classNameBindings: ['propertyA', 'propertyB'], + propertyA: 'from-a', + propertyB: computed(function() { + if (!this.get('propertyA')) { + return 'from-b'; + } + }), +}); + +Component.extend({ + classNameBindings: ['hovered'], + hovered: true, +}); + +Component.extend({ + classNameBindings: ['messages.empty'], + messages: Object.create({ + empty: true, + }), +}); + +Component.extend({ + classNameBindings: ['isEnabled:enabled:disabled'], + isEnabled: true, +}); + +Component.extend({ + classNameBindings: ['isEnabled::disabled'], + isEnabled: true, +}); + +Component.extend({ + tagName: 'a', + attributeBindings: ['href'], + href: 'http://google.com', +}); + +Component.extend({ + tagName: 'a', + attributeBindings: ['url:href'], + url: 'http://google.com', +}); + +Component.extend({ + tagName: 'use', + attributeBindings: ['xlinkHref:xlink:href'], + xlinkHref: '#triangle', +}); + +Component.extend({ + tagName: 'input', + attributeBindings: ['disabled'], + disabled: false, +}); + +Component.extend({ + tagName: 'input', + attributeBindings: ['disabled'], + disabled: computed(() => { + if ('someLogic') { + return true; + } else { + return false; + } + }), +}); + +Component.extend({ + tagName: 'form', + attributeBindings: ['novalidate'], + novalidate: null, +}); + +Component.extend({ + click(event: object) { + // will be called when an instance's + // rendered element is clicked + }, +}); diff --git a/types/ember/v2/test/computed.ts b/types/ember/v2/test/computed.ts new file mode 100755 index 0000000000..f93b07a0f5 --- /dev/null +++ b/types/ember/v2/test/computed.ts @@ -0,0 +1,166 @@ +import Ember from 'ember'; +import Component from '@ember/component'; +import Computed, { alias, or } from '@ember/object/computed'; +import { assertType } from './lib/assert'; + +const Person = Ember.Object.extend({ + firstName: '', + lastName: '', + age: 0, + + noArgs: Ember.computed(() => 'test'), + + fullName: Ember.computed('firstName', 'lastName', function() { + return `${this.get('firstName')} ${this.get('lastName')}`; + }), + + fullNameReadonly: Ember.computed('fullName', function() { + return this.get('fullName'); + }).readOnly(), + + fullNameWritable: Ember.computed('firstName', 'lastName', { + get() { + return this.get('fullName'); + }, + set(key, value) { + let [first, last] = value.split(' '); + this.set('firstName', first); + this.set('lastName', last); + return value; + } + }), + + fullNameGetOnly: Ember.computed('fullName', { + get() { + return this.get('fullName'); + } + }), + + fullNameSetOnly: Ember.computed('firstName', 'lastName', { + set(key, value) { + let [first, last] = value.split(' '); + this.set('firstName', first); + this.set('lastName', last); + return value; + } + }), + + combinators: Ember.computed(function() { + return this.get('firstName'); + }).property('firstName') + .meta({ foo: 'bar' }) + .volatile() + .readOnly(), + + explicitlyDeclared: alias('fullName') as Computed, +}); + +const person = Person.create({ + firstName: 'Fred', + lastName: 'Smith', + age: 29, +}); + +assertType(person.firstName); +assertType(person.age); +assertType>(person.noArgs); +assertType>(person.fullName); +assertType>(person.fullNameReadonly); +assertType>(person.fullNameWritable); +assertType>(person.fullNameGetOnly); +assertType>(person.fullNameSetOnly); +assertType>(person.combinators); +assertType>(person.explicitlyDeclared); + +assertType(person.get('firstName')); +assertType(person.get('age')); +assertType(person.get('noArgs')); +assertType(person.get('fullName')); +assertType(person.get('fullNameReadonly')); +assertType(person.get('fullNameWritable')); +assertType(person.get('fullNameGetOnly')); +assertType(person.get('fullNameSetOnly')); +assertType(person.get('combinators')); +assertType(person.get('explicitlyDeclared')); + +assertType<{ firstName: string, fullName: string, age: number }>(person.getProperties('firstName', 'fullName', 'age')); + +const person2 = Person.create({ + fullName: 'Fred Smith' +}); + +assertType(person2.get('firstName')); +assertType(person2.get('fullName')); + +const person3 = Person.extend({ + firstName: 'Fred', + fullName: 'Fred Smith' +}).create(); + +assertType(person3.get('firstName')); +assertType(person3.get('fullName')); + +const person4 = Person.extend({ + firstName: Ember.computed(() => 'Fred'), + fullName: Ember.computed(() => 'Fred Smith') +}).create(); + +assertType(person4.get('firstName')); +assertType(person4.get('fullName')); + +// computed property macros +const objectWithComputedProperties = Ember.Object.extend({ + alias: Ember.computed.alias('foo'), + and: Ember.computed.and('foo', 'bar', 'baz', 'qux'), + bool: Ember.computed.bool('foo'), + collect: Ember.computed.collect('foo', 'bar', 'baz', 'qux'), + deprecatingAlias: Ember.computed.deprecatingAlias('foo', { + id: 'hamster.deprecate-banana', + until: '3.0.0' + }), + empty: Ember.computed.empty('foo'), + equalNumber: Ember.computed.equal('foo', 1), + equalString: Ember.computed.equal('foo', 'bar'), + equalObject: Ember.computed.equal('foo', {}), + filter: Ember.computed.filter('foo', (item) => item === 'bar'), + filterBy1: Ember.computed.filterBy('foo', 'bar'), + filterBy2: Ember.computed.filterBy('foo', 'bar', false), + gt: Ember.computed.gt('foo', 3), + gte: Ember.computed.gte('foo', 3), + intersect: Ember.computed.intersect('foo', 'bar', 'baz', 'qux'), + lt: Ember.computed.lt('foo', 3), + lte: Ember.computed.lte('foo', 3), + map: Ember.computed.map('foo', (item, index) => item.bar), + mapBy: Ember.computed.mapBy('foo', 'bar'), + match: Ember.computed.match('foo', /^tom.ter$/), + max: Ember.computed.max('foo'), + min: Ember.computed.min('foo'), + none: Ember.computed.none('foo'), + not: Ember.computed.not('foo'), + notEmpty: Ember.computed.notEmpty('foo'), + oneWay: Ember.computed.oneWay('foo'), + or: Ember.computed.or('foo', 'bar', 'baz', 'qux'), + readOnly: Ember.computed.readOnly('foo'), + reads: Ember.computed.reads('foo'), + setDiff: Ember.computed.setDiff('foo', 'bar'), + sort1: Ember.computed.sort('foo', 'bar'), + sort2: Ember.computed.sort('foo', (itemA, itemB) => { + if (itemA < itemB) { + return -1; + } else if (itemA > itemB) { + return 1; + } else { + return 0; + } + }), + sum: Ember.computed.sum('foo'), + union: Ember.computed.union('foo', 'bar', 'baz', 'qux'), + uniq: Ember.computed.uniq('foo'), + uniqBy: Ember.computed.uniqBy('foo', 'bar') +}); + +const component2 = Component.extend({ + isAnimal: or('isDog', 'isCat') +}).create(); + +assertType(component2.get('isAnimal')); diff --git a/types/ember/v2/test/controller.ts b/types/ember/v2/test/controller.ts new file mode 100755 index 0000000000..02307f447c --- /dev/null +++ b/types/ember/v2/test/controller.ts @@ -0,0 +1,11 @@ +import Controller from '@ember/controller'; + +Controller.extend ({ + queryParams: ['category'], + category: null, + isExpanded: false, + + toggleBody() { + this.toggleProperty('isExpanded'); + } +}); diff --git a/types/ember/v2/test/create-negative.ts b/types/ember/v2/test/create-negative.ts new file mode 100644 index 0000000000..f0e32a2d5e --- /dev/null +++ b/types/ember/v2/test/create-negative.ts @@ -0,0 +1,9 @@ +import { assertType } from './lib/assert'; +import Ember from 'ember'; +import { PersonWithNumberName, Person } from './create'; + +const p3 = Person.create({ firstName: 99 }); // $ExpectError +const p2b = Person.create({}, { firstName: 99 }); // $ExpectError +const p2c = Person.create({}, {}, { firstName: 99 }); // $ExpectError + +const p4 = new PersonWithNumberName(); diff --git a/types/ember/v2/test/create.ts b/types/ember/v2/test/create.ts new file mode 100755 index 0000000000..5bd8d2a396 --- /dev/null +++ b/types/ember/v2/test/create.ts @@ -0,0 +1,39 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +const o = Ember.Object.create(); +assertType(o); + +const o1 = Ember.Object.create({x: 9}); +assertType(o1.x); + +const obj = Ember.Object.create({ a: 1 }, { b: 2 }, { c: 3 }); +assertType(obj.b); +assertType(obj.a); +assertType(obj.c); + +export class Person extends Ember.Object.extend({ + fullName: Ember.computed('firstName', 'lastName', function() { + return [this.firstName + this.lastName].join(' '); + }) +}) { + firstName: string; + lastName: string; + age: number; +} +const p = new Person(); +assertType(p.firstName); +assertType>(p.fullName); +assertType(p.get('fullName')); + +const p2 = Person.create({ firstName: 'string' }); +const p2b = Person.create({}, { firstName: 'string' }); +const p2c = Person.create({}, {}, { firstName: 'string' }); + +export class PersonWithNumberName extends Person.extend({ + fullName: 6 +}) {} + +const p4 = new PersonWithNumberName(); +assertType(p4.firstName); +assertType(p4.fullName); diff --git a/types/ember/v2/test/detect-instance.ts b/types/ember/v2/test/detect-instance.ts new file mode 100755 index 0000000000..1b25beb244 --- /dev/null +++ b/types/ember/v2/test/detect-instance.ts @@ -0,0 +1,20 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +const ExtendClass = Ember.Object.extend({ + foo: 'hello' +}); + +class ES6Class extends Ember.Object { + bar: string; +} + +let testObject = null; + +if (ExtendClass.detectInstance(testObject)) { + assertType(testObject.foo); +} + +if (ES6Class.detectInstance(testObject)) { + assertType(testObject.bar); +} diff --git a/types/ember/v2/test/detect.ts b/types/ember/v2/test/detect.ts new file mode 100755 index 0000000000..cd54880f9f --- /dev/null +++ b/types/ember/v2/test/detect.ts @@ -0,0 +1,20 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +const ExtendClass = Ember.Object.extend({ + foo: 'hello' +}); + +class ES6Class extends Ember.Object { + bar: string; +} + +let TestClass = Ember.Object; + +if (ExtendClass.detect(TestClass)) { + assertType(TestClass.create().foo); +} + +if (ES6Class.detect(TestClass)) { + assertType(TestClass.create().bar); +} diff --git a/types/ember/v2/test/ember-tests.ts b/types/ember/v2/test/ember-tests.ts new file mode 100755 index 0000000000..c049512eb0 --- /dev/null +++ b/types/ember/v2/test/ember-tests.ts @@ -0,0 +1,170 @@ +import Ember from 'ember'; + +let App: any; + +App = Ember.Application.create(); +App.president = Ember.Object.create({ + name: 'Barack Obama', +}); +App.country = Ember.Object.create({ + presidentNameBinding: 'MyApp.president.name', +}); +App.country.get('presidentName'); +App.president = Ember.Object.create({ + firstName: 'Barack', + lastName: 'Obama', + fullName: Ember.computed(function() { + return `${this.get('firstName')} ${this.get('lastName')}`; + }), +}); +App.president.get('fullName'); + +declare class MyPerson extends Ember.Object { + static createMan(): MyPerson; +} +MyPerson.createMan(); + +const Person1 = Ember.Object.extend({ + say: (thing: string) => { + alert(thing); + }, +}); + +declare class MyPerson2 extends Ember.Object { + helloWorld(): void; +} +MyPerson2.create().helloWorld(); + +const tom = Person1.create({ + name: 'Tom Dale', + helloWorld() { + this.say('Hi my name is ' + this.get('name')); + }, +}); +tom.helloWorld(); + +const PersonReopened = Person1.reopen({ isPerson: true }); +PersonReopened.create().get('isPerson'); + +App.todosController = Ember.Object.create({ + todos: [Ember.Object.create({ isDone: false })], + remaining: Ember.computed('todos.@each.isDone', function() { + const todos = this.get('todos'); + return todos.filterProperty('isDone', false).get('length'); + }), +}); + +const todos = App.todosController.get('todos'); +let todo = todos.objectAt(0); +todo.set('isDone', true); +App.todosController.get('remaining'); +todo = Ember.Object.create({ isDone: false }); +todos.pushObject(todo); +App.todosController.get('remaining'); + +App.wife = Ember.Object.create({ + householdIncome: 80000, +}); +App.husband = Ember.Object.create({ + householdIncomeBinding: 'App.wife.householdIncome', +}); +App.husband.get('householdIncome'); +App.husband.set('householdIncome', 90000); +App.wife.get('householdIncome'); + +App.user = Ember.Object.create({ + fullName: 'Kara Gates', +}); +App.user.set('fullName', 'Krang Gates'); +App.userView.set('userName', 'Truckasaurus Gates'); +App.user.get('fullName'); + +App = Ember.Application.create({ + rootElement: '#sidebar', +}); + +App.userController = Ember.Object.create({ + content: Ember.Object.create({ + firstName: 'Albert', + lastName: 'Hofmann', + posts: 25, + hobbies: 'Riding bicycles', + }), +}); + +Handlebars.registerHelper( + 'highlight', + (property: string, options: any) => + new Handlebars.SafeString('' + 'some value' + '') +); + +const coolView = App.CoolView.create(); + +const Person2 = Ember.Object.extend({ + name: '', + sayHello() { + console.log('Hello from ' + this.get('name')); + }, +}); +const people = Ember.A([ + Person2.create({ name: 'Juan' }), + Person2.create({ name: 'Charles' }), + Person2.create({ name: 'Majd' }), +]); +people.invoke('sayHello'); + +const arr = Ember.A([Ember.Object.create(), Ember.Object.create()]); +arr.setEach('name', 'unknown'); +arr.getEach('name'); + +const Person3 = Ember.Object.extend({ + name: '', + isHappy: false, +}); +const people2 = Ember.A([ + Person3.create({ name: 'Yehuda', isHappy: true }), + Person3.create({ name: 'Majd', isHappy: false }), +]); +const isHappy = (person: typeof Person3.prototype): boolean => { + return !!person.get('isHappy'); +}; +people2.every(isHappy); +people2.any(isHappy); +people2.isEvery('isHappy'); +people2.isEvery('isHappy', true); +people2.isAny('isHappy', 'true'); +people2.isAny('isHappy'); + +// Examples taken from http://emberjs.com/api/classes/Em.RSVP.Promise.html +const promise = new Ember.RSVP.Promise((resolve: Function, reject: Function) => { + // on success + resolve('ok!'); + + // on failure + reject('no-k!'); +}); + +promise.then( + (value: any) => { + // on fulfillment + }, + (reason: any) => { + // on rejection + } +); + +// make sure Ember.RSVP.Promise can be reference as a type +declare function promiseReturningFunction(urn: string): Ember.RSVP.Promise; + +const mix1 = Ember.Mixin.create({ + foo: 1, +}); + +const mix2 = Ember.Mixin.create({ + bar: 2, +}); + +const component1 = Ember.Component.extend(mix1, mix2, { + lyft: Ember.inject.service(), + cars: Ember.computed.readOnly('lyft.cars'), +}); diff --git a/types/ember/v2/test/engine-instance.ts b/types/ember/v2/test/engine-instance.ts new file mode 100644 index 0000000000..c74914dea5 --- /dev/null +++ b/types/ember/v2/test/engine-instance.ts @@ -0,0 +1,26 @@ +import EngineInstance from '@ember/engine/instance'; + +const engineInstance = EngineInstance.create(); +engineInstance.register('some:injection', class Foo {}); + +engineInstance.register('some:injection', class Foo {}, { + singleton: true, +}); + +engineInstance.register('some:injection', class Foo {}, { + instantiate: false, +}); + +engineInstance.register('some:injection', class Foo {}, { + singleton: false, + instantiate: true, +}); + +engineInstance.factoryFor('router:main'); +engineInstance.lookup('route:basic'); + +engineInstance.boot(); + +(async function() { + await engineInstance.boot(); +}()); diff --git a/types/ember/v2/test/error.ts b/types/ember/v2/test/error.ts new file mode 100644 index 0000000000..ad3c2ee8c3 --- /dev/null +++ b/types/ember/v2/test/error.ts @@ -0,0 +1,6 @@ +import { assertType } from "./lib/assert"; + +import Ember from "ember"; +import EmberError from "@ember/error"; + +assertType(EmberError); diff --git a/types/ember/v2/test/event.ts b/types/ember/v2/test/event.ts new file mode 100755 index 0000000000..c934072440 --- /dev/null +++ b/types/ember/v2/test/event.ts @@ -0,0 +1,58 @@ +import Ember from 'ember'; + +function testOn() { + let Job = Ember.Object.extend({ + logCompleted: Ember.on('completed', function() { + console.log('Job completed!'); + }) + }); + + let job = Job.create(); + + Ember.sendEvent(job, 'completed'); // Logs 'Job completed!' +} + +function testEvented() { + let Person = Ember.Object.extend(Ember.Evented, { + greet() { + this.trigger('greet'); + } + }); + + let person = Person.create(); + + person.on('greet', function() { + console.log('Our person has greeted'); + }); + + person.on('greet', function() { + console.log('Our person has greeted'); + }).one('greet', function() { + console.log('Offer one-time special'); + }).off('event', {}, function() {}); + + person.greet(); +} + +function testObserver() { + Ember.Object.extend({ + valueObserver: Ember.observer('value', function() { + // Executes whenever the "value" property changes + }) + }); +} + +function testListener() { + Ember.Component.extend({ + init() { + Ember.addListener(this, 'willDestroyElement', this, 'willDestroyListener'); + Ember.addListener(this, 'willDestroyElement', this, 'willDestroyListener', true); + Ember.addListener(this, 'willDestroyElement', this, this.willDestroyListener); + Ember.addListener(this, 'willDestroyElement', this, this.willDestroyListener, true); + Ember.removeListener(this, 'willDestroyElement', this, 'willDestroyListener'); + Ember.removeListener(this, 'willDestroyElement', this, this.willDestroyListener); + }, + willDestroyListener() { + } + }); +} diff --git a/types/ember/v2/test/extend.ts b/types/ember/v2/test/extend.ts new file mode 100755 index 0000000000..a54f81a600 --- /dev/null +++ b/types/ember/v2/test/extend.ts @@ -0,0 +1,61 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +const Person = Ember.Object.extend({ + firstName: '', + lastName: '', + + getFullName() { + return `${this.firstName} ${this.lastName}`; + }, + getFullName2(): string { + return `${this.get('firstName')} ${this.get('lastName')}`; + } +}); + +assertType(Person.prototype.firstName); +assertType<() => string>(Person.prototype.getFullName); + +const person = Person.create({ + firstName: 'Joe', + lastName: 'Blow', + extra: 42 +}); + +assertType(person.getFullName()); +assertType(person.extra); + +class ES6Person extends Ember.Object { + firstName: string; + lastName: string; + + get fullName() { + return `${this.firstName} ${this.lastName}`; + } + get fullName2(): string { + return `${this.get('firstName')} ${this.get('lastName')}`; + } +} + +assertType(ES6Person.prototype.firstName); +assertType(ES6Person.prototype.fullName); + +const es6Person = ES6Person.create({ + firstName: 'Joe', + lastName: 'Blow', + extra: 42 +}); + +assertType(es6Person.fullName); +assertType(es6Person.extra); + +class PersonWithStatics extends Ember.Object { + static isPerson = true; +} +const PersonWithStatics2 = PersonWithStatics.extend({}); +class PersonWithStatics3 extends PersonWithStatics {} +class PersonWithStatics4 extends PersonWithStatics2 {} +assertType(PersonWithStatics.isPerson); +assertType(PersonWithStatics2.isPerson); +assertType(PersonWithStatics3.isPerson); +assertType(PersonWithStatics4.isPerson); diff --git a/types/ember/v2/test/function-ext.ts b/types/ember/v2/test/function-ext.ts new file mode 100755 index 0000000000..37d831d49a --- /dev/null +++ b/types/ember/v2/test/function-ext.ts @@ -0,0 +1,21 @@ +import Ember from 'ember'; + +declare global { + interface Function extends Ember.FunctionPrototypeExtensions {} +} + +Ember.Object.extend({ + foo: '', + + arr: function() { + return []; + }.property(), + + alias: function(this: any) { + return this.get('foo'); + }.property('foo', 'bar.@each.baz'), + + observer: function() {}.observes('foo', 'bar'), + + on: function() {}.on('foo', 'bar'), +}); diff --git a/types/ember/v2/test/helper.ts b/types/ember/v2/test/helper.ts new file mode 100755 index 0000000000..2aa79a5ba1 --- /dev/null +++ b/types/ember/v2/test/helper.ts @@ -0,0 +1,41 @@ +import Ember from 'ember'; + +const FormatCurrencyHelper = Ember.Helper.helper(function(params, hash: { currency: string }) { + let cents = params[0]; + let currency = hash.currency; + return `${currency}${cents * 0.01}`; +}); + +class User extends Ember.Object { + email: string; +} + +class SessionService extends Ember.Service { + currentUser: User; +} + +const CurrentUserEmailHelper = Ember.Helper.extend({ + session: Ember.inject.service() as Ember.ComputedProperty, + onNewUser: Ember.observer('session.currentUser', function(this: Ember.Helper) { + this.recompute(); + }), + compute(): string { + return this.get('session') + .get('currentUser') + .get('email'); + }, +}); + +import { helper } from '@ember/component/helper'; + +function typedHelp(/*params, hash*/) { + return 'my type of help'; +} + +export default helper(typedHelp); + +function arrayNumHelp(/*params, hash*/) { + return [1, 2, 3]; +} + +helper(arrayNumHelp); diff --git a/types/ember/v2/test/inject.ts b/types/ember/v2/test/inject.ts new file mode 100755 index 0000000000..3ea0176ea6 --- /dev/null +++ b/types/ember/v2/test/inject.ts @@ -0,0 +1,59 @@ +import Ember from 'ember'; + +class AuthService extends Ember.Service { + isAuthenticated: boolean; +} + +class ApplicationController extends Ember.Controller { + model: {}; + string: string; + transitionToLogin() {} +} + +declare module '@ember/service' { + interface Registry { + 'auth': AuthService; + } +} + +declare module '@ember/controller' { + interface Registry { + 'application': ApplicationController; + } +} + +class LoginRoute extends Ember.Route { + auth = Ember.inject.service('auth'); + application = Ember.inject.controller('application'); + + didTransition() { + if (!this.get('auth').get('isAuthenticated')) { + this.get('application').transitionToLogin(); + } + } + + anyOldMethod() { + this.controllerFor('application').set('string', 'must be a string'); + } +} + +// New module injection style. +import Controller, { inject as controller } from '@ember/controller'; +import Service, { inject as service } from '@ember/service'; +import { assertType } from './lib/assert'; + +class ComponentInjection extends Ember.Component { + applicationController = controller('application'); + auth = service('auth'); + router = service('router'); + misc = service(); + + testem() { + assertType(this.get('misc')); + const url = this.get('router').urlFor('some-route', 1, 2, 3, { queryParams: { seriously: 'yes' } }); + assertType(url); + if (!this.get('auth').isAuthenticated) { + this.get('applicationController').transitionToLogin(); + } + } +} diff --git a/types/ember/v2/test/lib/assert.ts b/types/ember/v2/test/lib/assert.ts new file mode 100755 index 0000000000..d6748cd5bc --- /dev/null +++ b/types/ember/v2/test/lib/assert.ts @@ -0,0 +1,5 @@ +/** Static assertion that `value` has type `T` */ +// Disable tslint here b/c the generic is used to let us do a type coercion and +// validate that coercion works for the type value "passed into" the function. +// tslint:disable-next-line:no-unnecessary-generics +export declare function assertType(value: T): void; diff --git a/types/ember/v2/test/mixin.ts b/types/ember/v2/test/mixin.ts new file mode 100755 index 0000000000..a89f490a11 --- /dev/null +++ b/types/ember/v2/test/mixin.ts @@ -0,0 +1,57 @@ +import Ember from 'ember'; +import { assertType } from "./lib/assert"; + +interface EditableMixin { + edit(): void; + isEditing: boolean; +} + +const EditableMixin: Ember.Mixin = Ember.Mixin.create({ + edit() { + this.get('controller'); + console.log('starting to edit'); + this.set('isEditing', true); + }, + isEditing: false +}); + +const EditableComment = Ember.Route.extend(EditableMixin, { + postId: 0, + + canEdit() { + return !this.isEditing; + }, + + tryEdit() { + if (this.canEdit()) { + this.edit(); + } + } +}); + +const comment = EditableComment.create({ + postId: 42 +}); + +comment.edit(); +comment.canEdit(); +comment.tryEdit(); +assertType(comment.isEditing); +assertType(comment.postId); + +const LiteralMixins = Ember.Object.extend({ a: 1 }, { b: 2 }, { c: 3 }); +const obj = LiteralMixins.create(); +assertType(obj.a); +assertType(obj.b); +assertType(obj.c); + +/* Test composition of mixins */ +const EditableAndCancelableMixin = Ember.Mixin.create(EditableMixin, { + cancelled: false, +}); + +const EditableAndCancelableComment = Ember.Route.extend(EditableAndCancelableMixin); + +const editableAndCancelable = EditableAndCancelableComment.create(); +assertType(editableAndCancelable.isEditing); +assertType(editableAndCancelable.cancelled); diff --git a/types/ember/v2/test/object.ts b/types/ember/v2/test/object.ts new file mode 100755 index 0000000000..e1eefb75e9 --- /dev/null +++ b/types/ember/v2/test/object.ts @@ -0,0 +1,27 @@ +import Ember from 'ember'; + +const LifetimeHooks = Ember.Object.extend({ + resource: null as {} | null, + + init() { + this._super(); + this.resource = {}; + }, + + willDestroy() { + delete this.resource; + this._super(); + } +}); + +class MyObject30 extends Ember.Object { + constructor() { + super(); + } +} + +class MyObject31 extends Ember.Object { + constructor(properties: object) { + super(properties); + } +} diff --git a/types/ember/v2/test/observable.ts b/types/ember/v2/test/observable.ts new file mode 100755 index 0000000000..a642da271f --- /dev/null +++ b/types/ember/v2/test/observable.ts @@ -0,0 +1,113 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +class MyComponent extends Ember.Component { + foo = 'bar'; + + init() { + this._super.apply(this, arguments); + this.addObserver('foo', this, 'fooDidChange'); + this.addObserver('foo', this, this.fooDidChange); + Ember.addObserver(this, 'foo', this, 'fooDidChange'); + Ember.addObserver(this, 'foo', this, this.fooDidChange); + this.removeObserver('foo', this, 'fooDidChange'); + this.removeObserver('foo', this, this.fooDidChange); + Ember.removeObserver(this, 'foo', this, 'fooDidChange'); + Ember.removeObserver(this, 'foo', this, this.fooDidChange); + const lambda = () => { + this.fooDidChange(this, 'foo'); + }; + this.addObserver('foo', lambda); + this.removeObserver('foo', lambda); + Ember.addObserver(this, 'foo', lambda); + Ember.removeObserver(this, 'foo', lambda); + } + + fooDidChange(sender: MyComponent, key: 'foo') { + // your code + } +} + +const myComponent = MyComponent.create(); +myComponent.addObserver('foo', null, () => {}); +myComponent.set('foo', 'baz'); + +const person = Ember.Object.create({ + name: 'Fred', + age: 29, + capitalized: Ember.computed(function() { + return this.get('name').toUpperCase(); + }) +}); + +const pojo = { name: 'Fred', age: 29 }; + +function testGet() { + assertType(Ember.get(person, 'name')); + assertType(Ember.get(person, 'age')); + assertType(Ember.get(person, 'capitalized')); + assertType(person.get('name')); + assertType(person.get('age')); + assertType(person.get('capitalized')); + assertType(Ember.get(pojo, 'name')); +} + +function testGetProperties() { + assertType<{ name: string }>(Ember.getProperties(person, 'name')); + assertType<{ name: string, age: number }>(Ember.getProperties(person, 'name', 'age')); + assertType<{ name: string, age: number }>(Ember.getProperties(person, [ 'name', 'age' ])); + assertType<{ name: string, age: number, capitalized: string }>(Ember.getProperties(person, 'name', 'age', 'capitalized')); + assertType<{ name: string }>(person.getProperties('name')); + assertType<{ name: string, age: number }>(person.getProperties('name', 'age')); + assertType<{ name: string, age: number }>(person.getProperties([ 'name', 'age' ])); + assertType<{ name: string, age: number, capitalized: string }>(person.getProperties('name', 'age', 'capitalized')); + assertType<{ name: string, age: number }>(Ember.getProperties(pojo, 'name', 'age')); +} + +function testGetWithDefault() { + assertType(Ember.getWithDefault(person, 'name', 'Joe')); + assertType(Ember.getWithDefault(person, 'age', 20)); + assertType(Ember.getWithDefault(person, 'capitalized', 'JOE')); + assertType(person.getWithDefault('name', 'Joe')); + assertType(person.getWithDefault('age', 20)); + assertType(person.getWithDefault('capitalized', 'JOE')); + assertType(Ember.getWithDefault(pojo, 'name', 'JOE')); +} + +function testSet() { + assertType(Ember.set(person, 'name', 'Joe')); + assertType(Ember.set(person, 'age', 35)); + assertType(Ember.set(person, 'capitalized', 'JOE')); + assertType(person.set('name', 'Joe')); + assertType(person.set('age', 35)); + assertType(person.set('capitalized', 'JOE')); + assertType(Ember.set(pojo, 'name', 'Joe')); +} + +function testSetProperties() { + assertType<{ name: string }>(Ember.setProperties(person, { name: 'Joe' })); + assertType<{ name: string, age: number }>(Ember.setProperties(person, { name: 'Joe', age: 35 })); + assertType<{ name: string, capitalized: string }>(Ember.setProperties(person, { name: 'Joe', capitalized: 'JOE' })); + assertType<{ name: string }>(person.setProperties({ name: 'Joe' })); + assertType<{ name: string, age: number }>(person.setProperties({ name: 'Joe', age: 35 })); + assertType<{ name: string, capitalized: string }>(person.setProperties({ name: 'Joe', capitalized: 'JOE' })); + assertType<{ name: string, age: number }>(Ember.setProperties(pojo, { name: 'Joe', age: 35 })); +} + +function testDynamic() { + const obj: any = {}; + const dynamicKey: string = 'dummy'; // tslint:disable-line:no-inferrable-types + + assertType(Ember.get(obj, 'dummy')); + assertType(Ember.get(obj, dynamicKey)); + assertType(Ember.getWithDefault(obj, 'dummy', 'default')); + assertType(Ember.getWithDefault(obj, dynamicKey, 'default')); + assertType<{ dummy: any }>(Ember.getProperties(obj, 'dummy')); + assertType<{ dummy: any }>(Ember.getProperties(obj, [ 'dummy' ])); + assertType(Ember.getProperties(obj, dynamicKey)); + assertType(Ember.getProperties(obj, [ dynamicKey ])); + assertType(Ember.set(obj, 'dummy', 'value')); + assertType(Ember.set(obj, dynamicKey, 'value')); + assertType<{ dummy: string }>(Ember.setProperties(obj, { dummy: 'value '})); + assertType(Ember.setProperties(obj, { [dynamicKey]: 'value' })); +} diff --git a/types/ember/v2/test/reopen.ts b/types/ember/v2/test/reopen.ts new file mode 100755 index 0000000000..6c13ca4155 --- /dev/null +++ b/types/ember/v2/test/reopen.ts @@ -0,0 +1,65 @@ +import Ember from 'ember'; +import { assertType } from "./lib/assert"; + +type Person = typeof Person.prototype; +const Person = Ember.Object.extend({ + name: '', + sayHello() { + alert(`Hello. My name is ${this.get('name')}`); + } +}); + +assertType(Person.reopen()); + +assertType(Person.create().name); +assertType(Person.create().sayHello()); + +const Person2 = Person.reopenClass({ + species: 'Homo sapiens', + + createPerson(name: string): Person { + return Person.create({ name }); + } +}); + +assertType(Person2.create().name); +assertType(Person2.create().sayHello()); +assertType(Person2.species); + +let tom = Person2.create({ + name: 'Tom Dale' +}); +let yehuda = Person2.createPerson('Yehuda Katz'); + +tom.sayHello(); // "Hello. My name is Tom Dale" +yehuda.sayHello(); // "Hello. My name is Yehuda Katz" +alert(Person2.species); // "Homo sapiens" + +const Person3 = Person2.reopen({ + goodbyeMessage: 'goodbye', + + sayGoodbye() { + alert(`${this.get('goodbyeMessage')}, ${this.get('name')}`); + } +}); + +const person3 = Person3.create(); +person3.get('name'); +person3.get('goodbyeMessage'); +person3.sayHello(); +person3.sayGoodbye(); + +interface AutoResizeMixin { resizable: true; } +declare const AutoResizeMixin: Ember.Mixin; + +const ResizableTextArea = Ember.TextArea.reopen(AutoResizeMixin, { + scaling: 1.0 +}); +const text = ResizableTextArea.create(); +assertType(text.resizable); +assertType(text.scaling); + +const Reopened = Ember.Object.reopenClass({ a: 1 }, { b: 2 }, { c: 3 }); +assertType(Reopened.a); +assertType(Reopened.b); +assertType(Reopened.c); diff --git a/types/ember/v2/test/route.ts b/types/ember/v2/test/route.ts new file mode 100755 index 0000000000..84e432dbd3 --- /dev/null +++ b/types/ember/v2/test/route.ts @@ -0,0 +1,104 @@ +import Route from '@ember/routing/route'; +import Object from '@ember/object'; +import Array from '@ember/array'; +import Ember from 'ember'; // currently needed for Transition + +interface Post extends Ember.Object {} + +interface Posts extends Array {} + +Route.extend({ + beforeModel(transition: Ember.Transition) { + this.transitionTo('someOtherRoute'); + }, +}); + +Route.extend({ + afterModel(posts: Posts, transition: Ember.Transition) { + if (posts.length === 1) { + this.transitionTo('post.show', posts.firstObject); + } + }, +}); + +Route.extend({ + actions: { + showModal(evt: { modalName: string }) { + this.render(evt.modalName, { + outlet: 'modal', + into: 'application', + }); + }, + hideModal(evt: { modalName: string }) { + this.disconnectOutlet({ + outlet: 'modal', + parentView: 'application', + }); + }, + }, +}); + +Ember.Route.extend({ + model() { + return this.modelFor('post'); + }, +}); + +Route.extend({ + queryParams: { + memberQp: { refreshModel: true }, + }, +}); + +Route.extend({ + renderTemplate() { + this.render('photos', { + into: 'application', + outlet: 'anOutletName', + }); + }, +}); + +Route.extend({ + renderTemplate(controller: Ember.Controller, model: {}) { + this.render('posts', { + view: 'someView', // the template to render, referenced by name + into: 'application', // the template to render into, referenced by name + outlet: 'anOutletName', // the outlet inside `options.into` to render into. + controller: 'someControllerName', // the controller to use for this template, referenced by name + model, // the model to set on `options.controller`. + }); + }, +}); + +Route.extend({ + resetController(controller: Ember.Controller, isExiting: boolean, transition: boolean) { + if (isExiting) { + // controller.set('page', 1); + } + }, +}); + +Route.extend({ + setupController(controller: Ember.Controller, model: {}) { + this._super(controller, model); + this.controllerFor('application').set('model', model); + }, +}); + +class RouteUsingClass extends Route.extend({ + randomProperty: 'the .extend + extends bit type-checks properly', +}) { + beforeModel(this: RouteUsingClass) { + return 'beforeModel can return anything, not just promises'; + } + intermediateTransitionWithoutModel() { + this.intermediateTransitionTo('some-route'); + } + intermediateTransitionWithModel() { + this.intermediateTransitionTo('some.other.route', { }); + } + intermediateTransitionWithMultiModel() { + this.intermediateTransitionTo('some.other.route', 1, 2, { }); + } +} diff --git a/types/ember/v2/test/router.ts b/types/ember/v2/test/router.ts new file mode 100755 index 0000000000..760e9ed5bc --- /dev/null +++ b/types/ember/v2/test/router.ts @@ -0,0 +1,54 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +const AppRouter = Ember.Router.extend({ +}); + +AppRouter.map(function() { + this.route('index', { path: '/' }); + this.route('about'); + this.route('favorites', { path: '/favs' }); + this.route('posts', function() { + this.route('index', { path: '/' }); + this.route('new'); + this.route('post', { path: '/post/:post_id', resetNamespace: true }); + this.route('comments', { resetNamespace: true }, function() { + this.route('new'); + }); + }); + this.route('photo', { path: '/photo/:id' }, function() { + this.route('comment', { path: '/comment/:id' }); + }); + this.route('not-found', { path: '/*path' }); + this.mount('my-engine'); + this.mount('my-engine', { as: 'some-other-engine', path: '/some-other-engine'}); +}); + +const RouterServiceConsumer = Ember.Service.extend({ + router: Ember.inject.service('router'), + currentRouteName() { + const x: string = Ember.get(this, 'router').currentRouteName; + }, + currentURL() { + const x: string = Ember.get(this, 'router').currentURL; + }, + transitionWithoutModel() { + Ember.get(this, 'router') + .transitionTo('some-route'); + }, + transitionWithModel() { + const model = Ember.Object.create(); + Ember.get(this, 'router') + .transitionTo('some.other.route', model); + }, + transitionWithMultiModel() { + const model = Ember.Object.create(); + Ember.get(this, 'router') + .transitionTo('some.other.route', model, model); + }, + transitionWithModelAndOptions() { + const model = Ember.Object.create(); + Ember.get(this, 'router') + .transitionTo('index', model, { queryParams: { search: 'ember' }}); + } +}); diff --git a/types/ember/v2/test/run.ts b/types/ember/v2/test/run.ts new file mode 100755 index 0000000000..8d1c82e6e3 --- /dev/null +++ b/types/ember/v2/test/run.ts @@ -0,0 +1,204 @@ +import Ember from 'ember'; +import RSVP from 'rsvp'; +import { run } from '@ember/runloop'; +import { assertType } from "./lib/assert"; + +assertType(Ember.run.queues); + +function testRun() { + let r = run(function() { + // code to be executed within a RunLoop + return 123; + }); + assertType(r); + + function destroyApp(application: Ember.Application) { + Ember.run(application, 'destroy'); + run(application, function() { + this.destroy(); + }); + } +} + +function testBind() { + Ember.Component.extend({ + init() { + const bound = Ember.run.bind(this, this.setupEditor); + bound(); + }, + + editor: null as string | null, + + setupEditor(editor: string) { + this.set('editor', editor); + } + }); +} + +function testCancel() { + const myContext = {}; + + let runNext = run.next(myContext, function() { + // will not be executed + }); + + run.cancel(runNext); + + let runLater = run.later(myContext, function() { + // will not be executed + }, 500); + + run.cancel(runLater); + + let runScheduleOnce = run.scheduleOnce('afterRender', myContext, function() { + // will not be executed + }); + + run.cancel(runScheduleOnce); + + let runOnce = run.once(myContext, function() { + // will not be executed + }); + + run.cancel(runOnce); + + let throttle = run.throttle(myContext, function() { + // will not be executed + }, 1, false); + + run.cancel(throttle); + + let debounce = run.debounce(myContext, function() { + // will not be executed + }, 1); + + run.cancel(debounce); + + let debounceImmediate = run.debounce(myContext, function() { + // will be executed since we passed in true (immediate) + }, 100, true); + + // the 100ms delay until this method can be called again will be canceled + run.cancel(debounceImmediate); +} + +function testDebounce() { + function runIt() { + } + + let myContext = { name: 'debounce' }; + + run.debounce(runIt, 150); + run.debounce(myContext, runIt, 150); + run.debounce(myContext, runIt, 150, true); + + Ember.Component.extend({ + searchValue: 'test', + fetchResults(value: string) {}, + + actions: { + handleTyping() { + // the fetchResults function is passed into the component from its parent + Ember.run.debounce(this, this.get('fetchResults'), this.get('searchValue'), 250); + } + } + }); +} + +function testBegin() { + run.begin(); + // code to be executed within a RunLoop + run.end(); +} + +function testJoin() { + run.join(function() { + // creates a new run-loop + }); + + run(function() { + // creates a new run-loop + run.join(function() { + // joins with the existing run-loop, and queues for invocation on + // the existing run-loops action queue. + }); + }); + + new RSVP.Promise(function(resolve) { + Ember.run.later(function() { + resolve({ msg: 'Hold Your Horses' }); + }, 3000); + }); +} + +function testLater() { + const myContext = {}; + run.later(myContext, function() { + // code here will execute within a RunLoop in about 500ms with this == myContext + }, 500); +} + +function testNext() { + const myContext = {}; + run.next(myContext, function() { + // code to be executed in the next run loop, + // which will be scheduled after the current one + }); +} + +function testOnce() { + Ember.Component.extend({ + init() { + Ember.run.once(this, 'processFullName'); + }, + + processFullName() { + } + }); +} + +function testSchedule() { + Ember.Component.extend({ + init() { + run.schedule('sync', this, function() { + // this will be executed in the first RunLoop queue, when bindings are synced + console.log('scheduled on sync queue'); + }); + + run.schedule('actions', this, function() { + // this will be executed in the 'actions' queue, after bindings have synced. + console.log('scheduled on actions queue'); + }); + } + }); + + Ember.run.schedule('actions', () => { + // Do more things + }); +} + +function testScheduleOnce() { + function sayHi() { + console.log('hi'); + } + + const myContext = {}; + run(function() { + run.scheduleOnce('afterRender', myContext, sayHi); + run.scheduleOnce('afterRender', myContext, sayHi); + // sayHi will only be executed once, in the afterRender queue of the RunLoop + }); + run.scheduleOnce('actions', myContext, function() { + console.log('Closure'); + }); +} + +function testThrottle() { + function runIt() { + } + + let myContext = { name: 'throttle' }; + + run.throttle(runIt, 150); + run.throttle(myContext, runIt, 150); +} diff --git a/types/ember/v2/test/test.ts b/types/ember/v2/test/test.ts new file mode 100755 index 0000000000..6cd1b2b908 --- /dev/null +++ b/types/ember/v2/test/test.ts @@ -0,0 +1,32 @@ +import Ember from 'ember'; + +let pending = 0; +Ember.Test.registerWaiter(() => pending !== 0); + +declare const MyDb: { + hasPendingTransactions(): boolean; +}; +Ember.Test.registerWaiter(MyDb, MyDb.hasPendingTransactions); + +Ember.Test.promise(function(resolve) { + window.setTimeout(resolve, 500); +}); + +Ember.Test.registerHelper('boot', function(app) { + Ember.run(app, app.advanceReadiness); +}); + +Ember.Test.registerAsyncHelper('boot', function(app) { + Ember.run(app, app.advanceReadiness); +}); + +Ember.Test.registerAsyncHelper('waitForPromise', (app, promise) => { + return new Ember.Test.Promise((resolve) => { + Ember.Test.adapter.asyncStart(); + + promise.then(() => { + Ember.run.schedule('afterRender', null, resolve); + Ember.Test.adapter.asyncEnd(); + }); + }); +}); diff --git a/types/ember/v2/test/transition.ts b/types/ember/v2/test/transition.ts new file mode 100755 index 0000000000..3a64675c24 --- /dev/null +++ b/types/ember/v2/test/transition.ts @@ -0,0 +1,28 @@ +import Ember from 'ember'; + +Ember.Route.extend({ + beforeModel(transition: Ember.Transition) { + if (new Date() > new Date('January 1, 1980')) { + alert('Sorry, you need a time machine to enter this route.'); + transition.abort(); + } + } +}); + +Ember.Controller.extend({ + previousTransition: null, + + actions: { + login() { + // Log the user in, then reattempt previous transition if it exists. + let previousTransition = this.get('previousTransition'); + if (previousTransition) { + this.set('previousTransition', null); + previousTransition.retry(); + } else { + // Default back to homepage + this.transitionToRoute('index'); + } + } + } +}); diff --git a/types/ember/v2/test/utils.ts b/types/ember/v2/test/utils.ts new file mode 100755 index 0000000000..d729d472b8 --- /dev/null +++ b/types/ember/v2/test/utils.ts @@ -0,0 +1,71 @@ +import Ember from 'ember'; +import * as utils from '@ember/utils'; +import { assertType } from "./lib/assert"; + +function testIsNoneType() { + const maybeUndefined: string | undefined = 'not actually undefined'; + if (utils.isNone(maybeUndefined)) { + return; + } + + const anotherString = maybeUndefined + 'another string'; +} + +function testMerge() { + assertType<{ first: string, last: string }>( + Ember.merge({ first: 'Tom' }, { last: 'Dale' }) + ); +} + +function testAssign() { + assertType<{ first: string, middle: string, last: string }>( + Ember.assign({ first: 'Tom' }, { middle: 'M' }, { last: 'Dale' }) + ); +} + +function testOnError() { + Ember.onerror = function(error) { + Ember.$.post('/report-error', { + stack: error.stack, + otherInformation: 'whatever app state you want to provide' + }); + }; +} + +function testMakeArray() { + assertType(Ember.makeArray()); + assertType(Ember.makeArray(null)); + assertType(Ember.makeArray(undefined)); + assertType(Ember.makeArray('lindsay')); + assertType(Ember.makeArray([1, 2, 42])); +} + +function testDeprecateFunc() { + function newMethod(first: string, second: number): string { + return ''; + } + + let oldMethod = Ember.deprecateFunc('Please use the new method', { id: 'deprecated.id', until: '6.0' }, newMethod); + assertType(newMethod('first', 123)); + assertType(oldMethod('first', 123)); +} + +function testDefineProperty() { + const contact = {}; + + // ES5 compatible mode + Ember.defineProperty(contact, 'firstName', { + writable: true, + configurable: false, + enumerable: true, + value: 'Charles' + }); + + // define a simple property + Ember.defineProperty(contact, 'lastName', undefined, 'Jolley'); + + // define a computed property + Ember.defineProperty(contact, 'fullName', Ember.computed('firstName', 'lastName', function() { + return `${this.firstName} ${this.lastName}`; + })); +} diff --git a/types/ember/v2/test/view-utils.ts b/types/ember/v2/test/view-utils.ts new file mode 100644 index 0000000000..a3613064eb --- /dev/null +++ b/types/ember/v2/test/view-utils.ts @@ -0,0 +1,5 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +const { ViewUtils: { isSimpleClick } } = Ember; +assertType(isSimpleClick(new Event('wat'))); diff --git a/types/ember/v2/tsconfig.json b/types/ember/v2/tsconfig.json new file mode 100755 index 0000000000..3269fa01f1 --- /dev/null +++ b/types/ember/v2/tsconfig.json @@ -0,0 +1,59 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "ember": ["ember/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/lib/assert.ts", + "test/application.ts", + "test/application-instance.ts", + "test/engine-instance.ts", + "test/ember-tests.ts", + "test/error.ts", + "test/event.ts", + "test/extend.ts", + "test/create.ts", + "test/create-negative.ts", + "test/object.ts", + "test/observable.ts", + "test/mixin.ts", + "test/reopen.ts", + "test/detect.ts", + "test/detect-instance.ts", + "test/array.ts", + "test/array-ext.ts", + "test/array-proxy.ts", + "test/helper.ts", + "test/computed.ts", + "test/component.ts", + "test/function-ext.ts", + "test/inject.ts", + "test/utils.ts", + "test/transition.ts", + "test/router.ts", + "test/run.ts", + "test/test.ts", + "test/controller.ts", + "test/route.ts", + "test/view-utils.ts" + ] +} diff --git a/types/ember/v2/tslint.json b/types/ember/v2/tslint.json new file mode 100755 index 0000000000..f77f8d2ed8 --- /dev/null +++ b/types/ember/v2/tslint.json @@ -0,0 +1,30 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // Heavy use of Function type in this older package. + "ban-types": false, + "jsdoc-format": false, + "no-misused-new": false, + + // these are disabled because of rfc176 module exports + "strict-export-declare-modifiers": false, + "no-single-declare-module": false, + "no-declare-current-package": false, + "no-self-import": false, + + // We use interfaces in a number of places to express things (including + // mixins in particular, but also including extending a global + // interface) which TS currently can't express correctly. + "no-empty-interface": false, + + "no-duplicate-imports": false, + "no-unnecessary-qualifier": false, + "prefer-const": false, + "no-void-expression": false, + "only-arrow-functions": false, + "no-submodule-imports": false, + + // false positives + "unified-signatures": false + } +} diff --git a/types/ember__application/deprecations.d.ts b/types/ember__application/deprecations.d.ts new file mode 100644 index 0000000000..608ba5c7f7 --- /dev/null +++ b/types/ember__application/deprecations.d.ts @@ -0,0 +1,4 @@ +import Ember from 'ember'; + +export const deprecate: typeof Ember.deprecate; +export const deprecateFunc: typeof Ember.deprecateFunc; diff --git a/types/ember__application/globals-resolver.d.ts b/types/ember__application/globals-resolver.d.ts new file mode 100644 index 0000000000..e51f4681ed --- /dev/null +++ b/types/ember__application/globals-resolver.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class GlobalsResolver extends Ember.DefaultResolver { } diff --git a/types/ember__application/index.d.ts b/types/ember__application/index.d.ts new file mode 100644 index 0000000000..cdef372444 --- /dev/null +++ b/types/ember__application/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for @ember/application 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +export default class Application extends Ember.Application { } +export const getOwner: typeof Ember.getOwner; +export const onLoad: typeof Ember.onLoad; +export const runLoadHooks: typeof Ember.runLoadHooks; +export const setOwner: typeof Ember.setOwner; diff --git a/types/ember__application/instance.d.ts b/types/ember__application/instance.d.ts new file mode 100644 index 0000000000..0d01298d52 --- /dev/null +++ b/types/ember__application/instance.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class ApplicationInstance extends Ember.ApplicationInstance { } diff --git a/types/ember__application/resolver.d.ts b/types/ember__application/resolver.d.ts new file mode 100644 index 0000000000..a218fcd3e7 --- /dev/null +++ b/types/ember__application/resolver.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class Resolver extends Ember.Resolver { } diff --git a/types/ember__application/test/application-instance.ts b/types/ember__application/test/application-instance.ts new file mode 100644 index 0000000000..4ee5cb2027 --- /dev/null +++ b/types/ember__application/test/application-instance.ts @@ -0,0 +1,29 @@ +import ApplicationInstance from '@ember/application/instance'; +import hbs from 'htmlbars-inline-precompile'; + +const appInstance = ApplicationInstance.create(); +appInstance.register('some:injection', class Foo {}); + +appInstance.register('some:injection', class Foo {}, { + singleton: true, +}); + +appInstance.register('some:injection', class Foo {}, { + instantiate: false, +}); + +appInstance.register('templates:foo/bar', hbs`

Hello World

`); + +appInstance.register('some:injection', class Foo {}, { + singleton: false, + instantiate: true, +}); + +appInstance.factoryFor('router:main'); +appInstance.lookup('route:basic'); + +appInstance.boot(); + +(async () => { + await appInstance.boot(); +})(); diff --git a/types/ember__application/test/application.ts b/types/ember__application/test/application.ts new file mode 100755 index 0000000000..21d0237b71 --- /dev/null +++ b/types/ember__application/test/application.ts @@ -0,0 +1,41 @@ +import Application from "@ember/application"; +import EmberObject from "@ember/object"; + +const BaseApp = Application.extend({ + modulePrefix: 'my-app' +}); + +BaseApp.initializer({ + name: 'my-initializer', + initialize(app) { + app.register('foo:bar', EmberObject.extend({ foo: 'bar' })); + } +}); + +BaseApp.instanceInitializer({ + name: 'my-instance-initializer', + initialize(app) { + app.lookup('foo:bar').get('foo'); + } +}); + +const App1 = BaseApp.create({ + rootElement: '#app-one', + customEvents: { + paste: 'paste' + } +}); + +const App2 = BaseApp.create({ + rootElement: '#app-two', + customEvents: { + mouseenter: null, + mouseleave: null + } +}); + +const App3 = BaseApp.create(); + +const App3Instance1 = App3.buildInstance(); // $ExpectType ApplicationInstance + +const App3Instance2 = App3.buildInstance({ foo: 'bar' }); // $ExpectType ApplicationInstance diff --git a/types/ember__application/test/deprecations.ts b/types/ember__application/test/deprecations.ts new file mode 100644 index 0000000000..12639ad0b5 --- /dev/null +++ b/types/ember__application/test/deprecations.ts @@ -0,0 +1,14 @@ +import { deprecate, deprecateFunc } from '@ember/application/deprecations'; + +deprecate('this is no longer advised', false, { + id: 'no-longer-advised', + until: 'v4.0' +}); +deprecate('this is no longer advised', false); + +deprecateFunc('this is no longer advised', () => {}); +deprecateFunc( + 'this is no longer advised', + { id: 'no-longer-do-this', until: 'v4.0' }, + () => {} +); diff --git a/types/ember__application/test/globals-resolver.ts b/types/ember__application/test/globals-resolver.ts new file mode 100644 index 0000000000..c0efb5579b --- /dev/null +++ b/types/ember__application/test/globals-resolver.ts @@ -0,0 +1,6 @@ +import GlobalsResolver from "@ember/application/globals-resolver"; + +const gr = GlobalsResolver.create(); + +gr.resolve('App.IndexController'); +gr.resolve(); // $ExpectError diff --git a/types/ember__application/test/resolver.ts b/types/ember__application/test/resolver.ts new file mode 100644 index 0000000000..20413aa5a4 --- /dev/null +++ b/types/ember__application/test/resolver.ts @@ -0,0 +1,3 @@ +import Resolver from "@ember/application/resolver"; + +const res = Resolver.create(); diff --git a/types/ember__application/tsconfig.json b/types/ember__application/tsconfig.json new file mode 100644 index 0000000000..833859d183 --- /dev/null +++ b/types/ember__application/tsconfig.json @@ -0,0 +1,37 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/application": ["ember__application"], + "@ember/application/*": ["ember__application/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "deprecations.d.ts", + "globals-resolver.d.ts", + "index.d.ts", + "instance.d.ts", + "resolver.d.ts", + "test/application.ts", + "test/deprecations.ts", + "test/resolver.ts", + "test/globals-resolver.ts", + "test/application-instance.ts" + ] +} diff --git a/types/ember__application/tslint.json b/types/ember__application/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__application/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__array/index.d.ts b/types/ember__array/index.d.ts new file mode 100644 index 0000000000..991f7961f2 --- /dev/null +++ b/types/ember__array/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for @ember/array 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +type EmberArray = Ember.Array; +export const EmberArray: typeof Ember.Array; +export default EmberArray; +export const A: typeof Ember.A; +export const isArray: typeof Ember.isArray; diff --git a/types/ember__array/mutable.d.ts b/types/ember__array/mutable.d.ts new file mode 100644 index 0000000000..a477c92f69 --- /dev/null +++ b/types/ember__array/mutable.d.ts @@ -0,0 +1,5 @@ +import Ember from 'ember'; + +type MutableArray = Ember.MutableArray; +export const MutableArray: typeof Ember.MutableArray; +export default MutableArray; diff --git a/types/ember__array/proxy.d.ts b/types/ember__array/proxy.d.ts new file mode 100644 index 0000000000..ced7b5c14c --- /dev/null +++ b/types/ember__array/proxy.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class ArrayProxy extends Ember.ArrayProxy { } diff --git a/types/ember__array/test/array-ext.ts b/types/ember__array/test/array-ext.ts new file mode 100755 index 0000000000..72e9098100 --- /dev/null +++ b/types/ember__array/test/array-ext.ts @@ -0,0 +1,22 @@ +import { assertType } from './lib/assert'; +import EmberObject from '@ember/object'; +import { ArrayPrototypeExtensions } from '@ember/array/types/prototype-extensions'; + +declare global { + interface Array extends ArrayPrototypeExtensions {} +} + +class Person extends EmberObject { + name: string; +} + +const person = Person.create({ name: 'Joe' }); +const array = [person]; + +assertType(array.get('length')); +assertType(array.get('firstObject')); +assertType(array.mapBy('name')); +assertType(array.map(p => p.get('name'))); +assertType(array.sortBy('name')); +assertType(array.uniq()); +assertType(array.uniqBy('name')); diff --git a/types/ember__array/test/array-proxy.ts b/types/ember__array/test/array-proxy.ts new file mode 100644 index 0000000000..f4ca116e14 --- /dev/null +++ b/types/ember__array/test/array-proxy.ts @@ -0,0 +1,27 @@ +import { assertType } from './lib/assert'; +import ArrayProxy from '@ember/array/proxy'; +import { A } from '@ember/array'; + +const pets = ['dog', 'cat', 'fish']; +const proxy = ArrayProxy.create({ content: A(pets) }); + +proxy.get('firstObject'); // 'dog' +proxy.set('content', A(['amoeba', 'paramecium'])); +proxy.get('firstObject'); // 'amoeba' + +const overridden = ArrayProxy.create({ + content: A(pets), + objectAtContent(idx: number): string { + return this.get('content').objectAt(idx)!.toUpperCase(); + } +}); + +overridden.get('firstObject'); // 'DOG' + +class MyNewProxy extends ArrayProxy { + isNew = true; +} + +const x = MyNewProxy.create({ content: A([1, 2, 3]) }) as MyNewProxy; +assertType(x.get('firstObject')); +assertType(x.isNew); diff --git a/types/ember__array/test/array.ts b/types/ember__array/test/array.ts new file mode 100755 index 0000000000..5d578e4319 --- /dev/null +++ b/types/ember__array/test/array.ts @@ -0,0 +1,56 @@ +import { assertType } from './lib/assert'; +import EmberObject from '@ember/object'; +import EmberArray, { A } from '@ember/array'; +import MutableArray from '@ember/array/mutable'; + +type Person = typeof Person.prototype; +const Person = EmberObject.extend({ + name: '', + isHappy: false +}); + +const people = A([ + Person.create({ name: 'Yehuda', isHappy: true }), + Person.create({ name: 'Majd', isHappy: false }), +]); + +assertType(people.get('length')); +assertType(people.get('lastObject')); +assertType(people.get('firstObject')); +assertType(people.isAny('isHappy')); +assertType(people.isAny('isHappy', 'false')); + +const persons1: Person[] = people.filterBy('isHappy'); +const persons2: MutableArray = people.filterBy('isHappy'); +const persons3: Person[] = people.rejectBy('isHappy'); +const persons4: MutableArray = people.rejectBy('isHappy'); +const persons5: Person[] = people.filter((person) => person.get('name') === 'Yehuda'); +const persons6: MutableArray = people.filter((person) => person.get('name') === 'Yehuda'); + +assertType(people.get('[]')); +assertType(people.get('[]').get('firstObject')); // $ExpectType any + +assertType>(people.mapBy('isHappy')); // $ExpectType Array +assertType(people.mapBy('name.length')); + +const last = people.get('lastObject'); // $ExpectType ({ name: string; isHappy: boolean; } & EmberObject & { name: string; isHappy: boolean; }) | undefined +if (last) { + assertType(last.get('name')); +} + +const first = people.get('lastObject'); +if (first) { + assertType(first.get('isHappy')); +} + +const letters: EmberArray = A(['a', 'b', 'c']); +const codes: number[] = letters.map((item, index, enumerable) => { + assertType(item); + assertType(index); + return item.charCodeAt(0); +}); + +const value = '1,2,3'; +const filters = A(value.split(',')); +filters.push('4'); +filters.sort(); diff --git a/types/ember__array/test/lib/assert.ts b/types/ember__array/test/lib/assert.ts new file mode 100755 index 0000000000..262d18bc2c --- /dev/null +++ b/types/ember__array/test/lib/assert.ts @@ -0,0 +1,5 @@ +/** Static assertion that `value` has type `T` */ +// Disable tslint here b/c the generic is used to let us do a type coercion and +// validate that coercion works for the type value "passed into" the function. +// tslint:disable-next-line:no-unnecessary-generics +export declare function assertType(value: T): T; diff --git a/types/ember__array/tsconfig.json b/types/ember__array/tsconfig.json new file mode 100644 index 0000000000..e6c8d509e0 --- /dev/null +++ b/types/ember__array/tsconfig.json @@ -0,0 +1,35 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/array": ["ember__array"], + "@ember/array/*": ["ember__array/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mutable.d.ts", + "proxy.d.ts", + "types/prototype-extensions.d.ts", + "test/lib/assert.ts", + "test/array.ts", + "test/array-ext.ts", + "test/array-proxy.ts" + ] +} diff --git a/types/ember__array/tslint.json b/types/ember__array/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__array/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__array/types/prototype-extensions.d.ts b/types/ember__array/types/prototype-extensions.d.ts new file mode 100644 index 0000000000..a6197166ef --- /dev/null +++ b/types/ember__array/types/prototype-extensions.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export interface ArrayPrototypeExtensions extends Ember.MutableArray, Ember.Observable, Ember.Copyable {} diff --git a/types/ember__component/checkbox.d.ts b/types/ember__component/checkbox.d.ts new file mode 100644 index 0000000000..a71ee3602e --- /dev/null +++ b/types/ember__component/checkbox.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class Checkbox extends Ember.Checkbox { } diff --git a/types/ember__component/helper.d.ts b/types/ember__component/helper.d.ts new file mode 100644 index 0000000000..e89e6eab84 --- /dev/null +++ b/types/ember__component/helper.d.ts @@ -0,0 +1,17 @@ +import Ember from 'ember'; + +export default class Helper extends Ember.Helper { } +/** + * In many cases, the ceremony of a full `Helper` class is not required. + * The `helper` method create pure-function helpers without instances. For + * example: + * ```app/helpers/format-currency.js + * import { helper } from '@ember/component/helper'; + * export default helper(function(params, hash) { + * let cents = params[0]; + * let currency = hash.currency; + * return `${currency}${cents * 0.01}`; + * }); + * ``` + */ +export function helper(helperFn: (params: any[], hash?: any) => any): any; diff --git a/types/ember__component/index.d.ts b/types/ember__component/index.d.ts new file mode 100644 index 0000000000..147d717e2b --- /dev/null +++ b/types/ember__component/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for @ember/component 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +export default class Component extends Ember.Component { } diff --git a/types/ember__component/test/component.ts b/types/ember__component/test/component.ts new file mode 100644 index 0000000000..1d0b164647 --- /dev/null +++ b/types/ember__component/test/component.ts @@ -0,0 +1,123 @@ +import Component from '@ember/component'; +import Object, { computed, get } from '@ember/object'; +import hbs from 'htmlbars-inline-precompile'; +import { assertType } from "./lib/assert"; + +Component.extend({ + layout: hbs` +
+ {{yield}} +
+ `, +}); + +Component.extend({ + layout: 'my-layout', +}); + +const MyComponent = Component.extend(); +assertType(get(MyComponent, 'positionalParams')); + +const component1 = Component.extend({ + actions: { + hello(name: string) { + console.log('Hello', name); + }, + }, +}); + +Component.extend({ + name: '', + hello(name: string) { + this.set('name', name); + }, +}); + +Component.extend({ + tagName: 'em', +}); + +Component.extend({ + classNames: ['my-class', 'my-other-class'], +}); + +Component.extend({ + classNameBindings: ['propertyA', 'propertyB'], + propertyA: 'from-a', + propertyB: computed(function() { + if (!this.get('propertyA')) { + return 'from-b'; + } + }), +}); + +Component.extend({ + classNameBindings: ['hovered'], + hovered: true, +}); + +Component.extend({ + classNameBindings: ['messages.empty'], + messages: Object.create({ + empty: true, + }), +}); + +Component.extend({ + classNameBindings: ['isEnabled:enabled:disabled'], + isEnabled: true, +}); + +Component.extend({ + classNameBindings: ['isEnabled::disabled'], + isEnabled: true, +}); + +Component.extend({ + tagName: 'a', + attributeBindings: ['href'], + href: 'http://google.com', +}); + +Component.extend({ + tagName: 'a', + attributeBindings: ['url:href'], + url: 'http://google.com', +}); + +Component.extend({ + tagName: 'use', + attributeBindings: ['xlinkHref:xlink:href'], + xlinkHref: '#triangle', +}); + +Component.extend({ + tagName: 'input', + attributeBindings: ['disabled'], + disabled: false, +}); + +Component.extend({ + tagName: 'input', + attributeBindings: ['disabled'], + disabled: computed(() => { + if ('someLogic') { + return true; + } else { + return false; + } + }), +}); + +Component.extend({ + tagName: 'form', + attributeBindings: ['novalidate'], + novalidate: null, +}); + +Component.extend({ + click(event: object) { + // will be called when an instance's + // rendered element is clicked + }, +}); diff --git a/types/ember__component/test/helper.ts b/types/ember__component/test/helper.ts new file mode 100644 index 0000000000..bee6cc1d46 --- /dev/null +++ b/types/ember__component/test/helper.ts @@ -0,0 +1,25 @@ +import { assertType } from './lib/assert'; +import Helper, { helper } from '@ember/component/helper'; + +class Timestamp extends Helper { + timer?: ReturnType; + now = new Date(); + init() { + super.init(); + this.timer = setInterval(() => { + this.set('now', new Date()); + this.recompute(); + }, 100); + } + willDestroy() { + clearInterval(this.timer); + } +} + +const addHelper = helper(function add([a, b]: number[]) { + return a + b; +}); + +const dasherizeHelper = helper(function dasherize([str]: string[], { delim = '-'}) { + return str.split(/[\s\n\_\.]+/g).join(delim); +}); diff --git a/types/ember__component/test/lib/assert.ts b/types/ember__component/test/lib/assert.ts new file mode 100755 index 0000000000..262d18bc2c --- /dev/null +++ b/types/ember__component/test/lib/assert.ts @@ -0,0 +1,5 @@ +/** Static assertion that `value` has type `T` */ +// Disable tslint here b/c the generic is used to let us do a type coercion and +// validate that coercion works for the type value "passed into" the function. +// tslint:disable-next-line:no-unnecessary-generics +export declare function assertType(value: T): T; diff --git a/types/ember__component/text-area.d.ts b/types/ember__component/text-area.d.ts new file mode 100644 index 0000000000..859700a2d8 --- /dev/null +++ b/types/ember__component/text-area.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class TextArea extends Ember.TextArea { } diff --git a/types/ember__component/text-field.d.ts b/types/ember__component/text-field.d.ts new file mode 100644 index 0000000000..873995224b --- /dev/null +++ b/types/ember__component/text-field.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class TextField extends Ember.TextField { } diff --git a/types/ember__component/tsconfig.json b/types/ember__component/tsconfig.json new file mode 100644 index 0000000000..22181f6879 --- /dev/null +++ b/types/ember__component/tsconfig.json @@ -0,0 +1,35 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/component": ["ember__component"], + "@ember/component/*": ["ember__component/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "checkbox.d.ts", + "text-area.d.ts", + "text-field.d.ts", + "helper.d.ts", + "test/lib/assert.ts", + "test/component.ts", + "test/helper.ts" + ] +} diff --git a/types/ember__component/tslint.json b/types/ember__component/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__component/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__controller/ember__controller-tests.ts b/types/ember__controller/ember__controller-tests.ts new file mode 100644 index 0000000000..02307f447c --- /dev/null +++ b/types/ember__controller/ember__controller-tests.ts @@ -0,0 +1,11 @@ +import Controller from '@ember/controller'; + +Controller.extend ({ + queryParams: ['category'], + category: null, + isExpanded: false, + + toggleBody() { + this.toggleProperty('isExpanded'); + } +}); diff --git a/types/ember__controller/index.d.ts b/types/ember__controller/index.d.ts new file mode 100644 index 0000000000..f7505359b6 --- /dev/null +++ b/types/ember__controller/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for @ember/controller 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +export default class Controller extends Ember.Controller { } +export const inject: typeof Ember.inject.controller; + +// A type registry for Ember `Controller`s. Meant to be declaration-merged +// so string lookups resolve to the correct type. +// tslint:disable-next-line no-empty-interface +export interface Registry {} diff --git a/types/ember__controller/tsconfig.json b/types/ember__controller/tsconfig.json new file mode 100644 index 0000000000..de081123ec --- /dev/null +++ b/types/ember__controller/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/controller": ["ember__controller"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember__controller-tests.ts" + ] +} diff --git a/types/ember__controller/tslint.json b/types/ember__controller/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__controller/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__debug/container-debug-adapter.d.ts b/types/ember__debug/container-debug-adapter.d.ts new file mode 100644 index 0000000000..4bd24103a4 --- /dev/null +++ b/types/ember__debug/container-debug-adapter.d.ts @@ -0,0 +1,2 @@ +import Ember from 'ember'; +export default class ContainerDebugAdapter extends Ember.ContainerDebugAdapter { } diff --git a/types/ember__debug/data-adapter.d.ts b/types/ember__debug/data-adapter.d.ts new file mode 100644 index 0000000000..bc86573991 --- /dev/null +++ b/types/ember__debug/data-adapter.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class DataAdapter extends Ember.DataAdapter {} diff --git a/types/ember__debug/ember__debug-tests.ts b/types/ember__debug/ember__debug-tests.ts new file mode 100644 index 0000000000..0fbdcbc174 --- /dev/null +++ b/types/ember__debug/ember__debug-tests.ts @@ -0,0 +1,45 @@ +import { runInDebug, warn, debug, assert, registerWarnHandler, registerDeprecationHandler } from "@ember/debug"; + +/** + * @ember/debug tests + */ +runInDebug(); // $ExpectError +runInDebug(() => console.log('Should not show up in prod')); // $ExpectType void + +// Log a warning if we have more than 3 tomsters +const tomsterCount = 2; +warn('Too many tomsters!'); // $ExpectType void +warn('Too many tomsters!', tomsterCount <= 3); // $ExpectType void +warn('Too many tomsters!', tomsterCount <= 3, { // $ExpectType void + id: 'ember-debug.too-many-tomsters' +}); + +debug(); // $ExpectError +debug('Too many tomsters!'); // $ExpectType void +debug('Too many tomsters!', 'foo'); // $ExpectError + +// Test for truthiness +const str = 'hello'; +assert('Must pass a string', typeof str === 'string'); // $ExpectType void + +// Fail unconditionally +assert('This code path should never be run'); // $ExpectType void + +// next is not called, so no warnings get the default behavior +registerWarnHandler(); // $ExpectError +registerWarnHandler(() => {}); // $ExpectType void +registerWarnHandler((message, { id }, next) => { // $ExpectType void + message; // $ExpectType string + id; // $ExpectType string + next; // $ExpectType () => void +}); + +// next is not called, so no warnings get the default behavior +registerDeprecationHandler(); // $ExpectError +registerDeprecationHandler(() => {}); // $ExpectType void +registerDeprecationHandler((message, { id, until }, next) => { // $ExpectType void + message; // $ExpectType string + id; // $ExpectType string + until; // $ExpectType string + next; // $ExpectType () => void +}); diff --git a/types/ember__debug/index.d.ts b/types/ember__debug/index.d.ts new file mode 100644 index 0000000000..8f1352baff --- /dev/null +++ b/types/ember__debug/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for @ember/debug 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; +export const assert: typeof Ember.assert; +export const debug: typeof Ember.debug; +export const inspect: typeof Ember.inspect; +export const registerDeprecationHandler: typeof Ember.Debug.registerDeprecationHandler; +export const registerWarnHandler: typeof Ember.Debug.registerWarnHandler; +export const runInDebug: typeof Ember.runInDebug; +export const warn: typeof Ember.warn; diff --git a/types/ember__debug/tsconfig.json b/types/ember__debug/tsconfig.json new file mode 100644 index 0000000000..c7688e6861 --- /dev/null +++ b/types/ember__debug/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/debug": ["ember__debug"], + "@ember/debug/*": ["ember__debug/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "data-adapter.d.ts", + "container-debug-adapter.d.ts", + "ember__debug-tests.ts" + ] +} diff --git a/types/ember__debug/tslint.json b/types/ember__debug/tslint.json new file mode 100644 index 0000000000..1a60b8a5dd --- /dev/null +++ b/types/ember__debug/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": { } +} diff --git a/types/ember__engine/index.d.ts b/types/ember__engine/index.d.ts new file mode 100644 index 0000000000..1d86a53f39 --- /dev/null +++ b/types/ember__engine/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for @ember/engine 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +export default class Engine extends Ember.Engine { } +export const getEngineParent: typeof Ember.getEngineParent; diff --git a/types/ember__engine/instance.d.ts b/types/ember__engine/instance.d.ts new file mode 100644 index 0000000000..36e7948231 --- /dev/null +++ b/types/ember__engine/instance.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class EngineInstance extends Ember.EngineInstance { } diff --git a/types/ember__engine/test/engine-instance.ts b/types/ember__engine/test/engine-instance.ts new file mode 100644 index 0000000000..6358377639 --- /dev/null +++ b/types/ember__engine/test/engine-instance.ts @@ -0,0 +1,26 @@ +import EngineInstance from '@ember/engine/instance'; + +const engineInstance = EngineInstance.create(); +engineInstance.register('some:injection', class Foo {}); + +engineInstance.register('some:injection', class Foo {}, { + singleton: true, +}); + +engineInstance.register('some:injection', class Foo {}, { + instantiate: false, +}); + +engineInstance.register('some:injection', class Foo {}, { + singleton: false, + instantiate: true, +}); + +engineInstance.factoryFor('router:main'); +engineInstance.lookup('route:basic'); + +engineInstance.boot(); + +(async () => { + await engineInstance.boot(); +})(); diff --git a/types/ember__engine/test/engine.ts b/types/ember__engine/test/engine.ts new file mode 100755 index 0000000000..bc013d1026 --- /dev/null +++ b/types/ember__engine/test/engine.ts @@ -0,0 +1,41 @@ +import Engine from "@ember/engine"; +import EmberObject from "@ember/object"; + +const BaseEngine = Engine.extend({ + modulePrefix: 'my-engine' +}); + +BaseEngine.initializer({ + name: 'my-initializer', + initialize(engine) { + engine.register('foo:bar', EmberObject.extend({ foo: 'bar' })); + } +}); + +BaseEngine.instanceInitializer({ + name: 'my-instance-initializer', + initialize(engine) { + engine.lookup('foo:bar').get('foo'); + } +}); + +const Engine1 = BaseEngine.create({ + rootElement: '#engine-one', + customEvents: { + paste: 'paste' + } +}); + +const Engine2 = BaseEngine.create({ + rootElement: '#engine-two', + customEvents: { + mouseenter: null, + mouseleave: null + } +}); + +const Engine3 = BaseEngine.create(); + +const Engine3Instance1 = Engine3.buildInstance(); + +const Engine3Instance2 = Engine3.buildInstance({ foo: 'bar' }); diff --git a/types/ember__engine/tsconfig.json b/types/ember__engine/tsconfig.json new file mode 100644 index 0000000000..0c76748ca3 --- /dev/null +++ b/types/ember__engine/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/engine": ["ember__engine"], + "@ember/engine/*": ["ember__engine/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "instance.d.ts", + "test/engine.ts", + "test/engine-instance.ts" + ] +} diff --git a/types/ember__engine/tslint.json b/types/ember__engine/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__engine/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__polyfills/ember__polyfills-tests.ts b/types/ember__polyfills/ember__polyfills-tests.ts new file mode 100644 index 0000000000..044ed0413c --- /dev/null +++ b/types/ember__polyfills/ember__polyfills-tests.ts @@ -0,0 +1,25 @@ +import { assign, merge } from '@ember/polyfills'; + +(() => { /* assign */ + assign({}, { a: 'b'}); + assign({}, { a: 'b'}).a; // $ExpectType string + assign({ a: 6 }, { a: 'b'}).a; // $ExpectType string + assign({ a: 6 }, {}).a; // $ExpectType number + assign({ b: 6 }, {}).a; // $ExpectError + // TODO enable after https://github.com/typed-ember/ember-cli-typescript/issues/291 + // assign({}, { b: 6 }, {}).b; // $ExpectType number + assign({ a: 'hello' }, { b: 6 }, {}).a; // $ExpectType string + // TODO enable after https://github.com/typed-ember/ember-cli-typescript/issues/291 + // assign({ a: 'hello' }, { b: 6 }, { a: true }).a; // $ExpectType boolean + // TODO enable after https://github.com/typed-ember/ember-cli-typescript/issues/291 + // assign({ a: 'hello' }, '', { a: true }).a; // $ExpectError + assign({ d: ['gobias industries'] }, { a: 'hello' }, { b: 6 }, { a: true }).d; // $ExpectType string[] +})(); + +(() => { /* merge */ + merge({}, { a: 'b'}); + merge({}, { a: 'b'}).a; // $ExpectType string + merge({ a: 6 }, { a: 'b'}).a; // $ExpectType string + merge({ a: 6 }, {}).a; // $ExpectType number + merge({ b: 6 }, {}).a; // $ExpectError +})(); diff --git a/types/ember__polyfills/index.d.ts b/types/ember__polyfills/index.d.ts new file mode 100644 index 0000000000..2a3c9b4a93 --- /dev/null +++ b/types/ember__polyfills/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for @ember/polyfills 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +export const assign: typeof Ember.assign; +export const merge: typeof Ember.merge; diff --git a/types/ember__polyfills/tsconfig.json b/types/ember__polyfills/tsconfig.json new file mode 100644 index 0000000000..a2a6bd371b --- /dev/null +++ b/types/ember__polyfills/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/polyfills": ["ember__polyfills"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember__polyfills-tests.ts" + ] +} diff --git a/types/ember__polyfills/tslint.json b/types/ember__polyfills/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__polyfills/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__routing/auto-location.d.ts b/types/ember__routing/auto-location.d.ts new file mode 100644 index 0000000000..0c41a582f0 --- /dev/null +++ b/types/ember__routing/auto-location.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class AutoLocation extends Ember.AutoLocation { } diff --git a/types/ember__routing/hash-location.d.ts b/types/ember__routing/hash-location.d.ts new file mode 100644 index 0000000000..d55efdc3d8 --- /dev/null +++ b/types/ember__routing/hash-location.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class HashLocation extends Ember.HashLocation { } diff --git a/types/ember__routing/history-location.d.ts b/types/ember__routing/history-location.d.ts new file mode 100644 index 0000000000..342fe5f266 --- /dev/null +++ b/types/ember__routing/history-location.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class HistoryLocation extends Ember.HistoryLocation { } diff --git a/types/ember__routing/index.d.ts b/types/ember__routing/index.d.ts new file mode 100644 index 0000000000..76953906b1 --- /dev/null +++ b/types/ember__routing/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for @ember/routing 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export { default as Route } from '@ember/routing/route'; +export { default as Router } from '@ember/routing/router'; diff --git a/types/ember__routing/link-component.d.ts b/types/ember__routing/link-component.d.ts new file mode 100644 index 0000000000..5fbec30c21 --- /dev/null +++ b/types/ember__routing/link-component.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class LinkComponent extends Ember.LinkComponent { } diff --git a/types/ember__routing/location.d.ts b/types/ember__routing/location.d.ts new file mode 100644 index 0000000000..507c920f46 --- /dev/null +++ b/types/ember__routing/location.d.ts @@ -0,0 +1,4 @@ +import Ember from 'ember'; + +export const Location: typeof Ember.Location; +export default Location; diff --git a/types/ember__routing/none-location.d.ts b/types/ember__routing/none-location.d.ts new file mode 100644 index 0000000000..3c9d41d8ce --- /dev/null +++ b/types/ember__routing/none-location.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class NoneLocation extends Ember.NoneLocation { } diff --git a/types/ember__routing/route.d.ts b/types/ember__routing/route.d.ts new file mode 100644 index 0000000000..67209d2b66 --- /dev/null +++ b/types/ember__routing/route.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class Route extends Ember.Route { } diff --git a/types/ember__routing/router-service.d.ts b/types/ember__routing/router-service.d.ts new file mode 100644 index 0000000000..d243abc316 --- /dev/null +++ b/types/ember__routing/router-service.d.ts @@ -0,0 +1,3 @@ +import { RouterService } from 'ember'; + +export default class extends RouterService { } diff --git a/types/ember__routing/router.d.ts b/types/ember__routing/router.d.ts new file mode 100644 index 0000000000..d29fe2a21d --- /dev/null +++ b/types/ember__routing/router.d.ts @@ -0,0 +1,3 @@ +import Ember from 'ember'; + +export default class EmberRouter extends Ember.Router { } diff --git a/types/ember__routing/test/lib/assert.ts b/types/ember__routing/test/lib/assert.ts new file mode 100755 index 0000000000..262d18bc2c --- /dev/null +++ b/types/ember__routing/test/lib/assert.ts @@ -0,0 +1,5 @@ +/** Static assertion that `value` has type `T` */ +// Disable tslint here b/c the generic is used to let us do a type coercion and +// validate that coercion works for the type value "passed into" the function. +// tslint:disable-next-line:no-unnecessary-generics +export declare function assertType(value: T): T; diff --git a/types/ember__routing/test/route.ts b/types/ember__routing/test/route.ts new file mode 100755 index 0000000000..df96f585bf --- /dev/null +++ b/types/ember__routing/test/route.ts @@ -0,0 +1,112 @@ +import Route from '@ember/routing/route'; +import Array from '@ember/array'; +import Ember from 'ember'; // currently needed for Transition +import EmberObject from '@ember/object'; +import Controller from '@ember/controller'; + +class Post extends EmberObject {} + +interface Posts extends Array {} + +Route.extend({ + beforeModel(transition: Ember.Transition) { + this.transitionTo('someOtherRoute'); + }, +}); + +Route.extend({ + afterModel(posts: Posts, transition: Ember.Transition) { + if (posts.length === 1) { + this.transitionTo('post.show', posts.firstObject); + } + }, +}); + +Route.extend({ + actions: { + showModal(evt: { modalName: string }) { + this.render(evt.modalName, { + outlet: 'modal', + into: 'application', + }); + }, + hideModal(evt: { modalName: string }) { + this.disconnectOutlet({ + outlet: 'modal', + parentView: 'application', + }); + }, + }, +}); + +Ember.Route.extend({ + model() { + return this.modelFor('post'); + }, +}); + +Route.extend({ + queryParams: { + memberQp: { refreshModel: true }, + }, +}); + +Route.extend({ + renderTemplate() { + this.render('photos', { + into: 'application', + outlet: 'anOutletName', + }); + }, +}); + +Route.extend({ + renderTemplate(controller: Ember.Controller, model: {}) { + this.render('posts', { + view: 'someView', // the template to render, referenced by name + into: 'application', // the template to render into, referenced by name + outlet: 'anOutletName', // the outlet inside `options.into` to render into. + controller: 'someControllerName', // the controller to use for this template, referenced by name + model, // the model to set on `options.controller`. + }); + }, +}); + +Route.extend({ + resetController(controller: Ember.Controller, isExiting: boolean, transition: boolean) { + if (isExiting) { + // controller.set('page', 1); + } + }, +}); + +class ApplicationController extends Controller {} +declare module '@ember/controller' { + interface Registry { + application: ApplicationController; + } +} + +Route.extend({ + setupController(controller: Controller, model: {}) { + this._super(controller, model); + this.controllerFor('application').set('model', model); + }, +}); + +class RouteUsingClass extends Route.extend({ + randomProperty: 'the .extend + extends bit type-checks properly', +}) { + beforeModel(this: RouteUsingClass) { + return 'beforeModel can return anything, not just promises'; + } + intermediateTransitionWithoutModel() { + this.intermediateTransitionTo('some-route'); + } + intermediateTransitionWithModel() { + this.intermediateTransitionTo('some.other.route', { }); + } + intermediateTransitionWithMultiModel() { + this.intermediateTransitionTo('some.other.route', 1, 2, { }); + } +} diff --git a/types/ember__routing/test/router.ts b/types/ember__routing/test/router.ts new file mode 100755 index 0000000000..760e9ed5bc --- /dev/null +++ b/types/ember__routing/test/router.ts @@ -0,0 +1,54 @@ +import Ember from 'ember'; +import { assertType } from './lib/assert'; + +const AppRouter = Ember.Router.extend({ +}); + +AppRouter.map(function() { + this.route('index', { path: '/' }); + this.route('about'); + this.route('favorites', { path: '/favs' }); + this.route('posts', function() { + this.route('index', { path: '/' }); + this.route('new'); + this.route('post', { path: '/post/:post_id', resetNamespace: true }); + this.route('comments', { resetNamespace: true }, function() { + this.route('new'); + }); + }); + this.route('photo', { path: '/photo/:id' }, function() { + this.route('comment', { path: '/comment/:id' }); + }); + this.route('not-found', { path: '/*path' }); + this.mount('my-engine'); + this.mount('my-engine', { as: 'some-other-engine', path: '/some-other-engine'}); +}); + +const RouterServiceConsumer = Ember.Service.extend({ + router: Ember.inject.service('router'), + currentRouteName() { + const x: string = Ember.get(this, 'router').currentRouteName; + }, + currentURL() { + const x: string = Ember.get(this, 'router').currentURL; + }, + transitionWithoutModel() { + Ember.get(this, 'router') + .transitionTo('some-route'); + }, + transitionWithModel() { + const model = Ember.Object.create(); + Ember.get(this, 'router') + .transitionTo('some.other.route', model); + }, + transitionWithMultiModel() { + const model = Ember.Object.create(); + Ember.get(this, 'router') + .transitionTo('some.other.route', model, model); + }, + transitionWithModelAndOptions() { + const model = Ember.Object.create(); + Ember.get(this, 'router') + .transitionTo('index', model, { queryParams: { search: 'ember' }}); + } +}); diff --git a/types/ember__routing/tsconfig.json b/types/ember__routing/tsconfig.json new file mode 100644 index 0000000000..4bd4d95832 --- /dev/null +++ b/types/ember__routing/tsconfig.json @@ -0,0 +1,40 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/routing": ["ember__routing"], + "@ember/routing/*": ["ember__routing/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "auto-location.d.ts", + "hash-location.d.ts", + "history-location.d.ts", + "index.d.ts", + "link-component.d.ts", + "location.d.ts", + "none-location.d.ts", + "route.d.ts", + "router-service.d.ts", + "router.d.ts", + "test/lib/assert.ts", + "test/route.ts", + "test/router.ts" + ] +} diff --git a/types/ember__routing/tslint.json b/types/ember__routing/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__routing/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__service/ember__service-tests.ts b/types/ember__service/ember__service-tests.ts new file mode 100644 index 0000000000..ee2e39823c --- /dev/null +++ b/types/ember__service/ember__service-tests.ts @@ -0,0 +1,38 @@ +import Service, { inject } from "@ember/service"; +import EmberObject from "@ember/object"; + +class FirstSvc extends Service { + foo = 'bar'; + first() { return ''; } +} +const SecondSvc = Service.extend({ + foo: 'bar', + second() { return ''; } +}); + +class ThirdSvc extends Service.extend({ + foo: 'bar', + third() { return ''; } +}) { } + +declare module '@ember/service' { + interface Registry { + first: FirstSvc; + second: InstanceType; + third: ThirdSvc; + } +} + +const ServiceTriplet = EmberObject.extend({ + sFirst: inject('first'), + sSecond: inject('second'), + sThird: inject('third'), + unknownService: inject() +}); + +const obj = ServiceTriplet.create(); + +obj.get('sFirst'); // $ExpectType FirstSvc +obj.get('sSecond').second(); // $ExpectType "" +obj.get('sThird'); // $ExpectType ThirdSvc +obj.get('unknownService'); // $ExpectType Service diff --git a/types/ember__service/index.d.ts b/types/ember__service/index.d.ts new file mode 100644 index 0000000000..fa5d687441 --- /dev/null +++ b/types/ember__service/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for @ember/service 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +export default class Service extends Ember.Service { } +export const inject: typeof Ember.inject.service; + +// A type registry for Ember `Service`s. Meant to be declaration-merged so +// string lookups resolve to the correct type. +// tslint:disable-next-line no-empty-interface strict-export-declare-modifiers +interface Registry {} diff --git a/types/ember__service/tsconfig.json b/types/ember__service/tsconfig.json new file mode 100644 index 0000000000..9f0a8a04c2 --- /dev/null +++ b/types/ember__service/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/service": ["ember__service"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember__service-tests.ts" + ] +} diff --git a/types/ember__service/tslint.json b/types/ember__service/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/ember__service/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/ember__test-helpers/index.d.ts b/types/ember__test-helpers/index.d.ts index 067222b425..bd7720e3b1 100644 --- a/types/ember__test-helpers/index.d.ts +++ b/types/ember__test-helpers/index.d.ts @@ -2,8 +2,9 @@ // Project: https://github.com/emberjs/ember-test-helpers // Definitions by: Dan Freeman // James C. Davis +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/ember__utils/ember__utils-tests.ts b/types/ember__utils/ember__utils-tests.ts new file mode 100644 index 0000000000..8b270f1bec --- /dev/null +++ b/types/ember__utils/ember__utils-tests.ts @@ -0,0 +1,171 @@ +import { + compare, + isBlank, + isEmpty, + isEqual, + isNone, + isPresent, + tryInvoke, + typeOf +} from '@ember/utils'; +import EmberObject from '@ember/object'; + +(function() { + /** isNone */ + const maybeUndefined: string | undefined = 'not actually undefined'; + if (isNone(maybeUndefined)) { + return; + } + const anotherString = maybeUndefined + 'another string'; + // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/256 + // isNone(); // $ExpectType boolean + isNone(null); // $ExpectType boolean + isNone(undefined); // $ExpectType boolean + isNone(''); // $ExpectType boolean + isNone([]); // $ExpectType boolean + isNone(function() {}); // $ExpectType boolean +})(); + +(function() { + /** tryInvoke */ + let d = new Date('03/15/2013'); + + // TODO fix enhance in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/257 + // tryInvoke(d, 'getTime'); // $ExpectType number + // tryInvoke(d, 'setFullYear', [2014]); // $ExpectType number + // tryInvoke(d, 'noSuchMethod', [2014]); // $ExpectType undefined + tryInvoke(d, 'getTime'); + tryInvoke(d, 'setFullYear', [2014]); + tryInvoke(d, 'noSuchMethod', [2014]); +})(); + +(function() { + /** isPresent */ + // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/258 + // isPresent(); // $ExpectType boolean + isPresent(null); // $ExpectType boolean + isPresent(undefined); // $ExpectType boolean + isPresent(''); // $ExpectType boolean + isPresent(' '); // $ExpectType boolean + isPresent('\n\t'); // $ExpectType boolean + isPresent([]); // $ExpectType boolean + isPresent({ length: 0 }); // $ExpectType boolean + isPresent(false); // $ExpectType boolean + isPresent(true); // $ExpectType boolean + isPresent('string'); // $ExpectType boolean + isPresent(0); // $ExpectType boolean + isPresent(function() {}); // $ExpectType boolean + isPresent({}); // $ExpectType boolean + isPresent(false); // $ExpectType boolean + isPresent('\n\t Hello'); // $ExpectType boolean + isPresent([1, 2, 3]); // $ExpectType boolean +})(); + +(function() { + /** typeOf */ + // TODO: more specific return type in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/259 + // typeOf(null); // $ExpectType 'null' + // typeOf(undefined); // $ExpectType 'undefined' + // typeOf('michael'); // $ExpectType 'string' + // // tslint:disable-next-line:no-construct + // typeOf(new String('michael')); // $ExpectType 'string' + // typeOf(101); // $ExpectType 'number' + // // tslint:disable-next-line:no-construct + // typeOf(new Number(101)); // $ExpectType 'number' + // typeOf(true); // $ExpectType 'boolean' + // // tslint:disable-next-line:no-construct + // typeOf(new Boolean(true)); // $ExpectType 'boolean' + // typeOf(() => 4); // $ExpectType 'function' + // typeOf([1, 2, 90]); // $ExpectType 'array' + // typeOf(/abc/); // $ExpectType 'regexp' + // typeOf(new Date()); // $ExpectType 'date' + // typeOf(FileList); // $ExpectType 'filelist' + // // typeOf(EmberObject.extend()); // $ExpectType 'class' + // // typeOf(EmberObject.create()); // $ExpectType 'instance' + // typeOf(new Error('teamocil')); // $ExpectType 'error' + + // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/260 + // typeOf(); + typeOf(null); + typeOf(undefined); + typeOf('michael'); + // tslint:disable-next-line:no-construct + typeOf(new String('michael')); + typeOf(101); + // tslint:disable-next-line:no-construct + typeOf(new Number(101)); + typeOf(true); + // tslint:disable-next-line:no-construct + typeOf(new Boolean(true)); + typeOf(() => 4); + typeOf([1, 2, 90]); + typeOf(/abc/); + typeOf(new Date()); + typeOf(FileList); + typeOf(new Error('teamocil')); +})(); + +(function() { + /** isEqual */ + isEqual('foo', 'bar'); // $ExpectType boolean + isEqual(14, 37); // $ExpectType boolean + isEqual(14, '1'); // $ExpectType boolean + isEqual(() => 4, () => 37); // $ExpectType boolean + isEqual(14); // $ExpectError + isEqual(); // $ExpectError +})(); + +(function() { + /** compare */ + compare('foo', 'bar'); // $ExpectType number + compare(14, 37); // $ExpectType number + compare(class {}, class {}); // $ExpectType number + compare([], class {}); // $ExpectType number + compare([], undefined); // $ExpectType number + compare({}, () => 4); // $ExpectType number + compare(14); // $ExpectError + compare(); // $ExpectError +})(); + +(function() { + /** isBlank */ + + // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/254 + // isBlank(); // $ExpectType boolean + isBlank(null); // $ExpectType boolean + isBlank(undefined); // $ExpectType boolean + isBlank(''); // $ExpectType boolean + isBlank([]); // $ExpectType boolean + isBlank('\n\t'); // $ExpectType boolean + isBlank(' '); // $ExpectType boolean + isBlank({}); // $ExpectType boolean + isBlank('\n\t Hello'); // $ExpectType boolean + isBlank('Hello world'); // $ExpectType boolean + isBlank([1, 2, 3]); // $ExpectType boolean +})(); + +(function() { + /** isEmpty */ + + // TODO fix upstream in @types/ember https://github.com/typed-ember/ember-cli-typescript/issues/255 + // isEmpty(); // $ExpectType boolean + isEmpty(null); // $ExpectType boolean + isEmpty(undefined); // $ExpectType boolean + isEmpty(''); // $ExpectType boolean + isEmpty([]); // $ExpectType boolean + isEmpty({ size: 0 }); // $ExpectType boolean + isEmpty({}); // $ExpectType boolean + isEmpty('Adam Hawkins'); // $ExpectType boolean + isEmpty([0, 1, 2]); // $ExpectType boolean + isEmpty('\n\t'); // $ExpectType boolean + isEmpty(' '); // $ExpectType boolean + isEmpty({ size: 1 }); // $ExpectType boolean + isEmpty({ size: () => 0 }); // $ExpectType boolean +})(); + +class Foo extends EmberObject.extend({ + abc: true, + bar() { return '123'; } +}) { + def: 'hello'; +} diff --git a/types/ember__utils/index.d.ts b/types/ember__utils/index.d.ts new file mode 100644 index 0000000000..89a9a6cd96 --- /dev/null +++ b/types/ember__utils/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for @ember/utils 3.0 +// Project: http://emberjs.com/ +// Definitions by: Mike North +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import Ember from 'ember'; + +export const compare: typeof Ember.compare; +export const isBlank: typeof Ember.isBlank; +export const isEmpty: typeof Ember.isEmpty; +export const isEqual: typeof Ember.isEqual; +export const isNone: typeof Ember.isNone; +export const isPresent: typeof Ember.isPresent; +export const tryInvoke: typeof Ember.tryInvoke; +export const typeOf: typeof Ember.typeOf; diff --git a/types/ember__utils/tsconfig.json b/types/ember__utils/tsconfig.json new file mode 100644 index 0000000000..559e22e847 --- /dev/null +++ b/types/ember__utils/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@ember/utils": ["ember__utils"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ember__utils-tests.ts" + ] +} diff --git a/types/ember__utils/tslint.json b/types/ember__utils/tslint.json new file mode 100644 index 0000000000..f77f8d2ed8 --- /dev/null +++ b/types/ember__utils/tslint.json @@ -0,0 +1,30 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // Heavy use of Function type in this older package. + "ban-types": false, + "jsdoc-format": false, + "no-misused-new": false, + + // these are disabled because of rfc176 module exports + "strict-export-declare-modifiers": false, + "no-single-declare-module": false, + "no-declare-current-package": false, + "no-self-import": false, + + // We use interfaces in a number of places to express things (including + // mixins in particular, but also including extending a global + // interface) which TS currently can't express correctly. + "no-empty-interface": false, + + "no-duplicate-imports": false, + "no-unnecessary-qualifier": false, + "prefer-const": false, + "no-void-expression": false, + "only-arrow-functions": false, + "no-submodule-imports": false, + + // false positives + "unified-signatures": false + } +} diff --git a/types/env-paths/env-paths-tests.ts b/types/env-paths/env-paths-tests.ts index b143fb47b5..9f360bbe41 100644 --- a/types/env-paths/env-paths-tests.ts +++ b/types/env-paths/env-paths-tests.ts @@ -2,3 +2,9 @@ import envPaths = require('env-paths'); // $ExpectType Paths envPaths('./'); +// $ExpectType Paths +envPaths('./', {suffix: 'test'}); +// $ExpectType Paths +envPaths('./', {suffix: false}); +// $ExpectType Paths +envPaths('./', {suffix: true}); diff --git a/types/env-paths/index.d.ts b/types/env-paths/index.d.ts index c759f3875c..8b594d8a61 100644 --- a/types/env-paths/index.d.ts +++ b/types/env-paths/index.d.ts @@ -5,7 +5,7 @@ export = envPaths; -declare function envPaths(name: string, opts?: { suffix: string; }): envPaths.Paths; +declare function envPaths(name: string, opts?: { suffix: string | boolean }): envPaths.Paths; declare namespace envPaths { interface Paths { diff --git a/types/expect-puppeteer/expect-puppeteer-tests.ts b/types/expect-puppeteer/expect-puppeteer-tests.ts index 4c646da1d9..dc8c37365c 100644 --- a/types/expect-puppeteer/expect-puppeteer-tests.ts +++ b/types/expect-puppeteer/expect-puppeteer-tests.ts @@ -23,6 +23,9 @@ const testGlobal = async (instance: ElementHandle | Page) => { await expect(instance).toUploadFile("selector", "filePath"); await expect(instance).toUploadFile("selector", "filePath", { timeout: 777 }); + + await expect(instance).toFillForm("selector", { foo: 'bar', baz: 123 }); + await expect(instance).toFillForm("selector", { foo: 'bar', baz: 123 }, { timeout: 777 }); }; const testImported = async (instance: ElementHandle | Page) => { diff --git a/types/expect-puppeteer/index.d.ts b/types/expect-puppeteer/index.d.ts index 7c216f4259..b77bc948bd 100644 --- a/types/expect-puppeteer/index.d.ts +++ b/types/expect-puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for expect-puppeteer 2.2 +// Type definitions for expect-puppeteer 3.3 // Project: https://github.com/smooth-code/jest-puppeteer/tree/master/packages/expect-puppeteer // Definitions by: Josh Goldberg // Tanguy Krotoff @@ -57,6 +57,7 @@ declare global { toClick(selector: string, options?: ExpectToClickOptions): Promise; toDisplayDialog(block: () => Promise): Promise; toFill(selector: string, value: string, options?: ExpectTimingActions): Promise; + toFillForm(selector: string, value: { [key: string]: any}, options?: ExpectTimingActions): Promise; toMatch(selector: string, options?: ExpectTimingActions): Promise; toMatchElement(selector: string, options?: ExpectToClickOptions): Promise; toSelect(selector: string, valueOrText: string, options?: ExpectTimingActions): Promise; diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 0098a14489..ac1c6e3452 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -287,6 +287,30 @@ Camera.Constants.BarCodeType; } }} />); }; +async (camera: CameraObject) => { + const picture = await camera.takePictureAsync({ + quality: 0.5, + base64: true, + exif: true + }); + + picture.uri; + picture.width; + picture.height; + picture.exif; + picture.base64; + + camera.takePictureAsync({ + quality: 1, + onPictureSaved: pic => { + pic.uri; + pic.width; + pic.height; + pic.exif; + pic.base64; + } + }); +}; async () => { const result = await DocumentPicker.getDocumentAsync(); diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 868afd5e56..1376dea57c 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -769,6 +769,9 @@ export namespace Brightness { */ export interface PictureOptions { quality?: number; + base64?: boolean; + exif?: boolean; + onPictureSaved?: (data: PictureResponse) => void; } export interface PictureResponse { diff --git a/types/express-session/express-session-tests.ts b/types/express-session/express-session-tests.ts index 9189db1dfb..dc52a31a73 100644 --- a/types/express-session/express-session-tests.ts +++ b/types/express-session/express-session-tests.ts @@ -54,7 +54,7 @@ class MyStore extends session.Store { callback(null, sessionData); } - set = (sid: string, session: Express.Session, callback?: (err?: any) => void): void => { + set = (sid: string, session: Express.SessionData, callback?: (err?: any) => void): void => { this.sessions[sid] = JSON.stringify(session); if (callback) callback(); } diff --git a/types/express-session/index.d.ts b/types/express-session/index.d.ts index fdceafeeea..d26fbb6af8 100644 --- a/types/express-session/index.d.ts +++ b/types/express-session/index.d.ts @@ -79,26 +79,26 @@ declare namespace session { constructor(config?: any); regenerate: (req: express.Request, fn: (err?: any) => any) => void; - load: (sid: string, fn: (err: any, session?: Express.Session | null) => any) => void; + load: (sid: string, fn: (err: any, session?: Express.SessionData | null) => any) => void; createSession: (req: express.Request, sess: Express.SessionData) => void; get: (sid: string, callback: (err: any, session?: Express.SessionData | null) => void) => void; - set: (sid: string, session: Express.Session, callback?: (err?: any) => void) => void; + set: (sid: string, session: Express.SessionData, callback?: (err?: any) => void) => void; destroy: (sid: string, callback?: (err?: any) => void) => void; all: (callback: (err: any, obj?: { [sid: string]: Express.SessionData; } | null) => void) => void; length: (callback: (err: any, length?: number | null) => void) => void; clear: (callback?: (err?: any) => void) => void; - touch: (sid: string, session: Express.Session, callback?: (err?: any) => void) => void; + touch: (sid: string, session: Express.SessionData, callback?: (err?: any) => void) => void; } class MemoryStore implements BaseMemoryStore { get: (sid: string, callback: (err: any, session?: Express.SessionData | null) => void) => void; - set: (sid: string, session: Express.Session, callback?: (err?: any) => void) => void; + set: (sid: string, session: Express.SessionData, callback?: (err?: any) => void) => void; destroy: (sid: string, callback?: (err?: any) => void) => void; - all: (callback: (err: any, obj?: { [sid: string]: Express.Session; } | null) => void) => void; + all: (callback: (err: any, obj?: { [sid: string]: Express.SessionData; } | null) => void) => void; length: (callback: (err: any, length?: number | null) => void) => void; clear: (callback?: (err?: any) => void) => void; - touch: (sid: string, session: Express.Session, callback?: (err?: any) => void) => void; + touch: (sid: string, session: Express.SessionData, callback?: (err?: any) => void) => void; } } diff --git a/types/express-winston/express-winston-tests.ts b/types/express-winston/express-winston-tests.ts index 57b93c14f8..f370abdb5d 100644 --- a/types/express-winston/express-winston-tests.ts +++ b/types/express-winston/express-winston-tests.ts @@ -34,9 +34,11 @@ app.use(expressWinston.logger({ ], })); +const logger = winston.createLogger(); + // Logger with minimum options (winstonInstance) app.use(expressWinston.logger({ - winstonInstance: winston, + winstonInstance: logger, })); // Error Logger with all options @@ -62,7 +64,7 @@ app.use(expressWinston.errorLogger({ // Error Logger with min options (winstonInstance) app.use(expressWinston.errorLogger({ - winstonInstance: winston, + winstonInstance: logger, })); expressWinston.bodyBlacklist.push('potato'); diff --git a/types/express-winston/index.d.ts b/types/express-winston/index.d.ts index a691000dd8..462f3df1b3 100644 --- a/types/express-winston/index.d.ts +++ b/types/express-winston/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for express-winston 2.4 +// Type definitions for express-winston 3.0 // Project: https://github.com/bithavoc/express-winston#readme // Definitions by: Alex Brick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -44,7 +44,7 @@ export interface LoggerOptionsWithTransports extends BaseLoggerOptions { } export interface LoggerOptionsWithWinstonInstance extends BaseLoggerOptions { - winstonInstance: typeof winston; + winstonInstance: winston.Logger; } export type LoggerOptions = LoggerOptionsWithTransports | LoggerOptionsWithWinstonInstance; @@ -66,7 +66,7 @@ export interface ErrorLoggerOptionsWithTransports extends BaseErrorLoggerOptions } export interface ErrorLoggerOptionsWithWinstonInstance extends BaseErrorLoggerOptions { - winstonInstance: typeof winston; + winstonInstance: winston.Logger; } export type ErrorLoggerOptions = ErrorLoggerOptionsWithTransports | ErrorLoggerOptionsWithWinstonInstance; diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 783a4f41f7..6749f6b47c 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -3081,8 +3081,27 @@ interface ITextOptions extends IObjectOptions { fontFamily?: string; /** * Text decoration Possible values?: "", "underline", "overline" or "line-through". + * Feels like this has been deprecated in favor of underline, overline, linethrough props */ textDecoration?: string; + /** + * Text decoration underline. + * @type Boolean + * @default + */ + underline?: boolean; + /** + * Text decoration overline. + * @type Boolean + * @default + */ + overline?: boolean; + /** + * Text decoration linethrough. + * @type Boolean + * @default + */ + linethrough?: boolean; /** * Text alignment. Possible values?: "left", "center", or "right". */ @@ -3190,6 +3209,33 @@ export class Text extends Object { * @param textDecoration Text decoration */ setTextDecoration(textDecoration: string): Text; + /** + * Retrieves object's underline + */ + getUnderline(): boolean; + /** + * Sets object's underline + * @param underline Text underline + */ + setUnderline(underline: boolean): Text; + /** + * Retrieves object's overline + */ + getOverline(): boolean; + /** + * Sets object's overline + * @param overline Text overline + */ + setOverline(overline: boolean): Text; + /** + * Retrieves object's linethrough + */ + getLinethrough(): boolean; + /** + * Sets object's linethrough + * @param linethrough Text linethrough + */ + setLinethrough(linethrough: boolean): Text; /** * Retrieves object's fontStyle */ @@ -3311,6 +3357,52 @@ interface IITextOptions extends IObjectOptions, ITextOptions { */ caching?: boolean; } +export interface Textbox extends IText {} +export class Textbox extends IText { + /** + * Constructor + * @param text Text string + * @param [options] Options object + */ + constructor(text: string, options?: IITextOptions); + /** + * Detect if the text line is ended with an hard break + * text and itext do not have wrapping, return false + * @param {Number} lineIndex text to split + * @return {Boolean} + */ + isEndOfWrapping(lineIndex: number): boolean; + /** + * Get minimum width of text box + * @return {Number} + */ + getMinWidth(): number; + /** + * Selects entire text + * @return {fabric.Text} thisArg + * @chainable + */ + selectAll(): Textbox; + /** + * Selects a line based on the index + * @param {Number} selectionStart Index of a character + * @return {fabric.IText} thisArg + * @chainable + */ + selectLine(selectionStart: number): Textbox; + /** + * Enters editing state + * @return {fabric.Textbox} thisArg + * @chainable + */ + enterEditing(): Textbox; + /** + * Exits from editing state + * @return {fabric.Textbox} thisArg + * @chainable + */ + exitEditing(): Textbox; +} export interface IText extends Text, IITextOptions { } export class IText extends Object { /** @@ -3320,9 +3412,10 @@ export class IText extends Object { */ constructor(text: string, options?: IITextOptions); /** - * Returns true if object has no styling + * Returns true if object has no styling or no styling in a line + * @param {Number} lineIndex , lineIndex is on wrapped lines. */ - isEmptyStyles(): boolean; + isEmptyStyles(lineIndex: number): boolean; render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; /** * Returns object representation of an instance diff --git a/types/fabric/index.d.ts b/types/fabric/index.d.ts index 76ed1ab054..e8d31aef56 100644 --- a/types/fabric/index.d.ts +++ b/types/fabric/index.d.ts @@ -6,6 +6,7 @@ // Tiger Oakes // Brian Martinson // Rogerio Teixeira +// Bradley Hill // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 export import fabric = require("./fabric-impl"); diff --git a/types/faker/index.d.ts b/types/faker/index.d.ts index 248a0ba96c..a9d044cfcb 100644 --- a/types/faker/index.d.ts +++ b/types/faker/index.d.ts @@ -201,8 +201,8 @@ declare namespace Faker { }; system: { - fileName(ext: string, type: string): string; - commonFileName(ext: string, type: string): string; + fileName(ext?: string, type?: string): string; + commonFileName(ext: string, type?: string): string; mimeType(): string; commonFileType(): string; commonFileExt(): string; diff --git a/types/feathersjs__feathers/feathersjs__feathers-tests.ts b/types/feathersjs__feathers/feathersjs__feathers-tests.ts index a624187c68..7d0e961700 100644 --- a/types/feathersjs__feathers/feathersjs__feathers-tests.ts +++ b/types/feathersjs__feathers/feathersjs__feathers-tests.ts @@ -1,4 +1,4 @@ -import feathers, { Application } from '@feathersjs/feathers'; +import feathers, { Application, HookContext } from '@feathersjs/feathers'; interface User { id: number; @@ -14,3 +14,12 @@ const app = feathers() as Application; app.service('users').get(0).then(u => { const user: User = u; }); + +app.service('users').hooks({ + before: { + all: (context: HookContext) => { + context.statusCode = 200; + context.dispatch = { test: 'true' }; + } + } +}); diff --git a/types/feathersjs__feathers/index.d.ts b/types/feathersjs__feathers/index.d.ts index 1e448dbf4f..53cdf182a1 100644 --- a/types/feathersjs__feathers/index.d.ts +++ b/types/feathersjs__feathers/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for @feathersjs/feathers 3.0 // Project: http://feathersjs.com/ -// Definitions by: Jan Lohage , Abraao Alves +// Definitions by: Jan Lohage +// Abraao Alves +// Tim Mensch // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript // TypeScript Version: 2.3 @@ -51,16 +53,71 @@ export type Hook = (hook: HookContext) => (Promise { - app?: Application; + /** + * A read only property that contains the Feathers application object. This can be used to + * retrieve other services (via context.app.service('name')) or configuration values. + */ + readonly app: Application; + /** + * A writeable property containing the data of a create, update and patch service + * method call. + */ data?: T; + /** + * A writeable property with the error object that was thrown in a failed method call. + * It is only available in error hooks. + */ error?: any; + /** + * A writeable property and the id for a get, remove, update and patch service + * method call. For remove, update and patch context.id can also be null when + * modifying multiple entries. In all other cases it will be undefined. + */ id?: string | number; - method?: string; - params?: Params; - path?: string; + /** + * A read only property with the name of the service method (one of find, get, + * create, update, patch, remove). + */ + readonly method: string; + /** + * A writeable property that contains the service method parameters (including + * params.query). + */ + params: Params; + /** + * A read only property and contains the service name (or path) without leading or + * trailing slashes. + */ + readonly path: string; + /** + * A writeable property containing the result of the successful service method call. + * It is only available in after hooks. + * + * `context.result` can also be set in + * + * - A before hook to skip the actual service method (database) call + * - An error hook to swallow the error and return a result instead + */ result?: T; - service: Service; - type: 'before' | 'after' | 'error'; + /** + * A read only property and contains the service this hook currently runs on. + */ + readonly service: Service; + /** + * A writeable, optional property and contains a "safe" version of the data that + * should be sent to any client. If context.dispatch has not been set context.result + * will be sent to the client instead. + */ + dispatch?: T; + /** + * A writeable, optional property that allows to override the standard HTTP status + * code that should be returned. + */ + statusCode?: number; + /** + * A read only property with the hook type (one of before, after or error). + */ + readonly type: "before" | "after" | "error"; } export interface HookMap { diff --git a/types/feathersjs__feathers/tslint.json b/types/feathersjs__feathers/tslint.json index f93cf8562a..702f9354fc 100644 --- a/types/feathersjs__feathers/tslint.json +++ b/types/feathersjs__feathers/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "file-name-casing": false + } } diff --git a/types/firefox-webext-browser/firefox-webext-browser-tests.ts b/types/firefox-webext-browser/firefox-webext-browser-tests.ts index 53f3b5a928..a2d9f0bda0 100644 --- a/types/firefox-webext-browser/firefox-webext-browser-tests.ts +++ b/types/firefox-webext-browser/firefox-webext-browser-tests.ts @@ -5,7 +5,7 @@ browser.nonexistentNS.unknownMethod(); // $ExpectError browser.runtime.getManifest(); // $ExpectType WebExtensionManifest browser.test; // $ExpectError browser.manifest; // $ExpectError -browser._manifest; // $ExpectType typeof _manifest +browser._manifest; // $ExpectError browser._manifest.WebExtensionLangpackManifest; // $ExpectError browser._manifest.NativeManifest; // $ExpectError diff --git a/types/firefox-webext-browser/index.d.ts b/types/firefox-webext-browser/index.d.ts index 1ce4024f4d..47035f4f87 100644 --- a/types/firefox-webext-browser/index.d.ts +++ b/types/firefox-webext-browser/index.d.ts @@ -2,7 +2,7 @@ // Project: https://developer.mozilla.org/en-US/Add-ons/WebExtensions // Definitions by: Jacob Bom // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.9 // Generated using script at github.com/bomjacob/definitelytyped-firefox-webext-browser interface WebExtEventBase any, TCallback> { @@ -434,114 +434,102 @@ declare namespace browser._manifest { type KeyName = string; - enum _OptionalPermission { - browserSettings = "browserSettings", - cookies = "cookies", - clipboardRead = "clipboardRead", - clipboardWrite = "clipboardWrite", - geolocation = "geolocation", - idle = "idle", - notifications = "notifications", - topSites = "topSites", - webNavigation = "webNavigation", - webRequest = "webRequest", - webRequestBlocking = "webRequestBlocking", - bookmarks = "bookmarks", - find = "find", - history = "history", - activeTab = "activeTab", - tabs = "tabs" - } + type _OptionalPermission = + "browserSettings" + | "cookies" + | "clipboardRead" + | "clipboardWrite" + | "geolocation" + | "idle" + | "notifications" + | "topSites" + | "webNavigation" + | "webRequest" + | "webRequestBlocking" + | "bookmarks" + | "find" + | "history" + | "activeTab" + | "tabs"; - enum _Permission { - contextualIdentities = "contextualIdentities", - downloads = "downloads", - downloadsopen = "downloads.open", - identity = "identity", - management = "management", - alarms = "alarms", - mozillaAddons = "mozillaAddons", - storage = "storage", - unlimitedStorage = "unlimitedStorage", - privacy = "privacy", - proxy = "proxy", - nativeMessaging = "nativeMessaging", - theme = "theme", - browsingData = "browsingData", - devtools = "devtools", - geckoProfiler = "geckoProfiler", - menus = "menus", - contextMenus = "contextMenus", - pkcs11 = "pkcs11", - sessions = "sessions" - } + type _Permission = + "contextualIdentities" + | "downloads" + | "downloads.open" + | "identity" + | "management" + | "alarms" + | "mozillaAddons" + | "storage" + | "unlimitedStorage" + | "privacy" + | "proxy" + | "nativeMessaging" + | "theme" + | "browsingData" + | "devtools" + | "geckoProfiler" + | "menus" + | "contextMenus" + | "pkcs11" + | "sessions"; - enum _ProtocolHandlerProtocol { - bitcoin = "bitcoin", - geo = "geo", - gopher = "gopher", - im = "im", - irc = "irc", - ircs = "ircs", - magnet = "magnet", - mailto = "mailto", - mms = "mms", - news = "news", - nntp = "nntp", - sip = "sip", - sms = "sms", - smsto = "smsto", - ssh = "ssh", - tel = "tel", - urn = "urn", - webcal = "webcal", - wtai = "wtai", - xmpp = "xmpp" - } + type _ProtocolHandlerProtocol = + "bitcoin" + | "geo" + | "gopher" + | "im" + | "irc" + | "ircs" + | "magnet" + | "mailto" + | "mms" + | "news" + | "nntp" + | "sip" + | "sms" + | "smsto" + | "ssh" + | "tel" + | "urn" + | "webcal" + | "wtai" + | "xmpp"; - enum _WebExtensionManifestIncognito { - spanning = "spanning" - } + type _WebExtensionManifestIncognito = "spanning"; /** Defines the location the browserAction will appear by default. The default location is navbar. */ - enum _WebExtensionManifestBrowserActionDefaultArea { - navbar = "navbar", - menupanel = "menupanel", - tabstrip = "tabstrip", - personaltoolbar = "personaltoolbar" - } + type _WebExtensionManifestBrowserActionDefaultArea = + "navbar" + | "menupanel" + | "tabstrip" + | "personaltoolbar"; - enum _MatchPattern { - all_urls = "" - } + type _MatchPattern = ""; - enum _MatchPatternInternal { - all_urls = "" - } + type _MatchPatternInternal = ""; - enum _ThemeTypeAdditionalBackgroundsAlignment { - bottom = "bottom", - center = "center", - left = "left", - right = "right", - top = "top", - centerbottom = "center bottom", - centercenter = "center center", - centertop = "center top", - leftbottom = "left bottom", - leftcenter = "left center", - lefttop = "left top", - rightbottom = "right bottom", - rightcenter = "right center", - righttop = "right top" - } + type _ThemeTypeAdditionalBackgroundsAlignment = + "bottom" + | "center" + | "left" + | "right" + | "top" + | "center bottom" + | "center center" + | "center top" + | "left bottom" + | "left center" + | "left top" + | "right bottom" + | "right center" + | "right top"; - enum _ThemeTypeAdditionalBackgroundsTiling { - norepeat = "no-repeat", - repeat = "repeat", - repeatx = "repeat-x", - repeaty = "repeat-y" - } + type _ThemeTypeAdditionalBackgroundsTiling = + "no-repeat" + | "repeat" + | "repeat-x" + | "repeat-y"; } /** @@ -555,11 +543,10 @@ declare namespace browser.browserSettings { /* browserSettings types */ /** How images should be animated in the browser. */ - enum ImageAnimationBehavior { - normal = "normal", - none = "none", - once = "once" - } + type ImageAnimationBehavior = + "normal" + | "none" + | "once"; /* browserSettings properties */ /** Allows or disallows pop-up windows from opening in response to user events. */ @@ -596,10 +583,7 @@ declare namespace browser.clipboard { type ArrayBuffer = any; /** The type of imageData. */ - enum _SetImageData { - jpeg = "jpeg", - png = "png" - } + type _SetImageData = "jpeg" | "png"; /* clipboard functions */ /** @@ -766,13 +750,12 @@ declare namespace browser.cookies { * will be "evicted". If a cookie was automatically removed due to a "set" call that overwrote it, "cause" will be * "overwrite". Plan your response accordingly. */ - enum OnChangedCause { - evicted = "evicted", - expired = "expired", - explicit = "explicit", - expired_overwrite = "expired_overwrite", - overwrite = "overwrite" - } + type OnChangedCause = + "evicted" + | "expired" + | "explicit" + | "expired_overwrite" + | "overwrite"; /* cookies functions */ /** @@ -911,38 +894,36 @@ declare namespace browser.cookies { */ declare namespace browser.downloads { /* downloads types */ - enum FilenameConflictAction { - uniquify = "uniquify", - overwrite = "overwrite", - prompt = "prompt" - } + type FilenameConflictAction = + "uniquify" + | "overwrite" + | "prompt"; - enum InterruptReason { - FILE_FAILED = "FILE_FAILED", - FILE_ACCESS_DENIED = "FILE_ACCESS_DENIED", - FILE_NO_SPACE = "FILE_NO_SPACE", - FILE_NAME_TOO_LONG = "FILE_NAME_TOO_LONG", - FILE_TOO_LARGE = "FILE_TOO_LARGE", - FILE_VIRUS_INFECTED = "FILE_VIRUS_INFECTED", - FILE_TRANSIENT_ERROR = "FILE_TRANSIENT_ERROR", - FILE_BLOCKED = "FILE_BLOCKED", - FILE_SECURITY_CHECK_FAILED = "FILE_SECURITY_CHECK_FAILED", - FILE_TOO_SHORT = "FILE_TOO_SHORT", - NETWORK_FAILED = "NETWORK_FAILED", - NETWORK_TIMEOUT = "NETWORK_TIMEOUT", - NETWORK_DISCONNECTED = "NETWORK_DISCONNECTED", - NETWORK_SERVER_DOWN = "NETWORK_SERVER_DOWN", - NETWORK_INVALID_REQUEST = "NETWORK_INVALID_REQUEST", - SERVER_FAILED = "SERVER_FAILED", - SERVER_NO_RANGE = "SERVER_NO_RANGE", - SERVER_BAD_CONTENT = "SERVER_BAD_CONTENT", - SERVER_UNAUTHORIZED = "SERVER_UNAUTHORIZED", - SERVER_CERT_PROBLEM = "SERVER_CERT_PROBLEM", - SERVER_FORBIDDEN = "SERVER_FORBIDDEN", - USER_CANCELED = "USER_CANCELED", - USER_SHUTDOWN = "USER_SHUTDOWN", - CRASH = "CRASH" - } + type InterruptReason = + "FILE_FAILED" + | "FILE_ACCESS_DENIED" + | "FILE_NO_SPACE" + | "FILE_NAME_TOO_LONG" + | "FILE_TOO_LARGE" + | "FILE_VIRUS_INFECTED" + | "FILE_TRANSIENT_ERROR" + | "FILE_BLOCKED" + | "FILE_SECURITY_CHECK_FAILED" + | "FILE_TOO_SHORT" + | "NETWORK_FAILED" + | "NETWORK_TIMEOUT" + | "NETWORK_DISCONNECTED" + | "NETWORK_SERVER_DOWN" + | "NETWORK_INVALID_REQUEST" + | "SERVER_FAILED" + | "SERVER_NO_RANGE" + | "SERVER_BAD_CONTENT" + | "SERVER_UNAUTHORIZED" + | "SERVER_CERT_PROBLEM" + | "SERVER_FORBIDDEN" + | "USER_CANCELED" + | "USER_SHUTDOWN" + | "CRASH"; /** * *file*: @@ -958,16 +939,15 @@ declare namespace browser.downloads { * * These string constants will never change, however the set of DangerTypes may change. */ - enum DangerType { - file = "file", - url = "url", - content = "content", - uncommon = "uncommon", - host = "host", - unwanted = "unwanted", - safe = "safe", - accepted = "accepted" - } + type DangerType = + "file" + | "url" + | "content" + | "uncommon" + | "host" + | "unwanted" + | "safe" + | "accepted"; /** * *in_progress*: @@ -979,11 +959,10 @@ declare namespace browser.downloads { * * These string constants will never change, however the set of States may change. */ - enum State { - in_progress = "in_progress", - interrupted = "interrupted", - complete = "complete" - } + type State = + "in_progress" + | "interrupted" + | "complete"; interface DownloadItem { /** An identifier that is persistent across browser sessions. */ @@ -1106,10 +1085,9 @@ declare namespace browser.downloads { } /** The HTTP method to use if the URL uses the HTTP[S] protocol. */ - enum _DownloadMethod { - GET = "GET", - POST = "POST" - } + type _DownloadMethod = + "GET" + | "POST"; /* downloads functions */ /** @@ -1431,11 +1409,10 @@ declare namespace browser.extension { /* extension types */ /** The type of extension view. */ - enum ViewType { - tab = "tab", - popup = "popup", - sidebar = "sidebar" - } + type ViewType = + "tab" + | "popup" + | "sidebar"; /* extension properties */ /** @@ -1532,10 +1509,9 @@ declare namespace browser.extensionTypes { /* extensionTypes types */ /** The format of an image. */ - enum ImageFormat { - jpeg = "jpeg", - png = "png" - } + type ImageFormat = + "jpeg" + | "png"; /** Details about the format and quality of an image. */ interface ImageDetails { @@ -1550,17 +1526,15 @@ declare namespace browser.extensionTypes { } /** The soonest that the JavaScript or CSS will be injected into the tab. */ - enum RunAt { - document_start = "document_start", - document_end = "document_end", - document_idle = "document_idle" - } + type RunAt = + "document_start" + | "document_end" + | "document_idle"; /** The origin of the CSS to inject, this affects the cascading order (priority) of the stylesheet. */ - enum CSSOrigin { - user = "user", - author = "author" - } + type CSSOrigin = + "user" + | "author"; /** * Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be @@ -1732,10 +1706,9 @@ declare namespace browser.identity { */ declare namespace browser.idle { /* idle types */ - enum IdleState { - active = "active", - idle = "idle" - } + type IdleState = + "active" + | "idle"; /* idle functions */ /** @@ -1783,16 +1756,14 @@ declare namespace browser.management { } /** A reason the item is disabled. */ - enum ExtensionDisabledReason { - unknown = "unknown", - permissions_increase = "permissions_increase" - } + type ExtensionDisabledReason = + "unknown" + | "permissions_increase"; /** The type of this extension. Will always be 'extension'. */ - enum ExtensionType { - extension = "extension", - theme = "theme" - } + type ExtensionType = + "extension" + | "theme"; /** * How the extension was installed. One of @@ -1801,12 +1772,11 @@ declare namespace browser.management { * `sideload`: The extension was installed by other software on the machine, * `other`: The extension was installed by other means. */ - enum ExtensionInstallType { - development = "development", - normal = "normal", - sideload = "sideload", - other = "other" - } + type ExtensionInstallType = + "development" + | "normal" + | "sideload" + | "other"; /** Information about an installed extension. */ interface ExtensionInfo { @@ -1906,17 +1876,15 @@ declare namespace browser.management { */ declare namespace browser.notifications { /* notifications types */ - enum TemplateType { - basic = "basic", - image = "image", - list = "list", - progress = "progress" - } + type TemplateType = + "basic" + | "image" + | "list" + | "progress"; - enum PermissionLevel { - granted = "granted", - denied = "denied" - } + type PermissionLevel = + "granted" + | "denied"; interface NotificationItem { /** Title of one item of a list notification. */ @@ -2145,12 +2113,11 @@ declare namespace browser.privacy.network { /* privacy.network types */ /** The IP handling policy of WebRTC. */ - enum IPHandlingPolicy { - default = "default", - default_public_and_private_interfaces = "default_public_and_private_interfaces", - default_public_interface_only = "default_public_interface_only", - disable_non_proxied_udp = "disable_non_proxied_udp" - } + type IPHandlingPolicy = + "default" + | "default_public_and_private_interfaces" + | "default_public_interface_only" + | "disable_non_proxied_udp"; /* privacy.network properties */ /** @@ -2198,11 +2165,10 @@ declare namespace browser.privacy.websites { /* privacy.websites types */ /** The mode for tracking protection. */ - enum TrackingProtectionModeOption { - always = "always", - never = "never", - private_browsing = "private_browsing" - } + type TrackingProtectionModeOption = + "always" + | "never" + | "private_browsing"; /* privacy.websites properties */ /** @@ -2333,21 +2299,19 @@ declare namespace browser.runtime { } /** The operating system the browser is running on. */ - enum PlatformOs { - mac = "mac", - win = "win", - android = "android", - cros = "cros", - linux = "linux", - openbsd = "openbsd" - } + type PlatformOs = + "mac" + | "win" + | "android" + | "cros" + | "linux" + | "openbsd"; /** The machine's processor architecture. */ - enum PlatformArch { - arm = "arm", - x8632 = "x86-32", - x8664 = "x86-64" - } + type PlatformArch = + "arm" + | "x86-32" + | "x86-64"; /** An object containing information about the current platform. */ interface PlatformInfo { @@ -2375,18 +2339,16 @@ declare namespace browser.runtime { } /** Result of the update check. */ - enum RequestUpdateCheckStatus { - throttled = "throttled", - no_update = "no_update", - update_available = "update_available" - } + type RequestUpdateCheckStatus = + "throttled" + | "no_update" + | "update_available"; /** The reason that this event is being dispatched. */ - enum OnInstalledReason { - install = "install", - update = "update", - browser_update = "browser_update" - } + type OnInstalledReason = + "install" + | "update" + | "browser_update"; /** * The reason that the event is being dispatched. 'app_update' is used when the restart is needed because the @@ -2394,11 +2356,10 @@ declare namespace browser.runtime { * is updated to a newer version. 'periodic' is used when the system runs for more than the permitted uptime set in * the enterprise policy. */ - enum OnRestartRequiredReason { - app_update = "app_update", - os_update = "os_update", - periodic = "periodic" - } + type OnRestartRequiredReason = + "app_update" + | "os_update" + | "periodic"; type PlatformNaclArch = any; @@ -2834,12 +2795,11 @@ declare namespace browser.types { * * Only `regular` is supported by Firefox at this time. */ - enum SettingScope { - regular = "regular", - regular_only = "regular_only", - incognito_persistent = "incognito_persistent", - incognito_session_only = "incognito_session_only" - } + type SettingScope = + "regular" + | "regular_only" + | "incognito_persistent" + | "incognito_session_only"; /** * One of @@ -2849,12 +2809,11 @@ declare namespace browser.types { * * `controllable_by_this_extension`: can be controlled by this extension * * `controlled_by_this_extension`: controlled by this extension */ - enum LevelOfControl { - not_controllable = "not_controllable", - controlled_by_other_extensions = "controlled_by_other_extensions", - controllable_by_this_extension = "controllable_by_this_extension", - controlled_by_this_extension = "controlled_by_this_extension" - } + type LevelOfControl = + "not_controllable" + | "controlled_by_other_extensions" + | "controllable_by_this_extension" + | "controlled_by_this_extension"; interface Setting { /** @@ -2934,26 +2893,24 @@ declare namespace browser.webNavigation { * transition types as defined in the history API except with `"start_page"` in place of `"auto_toplevel"` (for * backwards compatibility). */ - enum TransitionType { - link = "link", - typed = "typed", - auto_bookmark = "auto_bookmark", - auto_subframe = "auto_subframe", - manual_subframe = "manual_subframe", - generated = "generated", - start_page = "start_page", - form_submit = "form_submit", - reload = "reload", - keyword = "keyword", - keyword_generated = "keyword_generated" - } + type TransitionType = + "link" + | "typed" + | "auto_bookmark" + | "auto_subframe" + | "manual_subframe" + | "generated" + | "start_page" + | "form_submit" + | "reload" + | "keyword" + | "keyword_generated"; - enum TransitionQualifier { - client_redirect = "client_redirect", - server_redirect = "server_redirect", - forward_back = "forward_back", - from_address_bar = "from_address_bar" - } + type TransitionQualifier = + "client_redirect" + | "server_redirect" + | "forward_back" + | "from_address_bar"; interface EventUrlFilters { url: events.UrlFilter[]; @@ -3263,65 +3220,52 @@ declare namespace browser.webNavigation { */ declare namespace browser.webRequest { /* webRequest types */ - enum ResourceType { - main_frame = "main_frame", - sub_frame = "sub_frame", - stylesheet = "stylesheet", - script = "script", - image = "image", - object = "object", - object_subrequest = "object_subrequest", - xmlhttprequest = "xmlhttprequest", - xbl = "xbl", - xslt = "xslt", - ping = "ping", - beacon = "beacon", - xml_dtd = "xml_dtd", - font = "font", - media = "media", - websocket = "websocket", - csp_report = "csp_report", - imageset = "imageset", - web_manifest = "web_manifest", - other = "other" - } + type ResourceType = + "main_frame" + | "sub_frame" + | "stylesheet" + | "script" + | "image" + | "object" + | "object_subrequest" + | "xmlhttprequest" + | "xbl" + | "xslt" + | "ping" + | "beacon" + | "xml_dtd" + | "font" + | "media" + | "websocket" + | "csp_report" + | "imageset" + | "web_manifest" + | "other"; - enum OnBeforeRequestOptions { - blocking = "blocking", - requestBody = "requestBody" - } + type OnBeforeRequestOptions = + "blocking" + | "requestBody"; - enum OnBeforeSendHeadersOptions { - requestHeaders = "requestHeaders", - blocking = "blocking" - } + type OnBeforeSendHeadersOptions = + "requestHeaders" + | "blocking"; - enum OnSendHeadersOptions { - requestHeaders = "requestHeaders" - } + type OnSendHeadersOptions = "requestHeaders"; - enum OnHeadersReceivedOptions { - blocking = "blocking", - responseHeaders = "responseHeaders" - } + type OnHeadersReceivedOptions = + "blocking" + | "responseHeaders"; - enum OnAuthRequiredOptions { - responseHeaders = "responseHeaders", - blocking = "blocking", - asyncBlocking = "asyncBlocking" - } + type OnAuthRequiredOptions = + "responseHeaders" + | "blocking" + | "asyncBlocking"; - enum OnResponseStartedOptions { - responseHeaders = "responseHeaders" - } + type OnResponseStartedOptions = "responseHeaders"; - enum OnBeforeRedirectOptions { - responseHeaders = "responseHeaders" - } + type OnBeforeRedirectOptions = "responseHeaders"; - enum OnCompletedOptions { - responseHeaders = "responseHeaders" - } + type OnCompletedOptions = "responseHeaders"; /** An object describing filters to apply to webRequest events. */ interface RequestFilter { @@ -3860,16 +3804,10 @@ declare namespace browser.bookmarks { * by the system administrator or by the custodian of a supervised user. Omitted if the node can be modified by the * user and the extension (default). */ - enum BookmarkTreeNodeUnmodifiable { - managed = "managed" - } + type BookmarkTreeNodeUnmodifiable = "managed"; /** Indicates the type of a BookmarkTreeNode, which can be one of bookmark, folder or separator. */ - enum BookmarkTreeNodeType { - bookmark = "bookmark", - folder = "folder", - separator = "separator" - } + type BookmarkTreeNodeType = "bookmark" | "folder" | "separator"; /** * A node (either a bookmark or a folder) in the bookmark tree. Child nodes are ordered within their parent folder. @@ -4756,18 +4694,17 @@ declare namespace browser.find { */ declare namespace browser.geckoProfiler { /* geckoProfiler types */ - enum ProfilerFeature { - java = "java", - js = "js", - leaf = "leaf", - mainthreadio = "mainthreadio", - memory = "memory", - privacy = "privacy", - restyle = "restyle", - stackwalk = "stackwalk", - tasktracer = "tasktracer", - threads = "threads" - } + type ProfilerFeature = + "java" + | "js" + | "leaf" + | "mainthreadio" + | "memory" + | "privacy" + | "restyle" + | "stackwalk" + | "tasktracer" + | "threads"; /* geckoProfiler functions */ /** Starts the profiler with the specified settings. */ @@ -4833,19 +4770,18 @@ declare namespace browser.history { /* history types */ /** The transition type for this visit from its referrer. */ - enum TransitionType { - link = "link", - typed = "typed", - auto_bookmark = "auto_bookmark", - auto_subframe = "auto_subframe", - manual_subframe = "manual_subframe", - generated = "generated", - auto_toplevel = "auto_toplevel", - form_submit = "form_submit", - reload = "reload", - keyword = "keyword", - keyword_generated = "keyword_generated" - } + type TransitionType = + "link" + | "typed" + | "auto_bookmark" + | "auto_subframe" + | "manual_subframe" + | "generated" + | "auto_toplevel" + | "form_submit" + | "reload" + | "keyword" + | "keyword_generated"; /** An object encapsulating one result of a history query. */ interface HistoryItem { @@ -4976,30 +4912,28 @@ declare namespace browser.contextMenus { * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other * contexts except for 'tab' and 'tools_menu'. */ - enum ContextType { - all = "all", - page = "page", - frame = "frame", - selection = "selection", - link = "link", - editable = "editable", - password = "password", - image = "image", - video = "video", - audio = "audio", - launcher = "launcher", - browser_action = "browser_action", - page_action = "page_action", - tab = "tab" - } + type ContextType = + "all" + | "page" + | "frame" + | "selection" + | "link" + | "editable" + | "password" + | "image" + | "video" + | "audio" + | "launcher" + | "browser_action" + | "page_action" + | "tab"; /** The type of menu item. */ - enum ItemType { - normal = "normal", - checkbox = "checkbox", - radio = "radio", - separator = "separator" - } + type ItemType = + "normal" + | "checkbox" + | "radio" + | "separator"; /** Information sent when a context menu item is clicked. */ interface OnClickData { @@ -5036,13 +4970,12 @@ declare namespace browser.contextMenus { modifiers: _OnClickDataModifiers[]; } - enum _OnClickDataModifiers { - Shift = "Shift", - Alt = "Alt", - Command = "Command", - Ctrl = "Ctrl", - MacCtrl = "MacCtrl" - } + type _OnClickDataModifiers = + "Shift" + | "Alt" + | "Command" + | "Ctrl" + | "MacCtrl"; /* contextMenus properties */ /** @@ -5169,31 +5102,29 @@ declare namespace browser.menus { * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other * contexts except for 'tab' and 'tools_menu'. */ - enum ContextType { - all = "all", - page = "page", - frame = "frame", - selection = "selection", - link = "link", - editable = "editable", - password = "password", - image = "image", - video = "video", - audio = "audio", - launcher = "launcher", - browser_action = "browser_action", - page_action = "page_action", - tab = "tab", - tools_menu = "tools_menu" - } + type ContextType = + "all" + | "page" + | "frame" + | "selection" + | "link" + | "editable" + | "password" + | "image" + | "video" + | "audio" + | "launcher" + | "browser_action" + | "page_action" + | "tab" + | "tools_menu"; /** The type of menu item. */ - enum ItemType { - normal = "normal", - checkbox = "checkbox", - radio = "radio", - separator = "separator" - } + type ItemType = + "normal" + | "checkbox" + | "radio" + | "separator"; /** Information sent when a context menu item is clicked. */ interface OnClickData { @@ -5230,13 +5161,12 @@ declare namespace browser.menus { modifiers: _OnClickDataModifiers[]; } - enum _OnClickDataModifiers { - Shift = "Shift", - Alt = "Alt", - Command = "Command", - Ctrl = "Ctrl", - MacCtrl = "MacCtrl" - } + type _OnClickDataModifiers = + "Shift" + | "Alt" + | "Command" + | "Ctrl" + | "MacCtrl"; /* menus properties */ /** @@ -5399,22 +5329,20 @@ declare namespace browser.omnibox { /* omnibox types */ /** The style type. */ - enum DescriptionStyleType { - url = "url", - match = "match", - dim = "dim" - } + type DescriptionStyleType = + "url" + | "match" + | "dim"; /** * The window disposition for the omnibox query. This is the recommended context to display results. For example, * if the omnibox command is to navigate to a certain URL, a disposition of 'newForegroundTab' means the navigation * should take place in a new selected tab. */ - enum OnInputEnteredDisposition { - currentTab = "currentTab", - newForegroundTab = "newForegroundTab", - newBackgroundTab = "newBackgroundTab" - } + type OnInputEnteredDisposition = + "currentTab" + | "newForegroundTab" + | "newBackgroundTab"; /** A suggest result. */ interface SuggestResult { @@ -5843,14 +5771,13 @@ declare namespace browser.tabs { /* tabs types */ /** An event that caused a muted state change. */ - enum MutedInfoReason { + type MutedInfoReason = /** A user input action has set/overridden the muted state. */ - user = "user", - /** Tab capture started, forcing a muted state change. */ - capture = "capture", - /** An extension, identified by the extensionId field, set the muted state. */ - extension = "extension" - } + "user" +/** Tab capture started, forcing a muted state change. */ + | "capture" +/** An extension, identified by the extensionId field, set the muted state. */ + | "extension"; /** Tab muted state and the reason for the last state change. */ interface MutedInfo { @@ -5942,41 +5869,39 @@ declare namespace browser.tabs { * Defines how zoom changes are handled, i.e. which entity is responsible for the actual scaling of the page; * defaults to `automatic`. */ - enum ZoomSettingsMode { + type ZoomSettingsMode = /** Zoom changes are handled automatically by the browser. */ - automatic = "automatic", + "automatic" /** * Overrides the automatic handling of zoom changes. The `onZoomChange` event will still be dispatched, and it * is the responsibility of the extension to listen for this event and manually scale the page. This mode does * not support `per-origin` zooming, and will thus ignore the `scope` zoom setting and assume `per-tab`. */ - manual = "manual", + | "manual" /** * Disables all zooming in the tab. The tab will revert to the default zoom level, and all attempted zoom * changes will be ignored. */ - disabled = "disabled" - } + | "disabled"; /** * Defines whether zoom changes will persist for the page's origin, or only take effect in this tab; defaults to * `per-origin` when in `automatic` mode, and `per-tab` otherwise. */ - enum ZoomSettingsScope { + type ZoomSettingsScope = /** * Zoom changes will persist in the zoomed page's origin, i.e. all other tabs navigated to that same origin * will be zoomed as well. Moreover, `per-origin` zoom changes are saved with the origin, meaning that when * navigating to other pages in the same origin, they will all be zoomed to the same zoom factor. The * `per-origin` scope is only available in the `automatic` mode. */ - perorigin = "per-origin", + | "per-origin" /** * Zoom changes only take effect in this tab, and zoom changes in other tabs will not affect the zooming of * this tab. Also, `per-tab` zoom changes are reset on navigation; navigating a tab will always load pages with * their `per-origin` zoom factors. */ - pertab = "per-tab" - } + | "per-tab"; /** Defines how zoom changes in a tab are handled and at what scope. */ interface ZoomSettings { @@ -6035,19 +5960,17 @@ declare namespace browser.tabs { } /** Whether the tabs have completed loading. */ - enum TabStatus { - loading = "loading", - complete = "complete" - } + type TabStatus = + "loading" + | "complete"; /** The type of window. */ - enum WindowType { - normal = "normal", - popup = "popup", - panel = "panel", - app = "app", - devtools = "devtools" - } + type WindowType = + "normal" + | "popup" + | "panel" + | "app" + | "devtools"; /* tabs properties */ /** An ID which represents the absence of a browser tab. */ @@ -6549,25 +6472,18 @@ declare namespace browser.windows { * The type of browser window this is. Under some circumstances a Window may not be assigned type property, for * example when querying closed windows from the `sessions` API. */ - enum WindowType { - normal = "normal", - popup = "popup", - panel = "panel", - app = "app", - devtools = "devtools" - } + type WindowType = "normal" | "popup" | "panel" | "app" | "devtools"; /** * The state of this browser window. Under some circumstances a Window may not be assigned state property, for * example when querying closed windows from the `sessions` API. */ - enum WindowState { - normal = "normal", - minimized = "minimized", - maximized = "maximized", - fullscreen = "fullscreen", - docked = "docked" - } + type WindowState = + "normal" + | "minimized" + | "maximized" + | "fullscreen" + | "docked"; interface Window { /** @@ -6618,12 +6534,7 @@ declare namespace browser.windows { * Specifies what type of browser window to create. The 'panel' and 'detached_panel' types create a popup unless * the '--enable-panels' flag is set. */ - enum CreateType { - normal = "normal", - popup = "popup", - panel = "panel", - detached_panel = "detached_panel" - } + type CreateType = "normal" | "popup" | "panel" | "detached_panel"; /* windows properties */ /** The windowId value that represents the absence of a browser window. */ diff --git a/types/ftpd/index.d.ts b/types/ftpd/index.d.ts index cd325109ee..e919e4b48a 100644 --- a/types/ftpd/index.d.ts +++ b/types/ftpd/index.d.ts @@ -130,20 +130,20 @@ export declare class FtpConnection extends events.EventEmitter { */ export interface FtpFileSystem { unlink: (path: string, callback?: (err?: NodeJS.ErrnoException) => void) => void; - readdir: (path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void) => void; + readdir: (path: string, callback?: (err?: NodeJS.ErrnoException, files?: string[]) => void) => void; mkdir: ((path: string, callback?: (err?: NodeJS.ErrnoException) => void) => void) | ((path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void) => void) | ((path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void) => void); - open: ((path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any) => void) - | ((path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any) => void) - | ((path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any) => void); + open: ((path: string, flags: string, callback?: (err?: NodeJS.ErrnoException, fd?: number) => any) => void) + | ((path: string, flags: string, mode: number, callback?: (err?: NodeJS.ErrnoException, fd?: number) => any) => void) + | ((path: string, flags: string, mode: string, callback?: (err?: NodeJS.ErrnoException, fd?: number) => any) => void); close: (fd: number, callback?: (err?: NodeJS.ErrnoException) => void) => void; rmdir: (path: string, callback?: (err?: NodeJS.ErrnoException) => void) => void; rename: (oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void) => void; /** * specific object properties: { mode, isDirectory(), size, mtime } */ - stat: (path: string, callback?: (err: NodeJS.ErrnoException, stats: fs.Stats) => any) => void; + stat: (path: string, callback?: (err?: NodeJS.ErrnoException, stats?: fs.Stats) => any) => void; /** * if useReadFile option is not set or is false */ diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index ffd8cb90c2..6f4cf1fe7f 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -131,12 +131,14 @@ export interface Props { onChildClick?(hoverKey: any, childProps: any): void; onChildMouseEnter?(hoverKey: any, childProps: any): void; onChildMouseLeave?(hoverKey: any, childProps: any): void; + onDrag?(args: any): void; onZoomAnimationStart?(args: any): void; onZoomAnimationEnd?(args: any): void; onMapTypeIdChange?(args: any): void; distanceToMouse?(pt: Point, mousePos: Point): void; googleMapLoader?(bootstrapURLKeys: any): void; onGoogleApiLoaded?(maps: { map: any, maps: any }): void; + onTilesLoaded?(): void; yesIWantToUseGoogleMapApiInternals?: boolean; } diff --git a/types/google-translate-api/google-translate-api-tests.ts b/types/google-translate-api/google-translate-api-tests.ts new file mode 100644 index 0000000000..25149c2660 --- /dev/null +++ b/types/google-translate-api/google-translate-api-tests.ts @@ -0,0 +1,3 @@ +import translate = require('google-translate-api'); + +translate('hello', { from: 'en', to: 'zh-tw' }); // $ExpectType Promise diff --git a/types/google-translate-api/index.d.ts b/types/google-translate-api/index.d.ts new file mode 100644 index 0000000000..1a53eacc4d --- /dev/null +++ b/types/google-translate-api/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for google-translate-api 2.3 +// Project: https://github.com/matheuss/google-translate-api#readme +// Definitions by: maple3142 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface TranslateOption { + from?: string; + to?: string; + raw?: boolean; +} +interface TranslateResult { + text: string; + from: { + language: { + didYouMean: boolean; + iso: string; + } + text: { + autoCorrected: boolean; + value: string; + didYouMean: boolean; + } + }; + raw: string; +} +declare function translate(text: string, options?: TranslateOption): Promise; +export = translate; diff --git a/types/google-translate-api/tsconfig.json b/types/google-translate-api/tsconfig.json new file mode 100644 index 0000000000..21eb234d62 --- /dev/null +++ b/types/google-translate-api/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "google-translate-api-tests.ts"] +} diff --git a/types/google-translate-api/tslint.json b/types/google-translate-api/tslint.json new file mode 100644 index 0000000000..381c23f5c5 --- /dev/null +++ b/types/google-translate-api/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "semicolon": true + } +} diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index dba5a5a5a1..531074b258 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -2,7 +2,8 @@ // Project: https://developers.google.com/maps/ // Definitions by: Folia A/S , // Chris Wrench , -// Kiarash Ghiaseddin , +// Kiarash Ghiaseddin +// , // Grant Hutchins , // Denis Atyasov , // Michael McMullin , @@ -37,2879 +38,3038 @@ THE SOFTWARE. */ declare namespace google.maps { - /***** Map *****/ - export class Map extends MVCObject { - constructor(mapDiv: Element|null, opts?: MapOptions); - fitBounds(bounds: LatLngBounds|LatLngBoundsLiteral, padding?: number|Padding): void; - getBounds(): LatLngBounds|null|undefined; - getCenter(): LatLng; - getDiv(): Element; - getHeading(): number; - getMapTypeId(): MapTypeId|string; - getProjection(): Projection; - getStreetView(): StreetViewPanorama; - getTilt(): number; - getZoom(): number; - panBy(x: number, y: number): void; - panTo(latLng: LatLng|LatLngLiteral): void; - panToBounds(latLngBounds: LatLngBounds|LatLngBoundsLiteral, padding?: number|Padding): void; - setCenter(latlng: LatLng|LatLngLiteral): void; - setHeading(heading: number): void; - setMapTypeId(mapTypeId: MapTypeId|string): void; - setOptions(options: MapOptions): void; - setStreetView(panorama: StreetViewPanorama): void; - setTilt(tilt: number): void; - setZoom(zoom: number): void; - controls: MVCArray[]; - data: Data; - mapTypes: MapTypeRegistry; - overlayMapTypes: MVCArray; - setClickableIcons(clickable: boolean): void; - } + /***** Map *****/ + export class Map extends MVCObject { + constructor(mapDiv: Element|null, opts?: MapOptions); + fitBounds( + bounds: LatLngBounds|LatLngBoundsLiteral, + padding?: number|Padding): void; + getBounds(): LatLngBounds|null|undefined; + getCenter(): LatLng; + getDiv(): Element; + getHeading(): number; + getMapTypeId(): MapTypeId|string; + getProjection(): Projection; + getStreetView(): StreetViewPanorama; + getTilt(): number; + getZoom(): number; + panBy(x: number, y: number): void; + panTo(latLng: LatLng|LatLngLiteral): void; + panToBounds( + latLngBounds: LatLngBounds|LatLngBoundsLiteral, + padding?: number|Padding): void; + setCenter(latlng: LatLng|LatLngLiteral): void; + setHeading(heading: number): void; + setMapTypeId(mapTypeId: MapTypeId|string): void; + setOptions(options: MapOptions): void; + setStreetView(panorama: StreetViewPanorama): void; + setTilt(tilt: number): void; + setZoom(zoom: number): void; + controls: MVCArray[]; + data: Data; + mapTypes: MapTypeRegistry; + overlayMapTypes: MVCArray; + setClickableIcons(clickable: boolean): void; + } - export interface Padding { - bottom: number; - left: number; - right: number; - top: number; - } - - export interface MapOptions { - /** - * Color used for the background of the Map div. This color will be visible when - * tiles have not yet loaded as the user pans. This option can only be set when - * the map is initialized. - */ - backgroundColor?: string; - /** The initial Map center. Required. */ - center?: LatLng|LatLngLiteral; - /** - * When false, map icons are not clickable. A map icon represents a point of - * interest, also known as a POI. By default map icons are clickable. - */ - clickableIcons?: boolean - /** Enables/disables all default UI. May be overridden individually. */ - disableDefaultUI?: boolean; - /** Enables/disables zoom and center on double click. Enabled by default. */ - disableDoubleClickZoom?: boolean; - /** If false, prevents the map from being dragged. Dragging is enabled by default. */ - draggable?: boolean; - /** - * The name or url of the cursor to display when mousing over a draggable map. - * This property uses the css cursor attribute to change the icon. As with the - * css property, you must specify at least one fallback cursor that is not a URL. - * For example: draggableCursor: 'url(http://www.example.com/icon.png), auto;'. - */ - draggableCursor?: string; - /** - * The name or url of the cursor to display when the map is being dragged. This - * property uses the css cursor attribute to change the icon. As with the css - * property, you must specify at least one fallback cursor that is not a URL. - * For example: draggingCursor: 'url(http://www.example.com/icon.png), auto;'. - */ - draggingCursor?: string; - /** The enabled/disabled state of the Fullscreen control. */ - fullscreenControl?: boolean; - /** The display options for the Fullscreen control. */ - fullscreenControlOptions?: FullscreenControlOptions; - /** - * This setting controls how gestures on the map are handled. - */ - gestureHandling?: GestureHandlingOptions; - /** - * The heading for aerial imagery in degrees measured clockwise from cardinal - * direction North. Headings are snapped to the nearest available angle for - * which imagery is available. - */ - heading?: number; - /** - * If false, prevents the map from being controlled by the keyboard. Keyboard - * shortcuts are enabled by default. - */ - keyboardShortcuts?: boolean; - /** The initial enabled/disabled state of the Map type control. */ - mapTypeControl?: boolean; - /** The initial display options for the Map type control. */ - mapTypeControlOptions?: MapTypeControlOptions; - /** The initial Map mapTypeId. Defaults to ROADMAP. */ - mapTypeId?: MapTypeId; - /** - * The maximum zoom level which will be displayed on the map. If omitted, or set - * to null, the maximum zoom from the current map type is used instead. Valid - * values: Integers between zero, and up to the supported maximum zoom level. - */ - maxZoom?: number; - /** - * The minimum zoom level which will be displayed on the map. If omitted, or set - * to null, the minimum zoom from the current map type is used instead. Valid - * values: Integers between zero, and up to the supported maximum zoom level. - */ - minZoom?: number; - /** If true, do not clear the contents of the Map div. */ - noClear?: boolean; - overviewMapControl?: boolean; - overviewMapControlOptions?: OverviewMapControlOptions; - /** - * The enabled/disabled state of the Pan control. - * Note: The Pan control is not available in the new set of controls introduced - * in v3.22 of the Google Maps JavaScript API. While using v3.22 and v3.23, you - * can choose to use the earlier set of controls rather than the new controls, - * thus making the Pan control available as part of the old control set. - * See {@link https://developers.google.com/maps/articles/v322-controls-diff|What's New in the v3.22 Map Controls}. - */ - panControl?: boolean; - /** - * The display options for the Pan control. - * Note: The Pan control is not available in the new set of controls introduced - * in v3.22 of the Google Maps JavaScript API. While using v3.22 and v3.23, you - * can choose to use the earlier set of controls rather than the new controls, - * thus making the Pan control available as part of the old control set. - * See {@link https://developers.google.com/maps/articles/v322-controls-diff|What's New in the v3.22 Map Controls}. - */ - panControlOptions?: PanControlOptions; - /** The enabled/disabled state of the Rotate control. */ - rotateControl?: boolean; - /** The display options for the Rotate control. */ - rotateControlOptions?: RotateControlOptions; - /** The initial enabled/disabled state of the Scale control. */ - scaleControl?: boolean; - /** The initial display options for the Scale control. */ - scaleControlOptions?: ScaleControlOptions; - /** If false, disables scrollwheel zooming on the map. The scrollwheel is enabled by default. */ - scrollwheel?: boolean; - /** - * The enabled/disabled state of the sign in control. This option only applies if - * signed_in=true has been passed as a URL parameter in the bootstrap request. - * You may want to use this option to hide the map's sign in control if you have - * provided another way for your users to sign in, such as the Google Sign-In - * button. This option does not affect the visibility of the Google avatar shown - * when the user is already signed in. - */ - signInControl?: boolean; - /** - * A StreetViewPanorama to display when the Street View pegman is dropped on the - * map. If no panorama is specified, a default StreetViewPanorama will be - * displayed in the map's div when the pegman is dropped. - */ - streetView?: StreetViewPanorama; - /** - * The initial enabled/disabled state of the Street View Pegman control. This - * control is part of the default UI, and should be set to false when displaying - * a map type on which the Street View road overlay should not appear - * (e.g. a non-Earth map type). - */ - streetViewControl?: boolean; - /** The initial display options for the Street View Pegman control. */ - streetViewControlOptions?: StreetViewControlOptions; - /** - * Styles to apply to each of the default map types. Note that for - * satellite/hybrid and terrain modes, these styles will only apply to labels - * and geometry. - */ - styles?: MapTypeStyle[]; - /** - * Controls the automatic switching behavior for the angle of incidence of the - * map. The only allowed values are 0 and 45. The value 0 causes the map to - * always use a 0° overhead view regardless of the zoom level and viewport. The - * value 45 causes the tilt angle to automatically switch to 45 whenever 45° - * imagery is available for the current zoom level and viewport, and switch back - * to 0 whenever 45° imagery is not available (this is the default behavior). - * 45° imagery is only available for satellite and hybrid map types, within some - * locations, and at some zoom levels. Note: getTilt returns the current tilt - * angle, not the value specified by this option. Because getTilt and this option - * refer to different things, do not bind() the tilt property; doing so may yield - * unpredictable effects. - */ - tilt?: number; - /** - * The initial Map zoom level. Required. Valid values: Integers between zero, and - * up to the supported maximum zoom level. - */ - zoom?: number; - /** The enabled/disabled state of the Zoom control. */ - zoomControl?: boolean; - /** The display options for the Zoom control. */ - zoomControlOptions?: ZoomControlOptions; - } + export interface Padding { + bottom: number; + left: number; + right: number; + top: number; + } + export interface MapOptions { /** - * Identifiers for common MapTypes. Specify these by value, or by using the - * constant's name. For example, 'satellite' or google.maps.MapTypeId.SATELLITE. + * Color used for the background of the Map div. This color will be visible + * when tiles have not yet loaded as the user pans. This option can only be + * set when the map is initialized. */ - export enum MapTypeId { - /** This map type displays a transparent layer of major streets on satellite images. */ - HYBRID, - /** This map type displays a normal street map. */ - ROADMAP, - /** This map type displays satellite images. */ - SATELLITE, - /** This map type displays maps with physical features such as terrain and vegetation. */ - TERRAIN - } - - /***** Controls *****/ - /** Options for the rendering of the map type control. */ - export interface MapTypeControlOptions { - /** IDs of map types to show in the control. */ - mapTypeIds?: (MapTypeId|string)[]; - /** - * Position id. Used to specify the position of the control on the map. - * The default position is TOP_RIGHT. - */ - position?: ControlPosition; - /** Style id. Used to select what style of map type control to display. */ - style?: MapTypeControlStyle; - } - - export enum MapTypeControlStyle { - DEFAULT, - DROPDOWN_MENU, - HORIZONTAL_BAR - } - - export interface OverviewMapControlOptions { - opened?: boolean; - } - - export type GestureHandlingOptions = - "cooperative" | - "greedy" | - "none" | - "auto"; - - /** Options for the rendering of the pan control. */ - export interface PanControlOptions { - /** - * Position id. Used to specify the position of the control on the map. - * The default position is TOP_LEFT. - */ - position?: ControlPosition; - } - - /** Options for the rendering of the rotate control. */ - export interface RotateControlOptions { - /** - * Position id. Used to specify the position of the control on the map. - * The default position is TOP_LEFT. - */ - position?: ControlPosition; - } - - /** Options for the rendering of the scale control. */ - export interface ScaleControlOptions { - /** Style id. Used to select what style of scale control to display. */ - style?: ScaleControlStyle; - } - - export enum ScaleControlStyle { - DEFAULT - } - - /** Options for the rendering of the Street View pegman control on the map. */ - export interface StreetViewControlOptions { - /** - * Position id. Used to specify the position of the control on the map. The - * default position is embedded within the navigation (zoom and pan) controls. - * If this position is empty or the same as that specified in the - * zoomControlOptions or panControlOptions, the Street View control will be - * displayed as part of the navigation controls. Otherwise, it will be displayed - * separately. - */ - position?: ControlPosition; - } - - /** Options for the rendering of the zoom control. */ - export interface ZoomControlOptions { - /** - * Position id. Used to specify the position of the control on the map. - * The default position is TOP_LEFT. - */ - position?: ControlPosition; - style?: ZoomControlStyle; - } - - export enum ZoomControlStyle { - DEFAULT, - LARGE, - SMALL - } - + backgroundColor?: string; + /** The initial Map center. Required. */ + center?: LatLng|LatLngLiteral; /** - * Identifiers used to specify the placement of controls on the map. Controls are - * positioned relative to other controls in the same layout position. Controls that - * are added first are positioned closer to the edge of the map. + * When false, map icons are not clickable. A map icon represents a point of + * interest, also known as a POI. By default map icons are clickable. */ - export enum ControlPosition { - /** Elements are positioned in the center of the bottom row. */ - BOTTOM_CENTER, - /** - * Elements are positioned in the bottom left and flow towards the middle. - * Elements are positioned to the right of the Google logo. - */ - BOTTOM_LEFT, - /** - * Elements are positioned in the bottom right and flow towards the middle. - * Elements are positioned to the left of the copyrights. - */ - BOTTOM_RIGHT, - /** - * Elements are positioned on the left, above bottom-left elements, and flow upwards. - */ - LEFT_BOTTOM, - /** Elements are positioned in the center of the left side. */ - LEFT_CENTER, - /** - * Elements are positioned on the left, below top-left elements, and flow downwards. - */ - LEFT_TOP, - /** - * Elements are positioned on the right, above bottom-right elements, and flow upwards. - */ - RIGHT_BOTTOM, - /** Elements are positioned in the center of the right side. */ - RIGHT_CENTER, - /** Elements are positioned on the right, below top-right elements, and flow downwards. */ - RIGHT_TOP, - /** Elements are positioned in the center of the top row. */ - TOP_CENTER, - /** Elements are positioned in the top left and flow towards the middle. */ - TOP_LEFT, - /** Elements are positioned in the top right and flow towards the middle. */ - TOP_RIGHT - } - - type DrawingMode = 'Point' | 'LineString' | 'Polygon'; - - /***** Data *****/ - export class Data extends MVCObject { - constructor(options?: Data.DataOptions); - add(feature: Data.Feature|Data.FeatureOptions): Data.Feature; - addGeoJson(geoJson: Object, options?: Data.GeoJsonOptions): Data.Feature[]; - contains(feature: Data.Feature): boolean; - forEach(callback: (feature: Data.Feature) => void): void; - getControlPosition(): ControlPosition; - getControls(): DrawingMode[]; - getDrawingMode(): DrawingMode | null; - getFeatureById(id: number|string): Data.Feature; - getMap(): Map; - getStyle(): Data.StylingFunction|Data.StyleOptions; - loadGeoJson(url: string, options?: Data.GeoJsonOptions, callback?: (features: Data.Feature[]) => void): void; - overrideStyle(feature: Data.Feature, style: Data.StyleOptions): void; - remove(feature: Data.Feature): void; - revertStyle(feature?: Data.Feature): void; - setControlPosition(controlPosition: ControlPosition): void; - setControls(controls: DrawingMode[] | null): void; - setDrawingMode(drawingMode: DrawingMode | null): void; - setMap(map: Map | null): void; - setStyle(style: Data.StylingFunction|Data.StyleOptions): void; - toGeoJson(callback: (feature: Object) => void): void; - } - - export module Data { - export interface DataOptions { - controlPosition?: ControlPosition; - controls?: DrawingMode[] | null; - drawingMode?: DrawingMode | null; - featureFactory?: (geometry: Data.Geometry) => Data.Feature; - map?: Map; - style?: Data.StylingFunction|Data.StyleOptions; - } - - export interface GeoJsonOptions { - idPropertyName?: string; - } - - export interface StyleOptions { - clickable?: boolean; - cursor?: string; - draggable?: boolean; - editable?: boolean; - fillColor?: string; - fillOpacity?: number; - icon?: string|Icon|Symbol; - shape?: MarkerShape; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - title?: string; - visible?: boolean; - zIndex?: number; - } - - export type StylingFunction = (feature: Data.Feature) => Data.StyleOptions; - - export class Feature { - constructor(options?: Data.FeatureOptions); - forEachProperty(callback: (value: any, name: string) => void): void; - getGeometry(): Data.Geometry; - getId(): number|string; - getProperty(name: string): any; - removeProperty(name: string): void; - setGeometry(newGeometry: Data.Geometry|LatLng|LatLngLiteral): void; - setProperty(name: string, newValue: any): void; - toGeoJson(callback: (feature: Object) => void): void; - } - - export interface FeatureOptions { - geometry?: Data.Geometry|LatLng|LatLngLiteral; - id?: number|string; - properties?: Object; - } - - export class Geometry { - getType(): string; - forEachLatLng(callback: (latLng: LatLng) => void): void; - } - - export class Point extends Data.Geometry { - constructor(latLng: LatLng|LatLngLiteral); - get(): LatLng; - } - - export class MultiPoint extends Data.Geometry { - constructor(elements: (LatLng|LatLngLiteral)[]); - getArray(): LatLng[]; - getAt(n: number): LatLng; - getLength(): number; - } - - export class LineString extends Data.Geometry { - constructor(elements: (LatLng|LatLngLiteral)[]); - getArray(): LatLng[]; - getAt(n: number): LatLng; - getLength(): number; - } - - export class MultiLineString extends Data.Geometry { - constructor(elements: (Data.LineString|(LatLng|LatLngLiteral)[])[]); - getArray(): Data.LineString[]; - getAt(n: number): Data.LineString; - getLength(): number; - } - - export class LinearRing extends Data.Geometry { - constructor(elements: (LatLng|LatLngLiteral)[]); - getArray(): LatLng[]; - getAt(n: number): LatLng; - getLength(): number; - } - - export class Polygon extends Data.Geometry { - constructor(elements: (Data.LinearRing|(LatLng|LatLngLiteral)[])[]); - getArray(): Data.LinearRing[]; - getAt(n: number): Data.LinearRing; - getLength(): number; - } - - export class MultiPolygon extends Data.Geometry { - constructor(elements: (Data.Polygon|(LinearRing|(LatLng|LatLngLiteral)[])[])[]); - getArray(): Data.Polygon[]; - getAt(n: number): Data.Polygon; - getLength(): number; - } - - export class GeometryCollection extends Data.Geometry { - constructor(elements: (Data.Geometry[]|LatLng[]|LatLngLiteral)[]); - getArray(): Data.Geometry[]; - getAt(n: number): Data.Geometry; - getLength(): number; - } - - export interface MouseEvent extends google.maps.MouseEvent { - feature: Data.Feature; - } - - export interface AddFeatureEvent { - feature: Data.Feature; - } - - export interface RemoveFeatureEvent { - feature: Data.Feature; - } - - export interface SetGeometryEvent { - feature: Data.Feature; - newGeometry: Data.Geometry; - oldGeometry: Data.Geometry; - } - - export interface SetPropertyEvent { - feature: Data.Feature; - name: string; - newValue: any; - oldValue: any; - } - - export interface RemovePropertyEvent { - feature: Data.Feature; - name: string; - oldValue: any; - } - } - - /***** Overlays *****/ - export class Marker extends MVCObject { - static MAX_ZINDEX: number; - constructor(opts?: MarkerOptions); - getAnimation(): Animation; - getAttribution(): Attribution; - getClickable(): boolean; - getCursor(): string; - getDraggable(): boolean; - getIcon(): string|Icon|Symbol; - getLabel(): MarkerLabel; - getMap(): Map|StreetViewPanorama; - getOpacity(): number; - getPlace(): Place; - getPosition(): LatLng; - getShape(): MarkerShape; - getTitle(): string; - getVisible(): boolean; - getZIndex(): number; - setAnimation(animation: Animation|null): void; - setAttribution(attribution: Attribution): void; - setClickable(flag: boolean): void; - setCursor(cursor: string): void; - setDraggable(flag: boolean): void; - setIcon(icon: string|Icon|Symbol): void; - setLabel(label: string|MarkerLabel): void; - setMap(map: Map|StreetViewPanorama|null): void; - setOpacity(opacity: number): void; - setOptions(options: MarkerOptions): void; - setPlace(place: Place): void; - setPosition(latlng: LatLng|LatLngLiteral): void; - setShape(shape: MarkerShape): void; - setTitle(title: string): void; - setVisible(visible: boolean): void; - setZIndex(zIndex: number): void; - } - - export interface MarkerOptions { - /** - * The offset from the marker's position to the tip of an InfoWindow - * that has been opened with the marker as anchor. - */ - anchorPoint?: Point; - /** Which animation to play when marker is added to a map. */ - animation?: Animation; - /** - * If true, the marker receives mouse and touch events. - * @default true - */ - clickable?: boolean; - /** Mouse cursor to show on hover. */ - cursor?: string; - /** - * If true, the marker can be dragged. - * @default false - */ - draggable?: boolean; - /** - * Icon for the foreground. - * If a string is provided, it is treated as though it were an Icon with the string as url. - * @type {(string|Icon|Symbol)} - */ - icon?: string|Icon|Symbol; - /** - * Adds a label to the marker. The label can either be a string, or a MarkerLabel object. - * Only the first character of the string will be displayed. - * @type {(string|MarkerLabel)} - */ - label?: string|MarkerLabel; - /** - * Map on which to display Marker. - * @type {(Map|StreetViewPanorama)} - * - */ - map?: Map|StreetViewPanorama; - /** The marker's opacity between 0.0 and 1.0. */ - opacity?: number; - /** - * Optimization renders many markers as a single static element. - * Optimized rendering is enabled by default. - * Disable optimized rendering for animated GIFs or PNGs, or when each - * marker must be rendered as a separate DOM element (advanced usage - * only). - */ - optimized?: boolean; - /** - * Place information, used to identify and describe the place - * associated with this Marker. In this context, 'place' means a - * business, point of interest or geographic location. To allow a user - * to save this place, open an info window anchored on this marker. - * The info window will contain information about the place and an - * option for the user to save it. Only one of position or place can - * be specified. - */ - place?: Place; - /** - * Marker position. Required. - */ - position: LatLng|LatLngLiteral; - /** Image map region definition used for drag/click. */ - shape?: MarkerShape; - /** Rollover text. */ - title?: string; - /** If true, the marker is visible. */ - visible?: boolean; - /** - * All markers are displayed on the map in order of their zIndex, - * with higher values displaying in front of markers with lower values. - * By default, markers are displayed according to their vertical position on screen, - * with lower markers appearing in front of markers further up the screen. - */ - zIndex?: number; - } - - export interface Icon { - /** - * The position at which to anchor an image in correspondence to the - * location of the marker on the map. By default, the anchor is - * located along the center point of the bottom of the image. - */ - anchor?: Point; - /** - * The origin of the label relative to the top-left corner of the icon - * image, if a label is supplied by the marker. By default, the origin - * is located in the center point of the image. - */ - labelOrigin?: Point; - /** - * The position of the image within a sprite, if any. By default, the - * origin is located at the top left corner of the image (0, 0). - */ - origin?: Point; - /** - * The size of the entire image after scaling, if any. Use this - * property to stretch/ shrink an image or a sprite. - */ - scaledSize?: Size; - /** - * The display size of the sprite or image. When using sprites, you - * must specify the sprite size. If the size is not provided, it will - * be set when the image loads. - */ - size?: Size; - /** The URL of the image or sprite sheet. */ - url?: string; - } - - export interface MarkerLabel { - /** The color of the label text. Default color is black. */ - color?: string; - /** The font family of the label text (equivalent to the CSS font-family property). */ - fontFamily?: string; - /** The font size of the label text (equivalent to the CSS font-size property). Default size is 14px. */ - fontSize?: string; - /** The font weight of the label text (equivalent to the CSS font-weight property). */ - fontWeight?: string; - /** The text to be displayed in the label. Only the first character of this string will be shown. */ - text?: string; - } - - export interface MarkerShape { - coords?: number[]; - type?: string; - } - - export interface Symbol { - /** - * The position of the symbol relative to the marker or polyline. - * The coordinates of the symbol's path are translated left and up by the anchor's x and y coordinates respectively. - * By default, a symbol is anchored at (0, 0). - * The position is expressed in the same coordinate system as the symbol's path. - */ - anchor?: Point; - /** - * The symbol's fill color. - * All CSS3 colors are supported except for extended named colors. For symbol markers, this defaults to 'black'. - * For symbols on polylines, this defaults to the stroke color of the corresponding polyline. - */ - fillColor?: string; - /** - * The symbol's fill opacity. - * @default 0 - */ - fillOpacity?: number; - /** - * The symbol's path, which is a built-in symbol path, or a custom path expressed using SVG path notation. Required. - * @type {(SymbolPath|string)} - */ - path?: SymbolPath|string; - /** - * The angle by which to rotate the symbol, expressed clockwise in degrees. - * Defaults to 0. - * A symbol in an IconSequence where fixedRotation is false is rotated relative to the angle of the edge on which it lies. - */ - rotation?: number; - /** - * The amount by which the symbol is scaled in size. - * For symbol markers, this defaults to 1; after scaling, the symbol may be of any size. - * For symbols on a polyline, this defaults to the stroke weight of the polyline; - * after scaling, the symbol must lie inside a square 22 pixels in size centered at the symbol's anchor. - */ - scale?: number; - /** - * The symbol's stroke color. All CSS3 colors are supported except for extended named colors. - * For symbol markers, this defaults to 'black'. - * For symbols on a polyline, this defaults to the stroke color of the polyline. - */ - strokeColor?: string; - /** - * The symbol's stroke opacity. For symbol markers, this defaults to 1. - * For symbols on a polyline, this defaults to the stroke opacity of the polyline. - */ - strokeOpacity?: number; - /** The symbol's stroke weight. Defaults to the scale of the symbol.v*/ - strokeWeight?: number; - } - - /** Built-in symbol paths. */ - export enum SymbolPath { - /** A backward-pointing closed arrow. */ - BACKWARD_CLOSED_ARROW, - /** A backward-pointing open arrow. */ - BACKWARD_OPEN_ARROW, - /** A circle. */ - CIRCLE, - /** A forward-pointing closed arrow. */ - FORWARD_CLOSED_ARROW, - /** A forward-pointing open arrow. */ - FORWARD_OPEN_ARROW - } - - export enum Animation { - BOUNCE, - DROP - } - + clickableIcons?: boolean + /** Enables/disables all default UI. May be overridden individually. */ + disableDefaultUI?: boolean; + /** Enables/disables zoom and center on double click. Enabled by default. */ + disableDoubleClickZoom?: boolean; /** - * An overlay that looks like a bubble and is often connected to a marker. - * This class extends MVCObject. + * If false, prevents the map from being dragged. Dragging is enabled by + * default. */ - export class InfoWindow extends MVCObject { - /** - * Creates an info window with the given options. An InfoWindow can be - * placed on a map at a particular position or above a marker, - * depending on what is specified in the options. Unless auto-pan is - * disabled, an InfoWindow will pan the map to make itself visible - * when it is opened. After constructing an InfoWindow, you must call - * open to display it on the map. The user can click the close button - * on the InfoWindow to remove it from the map, or the developer can - * call close() for the same effect. - */ - constructor(opts?: InfoWindowOptions); - /** Closes this InfoWindow by removing it from the DOM structure. */ - close(): void; - getContent(): string|Element; - getPosition(): LatLng; - getZIndex(): number; - /** - * Opens this InfoWindow on the given map. Optionally, an InfoWindow can be associated with an anchor. - * In the core API, the only anchor is the Marker class. - * However, an anchor can be any MVCObject that exposes a LatLng position property and optionally - * a Point anchorPoint property for calculating the pixelOffset (see InfoWindowOptions). - * The anchorPoint is the offset from the anchor's position to the tip of the InfoWindow. - */ - open(map?: Map|StreetViewPanorama, anchor?: MVCObject): void; - setContent(content: string|Node): void; - setOptions(options: InfoWindowOptions): void; - setPosition(position: LatLng|LatLngLiteral): void; - setZIndex(zIndex: number): void; - } - - export interface InfoWindowOptions { - /** - * Content to display in the InfoWindow. This can be an HTML element, a plain-text string, or a string containing HTML. - * The InfoWindow will be sized according to the content. - * To set an explicit size for the content, set content to be a HTML element with that size. - * @type {(string|Node)} - */ - content?: string|Node; - /** - * Disable auto-pan on open. By default, the info window will pan the map so that it is fully visible when it opens. - */ - disableAutoPan?: boolean; - /** - * Maximum width of the infowindow, regardless of content's width. - * This value is only considered if it is set before a call to open. - * To change the maximum width when changing content, call close, setOptions, and then open. - */ - maxWidth?: number; - /** - * The offset, in pixels, of the tip of the info window from the point on the map - * at whose geographical coordinates the info window is anchored. - * If an InfoWindow is opened with an anchor, the pixelOffset will be calculated from the anchor's anchorPoint property. - */ - pixelOffset?: Size; - /** - * The LatLng at which to display this InfoWindow. If the InfoWindow is opened with an anchor, the anchor's position will be used instead. - */ - position?: LatLng|LatLngLiteral; - /** - * All InfoWindows are displayed on the map in order of their zIndex, - * with higher values displaying in front of InfoWindows with lower values. - * By default, InfoWindows are displayed according to their latitude, - * with InfoWindows of lower latitudes appearing in front of InfoWindows at higher latitudes. - * InfoWindows are always displayed in front of markers. - */ - zIndex?: number; - } - - export class Polyline extends MVCObject { - constructor(opts?: PolylineOptions); - getDraggable(): boolean; - getEditable(): boolean; - getMap(): Map; - getPath(): MVCArray; - getVisible(): boolean; - setDraggable(draggable: boolean): void; - setEditable(editable: boolean): void; - setMap(map: Map | null): void; - setOptions(options: PolylineOptions): void; - setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; - setVisible(visible: boolean): void; - } - - export interface PolylineOptions { - /** Indicates whether this Polyline handles mouse events. Defaults to true. */ - clickable?: boolean; - /** - * If set to true, the user can drag this shape over the map. - * The geodesic property defines the mode of dragging. Defaults to false. - */ - draggable?: boolean; - /** - * If set to true, the user can edit this shape by dragging the control points shown at the vertices and on - * each segment. Defaults to false. - */ - editable?: boolean; - /** - * When true, edges of the polygon are interpreted as geodesic and will follow the curvature of the Earth. - * When false, edges of the polygon are rendered as straight lines in screen space. Note that the shape of a - * geodesic polygon may appear to change when dragged, as the dimensions are maintained relative to the - * surface of the earth. Defaults to false. - */ - geodesic?: boolean; - /** The icons to be rendered along the polyline. */ - icons?: IconSequence[]; - /** Map on which to display Polyline. */ - map?: Map; - /** - * The ordered sequence of coordinates of the Polyline. - * This path may be specified using either a simple array of LatLngs, or an MVCArray of LatLngs. - * Note that if you pass a simple array, it will be converted to an MVCArray Inserting or removing LatLngs - * in the MVCArray will automatically update the polyline on the map. - */ - path?: MVCArray|LatLng[]|LatLngLiteral[]; - /** The stroke color. All CSS3 colors are supported except for extended named colors. */ - strokeColor?: string; - /** The stroke opacity between 0.0 and 1.0. */ - strokeOpacity?: number; - /** The stroke width in pixels. */ - strokeWeight?: number; - /** Whether this polyline is visible on the map. Defaults to true. */ - visible?: boolean; - /** The zIndex compared to other polys. */ - zIndex?: number; - } - - export interface IconSequence { - fixedRotation?: boolean; - icon?: Symbol; - offset?: string; - repeat?: string; - } - - export class Polygon extends MVCObject { - constructor(opts?: PolygonOptions); - getDraggable(): boolean; - getEditable(): boolean; - getMap(): Map; - /** Retrieves the first path. */ - getPath(): MVCArray; - /** Retrieves the paths for this polygon. */ - getPaths(): MVCArray>; - getVisible(): boolean; - setDraggable(draggable: boolean): void; - setEditable(editable: boolean): void; - setMap(map: Map | null): void; - setOptions(options: PolygonOptions): void; - setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; - setPaths(paths: MVCArray> | MVCArray | LatLng[][] | LatLngLiteral[][] | LatLng[] | LatLngLiteral[]): void; - setVisible(visible: boolean): void; - } - - export interface PolygonOptions { - /** Indicates whether this Polygon handles mouse events. Defaults to true. */ - clickable?: boolean; - /** - * If set to true, the user can drag this shape over the map. - * The geodesic property defines the mode of dragging. Defaults to false. - */ - draggable?: boolean; - /** - * If set to true, the user can edit this shape by dragging the control points - * shown at the vertices and on each segment. Defaults to false. - */ - editable?: boolean; - /** The fill color. All CSS3 colors are supported except for extended named colors. */ - fillColor?: string; - /** The fill opacity between 0.0 and 1.0 */ - fillOpacity?: number; - /** - * When true, edges of the polygon are interpreted as geodesic and will follow - * the curvature of the Earth. When false, edges of the polygon are rendered as - * straight lines in screen space. Note that the shape of a geodesic polygon may - * appear to change when dragged, as the dimensions are maintained relative to - * the surface of the earth. Defaults to false. - */ - geodesic?: boolean; - /** Map on which to display Polygon. */ - map?: Map; - /** - * The ordered sequence of coordinates that designates a closed loop. Unlike - * polylines, a polygon may consist of one or more paths. As a result, the paths - * property may specify one or more arrays of LatLng coordinates. Paths are - * closed automatically; do not repeat the first vertex of the path as the last - * vertex. Simple polygons may be defined using a single array of LatLngs. More - * complex polygons may specify an array of arrays. Any simple arrays are - * converted into MVCArrays. Inserting or removing LatLngs from the MVCArray - * will automatically update the polygon on the map. - */ - paths?: MVCArray> | MVCArray | LatLng[][] | LatLngLiteral[][] | LatLng[] | LatLngLiteral[]; - /** - * The stroke color. - * All CSS3 colors are supported except for extended named colors. - */ - strokeColor?: string; - /** The stroke opacity between 0.0 and 1.0 */ - strokeOpacity?: number; - /** - * The stroke position. Defaults to CENTER. - * This property is not supported on Internet Explorer 8 and earlier. - */ - strokePosition?: StrokePosition; - /** The stroke width in pixels. */ - strokeWeight?: number; - /** Whether this polygon is visible on the map. Defaults to true. */ - visible?: boolean; - /** The zIndex compared to other polys. */ - zIndex?: number; - } - - export interface PolyMouseEvent extends MouseEvent { - edge?: number; - path?: number; - vertex?: number; - } - - export class Rectangle extends MVCObject { - constructor(opts?: RectangleOptions); - getBounds(): LatLngBounds; - getDraggable(): boolean; - getEditable(): boolean; - getMap(): Map; - getVisible(): boolean; - setBounds(bounds: LatLngBounds|LatLngBoundsLiteral): void; - setDraggable(draggable: boolean): void; - setEditable(editable: boolean): void; - setMap(map: Map | null): void; - setOptions(options: RectangleOptions): void; - setVisible(visible: boolean): void; - } - - export interface RectangleOptions { - bounds?: LatLngBounds | LatLngBoundsLiteral; - clickable?: boolean; - draggable?: boolean; - editable?: boolean; - fillColor?: string; - fillOpacity?: number; - map?: Map; - strokeColor?: string; - strokeOpacity?: number; - strokePosition?: StrokePosition; - strokeWeight?: number; - visible?: boolean; - zIndex?: number; - } - - /** A circle on the Earth's surface; also known as a "spherical cap". */ - export class Circle extends MVCObject { - /** Create a circle using the passed CircleOptions, which specify the center, radius, and style. */ - constructor(opts?: CircleOptions); - /** Gets the LatLngBounds of this Circle. */ - getBounds(): LatLngBounds; - /** Returns the center of this circle. */ - getCenter(): LatLng; - /** Returns whether this circle can be dragged by the user. */ - getDraggable(): boolean; - /** Returns whether this circle can be edited by the user. */ - getEditable(): boolean; - /** Returns the map on which this circle is displayed. */ - getMap(): Map; - /** Returns the radius of this circle (in meters). */ - getRadius(): number; - /** Returns whether this circle is visible on the map. */ - getVisible(): boolean; - /** Sets the center of this circle. */ - setCenter(center: LatLng|LatLngLiteral): void; - /** If set to true, the user can drag this circle over the map. */ - setDraggable(draggable: boolean): void; - /** - * If set to true, the user can edit this circle by dragging the control points shown at the center and around - * the circumference of the circle. - */ - setEditable(editable: boolean): void; - /** Renders the circle on the specified map. If map is set to null, the circle will be removed. */ - setMap(map: Map | null): void; - setOptions(options: CircleOptions): void; - /** Sets the radius of this circle (in meters). */ - setRadius(radius: number): void; - /** Hides this circle if set to false. */ - setVisible(visible: boolean): void; - } - - export interface CircleOptions { - /** The center */ - center?: LatLng|LatLngLiteral; - /** Indicates whether this Circle handles mouse events. Defaults to true. */ - clickable?: boolean; - /** If set to true, the user can drag this circle over the map. Defaults to false. */ - draggable?: boolean; - /** - * If set to true, the user can edit this circle by dragging the control points shown at the center and around - * the circumference of the circle. Defaults to false. - */ - editable?: boolean; - /** The fill color. All CSS3 colors are supported except for extended named colors. */ - fillColor?: string; - /** The fill opacity between 0.0 and 1.0 */ - fillOpacity?: number; - /** Map on which to display Circle. */ - map?: Map; - /** The radius in meters on the Earth's surface */ - radius?: number; - /** The stroke color. All CSS3 colors are supported except for extended named colors. */ - strokeColor?: string; - /** The stroke opacity between 0.0 and 1.0 */ - strokeOpacity?: number; - /** - * The stroke position. Defaults to CENTER. This property is not supported on Internet Explorer 8 and earlier. - */ - strokePosition?: StrokePosition; - /** The stroke width in pixels. */ - strokeWeight?: number; - /** Whether this circle is visible on the map. Defaults to true. */ - visible?: boolean; - /** The zIndex compared to other polys. */ - zIndex?: number; - } - - export interface CircleLiteral extends CircleOptions { - /** The center of the Circle. */ - center?: LatLng|LatLngLiteral; - /** The radius in meters on the Earth's surface. */ - radius?: number; - } - + draggable?: boolean; /** - * The possible positions of the stroke on a polygon. + * The name or url of the cursor to display when mousing over a draggable + * map. This property uses the css cursor attribute to change the icon. As + * with the css property, you must specify at least one fallback cursor that + * is not a URL. For example: draggableCursor: + * 'url(http://www.example.com/icon.png), auto;'. */ - export enum StrokePosition { - /** - * The stroke is centered on the polygon's path, with half the stroke inside - * the polygon and half the stroke outside the polygon. - */ - CENTER, - /** The stroke lies inside the polygon. */ - INSIDE, - /** The stroke lies outside the polygon. */ - OUTSIDE - } - - export class GroundOverlay extends MVCObject { - constructor(url: string, bounds: LatLngBounds|LatLngBoundsLiteral, opts?: GroundOverlayOptions); - getBounds(): LatLngBounds; - getMap(): Map; - getOpacity(): number; - getUrl(): string; - setMap(map: Map | null): void; - setOpacity(opacity: number): void; - } - - export interface GroundOverlayOptions { - clickable?: boolean; - map?: Map; - opacity?: number; - } - - export class OverlayView extends MVCObject { - draw(): void; - getMap(): Map|StreetViewPanorama; - getPanes(): MapPanes; - getProjection(): MapCanvasProjection; - onAdd(): void; - onRemove(): void; - setMap(map: Map | StreetViewPanorama | null): void; - } - - export interface MapPanes { - floatPane: Element; - floatShadow: Element; - mapPane: Element; - markerLayer: Element; - overlayImage: Element; - overlayLayer: Element; - overlayMouseTarget: Element; - overlayShadow: Element; - } - - export class MapCanvasProjection extends MVCObject { - fromContainerPixelToLatLng(pixel: Point, nowrap?: boolean): LatLng; - fromDivPixelToLatLng(pixel: Point, nowrap?: boolean): LatLng; - fromLatLngToContainerPixel(latLng: LatLng): Point; - fromLatLngToDivPixel(latLng: LatLng): Point; - getWorldWidth(): number; - } - - /***** Services *****/ - export class Geocoder { - geocode(request: GeocoderRequest, callback: (results: GeocoderResult[], status: GeocoderStatus) => void ): void; - } - - export interface GeocoderRequest { - address?: string; - bounds?: LatLngBounds|LatLngBoundsLiteral; - componentRestrictions?: GeocoderComponentRestrictions; - location?: LatLng|LatLngLiteral; - placeId?: string; - region?: string; - } - - export interface GeocoderComponentRestrictions { - administrativeArea?: string; - country?: string | string[]; - locality?: string; - postalCode?: string; - route?: string; - } - - export enum GeocoderStatus { - ERROR, - INVALID_REQUEST, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export interface GeocoderResult { - address_components: GeocoderAddressComponent[]; - formatted_address: string; - geometry: GeocoderGeometry; - partial_match: boolean; - place_id: string; - postcode_localities: string[]; - types: string[]; - } - - export interface GeocoderAddressComponent { - long_name: string; - short_name: string; - types: string[]; - } - - export interface GeocoderGeometry { - bounds: LatLngBounds; - location: LatLng; - location_type: GeocoderLocationType; - viewport: LatLngBounds; - } - - export enum GeocoderLocationType { - APPROXIMATE, - GEOMETRIC_CENTER, - RANGE_INTERPOLATED, - ROOFTOP - } - - export class DirectionsRenderer extends MVCObject { - constructor(opts?: DirectionsRendererOptions); - getDirections(): DirectionsResult; - getMap(): Map; - getPanel(): Element; - getRouteIndex(): number; - setDirections(directions: DirectionsResult): void; - setMap(map: Map | null): void; - setOptions(options: DirectionsRendererOptions): void; - setPanel(panel: Element): void; - setRouteIndex(routeIndex: number): void; - } - - export interface DirectionsRendererOptions { - directions?: DirectionsResult; - draggable?: boolean; - hideRouteList?: boolean; - infoWindow?: InfoWindow; - map?: Map; - markerOptions?: MarkerOptions; - panel?: Element; - polylineOptions?: PolylineOptions; - preserveViewport?: boolean; - routeIndex?: number; - suppressBicyclingLayer?: boolean; - suppressInfoWindows?: boolean; - suppressMarkers?: boolean; - suppressPolylines?: boolean; - } - - export class DirectionsService { - route(request: DirectionsRequest, callback: (result: DirectionsResult, status: DirectionsStatus) => void ): void; - } - - /** A directions query to be sent to the DirectionsService. */ - export interface DirectionsRequest { - /** If true, instructs the Directions service to avoid ferries where possible. Optional. */ - avoidFerries?: boolean; - /** If true, instructs the Directions service to avoid highways where possible. Optional. */ - avoidHighways?: boolean; - /** If true, instructs the Directions service to avoid toll roads where possible. Optional. */ - avoidTolls?: boolean; - /** - * Location of destination. This can be specified as either a string to be geocoded, or a LatLng, - * or a Place. Required. - */ - destination?: string|LatLng|LatLngLiteral|Place; - /** Deprecated. Use drivingOptions field instead */ - durationInTraffic?: boolean; - /** - * Settings that apply only to requests where travelMode is DRIVING. This object will have no effect - * for other travel modes. - */ - drivingOptions?: DrivingOptions; - /** - * If set to true, the DirectionService will attempt to re-order the supplied intermediate waypoints - * to minimize overall cost of the route. If waypoints are optimized, inspect DirectionsRoute.waypoint_order - * in the response to determine the new ordering. - */ - optimizeWaypoints?: boolean; - /** - * Location of origin. This can be specified as either a string to be geocoded, or a LatLng, or a Place. - * Required. - */ - origin?: string|LatLng|LatLngLiteral|Place; - /** Whether or not route alternatives should be provided. Optional. */ - provideRouteAlternatives?: boolean; - /** Region code used as a bias for geocoding requests. Optional. */ - region?: string; - /** - * Settings that apply only to requests where travelMode is TRANSIT. This object will have no effect for - * other travel modes. - */ - transitOptions?: TransitOptions; - /** Type of routing requested. Required. */ - travelMode?: TravelMode; - /** - * Preferred unit system to use when displaying distance. Defaults to the unit system used - * in the country of origin. - */ - unitSystem?: UnitSystem; - /** - * Array of intermediate waypoints. Directions will be calculated from the origin to the destination by way - * of each waypoint in this array. The maximum allowed waypoints is 8, plus the origin, and destination. - * Premium Plan customers are allowed 23 waypoints, plus the origin, and destination. - * Waypoints are not supported for transit directions. Optional. - */ - waypoints?: DirectionsWaypoint[]; - } - - export enum TravelMode { - BICYCLING, - DRIVING, - TRANSIT, - WALKING - } - - export enum UnitSystem { - IMPERIAL, - METRIC - } - - export interface TransitOptions { - arrivalTime?: Date; - departureTime?: Date; - modes?: TransitMode[]; - routingPreference?: TransitRoutePreference; - } - - export enum TransitMode { - BUS, - RAIL, - SUBWAY, - TRAIN, - TRAM - } - - export enum TransitRoutePreference - { - FEWER_TRANSFERS, - LESS_WALKING - } - - export interface TransitFare { } - - export interface DrivingOptions { - departureTime: Date; - trafficModel?: TrafficModel - } - - export enum TrafficModel - { - BEST_GUESS, - OPTIMISTIC, - PESSIMISTIC - } - + draggableCursor?: string; /** - * A DirectionsWaypoint represents a location between origin and destination - * through which the trip should be routed. + * The name or url of the cursor to display when the map is being dragged. + * This property uses the css cursor attribute to change the icon. As with + * the css property, you must specify at least one fallback cursor that is + * not a URL. For example: draggingCursor: + * 'url(http://www.example.com/icon.png), auto;'. */ - export interface DirectionsWaypoint { - /** Waypoint location. Can be an address string, a LatLng, or a Place. Optional. */ - location: LatLng|LatLngLiteral|string; - /** - * If true, indicates that this waypoint is a stop between the origin and destination. - * This has the effect of splitting the route into two legs. If false, indicates that the route - * should be biased to go through this waypoint, but not split into two legs. This is useful - * if you want to create a route in response to the user dragging waypoints on a map. - * This value is true by default. Optional. - */ - stopover: boolean; - } - - export enum DirectionsStatus { - INVALID_REQUEST, - MAX_WAYPOINTS_EXCEEDED, - NOT_FOUND, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export interface DirectionsResult { - geocoded_waypoints: DirectionsGeocodedWaypoint[]; - routes: DirectionsRoute[]; - } - + draggingCursor?: string; + /** The enabled/disabled state of the Fullscreen control. */ + fullscreenControl?: boolean; + /** The display options for the Fullscreen control. */ + fullscreenControlOptions?: FullscreenControlOptions; /** - * A single geocoded waypoint. + * This setting controls how gestures on the map are handled. */ - export interface DirectionsGeocodedWaypoint { - partial_match: boolean; - place_id: string; - types: string[]; - } - + gestureHandling?: GestureHandlingOptions; /** - * A single route containing a set of legs in a DirectionsResult. - * Note that though this object is "JSON-like," it is not strictly JSON, - * as it directly and indirectly includes LatLng objects. + * The heading for aerial imagery in degrees measured clockwise from + * cardinal direction North. Headings are snapped to the nearest available + * angle for which imagery is available. */ - export interface DirectionsRoute { - /** The bounds for this route. */ - bounds: LatLngBounds; - /** Copyrights text to be displayed for this route. */ - copyrights: string; - /** The total fare for the whole transit trip. Only applicable to transit requests. */ - fare: TransitFare; - /** - * An array of DirectionsLegs, each of which contains information about the steps of which it is composed. - * There will be one leg for each stopover waypoint or destination specified. So a route with no stopover - * waypoints will contain one DirectionsLeg and a route with one stopover waypoint will contain two. - */ - legs: DirectionsLeg[]; - /** - * An array of LatLngs representing the entire course of this route. The path is simplified in order to make - * it suitable in contexts where a small number of vertices is required (such as Static Maps API URLs). - */ - overview_path: LatLng[]; - /** - * An encoded polyline representation of the route in overview_path. - * This polyline is an approximate (smoothed) path of the resulting directions. - */ - overview_polyline: string; - /** Warnings to be displayed when showing these directions. */ - warnings: string[]; - /** - * If optimizeWaypoints was set to true, this field will contain the re-ordered permutation - * of the input waypoints. For example, if the input was: - * Origin: Los Angeles - * Waypoints: Dallas, Bangor, Phoenix - * Destination: New York - * and the optimized output was ordered as follows: - * Origin: Los Angeles - * Waypoints: Phoenix, Dallas, Bangor - * Destination: New York - * then this field will be an Array containing the values [2, 0, 1]. Note that the numbering of waypoints - * is zero-based. If any of the input waypoints has stopover set to false, this field will be empty, - * since route optimization is not available for such queries. - */ - waypoint_order: number[]; - } - - export interface DirectionsLeg { - arrival_time: Time; - departure_time: Time; - distance: Distance; - duration: Duration; - duration_in_traffic: Duration; - end_address: string; - end_location: LatLng; - start_address: string; - start_location: LatLng; - steps: DirectionsStep[]; - via_waypoints: LatLng[]; - } - - export interface DirectionsStep { - distance: Distance; - duration: Duration; - end_location: LatLng; - instructions: string; - path: LatLng[]; - start_location: LatLng; - steps: DirectionsStep; - transit: TransitDetails; - travel_mode: TravelMode; - } - - export interface Distance { - text: string; - value: number; - } - - export interface Duration { - text: string; - value: number; - } - - export interface Time { - text: string; - time_zone: string; - value: Date; - } - - export interface TransitDetails { - arrival_stop: TransitStop; - arrival_time: Time; - departure_stop: TransitStop; - departure_time: Time; - headsign: string; - headway: number; - line: TransitLine; - num_stops: number; - } - - export interface TransitStop { - location: LatLng; - name: string; - } - - export interface TransitLine { - agencies: TransitAgency[]; - color: string; - icon: string; - name: string; - short_name: string; - text_color: string; - url: string; - vehicle: TransitVehicle; - } - - export interface TransitAgency { - name: string; - phone: string; - url: string; - } - - export interface TransitVehicle { - icon: string; - local_icon: string; - name: string; - type: VehicleType; - } - - export enum VehicleType - { - BUS, - CABLE_CAR, - COMMUTER_TRAIN, - FERRY, - FUNICULAR, - GONDOLA_LIFT, - HEAVY_RAIL, - HIGH_SPEED_TRAIN, - INTERCITY_BUS, - METRO_RAIL, - MONORAIL, - OTHER, - RAIL, - SHARE_TAXI, - SUBWAY, - TRAM, - TROLLEYBUS - } - - export class ElevationService { - getElevationAlongPath(request: PathElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; - getElevationForLocations(request: LocationElevationRequest, callback: (results: ElevationResult[], status: ElevationStatus) => void ): void; - } - - export interface LocationElevationRequest { - locations: LatLng[]; - } - - export interface PathElevationRequest { - path?: LatLng[]; - samples?: number; - } - - export interface ElevationResult { - elevation: number; - location: LatLng; - resolution: number; - } - - export enum ElevationStatus { - INVALID_REQUEST, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR - } - - export class MaxZoomService { - getMaxZoomAtLatLng(latlng: LatLng|LatLngLiteral, callback: (result: MaxZoomResult) => void ): void; - } - - export interface MaxZoomResult { - status: MaxZoomStatus; - zoom: number; - } - - export enum MaxZoomStatus { - ERROR, - OK - } - - export class DistanceMatrixService { - getDistanceMatrix(request: DistanceMatrixRequest, callback: (response: DistanceMatrixResponse, status: DistanceMatrixStatus) => void ): void; - } - - export interface DistanceMatrixRequest { - avoidFerries?: boolean; - avoidHighways?: boolean; - avoidTolls?: boolean; - destinations?: string[]|LatLng[]|LatLngLiteral[]|Place[]; - drivingOptions?: DrivingOptions; - durationInTraffic?: boolean; - origins?: string[]|LatLng[]|LatLngLiteral[]|Place[]; - region?: string; - transitOptions?: TransitOptions; - travelMode?: TravelMode; - unitSystem?: UnitSystem; - } - - export interface DistanceMatrixResponse { - destinationAddresses: string[]; - originAddresses: string[]; - rows: DistanceMatrixResponseRow[]; - } - - export interface DistanceMatrixResponseRow { - elements: DistanceMatrixResponseElement[]; - } - - export interface DistanceMatrixResponseElement { - distance: Distance; - duration: Duration; - duration_in_traffic: Duration; - fare: TransitFare; - status: DistanceMatrixElementStatus; - } - - export enum DistanceMatrixStatus { - INVALID_REQUEST, - MAX_DIMENSIONS_EXCEEDED, - MAX_ELEMENTS_EXCEEDED, - OK, - OVER_QUERY_LIMIT, - REQUEST_DENIED, - UNKNOWN_ERROR - } - - export enum DistanceMatrixElementStatus { - NOT_FOUND, - OK, - ZERO_RESULTS - } - - /***** Save to Google Maps *****/ - export interface Attribution { - iosDeepLinkId?: string; - source?: string; - webUrl?: string; - } - - export interface Place { - location?: LatLng|LatLngLiteral; - placeId?: string; - query?: string; - } - - export class SaveWidget { - constructor(container: Node, opts?: SaveWidgetOptions); - getAttribution(): Attribution; - getPlace(): Place; - setAttribution(attribution: Attribution): void; - setOptions(opts: SaveWidgetOptions): void; - setPlace(place: Place): void; - } - - export interface SaveWidgetOptions{ - attribution?: Attribution; - place?: Place; - } - - /***** Map Types *****/ - export interface MapType { - getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; - releaseTile(tile: Element): void; - alt?: string; - maxZoom?: number; - minZoom?: number; - name?: string; - projection?: Projection; - radius?: number; - tileSize?: Size; - } - - export class MapTypeRegistry extends MVCObject { - constructor(); - set(id: string, mapType: MapType): void; - } - - export interface Projection { - fromLatLngToPoint(latLng: LatLng, point?: Point): Point; - fromPointToLatLng(pixel: Point, noWrap?: boolean): LatLng; - } - - export class ImageMapType extends MVCObject implements MapType { - constructor(opts: ImageMapTypeOptions); - getOpacity(): number; - getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; - releaseTile(tile: Element): void; - setOpacity(opacity: number): void; - } - - export interface ImageMapTypeOptions { - alt?: string; - getTileUrl(tileCoord: Point, zoom: number): string; - maxZoom?: number; - minZoom?: number; - name?: string; - opacity?: number; - tileSize?: Size; - } - - export class StyledMapType extends MVCObject implements MapType { - constructor(styles: MapTypeStyle[], options?: StyledMapTypeOptions); - getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; - releaseTile(tile: Element): void; - } - - export interface StyledMapTypeOptions { - alt?: string; - maxZoom?: number; - minZoom?: number; - name?: string; - } - - export interface MapTypeStyle { - elementType?: MapTypeStyleElementType; - featureType?: MapTypeStyleFeatureType; - stylers?: MapTypeStyler[]; - } - - export type MapTypeStyleFeatureType = - 'all' | - 'administrative' | - 'administrative.country' | - 'administrative.land_parcel' | - 'administrative.locality' | - 'administrative.neighborhood' | - 'administrative.province' | - 'landscape' | - 'landscape.man_made' | - 'landscape.natural' | - 'landscape.natural.landcover' | - 'landscape.natural.terrain' | - 'poi' | - 'poi.attraction' | - 'poi.business' | - 'poi.government' | - 'poi.medical' | - 'poi.park' | - 'poi.place_of_worship' | - 'poi.school' | - 'poi.sports_complex' | - 'road' | - 'road.arterial' | - 'road.highway' | - 'road.highway.controlled_access' | - 'road.local' | - 'transit' | - 'transit.line' | - 'transit.station' | - 'transit.station.airport' | - 'transit.station.bus' | - 'transit.station.rail' | - 'water'; - - export type MapTypeStyleElementType = - 'all' | - 'geometry' | - 'geometry.fill' | - 'geometry.stroke' | - 'labels' | - 'labels.icon' | - 'labels.text' | - 'labels.text.fill' | - 'labels.text.stroke'; - - export interface MapTypeStyler { - color?: string; - gamma?: number; - hue?: string; - invert_lightness?: boolean; - lightness?: number; - saturation?: number; - visibility?: string; - weight?: number; - } - - /***** Layers *****/ - export class BicyclingLayer extends MVCObject { - constructor(); - getMap(): Map; - setMap(map: Map | null): void; - } - - export class FusionTablesLayer extends MVCObject { - constructor(options: FusionTablesLayerOptions); - getMap(): Map; - setMap(map: Map | null): void; - setOptions(options: FusionTablesLayerOptions): void; - } - - export interface FusionTablesLayerOptions { - clickable?: boolean; - heatmap?: FusionTablesHeatmap; - map?: Map; - query?: FusionTablesQuery; - styles?: FusionTablesStyle[]; - suppressInfoWindows?: boolean; - } - - export interface FusionTablesQuery { - from?: string; - limit?: number; - offset?: number; - orderBy?: string; - select?: string; - where?: string; - } - - export interface FusionTablesStyle { - markerOptions?: FusionTablesMarkerOptions; - polygonOptions?: FusionTablesPolygonOptions; - polylineOptions?: FusionTablesPolylineOptions; - where?: string; - } - - export interface FusionTablesHeatmap { - enabled: boolean; - } - - export interface FusionTablesMarkerOptions { - iconName: string; - } - - export interface FusionTablesPolygonOptions { - fillColor?: string; - fillOpacity?: number; - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - } - - export interface FusionTablesPolylineOptions { - strokeColor?: string; - strokeOpacity?: number; - strokeWeight?: number; - } - - export interface FusionTablesMouseEvent { - infoWindowHtml?: string; - latLng?: LatLng; - pixelOffset?: Size; - row?: Object; // Object - } - - export interface FusionTablesCell { - columnName?: string; - value?: string; - } - - export class KmlLayer extends MVCObject { - constructor(opts?: KmlLayerOptions); - getDefaultViewport(): LatLngBounds; - getMap(): Map; - getMetadata(): KmlLayerMetadata; - getStatus(): KmlLayerStatus; - getUrl(): string; - getZIndex(): number; - setMap(map: Map | null): void; - setUrl(url: string): void; - setZIndex(zIndex: number): void; - setOptions(options: KmlLayerOptions): void; - } - - export interface KmlLayerOptions { - clickable?: boolean; - map?: Map; - preserveViewport?: boolean; - screenOverlays?: boolean; - suppressInfoWindows?: boolean; - url?: string; - zIndex?: number; - } - - export interface KmlLayerMetadata { - author: KmlAuthor; - description: string; - hasScreenOverlays: boolean; - name: string; - snippet: string; - } - - export enum KmlLayerStatus { - DOCUMENT_NOT_FOUND, - DOCUMENT_TOO_LARGE, - FETCH_ERROR, - INVALID_DOCUMENT, - INVALID_REQUEST, - LIMITS_EXCEEDED, - OK, - TIMED_OUT, - UNKNOWN - } - - export interface KmlMouseEvent { - featureData: KmlFeatureData; - latLng: LatLng; - pixelOffset: Size; - } - - export interface KmlFeatureData { - author: KmlAuthor; - description: string; - id: string; - infoWindowHtml: string; - name: string; - snippet: string; - } - - export interface KmlAuthor { - email: string; - name: string; - uri: string; - } - - export class TrafficLayer extends MVCObject { - constructor(opts?: TrafficLayerOptions); - getMap(): Map; - setMap(map: Map | null): void; - setOptions(options: TrafficLayerOptions): void; - } - - export interface TrafficLayerOptions { - autoRefresh?: boolean; - map?: Map; - } - - export class TransitLayer extends MVCObject { - constructor(); - getMap(): void; - setMap(map: Map | null): void; - } - - /***** Street View *****/ - export class StreetViewPanorama extends MVCObject { - constructor(container: Element, opts?: StreetViewPanoramaOptions); - controls: MVCArray[]; - getLinks(): StreetViewLink[]; - getLocation(): StreetViewLocation; - getMotionTracking(): boolean; - getPano(): string; - getPhotographerPov(): StreetViewPov; - getPosition(): LatLng; - getPov(): StreetViewPov; - getStatus(): StreetViewStatus; - getVisible(): boolean; - getZoom(): number; - registerPanoProvider(provider: (input: string) => StreetViewPanoramaData): void; - setLinks(links: Array): void; - setMotionTracking(motionTracking: boolean): void; - setOptions(options: StreetViewPanoramaOptions): void; - setPano(pano: string): void; - setPosition(latLng: LatLng|LatLngLiteral): void; - setPov(pov: StreetViewPov): void; - setVisible(flag: boolean): void; - setZoom(zoom: number): void; - } - - /** Options for the rendering of the fullscreen control. */ - export interface FullscreenControlOptions { - /** - * Position id. Used to specify the position of the control on the map. - * The default position is RIGHT_TOP. - */ - position?: ControlPosition; - } - - export interface StreetViewPanoramaOptions { - addressControl?: boolean; - addressControlOptions?: StreetViewAddressControlOptions; - clickToGo?: boolean; - disableDefaultUI?: boolean; - disableDoubleClickZoom?: boolean; - enableCloseButton?: boolean; - fullscreenControl?: boolean; - fullscreenControlOptions?: FullscreenControlOptions; - imageDateControl?: boolean; - linksControl?: boolean; - motionTracking?: boolean; - motionTrackingControl?: boolean; - motionTrackingControlOptions?: MotionTrackingControlOptions; - mode?: "html4" | "html5" |"webgl"; - panControl?: boolean; - panControlOptions?: PanControlOptions; - pano?: string; - panoProvider?: (input: string) => StreetViewPanoramaData; - position?: LatLng|LatLngLiteral; - pov?: StreetViewPov; - scrollwheel?: boolean; - visible?: boolean; - zoom?: number; - zoomControl?: boolean; - zoomControlOptions?: ZoomControlOptions; - } - - export interface StreetViewAddressControlOptions { - position?: ControlPosition; - } - - export interface StreetViewLink { - description?: string; - heading?: number; - pano?: string; - } - - export interface StreetViewPov { - heading?: number; - pitch?: number; - } - - export interface StreetViewPanoramaData { - copyright?: string; - imageDate?: string; - links?: StreetViewLink[]; - location?: StreetViewLocation; - tiles?: StreetViewTileData; - } - - export interface StreetViewLocation { - description?: string; - latLng?: LatLng; - pano?: string; - shortDescription?: string; - } - - export interface StreetViewTileData { - getTileUrl(pano: string, tileZoom: number, tileX: number, tileY: number): string; - centerHeading?: number; - tileSize?: Size; - worldSize?: Size; - } - - export enum StreetViewPreference { - BEST, - NEAREST - } - - export enum StreetViewSource { - DEFAULT, - OUTDOOR - } - - export interface StreetViewLocationRequest { - location: LatLng|LatLngLiteral; - preference?: StreetViewPreference; - radius?: number; - source?: StreetViewSource; - } - - export interface StreetViewPanoRequest { - pano: string; - } - - export class StreetViewService { - getPanorama(request: StreetViewLocationRequest|StreetViewPanoRequest, cb: (data: StreetViewPanoramaData, status: StreetViewStatus) => void): void; - getPanoramaById(pano: string, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void): void; - getPanoramaByLocation(latlng: LatLng|LatLngLiteral, radius: number, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void ): void; - } - - export enum StreetViewStatus { - OK, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export class StreetViewCoverageLayer extends MVCObject { - getMap(): Map; - setMap(map: Map | null): void; - } - - export interface MotionTrackingControlOptions { - position?: ControlPosition; - } - - /***** Events *****/ - export interface MapsEventListener { - /** Removes the listener. Equivalent to calling google.maps.event.removeListener(listener). */ - remove(): void; - } - - export class event { - /** - * Cross browser event handler registration. This listener is removed by calling - * removeListener(handle) for the handle that is returned by this function. - */ - static addDomListener(instance: Object, eventName: string, handler: Function, capture?: boolean): MapsEventListener; - /** - * Wrapper around addDomListener that removes the listener after the first event. - */ - static addDomListenerOnce(instance: Object, eventName: string, handler: Function, capture?: boolean): MapsEventListener; - /** - * Adds the given listener function to the given event name for the given object - * instance. Returns an identifier for this listener that can be used with - * removeListener(). - */ - static addListener(instance: Object, eventName: string, handler: Function): MapsEventListener; - /** - * Like addListener, but the handler removes itself after handling the first event. - */ - static addListenerOnce(instance: Object, eventName: string, handler: Function): MapsEventListener; - /** - * Removes all listeners for all events for the given instance. - */ - static clearInstanceListeners(instance: Object): void; - /** - * Removes all listeners for the given event for the given instance. - */ - static clearListeners(instance: Object, eventName: string): void; - /** - * Removes the given listener, which should have been returned by addListener above. - * Equivalent to calling listener.remove(). - */ - static removeListener(listener: MapsEventListener): void; - /** - * Triggers the given event. All arguments after eventName are passed as arguments to - * the listeners. - */ - static trigger(instance: any, eventName: string, ...args: any[]): void; - } - + heading?: number; /** - * This object is returned from various mouse events on the map and overlays, - * and contains all the fields shown below. + * If false, prevents the map from being controlled by the keyboard. + * Keyboard shortcuts are enabled by default. */ - export interface MouseEvent { - /** Prevents this event from propagating further. */ - stop(): void; - /** The latitude/longitude that was below the cursor when the event occurred. */ - latLng: LatLng; - } - + keyboardShortcuts?: boolean; + /** The initial enabled/disabled state of the Map type control. */ + mapTypeControl?: boolean; + /** The initial display options for the Map type control. */ + mapTypeControlOptions?: MapTypeControlOptions; + /** The initial Map mapTypeId. Defaults to ROADMAP. */ + mapTypeId?: MapTypeId; /** - * This object is sent in an event when a user clicks on an icon on the map. - * The place ID of this place is stored in the placeId member. - * To prevent the default info window from showing up, call the stop() method on this event to prevent it being - * propagated. Learn more about place IDs in the Places API developer guide. + * The maximum zoom level which will be displayed on the map. If omitted, or + * set to null, the maximum zoom from the current map type is used instead. + * Valid values: Integers between zero, and up to the supported maximum zoom + * level. */ - export interface IconMouseEvent extends MouseEvent { - /** - * The place ID of the place that was clicked. - * This place ID can be used to query more information about the feature that was clicked. - */ - placeId: string; + maxZoom?: number; + /** + * The minimum zoom level which will be displayed on the map. If omitted, or + * set to null, the minimum zoom from the current map type is used instead. + * Valid values: Integers between zero, and up to the supported maximum zoom + * level. + */ + minZoom?: number; + /** If true, do not clear the contents of the Map div. */ + noClear?: boolean; + overviewMapControl?: boolean; + overviewMapControlOptions?: OverviewMapControlOptions; + /** + * The enabled/disabled state of the Pan control. + * Note: The Pan control is not available in the new set of controls + * introduced in v3.22 of the Google Maps JavaScript API. While using v3.22 + * and v3.23, you can choose to use the earlier set of controls rather than + * the new controls, thus making the Pan control available as part of the + * old control set. See {@link + * https://developers.google.com/maps/articles/v322-controls-diff|What's New + * in the v3.22 Map Controls}. + */ + panControl?: boolean; + /** + * The display options for the Pan control. + * Note: The Pan control is not available in the new set of controls + * introduced in v3.22 of the Google Maps JavaScript API. While using v3.22 + * and v3.23, you can choose to use the earlier set of controls rather than + * the new controls, thus making the Pan control available as part of the + * old control set. See {@link + * https://developers.google.com/maps/articles/v322-controls-diff|What's New + * in the v3.22 Map Controls}. + */ + panControlOptions?: PanControlOptions; + /** The enabled/disabled state of the Rotate control. */ + rotateControl?: boolean; + /** The display options for the Rotate control. */ + rotateControlOptions?: RotateControlOptions; + /** The initial enabled/disabled state of the Scale control. */ + scaleControl?: boolean; + /** The initial display options for the Scale control. */ + scaleControlOptions?: ScaleControlOptions; + /** + * If false, disables scrollwheel zooming on the map. The scrollwheel is + * enabled by default. + */ + scrollwheel?: boolean; + /** + * The enabled/disabled state of the sign in control. This option only + * applies if signed_in=true has been passed as a URL parameter in the + * bootstrap request. You may want to use this option to hide the map's sign + * in control if you have provided another way for your users to sign in, + * such as the Google Sign-In button. This option does not affect the + * visibility of the Google avatar shown when the user is already signed in. + */ + signInControl?: boolean; + /** + * A StreetViewPanorama to display when the Street View pegman is dropped on + * the map. If no panorama is specified, a default StreetViewPanorama will + * be displayed in the map's div when the pegman is dropped. + */ + streetView?: StreetViewPanorama; + /** + * The initial enabled/disabled state of the Street View Pegman control. + * This control is part of the default UI, and should be set to false when + * displaying a map type on which the Street View road overlay should not + * appear (e.g. a non-Earth map type). + */ + streetViewControl?: boolean; + /** The initial display options for the Street View Pegman control. */ + streetViewControlOptions?: StreetViewControlOptions; + /** + * Styles to apply to each of the default map types. Note that for + * satellite/hybrid and terrain modes, these styles will only apply to + * labels and geometry. + */ + styles?: MapTypeStyle[]; + /** + * Controls the automatic switching behavior for the angle of incidence of + * the map. The only allowed values are 0 and 45. The value 0 causes the map + * to always use a 0° overhead view regardless of the zoom level and + * viewport. The value 45 causes the tilt angle to automatically switch to + * 45 whenever 45° imagery is available for the current zoom level and + * viewport, and switch back to 0 whenever 45° imagery is not available + * (this is the default behavior). 45° imagery is only available for + * satellite and hybrid map types, within some locations, and at some zoom + * levels. Note: getTilt returns the current tilt angle, not the value + * specified by this option. Because getTilt and this option refer to + * different things, do not bind() the tilt property; doing so may yield + * unpredictable effects. + */ + tilt?: number; + /** + * The initial Map zoom level. Required. Valid values: Integers between + * zero, and up to the supported maximum zoom level. + */ + zoom?: number; + /** The enabled/disabled state of the Zoom control. */ + zoomControl?: boolean; + /** The display options for the Zoom control. */ + zoomControlOptions?: ZoomControlOptions; + } + + /** + * Identifiers for common MapTypes. Specify these by value, or by using the + * constant's name. For example, 'satellite' or + * google.maps.MapTypeId.SATELLITE. + */ + export enum MapTypeId { + /** + This map type displays a transparent layer of major streets on satellite + images. + */ + HYBRID, + /** This map type displays a normal street map. */ + ROADMAP, + /** This map type displays satellite images. */ + SATELLITE, + /** + This map type displays maps with physical features such as terrain and + vegetation. + */ + TERRAIN + } + + /***** Controls *****/ + /** Options for the rendering of the map type control. */ + export interface MapTypeControlOptions { + /** IDs of map types to show in the control. */ + mapTypeIds?: (MapTypeId|string)[]; + /** + * Position id. Used to specify the position of the control on the map. + * The default position is TOP_RIGHT. + */ + position?: ControlPosition; + /** Style id. Used to select what style of map type control to display. */ + style?: MapTypeControlStyle; + } + + export enum MapTypeControlStyle {DEFAULT, DROPDOWN_MENU, HORIZONTAL_BAR} + + export interface OverviewMapControlOptions { + opened?: boolean; + } + + export type GestureHandlingOptions = 'cooperative'|'greedy'|'none'|'auto'; + + /** Options for the rendering of the pan control. */ + export interface PanControlOptions { + /** + * Position id. Used to specify the position of the control on the map. + * The default position is TOP_LEFT. + */ + position?: ControlPosition; + } + + /** Options for the rendering of the rotate control. */ + export interface RotateControlOptions { + /** + * Position id. Used to specify the position of the control on the map. + * The default position is TOP_LEFT. + */ + position?: ControlPosition; + } + + /** Options for the rendering of the scale control. */ + export interface ScaleControlOptions { + /** Style id. Used to select what style of scale control to display. */ + style?: ScaleControlStyle; + } + + export enum ScaleControlStyle {DEFAULT} + + /** Options for the rendering of the Street View pegman control on the map. */ + export interface StreetViewControlOptions { + /** + * Position id. Used to specify the position of the control on the map. The + * default position is embedded within the navigation (zoom and pan) + * controls. If this position is empty or the same as that specified in the + * zoomControlOptions or panControlOptions, the Street View control will be + * displayed as part of the navigation controls. Otherwise, it will be + * displayed separately. + */ + position?: ControlPosition; + } + + /** Options for the rendering of the zoom control. */ + export interface ZoomControlOptions { + /** + * Position id. Used to specify the position of the control on the map. + * The default position is TOP_LEFT. + */ + position?: ControlPosition; + style?: ZoomControlStyle; + } + + export enum ZoomControlStyle {DEFAULT, LARGE, SMALL} + + /** + * Identifiers used to specify the placement of controls on the map. Controls + * are positioned relative to other controls in the same layout position. + * Controls that are added first are positioned closer to the edge of the map. + */ + export enum ControlPosition { + /** Elements are positioned in the center of the bottom row. */ + BOTTOM_CENTER, + /** + * Elements are positioned in the bottom left and flow towards the middle. + * Elements are positioned to the right of the Google logo. + */ + BOTTOM_LEFT, + /** + * Elements are positioned in the bottom right and flow towards the middle. + * Elements are positioned to the left of the copyrights. + */ + BOTTOM_RIGHT, + /** + * Elements are positioned on the left, above bottom-left elements, and flow + * upwards. + */ + LEFT_BOTTOM, + /** Elements are positioned in the center of the left side. */ + LEFT_CENTER, + /** + * Elements are positioned on the left, below top-left elements, and flow + * downwards. + */ + LEFT_TOP, + /** + * Elements are positioned on the right, above bottom-right elements, and + * flow upwards. + */ + RIGHT_BOTTOM, + /** Elements are positioned in the center of the right side. */ + RIGHT_CENTER, + /** + Elements are positioned on the right, below top-right elements, and flow + downwards. + */ + RIGHT_TOP, + /** Elements are positioned in the center of the top row. */ + TOP_CENTER, + /** Elements are positioned in the top left and flow towards the middle. */ + TOP_LEFT, + /** Elements are positioned in the top right and flow towards the middle. */ + TOP_RIGHT + } + + type DrawingMode = 'Point'|'LineString'|'Polygon'; + + /***** Data *****/ + export class Data extends MVCObject { + constructor(options?: Data.DataOptions); + add(feature: Data.Feature|Data.FeatureOptions): Data.Feature; + addGeoJson(geoJson: Object, options?: Data.GeoJsonOptions): Data.Feature[]; + contains(feature: Data.Feature): boolean; + forEach(callback: (feature: Data.Feature) => void): void; + getControlPosition(): ControlPosition; + getControls(): DrawingMode[]; + getDrawingMode(): DrawingMode|null; + getFeatureById(id: number|string): Data.Feature; + getMap(): Map; + getStyle(): Data.StylingFunction|Data.StyleOptions; + loadGeoJson( + url: string, options?: Data.GeoJsonOptions, + callback?: (features: Data.Feature[]) => void): void; + overrideStyle(feature: Data.Feature, style: Data.StyleOptions): void; + remove(feature: Data.Feature): void; + revertStyle(feature?: Data.Feature): void; + setControlPosition(controlPosition: ControlPosition): void; + setControls(controls: DrawingMode[]|null): void; + setDrawingMode(drawingMode: DrawingMode|null): void; + setMap(map: Map|null): void; + setStyle(style: Data.StylingFunction|Data.StyleOptions): void; + toGeoJson(callback: (feature: Object) => void): void; + } + + export module Data { + export interface DataOptions { + controlPosition?: ControlPosition; + controls?: DrawingMode[]|null; + drawingMode?: DrawingMode|null; + featureFactory?: (geometry: Data.Geometry) => Data.Feature; + map?: Map; + style?: Data.StylingFunction|Data.StyleOptions; } - /* **** Base **** */ + export interface GeoJsonOptions { + idPropertyName?: string; + } + export interface StyleOptions { + clickable?: boolean; + cursor?: string; + draggable?: boolean; + editable?: boolean; + fillColor?: string; + fillOpacity?: number; + icon?: string|Icon|Symbol; + shape?: MarkerShape; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + title?: string; + visible?: boolean; + zIndex?: number; + } + + export type StylingFunction = (feature: Data.Feature) => Data.StyleOptions; + + export class Feature { + constructor(options?: Data.FeatureOptions); + forEachProperty(callback: (value: any, name: string) => void): void; + getGeometry(): Data.Geometry; + getId(): number|string; + getProperty(name: string): any; + removeProperty(name: string): void; + setGeometry(newGeometry: Data.Geometry|LatLng|LatLngLiteral): void; + setProperty(name: string, newValue: any): void; + toGeoJson(callback: (feature: Object) => void): void; + } + + export interface FeatureOptions { + geometry?: Data.Geometry|LatLng|LatLngLiteral; + id?: number|string; + properties?: Object; + } + + export class Geometry { + getType(): string; + forEachLatLng(callback: (latLng: LatLng) => void): void; + } + + export class Point extends Data.Geometry { + constructor(latLng: LatLng|LatLngLiteral); + get(): LatLng; + } + + export class MultiPoint extends Data.Geometry { + constructor(elements: (LatLng|LatLngLiteral)[]); + getArray(): LatLng[]; + getAt(n: number): LatLng; + getLength(): number; + } + + export class LineString extends Data.Geometry { + constructor(elements: (LatLng|LatLngLiteral)[]); + getArray(): LatLng[]; + getAt(n: number): LatLng; + getLength(): number; + } + + export class MultiLineString extends Data.Geometry { + constructor(elements: (Data.LineString|(LatLng|LatLngLiteral)[])[]); + getArray(): Data.LineString[]; + getAt(n: number): Data.LineString; + getLength(): number; + } + + export class LinearRing extends Data.Geometry { + constructor(elements: (LatLng|LatLngLiteral)[]); + getArray(): LatLng[]; + getAt(n: number): LatLng; + getLength(): number; + } + + export class Polygon extends Data.Geometry { + constructor(elements: (Data.LinearRing|(LatLng|LatLngLiteral)[])[]); + getArray(): Data.LinearRing[]; + getAt(n: number): Data.LinearRing; + getLength(): number; + } + + export class MultiPolygon extends Data.Geometry { + constructor(elements: (Data.Polygon| + (LinearRing|(LatLng|LatLngLiteral)[])[])[]); + getArray(): Data.Polygon[]; + getAt(n: number): Data.Polygon; + getLength(): number; + } + + export class GeometryCollection extends Data.Geometry { + constructor(elements: (Data.Geometry[]|LatLng[]|LatLngLiteral)[]); + getArray(): Data.Geometry[]; + getAt(n: number): Data.Geometry; + getLength(): number; + } + + export interface MouseEvent extends google.maps.MouseEvent { + feature: Data.Feature; + } + + export interface AddFeatureEvent { + feature: Data.Feature; + } + + export interface RemoveFeatureEvent { + feature: Data.Feature; + } + + export interface SetGeometryEvent { + feature: Data.Feature; + newGeometry: Data.Geometry; + oldGeometry: Data.Geometry; + } + + export interface SetPropertyEvent { + feature: Data.Feature; + name: string; + newValue: any; + oldValue: any; + } + + export interface RemovePropertyEvent { + feature: Data.Feature; + name: string; + oldValue: any; + } + } + + /***** Overlays *****/ + export class Marker extends MVCObject { + static MAX_ZINDEX: number; + constructor(opts?: MarkerOptions); + getAnimation(): Animation; + getAttribution(): Attribution; + getClickable(): boolean; + getCursor(): string; + getDraggable(): boolean; + getIcon(): string|Icon|Symbol; + getLabel(): MarkerLabel; + getMap(): Map|StreetViewPanorama; + getOpacity(): number; + getPlace(): Place; + getPosition(): LatLng; + getShape(): MarkerShape; + getTitle(): string; + getVisible(): boolean; + getZIndex(): number; + setAnimation(animation: Animation|null): void; + setAttribution(attribution: Attribution): void; + setClickable(flag: boolean): void; + setCursor(cursor: string): void; + setDraggable(flag: boolean): void; + setIcon(icon: string|Icon|Symbol): void; + setLabel(label: string|MarkerLabel): void; + setMap(map: Map|StreetViewPanorama|null): void; + setOpacity(opacity: number): void; + setOptions(options: MarkerOptions): void; + setPlace(place: Place): void; + setPosition(latlng: LatLng|LatLngLiteral): void; + setShape(shape: MarkerShape): void; + setTitle(title: string): void; + setVisible(visible: boolean): void; + setZIndex(zIndex: number): void; + } + + export interface MarkerOptions { /** - * A LatLng is a point in geographical coordinates: latitude and longitude. + * The offset from the marker's position to the tip of an InfoWindow + * that has been opened with the marker as anchor. + */ + anchorPoint?: Point; + /** Which animation to play when marker is added to a map. */ + animation?: Animation; + /** + * If true, the marker receives mouse and touch events. + * @default true + */ + clickable?: boolean; + /** Mouse cursor to show on hover. */ + cursor?: string; + /** + * If true, the marker can be dragged. + * @default false + */ + draggable?: boolean; + /** + * Icon for the foreground. + * If a string is provided, it is treated as though it were an Icon with the + * string as url. + * @type {(string|Icon|Symbol)} + */ + icon?: string|Icon|Symbol; + /** + * Adds a label to the marker. The label can either be a string, or a + * MarkerLabel object. Only the first character of the string will be + * displayed. + * @type {(string|MarkerLabel)} + */ + label?: string|MarkerLabel; + /** + * Map on which to display Marker. + * @type {(Map|StreetViewPanorama)} * - * * Latitude ranges between -90 and 90 degrees, inclusive. Values above or - * below this range will be clamped to the range [-90, 90]. This means - * that if the value specified is less than -90, it will be set to -90. - * And if the value is greater than 90, it will be set to 90. - * * Longitude ranges between -180 and 180 degrees, inclusive. Values above - * or below this range will be wrapped so that they fall within the - * range. For example, a value of -190 will be converted to 170. A value - * of 190 will be converted to -170. This reflects the fact that - * longitudes wrap around the globe. - * - * Although the default map projection associates longitude with the - * x-coordinate of the map, and latitude with the y-coordinate, the - * latitude coordinate is always written first, followed by the longitude. - * Notice that you cannot modify the coordinates of a LatLng. If you want - * to compute another point, you have to create a new one. */ - export class LatLng { - /** - * Creates a LatLng object representing a geographic point. - * Note the ordering of latitude and longitude. - * @param lat Latitude is specified in degrees within the range [-90, 90]. - * @param lng Longitude is specified in degrees within the range [-180, 180]. - * @param noWrap Set noWrap to true to enable values outside of this range. - */ - constructor(lat: number, lng: number, noWrap?: boolean); - /** Comparison function. */ - equals(other: LatLng): boolean; - /** Returns the latitude in degrees. */ - lat(): number; - /** Returns the longitude in degrees. */ - lng(): number; - /** Converts to string representation. */ - toString(): string; - /** Returns a string of the form "lat,lng". We round the lat/lng values to 6 decimal places by default. */ - toUrlValue(precision?: number): string; - /** Converts to JSON representation. This function is intended to be used via JSON.stringify. */ - toJSON(): LatLngLiteral; - } + map?: Map|StreetViewPanorama; + /** The marker's opacity between 0.0 and 1.0. */ + opacity?: number; + /** + * Optimization renders many markers as a single static element. + * Optimized rendering is enabled by default. + * Disable optimized rendering for animated GIFs or PNGs, or when each + * marker must be rendered as a separate DOM element (advanced usage + * only). + */ + optimized?: boolean; + /** + * Place information, used to identify and describe the place + * associated with this Marker. In this context, 'place' means a + * business, point of interest or geographic location. To allow a user + * to save this place, open an info window anchored on this marker. + * The info window will contain information about the place and an + * option for the user to save it. Only one of position or place can + * be specified. + */ + place?: Place; + /** + * Marker position. Required. + */ + position: LatLng|LatLngLiteral; + /** Image map region definition used for drag/click. */ + shape?: MarkerShape; + /** Rollover text. */ + title?: string; + /** If true, the marker is visible. */ + visible?: boolean; + /** + * All markers are displayed on the map in order of their zIndex, + * with higher values displaying in front of markers with lower values. + * By default, markers are displayed according to their vertical position on + * screen, with lower markers appearing in front of markers further up the + * screen. + */ + zIndex?: number; + } - export type LatLngLiteral = { lat: number; lng: number } - export type LatLngBoundsLiteral = { east: number; north: number; south: number; west: number } + export interface Icon { + /** + * The position at which to anchor an image in correspondence to the + * location of the marker on the map. By default, the anchor is + * located along the center point of the bottom of the image. + */ + anchor?: Point; + /** + * The origin of the label relative to the top-left corner of the icon + * image, if a label is supplied by the marker. By default, the origin + * is located in the center point of the image. + */ + labelOrigin?: Point; + /** + * The position of the image within a sprite, if any. By default, the + * origin is located at the top left corner of the image (0, 0). + */ + origin?: Point; + /** + * The size of the entire image after scaling, if any. Use this + * property to stretch/ shrink an image or a sprite. + */ + scaledSize?: Size; + /** + * The display size of the sprite or image. When using sprites, you + * must specify the sprite size. If the size is not provided, it will + * be set when the image loads. + */ + size?: Size; + /** The URL of the image or sprite sheet. */ + url?: string; + } + + export interface MarkerLabel { + /** The color of the label text. Default color is black. */ + color?: string; + /** + * The font family of the label text (equivalent to the CSS font-family + * property). + */ + fontFamily?: string; + /** + * The font size of the label text (equivalent to the CSS font-size + * property). Default size is 14px. + */ + fontSize?: string; + /** + * The font weight of the label text (equivalent to the CSS font-weight + * property). + */ + fontWeight?: string; + /** + * The text to be displayed in the label. Only the first character of this + * string will be shown. + */ + text?: string; + } + + export interface MarkerShape { + coords?: number[]; + type?: string; + } + + export interface Symbol { + /** + * The position of the symbol relative to the marker or polyline. + * The coordinates of the symbol's path are translated left and up by the + * anchor's x and y coordinates respectively. By default, a symbol is + * anchored at (0, 0). The position is expressed in the same coordinate + * system as the symbol's path. + */ + anchor?: Point; + /** + * The symbol's fill color. + * All CSS3 colors are supported except for extended named colors. For + * symbol markers, this defaults to 'black'. For symbols on polylines, this + * defaults to the stroke color of the corresponding polyline. + */ + fillColor?: string; + /** + * The symbol's fill opacity. + * @default 0 + */ + fillOpacity?: number; + /** + * The symbol's path, which is a built-in symbol path, or a custom path + * expressed using SVG path notation. Required. + * @type {(SymbolPath|string)} + */ + path?: SymbolPath|string; + /** + * The angle by which to rotate the symbol, expressed clockwise in degrees. + * Defaults to 0. + * A symbol in an IconSequence where fixedRotation is false is rotated + * relative to the angle of the edge on which it lies. + */ + rotation?: number; + /** + * The amount by which the symbol is scaled in size. + * For symbol markers, this defaults to 1; after scaling, the symbol may be + * of any size. For symbols on a polyline, this defaults to the stroke + * weight of the polyline; after scaling, the symbol must lie inside a + * square 22 pixels in size centered at the symbol's anchor. + */ + scale?: number; + /** + * The symbol's stroke color. All CSS3 colors are supported except for + * extended named colors. For symbol markers, this defaults to 'black'. For + * symbols on a polyline, this defaults to the stroke color of the polyline. + */ + strokeColor?: string; + /** + * The symbol's stroke opacity. For symbol markers, this defaults to 1. + * For symbols on a polyline, this defaults to the stroke opacity of the + * polyline. + */ + strokeOpacity?: number; + /** The symbol's stroke weight. Defaults to the scale of the symbol.v*/ + strokeWeight?: number; + } + + /** Built-in symbol paths. */ + export enum SymbolPath { + /** A backward-pointing closed arrow. */ + BACKWARD_CLOSED_ARROW, + /** A backward-pointing open arrow. */ + BACKWARD_OPEN_ARROW, + /** A circle. */ + CIRCLE, + /** A forward-pointing closed arrow. */ + FORWARD_CLOSED_ARROW, + /** A forward-pointing open arrow. */ + FORWARD_OPEN_ARROW + } + + export enum Animation {BOUNCE, DROP} + + /** + * An overlay that looks like a bubble and is often connected to a marker. + * This class extends MVCObject. + */ + export class InfoWindow extends MVCObject { + /** + * Creates an info window with the given options. An InfoWindow can be + * placed on a map at a particular position or above a marker, + * depending on what is specified in the options. Unless auto-pan is + * disabled, an InfoWindow will pan the map to make itself visible + * when it is opened. After constructing an InfoWindow, you must call + * open to display it on the map. The user can click the close button + * on the InfoWindow to remove it from the map, or the developer can + * call close() for the same effect. + */ + constructor(opts?: InfoWindowOptions); + /** Closes this InfoWindow by removing it from the DOM structure. */ + close(): void; + getContent(): string|Element; + getPosition(): LatLng; + getZIndex(): number; + /** + * Opens this InfoWindow on the given map. Optionally, an InfoWindow can be + * associated with an anchor. In the core API, the only anchor is the Marker + * class. However, an anchor can be any MVCObject that exposes a LatLng + * position property and optionally a Point anchorPoint property for + * calculating the pixelOffset (see InfoWindowOptions). The anchorPoint is + * the offset from the anchor's position to the tip of the InfoWindow. + */ + open(map?: Map|StreetViewPanorama, anchor?: MVCObject): void; + setContent(content: string|Node): void; + setOptions(options: InfoWindowOptions): void; + setPosition(position: LatLng|LatLngLiteral): void; + setZIndex(zIndex: number): void; + } + + export interface InfoWindowOptions { + /** + * Content to display in the InfoWindow. This can be an HTML element, a + * plain-text string, or a string containing HTML. The InfoWindow will be + * sized according to the content. To set an explicit size for the content, + * set content to be a HTML element with that size. + * @type {(string|Node)} + */ + content?: string|Node; + /** + * Disable auto-pan on open. By default, the info window will pan the map so + * that it is fully visible when it opens. + */ + disableAutoPan?: boolean; + /** + * Maximum width of the infowindow, regardless of content's width. + * This value is only considered if it is set before a call to open. + * To change the maximum width when changing content, call close, + * setOptions, and then open. + */ + maxWidth?: number; + /** + * The offset, in pixels, of the tip of the info window from the point on + * the map at whose geographical coordinates the info window is anchored. If + * an InfoWindow is opened with an anchor, the pixelOffset will be + * calculated from the anchor's anchorPoint property. + */ + pixelOffset?: Size; + /** + * The LatLng at which to display this InfoWindow. If the InfoWindow is + * opened with an anchor, the anchor's position will be used instead. + */ + position?: LatLng|LatLngLiteral; + /** + * All InfoWindows are displayed on the map in order of their zIndex, + * with higher values displaying in front of InfoWindows with lower values. + * By default, InfoWindows are displayed according to their latitude, + * with InfoWindows of lower latitudes appearing in front of InfoWindows at + * higher latitudes. InfoWindows are always displayed in front of markers. + */ + zIndex?: number; + } + + export class Polyline extends MVCObject { + constructor(opts?: PolylineOptions); + getDraggable(): boolean; + getEditable(): boolean; + getMap(): Map; + getPath(): MVCArray; + getVisible(): boolean; + setDraggable(draggable: boolean): void; + setEditable(editable: boolean): void; + setMap(map: Map|null): void; + setOptions(options: PolylineOptions): void; + setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; + setVisible(visible: boolean): void; + } + + export interface PolylineOptions { + /** + * Indicates whether this Polyline handles mouse events. Defaults to true. + */ + clickable?: boolean; + /** + * If set to true, the user can drag this shape over the map. + * The geodesic property defines the mode of dragging. Defaults to false. + */ + draggable?: boolean; + /** + * If set to true, the user can edit this shape by dragging the control + * points shown at the vertices and on each segment. Defaults to false. + */ + editable?: boolean; + /** + * When true, edges of the polygon are interpreted as geodesic and will + * follow the curvature of the Earth. When false, edges of the polygon are + * rendered as straight lines in screen space. Note that the shape of a + * geodesic polygon may appear to change when dragged, as the dimensions are + * maintained relative to the surface of the earth. Defaults to false. + */ + geodesic?: boolean; + /** The icons to be rendered along the polyline. */ + icons?: IconSequence[]; + /** Map on which to display Polyline. */ + map?: Map; + /** + * The ordered sequence of coordinates of the Polyline. + * This path may be specified using either a simple array of LatLngs, or an + * MVCArray of LatLngs. Note that if you pass a simple array, it will be + * converted to an MVCArray Inserting or removing LatLngs in the MVCArray + * will automatically update the polyline on the map. + */ + path?: MVCArray|LatLng[]|LatLngLiteral[]; + /** + * The stroke color. All CSS3 colors are supported except for extended + * named colors. + */ + strokeColor?: string; + /** The stroke opacity between 0.0 and 1.0. */ + strokeOpacity?: number; + /** The stroke width in pixels. */ + strokeWeight?: number; + /** Whether this polyline is visible on the map. Defaults to true. */ + visible?: boolean; + /** The zIndex compared to other polys. */ + zIndex?: number; + } + + export interface IconSequence { + fixedRotation?: boolean; + icon?: Symbol; + offset?: string; + repeat?: string; + } + + export class Polygon extends MVCObject { + constructor(opts?: PolygonOptions); + getDraggable(): boolean; + getEditable(): boolean; + getMap(): Map; + /** Retrieves the first path. */ + getPath(): MVCArray; + /** Retrieves the paths for this polygon. */ + getPaths(): MVCArray>; + getVisible(): boolean; + setDraggable(draggable: boolean): void; + setEditable(editable: boolean): void; + setMap(map: Map|null): void; + setOptions(options: PolygonOptions): void; + setPath(path: MVCArray|LatLng[]|LatLngLiteral[]): void; + setPaths(paths: MVCArray>|MVCArray|LatLng[][]| + LatLngLiteral[][]|LatLng[]|LatLngLiteral[]): void; + setVisible(visible: boolean): void; + } + + export interface PolygonOptions { + /** + * Indicates whether this Polygon handles mouse events. Defaults to true. + */ + clickable?: boolean; + /** + * If set to true, the user can drag this shape over the map. + * The geodesic property defines the mode of dragging. Defaults to false. + */ + draggable?: boolean; + /** + * If set to true, the user can edit this shape by dragging the control + * points shown at the vertices and on each segment. Defaults to false. + */ + editable?: boolean; + /** + * The fill color. All CSS3 colors are supported except for extended named + * colors. + */ + fillColor?: string; + /** The fill opacity between 0.0 and 1.0 */ + fillOpacity?: number; + /** + * When true, edges of the polygon are interpreted as geodesic and will + * follow the curvature of the Earth. When false, edges of the polygon are + * rendered as straight lines in screen space. Note that the shape of a + * geodesic polygon may appear to change when dragged, as the dimensions are + * maintained relative to the surface of the earth. Defaults to false. + */ + geodesic?: boolean; + /** Map on which to display Polygon. */ + map?: Map; + /** + * The ordered sequence of coordinates that designates a closed loop. Unlike + * polylines, a polygon may consist of one or more paths. As a result, the + * paths property may specify one or more arrays of LatLng coordinates. + * Paths are closed automatically; do not repeat the first vertex of the + * path as the last vertex. Simple polygons may be defined using a single + * array of LatLngs. More complex polygons may specify an array of arrays. + * Any simple arrays are converted into MVCArrays. Inserting or removing + * LatLngs from the MVCArray will automatically update the polygon on the + * map. + */ + paths?: MVCArray>|MVCArray|LatLng[][]| + LatLngLiteral[][]|LatLng[]|LatLngLiteral[]; + /** + * The stroke color. + * All CSS3 colors are supported except for extended named colors. + */ + strokeColor?: string; + /** The stroke opacity between 0.0 and 1.0 */ + strokeOpacity?: number; + /** + * The stroke position. Defaults to CENTER. + * This property is not supported on Internet Explorer 8 and earlier. + */ + strokePosition?: StrokePosition; + /** The stroke width in pixels. */ + strokeWeight?: number; + /** Whether this polygon is visible on the map. Defaults to true. */ + visible?: boolean; + /** The zIndex compared to other polys. */ + zIndex?: number; + } + + export interface PolyMouseEvent extends MouseEvent { + edge?: number; + path?: number; + vertex?: number; + } + + export class Rectangle extends MVCObject { + constructor(opts?: RectangleOptions); + getBounds(): LatLngBounds; + getDraggable(): boolean; + getEditable(): boolean; + getMap(): Map; + getVisible(): boolean; + setBounds(bounds: LatLngBounds|LatLngBoundsLiteral): void; + setDraggable(draggable: boolean): void; + setEditable(editable: boolean): void; + setMap(map: Map|null): void; + setOptions(options: RectangleOptions): void; + setVisible(visible: boolean): void; + } + + export interface RectangleOptions { + bounds?: LatLngBounds|LatLngBoundsLiteral; + clickable?: boolean; + draggable?: boolean; + editable?: boolean; + fillColor?: string; + fillOpacity?: number; + map?: Map; + strokeColor?: string; + strokeOpacity?: number; + strokePosition?: StrokePosition; + strokeWeight?: number; + visible?: boolean; + zIndex?: number; + } + + /** A circle on the Earth's surface; also known as a "spherical cap". */ + export class Circle extends MVCObject { + /** + * Create a circle using the passed CircleOptions, which specify the + * center, radius, and style. + */ + constructor(opts?: CircleOptions); + /** Gets the LatLngBounds of this Circle. */ + getBounds(): LatLngBounds; + /** Returns the center of this circle. */ + getCenter(): LatLng; + /** Returns whether this circle can be dragged by the user. */ + getDraggable(): boolean; + /** Returns whether this circle can be edited by the user. */ + getEditable(): boolean; + /** Returns the map on which this circle is displayed. */ + getMap(): Map; + /** Returns the radius of this circle (in meters). */ + getRadius(): number; + /** Returns whether this circle is visible on the map. */ + getVisible(): boolean; + /** Sets the center of this circle. */ + setCenter(center: LatLng|LatLngLiteral): void; + /** If set to true, the user can drag this circle over the map. */ + setDraggable(draggable: boolean): void; + /** + * If set to true, the user can edit this circle by dragging the control + * points shown at the center and around the circumference of the circle. + */ + setEditable(editable: boolean): void; + /** + * Renders the circle on the specified map. If map is set to null, the + * circle will be removed. + */ + setMap(map: Map|null): void; + setOptions(options: CircleOptions): void; + /** Sets the radius of this circle (in meters). */ + setRadius(radius: number): void; + /** Hides this circle if set to false. */ + setVisible(visible: boolean): void; + } + + export interface CircleOptions { + /** The center */ + center?: LatLng|LatLngLiteral; + /** Indicates whether this Circle handles mouse events. Defaults to true. */ + clickable?: boolean; + /** + * If set to true, the user can drag this circle over the map. Defaults to + * false. + */ + draggable?: boolean; + /** + * If set to true, the user can edit this circle by dragging the control + * points shown at the center and around the circumference of the circle. + * Defaults to false. + */ + editable?: boolean; + /** + * The fill color. All CSS3 colors are supported except for extended named + * colors. + */ + fillColor?: string; + /** The fill opacity between 0.0 and 1.0 */ + fillOpacity?: number; + /** Map on which to display Circle. */ + map?: Map; + /** The radius in meters on the Earth's surface */ + radius?: number; + /** + * The stroke color. All CSS3 colors are supported except for extended + * named colors. + */ + strokeColor?: string; + /** The stroke opacity between 0.0 and 1.0 */ + strokeOpacity?: number; + /** + * The stroke position. Defaults to CENTER. This property is not supported + * on Internet Explorer 8 and earlier. + */ + strokePosition?: StrokePosition; + /** The stroke width in pixels. */ + strokeWeight?: number; + /** Whether this circle is visible on the map. Defaults to true. */ + visible?: boolean; + /** The zIndex compared to other polys. */ + zIndex?: number; + } + + export interface CircleLiteral extends CircleOptions { + /** The center of the Circle. */ + center?: LatLng|LatLngLiteral; + /** The radius in meters on the Earth's surface. */ + radius?: number; + } + + /** + * The possible positions of the stroke on a polygon. + */ + export enum StrokePosition { + /** + * The stroke is centered on the polygon's path, with half the stroke inside + * the polygon and half the stroke outside the polygon. + */ + CENTER, + /** The stroke lies inside the polygon. */ + INSIDE, + /** The stroke lies outside the polygon. */ + OUTSIDE + } + + export class GroundOverlay extends MVCObject { + constructor( + url: string, bounds: LatLngBounds|LatLngBoundsLiteral, + opts?: GroundOverlayOptions); + getBounds(): LatLngBounds; + getMap(): Map; + getOpacity(): number; + getUrl(): string; + setMap(map: Map|null): void; + setOpacity(opacity: number): void; + } + + export interface GroundOverlayOptions { + clickable?: boolean; + map?: Map; + opacity?: number; + } + + export class OverlayView extends MVCObject { + draw(): void; + getMap(): Map|StreetViewPanorama; + getPanes(): MapPanes; + getProjection(): MapCanvasProjection; + onAdd(): void; + onRemove(): void; + setMap(map: Map|StreetViewPanorama|null): void; + } + + export interface MapPanes { + floatPane: Element; + floatShadow: Element; + mapPane: Element; + markerLayer: Element; + overlayImage: Element; + overlayLayer: Element; + overlayMouseTarget: Element; + overlayShadow: Element; + } + + export class MapCanvasProjection extends MVCObject { + fromContainerPixelToLatLng(pixel: Point, nowrap?: boolean): LatLng; + fromDivPixelToLatLng(pixel: Point, nowrap?: boolean): LatLng; + fromLatLngToContainerPixel(latLng: LatLng): Point; + fromLatLngToDivPixel(latLng: LatLng): Point; + getWorldWidth(): number; + } + + /***** Services *****/ + export class Geocoder { + geocode( + request: GeocoderRequest, + callback: (results: GeocoderResult[], status: GeocoderStatus) => void): + void; + } + + export interface GeocoderRequest { + address?: string; + bounds?: LatLngBounds|LatLngBoundsLiteral; + componentRestrictions?: GeocoderComponentRestrictions; + location?: LatLng|LatLngLiteral; + placeId?: string; + region?: string; + } + + export interface GeocoderComponentRestrictions { + administrativeArea?: string; + country?: string|string[]; + locality?: string; + postalCode?: string; + route?: string; + } + + export enum GeocoderStatus { + ERROR, + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface GeocoderResult { + address_components: GeocoderAddressComponent[]; + formatted_address: string; + geometry: GeocoderGeometry; + partial_match: boolean; + place_id: string; + postcode_localities: string[]; + types: string[]; + } + + export interface GeocoderAddressComponent { + long_name: string; + short_name: string; + types: string[]; + } + + export interface GeocoderGeometry { + bounds: LatLngBounds; + location: LatLng; + location_type: GeocoderLocationType; + viewport: LatLngBounds; + } + + export enum GeocoderLocationType { + APPROXIMATE, + GEOMETRIC_CENTER, + RANGE_INTERPOLATED, + ROOFTOP + } + + export class DirectionsRenderer extends MVCObject { + constructor(opts?: DirectionsRendererOptions); + getDirections(): DirectionsResult; + getMap(): Map; + getPanel(): Element; + getRouteIndex(): number; + setDirections(directions: DirectionsResult): void; + setMap(map: Map|null): void; + setOptions(options: DirectionsRendererOptions): void; + setPanel(panel: Element): void; + setRouteIndex(routeIndex: number): void; + } + + export interface DirectionsRendererOptions { + directions?: DirectionsResult; + draggable?: boolean; + hideRouteList?: boolean; + infoWindow?: InfoWindow; + map?: Map; + markerOptions?: MarkerOptions; + panel?: Element; + polylineOptions?: PolylineOptions; + preserveViewport?: boolean; + routeIndex?: number; + suppressBicyclingLayer?: boolean; + suppressInfoWindows?: boolean; + suppressMarkers?: boolean; + suppressPolylines?: boolean; + } + + export class DirectionsService { + route( + request: DirectionsRequest, + callback: (result: DirectionsResult, status: DirectionsStatus) => void): + void; + } + + /** A directions query to be sent to the DirectionsService. */ + export interface DirectionsRequest { + /** + * If true, instructs the Directions service to avoid ferries where + * possible. Optional. + */ + avoidFerries?: boolean; + /** + * If true, instructs the Directions service to avoid highways where + * possible. Optional. + */ + avoidHighways?: boolean; + /** + * If true, instructs the Directions service to avoid toll roads where + * possible. Optional. + */ + avoidTolls?: boolean; + /** + * Location of destination. This can be specified as either a string to be + * geocoded, or a LatLng, or a Place. Required. + */ + destination?: string|LatLng|LatLngLiteral|Place; + /** Deprecated. Use drivingOptions field instead */ + durationInTraffic?: boolean; + /** + * Settings that apply only to requests where travelMode is DRIVING. This + * object will have no effect for other travel modes. + */ + drivingOptions?: DrivingOptions; + /** + * If set to true, the DirectionService will attempt to re-order the + * supplied intermediate waypoints to minimize overall cost of the route. If + * waypoints are optimized, inspect DirectionsRoute.waypoint_order in the + * response to determine the new ordering. + */ + optimizeWaypoints?: boolean; + /** + * Location of origin. This can be specified as either a string to be + * geocoded, or a LatLng, or a Place. Required. + */ + origin?: string|LatLng|LatLngLiteral|Place; + /** Whether or not route alternatives should be provided. Optional. */ + provideRouteAlternatives?: boolean; + /** Region code used as a bias for geocoding requests. Optional. */ + region?: string; + /** + * Settings that apply only to requests where travelMode is TRANSIT. This + * object will have no effect for other travel modes. + */ + transitOptions?: TransitOptions; + /** Type of routing requested. Required. */ + travelMode?: TravelMode; + /** + * Preferred unit system to use when displaying distance. Defaults to the + * unit system used in the country of origin. + */ + unitSystem?: UnitSystem; + /** + * Array of intermediate waypoints. Directions will be calculated from the + * origin to the destination by way of each waypoint in this array. The + * maximum allowed waypoints is 8, plus the origin, and destination. Premium + * Plan customers are allowed 23 waypoints, plus the origin, and + * destination. Waypoints are not supported for transit directions. + * Optional. + */ + waypoints?: DirectionsWaypoint[]; + } + + export enum TravelMode {BICYCLING, DRIVING, TRANSIT, WALKING} + + export enum UnitSystem {IMPERIAL, METRIC} + + export interface TransitOptions { + arrivalTime?: Date; + departureTime?: Date; + modes?: TransitMode[]; + routingPreference?: TransitRoutePreference; + } + + export enum TransitMode {BUS, RAIL, SUBWAY, TRAIN, TRAM} + + export enum TransitRoutePreference {FEWER_TRANSFERS, LESS_WALKING} + + export interface TransitFare {} + + export interface DrivingOptions { + departureTime: Date; + trafficModel?: TrafficModel + } + + export enum TrafficModel {BEST_GUESS, OPTIMISTIC, PESSIMISTIC} + + /** + * A DirectionsWaypoint represents a location between origin and destination + * through which the trip should be routed. + */ + export interface DirectionsWaypoint { + /** + * Waypoint location. Can be an address string, a LatLng, or a Place. + * Optional. + */ + location: LatLng|LatLngLiteral|string; + /** + * If true, indicates that this waypoint is a stop between the origin and + * destination. This has the effect of splitting the route into two legs. If + * false, indicates that the route should be biased to go through this + * waypoint, but not split into two legs. This is useful if you want to + * create a route in response to the user dragging waypoints on a map. This + * value is true by default. Optional. + */ + stopover: boolean; + } + + export enum DirectionsStatus { + INVALID_REQUEST, + MAX_WAYPOINTS_EXCEEDED, + NOT_FOUND, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface DirectionsResult { + geocoded_waypoints: DirectionsGeocodedWaypoint[]; + routes: DirectionsRoute[]; + } + + /** + * A single geocoded waypoint. + */ + export interface DirectionsGeocodedWaypoint { + partial_match: boolean; + place_id: string; + types: string[]; + } + + /** + * A single route containing a set of legs in a DirectionsResult. + * Note that though this object is "JSON-like," it is not strictly JSON, + * as it directly and indirectly includes LatLng objects. + */ + export interface DirectionsRoute { + /** The bounds for this route. */ + bounds: LatLngBounds; + /** Copyrights text to be displayed for this route. */ + copyrights: string; + /** + * The total fare for the whole transit trip. Only applicable to transit + * requests. + */ + fare: TransitFare; + /** + * An array of DirectionsLegs, each of which contains information about the + * steps of which it is composed. There will be one leg for each stopover + * waypoint or destination specified. So a route with no stopover waypoints + * will contain one DirectionsLeg and a route with one stopover waypoint + * will contain two. + */ + legs: DirectionsLeg[]; + /** + * An array of LatLngs representing the entire course of this route. The + * path is simplified in order to make it suitable in contexts where a small + * number of vertices is required (such as Static Maps API URLs). + */ + overview_path: LatLng[]; + /** + * An encoded polyline representation of the route in overview_path. + * This polyline is an approximate (smoothed) path of the resulting + * directions. + */ + overview_polyline: string; + /** Warnings to be displayed when showing these directions. */ + warnings: string[]; + /** + * If optimizeWaypoints was set to true, this field will contain the + * re-ordered permutation of the input waypoints. For example, if the input + * was: Origin: Los Angeles Waypoints: Dallas, Bangor, Phoenix Destination: + * New York and the optimized output was ordered as follows: Origin: Los + * Angeles Waypoints: Phoenix, Dallas, Bangor Destination: New York then + * this field will be an Array containing the values [2, 0, 1]. Note that + * the numbering of waypoints is zero-based. If any of the input waypoints + * has stopover set to false, this field will be empty, since route + * optimization is not available for such queries. + */ + waypoint_order: number[]; + } + + export interface DirectionsLeg { + arrival_time: Time; + departure_time: Time; + distance: Distance; + duration: Duration; + duration_in_traffic: Duration; + end_address: string; + end_location: LatLng; + start_address: string; + start_location: LatLng; + steps: DirectionsStep[]; + via_waypoints: LatLng[]; + } + + export interface DirectionsStep { + distance: Distance; + duration: Duration; + end_location: LatLng; + instructions: string; + path: LatLng[]; + start_location: LatLng; + steps: DirectionsStep; + transit: TransitDetails; + travel_mode: TravelMode; + } + + export interface Distance { + text: string; + value: number; + } + + export interface Duration { + text: string; + value: number; + } + + export interface Time { + text: string; + time_zone: string; + value: Date; + } + + export interface TransitDetails { + arrival_stop: TransitStop; + arrival_time: Time; + departure_stop: TransitStop; + departure_time: Time; + headsign: string; + headway: number; + line: TransitLine; + num_stops: number; + } + + export interface TransitStop { + location: LatLng; + name: string; + } + + export interface TransitLine { + agencies: TransitAgency[]; + color: string; + icon: string; + name: string; + short_name: string; + text_color: string; + url: string; + vehicle: TransitVehicle; + } + + export interface TransitAgency { + name: string; + phone: string; + url: string; + } + + export interface TransitVehicle { + icon: string; + local_icon: string; + name: string; + type: VehicleType; + } + + export enum VehicleType { + BUS, + CABLE_CAR, + COMMUTER_TRAIN, + FERRY, + FUNICULAR, + GONDOLA_LIFT, + HEAVY_RAIL, + HIGH_SPEED_TRAIN, + INTERCITY_BUS, + METRO_RAIL, + MONORAIL, + OTHER, + RAIL, + SHARE_TAXI, + SUBWAY, + TRAM, + TROLLEYBUS + } + + export class ElevationService { + getElevationAlongPath( + request: PathElevationRequest, + callback: + (results: ElevationResult[], status: ElevationStatus) => void): + void; + getElevationForLocations( + request: LocationElevationRequest, + callback: + (results: ElevationResult[], status: ElevationStatus) => void): + void; + } + + export interface LocationElevationRequest { + locations: LatLng[]; + } + + export interface PathElevationRequest { + path?: LatLng[]; + samples?: number; + } + + export interface ElevationResult { + elevation: number; + location: LatLng; + resolution: number; + } + + export enum ElevationStatus { + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR + } + + export class MaxZoomService { + getMaxZoomAtLatLng( + latlng: LatLng|LatLngLiteral, + callback: (result: MaxZoomResult) => void): void; + } + + export interface MaxZoomResult { + status: MaxZoomStatus; + zoom: number; + } + + export enum MaxZoomStatus {ERROR, OK} + + export class DistanceMatrixService { + getDistanceMatrix( + request: DistanceMatrixRequest, + callback: + (response: DistanceMatrixResponse, + status: DistanceMatrixStatus) => void): void; + } + + export interface DistanceMatrixRequest { + avoidFerries?: boolean; + avoidHighways?: boolean; + avoidTolls?: boolean; + destinations?: string[]|LatLng[]|LatLngLiteral[]|Place[]; + drivingOptions?: DrivingOptions; + durationInTraffic?: boolean; + origins?: string[]|LatLng[]|LatLngLiteral[]|Place[]; + region?: string; + transitOptions?: TransitOptions; + travelMode?: TravelMode; + unitSystem?: UnitSystem; + } + + export interface DistanceMatrixResponse { + destinationAddresses: string[]; + originAddresses: string[]; + rows: DistanceMatrixResponseRow[]; + } + + export interface DistanceMatrixResponseRow { + elements: DistanceMatrixResponseElement[]; + } + + export interface DistanceMatrixResponseElement { + distance: Distance; + duration: Duration; + duration_in_traffic: Duration; + fare: TransitFare; + status: DistanceMatrixElementStatus; + } + + export enum DistanceMatrixStatus { + INVALID_REQUEST, + MAX_DIMENSIONS_EXCEEDED, + MAX_ELEMENTS_EXCEEDED, + OK, + OVER_QUERY_LIMIT, + REQUEST_DENIED, + UNKNOWN_ERROR + } + + export enum DistanceMatrixElementStatus {NOT_FOUND, OK, ZERO_RESULTS} + + /***** Save to Google Maps *****/ + export interface Attribution { + iosDeepLinkId?: string; + source?: string; + webUrl?: string; + } + + export interface Place { + location?: LatLng|LatLngLiteral; + placeId?: string; + query?: string; + } + + export class SaveWidget { + constructor(container: Node, opts?: SaveWidgetOptions); + getAttribution(): Attribution; + getPlace(): Place; + setAttribution(attribution: Attribution): void; + setOptions(opts: SaveWidgetOptions): void; + setPlace(place: Place): void; + } + + export interface SaveWidgetOptions { + attribution?: Attribution; + place?: Place; + } + + /***** Map Types *****/ + export interface MapType { + getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; + releaseTile(tile: Element): void; + alt?: string; + maxZoom?: number; + minZoom?: number; + name?: string; + projection?: Projection; + radius?: number; + tileSize?: Size; + } + + export class MapTypeRegistry extends MVCObject { + constructor(); + set(id: string, mapType: MapType): void; + } + + export interface Projection { + fromLatLngToPoint(latLng: LatLng, point?: Point): Point; + fromPointToLatLng(pixel: Point, noWrap?: boolean): LatLng; + } + + export class ImageMapType extends MVCObject implements MapType { + constructor(opts: ImageMapTypeOptions); + getOpacity(): number; + getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; + releaseTile(tile: Element): void; + setOpacity(opacity: number): void; + } + + export interface ImageMapTypeOptions { + alt?: string; + getTileUrl(tileCoord: Point, zoom: number): string; + maxZoom?: number; + minZoom?: number; + name?: string; + opacity?: number; + tileSize?: Size; + } + + export class StyledMapType extends MVCObject implements MapType { + constructor(styles: MapTypeStyle[], options?: StyledMapTypeOptions); + getTile(tileCoord: Point, zoom: number, ownerDocument: Document): Element; + releaseTile(tile: Element): void; + } + + export interface StyledMapTypeOptions { + alt?: string; + maxZoom?: number; + minZoom?: number; + name?: string; + } + + export interface MapTypeStyle { + elementType?: MapTypeStyleElementType; + featureType?: MapTypeStyleFeatureType; + stylers?: MapTypeStyler[]; + } + + export type MapTypeStyleFeatureType = + 'all'|'administrative'|'administrative.country'| + 'administrative.land_parcel'|'administrative.locality'| + 'administrative.neighborhood'|'administrative.province'|'landscape'| + 'landscape.man_made'|'landscape.natural'|'landscape.natural.landcover'| + 'landscape.natural.terrain'|'poi'|'poi.attraction'|'poi.business'| + 'poi.government'|'poi.medical'|'poi.park'|'poi.place_of_worship'| + 'poi.school'|'poi.sports_complex'|'road'|'road.arterial'|'road.highway'| + 'road.highway.controlled_access'|'road.local'|'transit'|'transit.line'| + 'transit.station'|'transit.station.airport'|'transit.station.bus'| + 'transit.station.rail'|'water'; + + export type MapTypeStyleElementType = + 'all'|'geometry'|'geometry.fill'|'geometry.stroke'|'labels'|'labels.icon'| + 'labels.text'|'labels.text.fill'|'labels.text.stroke'; + + export interface MapTypeStyler { + color?: string; + gamma?: number; + hue?: string; + invert_lightness?: boolean; + lightness?: number; + saturation?: number; + visibility?: string; + weight?: number; + } + + /***** Layers *****/ + export class BicyclingLayer extends MVCObject { + constructor(); + getMap(): Map; + setMap(map: Map|null): void; + } + + export class FusionTablesLayer extends MVCObject { + constructor(options: FusionTablesLayerOptions); + getMap(): Map; + setMap(map: Map|null): void; + setOptions(options: FusionTablesLayerOptions): void; + } + + export interface FusionTablesLayerOptions { + clickable?: boolean; + heatmap?: FusionTablesHeatmap; + map?: Map; + query?: FusionTablesQuery; + styles?: FusionTablesStyle[]; + suppressInfoWindows?: boolean; + } + + export interface FusionTablesQuery { + from?: string; + limit?: number; + offset?: number; + orderBy?: string; + select?: string; + where?: string; + } + + export interface FusionTablesStyle { + markerOptions?: FusionTablesMarkerOptions; + polygonOptions?: FusionTablesPolygonOptions; + polylineOptions?: FusionTablesPolylineOptions; + where?: string; + } + + export interface FusionTablesHeatmap { + enabled: boolean; + } + + export interface FusionTablesMarkerOptions { + iconName: string; + } + + export interface FusionTablesPolygonOptions { + fillColor?: string; + fillOpacity?: number; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export interface FusionTablesPolylineOptions { + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + } + + export interface FusionTablesMouseEvent { + infoWindowHtml?: string; + latLng?: LatLng; + pixelOffset?: Size; + row?: Object; // Object + } + + export interface FusionTablesCell { + columnName?: string; + value?: string; + } + + export class KmlLayer extends MVCObject { + constructor(opts?: KmlLayerOptions); + getDefaultViewport(): LatLngBounds; + getMap(): Map; + getMetadata(): KmlLayerMetadata; + getStatus(): KmlLayerStatus; + getUrl(): string; + getZIndex(): number; + setMap(map: Map|null): void; + setUrl(url: string): void; + setZIndex(zIndex: number): void; + setOptions(options: KmlLayerOptions): void; + } + + export interface KmlLayerOptions { + clickable?: boolean; + map?: Map; + preserveViewport?: boolean; + screenOverlays?: boolean; + suppressInfoWindows?: boolean; + url?: string; + zIndex?: number; + } + + export interface KmlLayerMetadata { + author: KmlAuthor; + description: string; + hasScreenOverlays: boolean; + name: string; + snippet: string; + } + + export enum KmlLayerStatus { + DOCUMENT_NOT_FOUND, + DOCUMENT_TOO_LARGE, + FETCH_ERROR, + INVALID_DOCUMENT, + INVALID_REQUEST, + LIMITS_EXCEEDED, + OK, + TIMED_OUT, + UNKNOWN + } + + export interface KmlMouseEvent { + featureData: KmlFeatureData; + latLng: LatLng; + pixelOffset: Size; + } + + export interface KmlFeatureData { + author: KmlAuthor; + description: string; + id: string; + infoWindowHtml: string; + name: string; + snippet: string; + } + + export interface KmlAuthor { + email: string; + name: string; + uri: string; + } + + export class TrafficLayer extends MVCObject { + constructor(opts?: TrafficLayerOptions); + getMap(): Map; + setMap(map: Map|null): void; + setOptions(options: TrafficLayerOptions): void; + } + + export interface TrafficLayerOptions { + autoRefresh?: boolean; + map?: Map; + } + + export class TransitLayer extends MVCObject { + constructor(); + getMap(): void; + setMap(map: Map|null): void; + } + + /***** Street View *****/ + export class StreetViewPanorama extends MVCObject { + constructor(container: Element, opts?: StreetViewPanoramaOptions); + controls: MVCArray[]; + getLinks(): StreetViewLink[]; + getLocation(): StreetViewLocation; + getMotionTracking(): boolean; + getPano(): string; + getPhotographerPov(): StreetViewPov; + getPosition(): LatLng; + getPov(): StreetViewPov; + getStatus(): StreetViewStatus; + getVisible(): boolean; + getZoom(): number; + registerPanoProvider(provider: (input: string) => StreetViewPanoramaData): + void; + setLinks(links: Array): void; + setMotionTracking(motionTracking: boolean): void; + setOptions(options: StreetViewPanoramaOptions): void; + setPano(pano: string): void; + setPosition(latLng: LatLng|LatLngLiteral): void; + setPov(pov: StreetViewPov): void; + setVisible(flag: boolean): void; + setZoom(zoom: number): void; + } + + /** Options for the rendering of the fullscreen control. */ + export interface FullscreenControlOptions { + /** + * Position id. Used to specify the position of the control on the map. + * The default position is RIGHT_TOP. + */ + position?: ControlPosition; + } + + export interface StreetViewPanoramaOptions { + addressControl?: boolean; + addressControlOptions?: StreetViewAddressControlOptions; + clickToGo?: boolean; + disableDefaultUI?: boolean; + disableDoubleClickZoom?: boolean; + enableCloseButton?: boolean; + fullscreenControl?: boolean; + fullscreenControlOptions?: FullscreenControlOptions; + imageDateControl?: boolean; + linksControl?: boolean; + motionTracking?: boolean; + motionTrackingControl?: boolean; + motionTrackingControlOptions?: MotionTrackingControlOptions; + mode?: 'html4'|'html5'|'webgl'; + panControl?: boolean; + panControlOptions?: PanControlOptions; + pano?: string; + panoProvider?: (input: string) => StreetViewPanoramaData; + position?: LatLng|LatLngLiteral; + pov?: StreetViewPov; + scrollwheel?: boolean; + visible?: boolean; + zoom?: number; + zoomControl?: boolean; + zoomControlOptions?: ZoomControlOptions; + } + + export interface StreetViewAddressControlOptions { + position?: ControlPosition; + } + + export interface StreetViewLink { + description?: string; + heading?: number; + pano?: string; + } + + export interface StreetViewPov { + heading?: number; + pitch?: number; + } + + export interface StreetViewPanoramaData { + copyright?: string; + imageDate?: string; + links?: StreetViewLink[]; + location?: StreetViewLocation; + tiles?: StreetViewTileData; + } + + export interface StreetViewLocation { + description?: string; + latLng?: LatLng; + pano?: string; + shortDescription?: string; + } + + export interface StreetViewTileData { + getTileUrl(pano: string, tileZoom: number, tileX: number, tileY: number): + string; + centerHeading?: number; + tileSize?: Size; + worldSize?: Size; + } + + export enum StreetViewPreference {BEST, NEAREST} + + export enum StreetViewSource {DEFAULT, OUTDOOR} + + export interface StreetViewLocationRequest { + location: LatLng|LatLngLiteral; + preference?: StreetViewPreference; + radius?: number; + source?: StreetViewSource; + } + + export interface StreetViewPanoRequest { + pano: string; + } + + export class StreetViewService { + getPanorama( + request: StreetViewLocationRequest|StreetViewPanoRequest, + cb: (data: StreetViewPanoramaData, status: StreetViewStatus) => void): + void; + getPanoramaById( + pano: string, + callback: + (streetViewPanoramaData: StreetViewPanoramaData, + streetViewStatus: StreetViewStatus) => void): void; + getPanoramaByLocation( + latlng: LatLng|LatLngLiteral, radius: number, + callback: + (streetViewPanoramaData: StreetViewPanoramaData, + streetViewStatus: StreetViewStatus) => void): void; + } + + export enum StreetViewStatus {OK, UNKNOWN_ERROR, ZERO_RESULTS} + + export class StreetViewCoverageLayer extends MVCObject { + getMap(): Map; + setMap(map: Map|null): void; + } + + export interface MotionTrackingControlOptions { + position?: ControlPosition; + } + + /***** Events *****/ + export interface MapsEventListener { + /** + * Removes the listener. Equivalent to calling + * google.maps.event.removeListener(listener). + */ + remove(): void; + } + + export class event { + /** + * Cross browser event handler registration. This listener is removed by + * calling removeListener(handle) for the handle that is returned by this + * function. + */ + static addDomListener( + instance: Object, eventName: string, handler: Function, + capture?: boolean): MapsEventListener; + /** + * Wrapper around addDomListener that removes the listener after the first + * event. + */ + static addDomListenerOnce( + instance: Object, eventName: string, handler: Function, + capture?: boolean): MapsEventListener; + /** + * Adds the given listener function to the given event name for the given + * object instance. Returns an identifier for this listener that can be used + * with removeListener(). + */ + static addListener(instance: Object, eventName: string, handler: Function): + MapsEventListener; + /** + * Like addListener, but the handler removes itself after handling the first + * event. + */ + static addListenerOnce( + instance: Object, eventName: string, + handler: Function): MapsEventListener; + /** + * Removes all listeners for all events for the given instance. + */ + static clearInstanceListeners(instance: Object): void; + /** + * Removes all listeners for the given event for the given instance. + */ + static clearListeners(instance: Object, eventName: string): void; + /** + * Removes the given listener, which should have been returned by + * addListener above. Equivalent to calling listener.remove(). + */ + static removeListener(listener: MapsEventListener): void; + /** + * Triggers the given event. All arguments after eventName are passed as + * arguments to the listeners. + */ + static trigger(instance: any, eventName: string, ...args: any[]): void; + } + + /** + * This object is returned from various mouse events on the map and overlays, + * and contains all the fields shown below. + */ + export interface MouseEvent { + /** Prevents this event from propagating further. */ + stop(): void; + /** + * The latitude/longitude that was below the cursor when the event + * occurred. + */ + latLng: LatLng; + } + + /** + * This object is sent in an event when a user clicks on an icon on the map. + * The place ID of this place is stored in the placeId member. + * To prevent the default info window from showing up, call the stop() method + * on this event to prevent it being propagated. Learn more about place IDs in + * the Places API developer guide. + */ + export interface IconMouseEvent extends MouseEvent { + /** + * The place ID of the place that was clicked. + * This place ID can be used to query more information about the feature + * that was clicked. + */ + placeId: string; + } + + /* **** Base **** */ + + /** + * A LatLng is a point in geographical coordinates: latitude and longitude. + * + * * Latitude ranges between -90 and 90 degrees, inclusive. Values above or + * below this range will be clamped to the range [-90, 90]. This means + * that if the value specified is less than -90, it will be set to -90. + * And if the value is greater than 90, it will be set to 90. + * * Longitude ranges between -180 and 180 degrees, inclusive. Values above + * or below this range will be wrapped so that they fall within the + * range. For example, a value of -190 will be converted to 170. A value + * of 190 will be converted to -170. This reflects the fact that + * longitudes wrap around the globe. + * + * Although the default map projection associates longitude with the + * x-coordinate of the map, and latitude with the y-coordinate, the + * latitude coordinate is always written first, followed by the longitude. + * Notice that you cannot modify the coordinates of a LatLng. If you want + * to compute another point, you have to create a new one. + */ + export class LatLng { + /** + * Creates a LatLng object representing a geographic point. + * Note the ordering of latitude and longitude. + * @param lat Latitude is specified in degrees within the range [-90, 90]. + * @param lng Longitude is specified in degrees within the range [-180, + * 180]. + * @param noWrap Set noWrap to true to enable values outside of this range. + */ + constructor(lat: number, lng: number, noWrap?: boolean); + /** Comparison function. */ + equals(other: LatLng): boolean; + /** Returns the latitude in degrees. */ + lat(): number; + /** Returns the longitude in degrees. */ + lng(): number; + /** Converts to string representation. */ + toString(): string; + /** + * Returns a string of the form "lat,lng". We round the lat/lng values to 6 + * decimal places by default. + */ + toUrlValue(precision?: number): string; + /** + * Converts to JSON representation. This function is intended to be used + * via JSON.stringify. + */ + toJSON(): LatLngLiteral; + } + + export type LatLngLiteral = { + lat: number; lng: number + } + + export type LatLngBoundsLiteral = { + east: number; north: number; south: number; west: number + } + + /** + * A LatLngBounds instance represents a rectangle in geographical coordinates, + * including one that crosses the 180 degrees longitudinal meridian. + */ + export class LatLngBounds { + /** + * Constructs a rectangle from the points at its south-west and north-east + * corners. + */ + constructor(sw?: LatLng|LatLngLiteral, ne?: LatLng|LatLngLiteral); + /** Returns true if the given lat/lng is in this bounds. */ + contains(latLng: LatLng|LatLngLiteral): boolean; + /** Returns true if this bounds approximately equals the given bounds. */ + equals(other: LatLngBounds|LatLngBoundsLiteral): boolean; + /** Extends this bounds to contain the given point. */ + extend(point: LatLng|LatLngLiteral): LatLngBounds; + /** Computes the center of this LatLngBounds */ + getCenter(): LatLng; + /** Returns the north-east corner of this bounds. */ + getNorthEast(): LatLng; + /** Returns the south-west corner of this bounds. */ + getSouthWest(): LatLng; + /** Returns true if this bounds shares any points with the other bounds. */ + intersects(other: LatLngBounds|LatLngBoundsLiteral): boolean; + /** Returns if the bounds are empty. */ + isEmpty(): boolean; + /** + * Converts to JSON representation. This function is intended to be used + * via JSON.stringify. + */ + toJSON(): LatLngBoundsLiteral; + /** Converts the given map bounds to a lat/lng span. */ + toSpan(): LatLng; + /** Converts to string. */ + toString(): string; + /** + * Returns a string of the form "lat_lo,lng_lo,lat_hi,lng_hi" for this + * bounds, where "lo" corresponds to the southwest corner of the bounding + * box, while "hi" corresponds to the northeast corner of that box. + */ + toUrlValue(precision?: number): string; + /** + * Extends this bounds to contain the union of this and the given bounds. + */ + union(other: LatLngBounds|LatLngBoundsLiteral): LatLngBounds; + } + + export class Point { + /** A point on a two-dimensional plane. */ + constructor(x: number, y: number); + /** The X coordinate */ + x: number; + /** The Y coordinate */ + y: number; + /** Compares two Points */ + equals(other: Point): boolean; + /** Returns a string representation of this Point. */ + toString(): string; + } + + export class Size { + constructor( + width: number, height: number, widthUnit?: string, heightUnit?: string); + height: number; + width: number; + equals(other: Size): boolean; + toString(): string; + } + + /***** MVC *****/ + /** Base class implementing KVO. */ + export class MVCObject { + /** + * The MVCObject constructor is guaranteed to be an empty function, and so + * you may inherit from MVCObject by simply writing MySubclass.prototype = + * new google.maps.MVCObject();. Unless otherwise noted, this is not true of + * other classes in the API, and inheriting from other classes in the API is + * not supported. + */ + constructor(); + /** + * Adds the given listener function to the given event name. Returns an + * identifier for this listener that can be used with + * google.maps.event.removeListener. + */ + addListener(eventName: string, handler: (...args: any[]) => void): + MapsEventListener; + /** Binds a View to a Model. */ + bindTo( + key: string, target: MVCObject, targetKey?: string, + noNotify?: boolean): void; + changed(key: string): void; + /** Gets a value. */ + get(key: string): any; + /** + * Notify all observers of a change on this property. This notifies both + * objects that are bound to the object's property as well as the object + * that it is bound to. + */ + notify(key: string): void; + /** Sets a value. */ + set(key: string, value: any): void; + /** Sets a collection of key-value pairs. */ + setValues(values: any): void; + /** + * Removes a binding. Unbinding will set the unbound property to the current + * value. The object will not be notified, as the value has not changed. + */ + unbind(key: string): void; + /** Removes all bindings. */ + unbindAll(): void; + } + + /** This class extends MVCObject. */ + export class MVCArray extends MVCObject { + /** A mutable MVC Array. */ + constructor(array?: T[]); + /** Removes all elements from the array. */ + clear(): void; + /** + * Iterate over each element, calling the provided callback. + * The callback is called for each element like: callback(element, index). + */ + forEach(callback: (elem: T, i: number) => void): void; + /** + * Returns a reference to the underlying Array. + * Warning: if the Array is mutated, no events will be fired by this object. + */ + getArray(): T[]; + /** Returns the element at the specified index. */ + getAt(i: number): T; + /** Returns the number of elements in this array. */ + getLength(): number; + /** Inserts an element at the specified index. */ + insertAt(i: number, elem: T): void; + /** Removes the last element of the array and returns that element. */ + pop(): T; + /** + * Adds one element to the end of the array and returns the new length of + * the array. + */ + push(elem: T): number; + /** Removes an element from the specified index. */ + removeAt(i: number): T; + /** Sets an element at the specified index. */ + setAt(i: number, elem: T): void; + } + + /***** Geometry Library *****/ + export module geometry { + export class encoding { + static decodePath(encodedPath: string): LatLng[]; + static encodePath(path: LatLng[]|MVCArray): string; + } /** - * A LatLngBounds instance represents a rectangle in geographical coordinates, including one - * that crosses the 180 degrees longitudinal meridian. + * Utility functions for computing geodesic angles, distances and areas. + * The default radius is Earth's radius of 6378137 meters. */ - export class LatLngBounds { - /** Constructs a rectangle from the points at its south-west and north-east corners. */ - constructor(sw?: LatLng|LatLngLiteral, ne?: LatLng|LatLngLiteral); - /** Returns true if the given lat/lng is in this bounds. */ - contains(latLng: LatLng|LatLngLiteral): boolean; - /** Returns true if this bounds approximately equals the given bounds. */ - equals(other: LatLngBounds|LatLngBoundsLiteral): boolean; - /** Extends this bounds to contain the given point. */ - extend(point: LatLng|LatLngLiteral): LatLngBounds; - /** Computes the center of this LatLngBounds */ - getCenter(): LatLng; - /** Returns the north-east corner of this bounds. */ - getNorthEast(): LatLng; - /** Returns the south-west corner of this bounds. */ - getSouthWest(): LatLng; - /** Returns true if this bounds shares any points with the other bounds. */ - intersects(other: LatLngBounds|LatLngBoundsLiteral): boolean; - /** Returns if the bounds are empty. */ - isEmpty(): boolean; - /** Converts to JSON representation. This function is intended to be used via JSON.stringify. */ - toJSON(): LatLngBoundsLiteral; - /** Converts the given map bounds to a lat/lng span. */ - toSpan(): LatLng; - /** Converts to string. */ - toString(): string; - /** - * Returns a string of the form "lat_lo,lng_lo,lat_hi,lng_hi" for this bounds, where "lo" corresponds to the - * southwest corner of the bounding box, while "hi" corresponds to the northeast corner of that box. - */ - toUrlValue(precision?: number): string; - /** Extends this bounds to contain the union of this and the given bounds. */ - union(other: LatLngBounds|LatLngBoundsLiteral): LatLngBounds; + export class spherical { + /** + * Returns the area of a closed path. + * The computed area uses the same units as the radius. + * The radius defaults to the Earth's radius in meters, + * in which case the area is in square meters. + */ + static computeArea(path: LatLng[]|MVCArray, radius?: number): + number; + /** + * Returns the distance, in meters, between two LatLngs. + * You can optionally specify a custom radius. + * The radius defaults to the radius of the Earth. + */ + static computeDistanceBetween(from: LatLng, to: LatLng, radius?: number): + number; + /** + * Returns the heading from one LatLng to another LatLng. + * Headings are expressed in degrees clockwise from North within the range + * [-180,180). + */ + static computeHeading(from: LatLng, to: LatLng): number; + /** + * Returns the length of the given path. + */ + static computeLength(path: LatLng[]|MVCArray, radius?: number): + number; + /** + * Returns the LatLng resulting from moving a distance from an origin in + * the specified heading (expressed in degrees clockwise from north). + */ + static computeOffset( + from: LatLng, distance: number, heading: number, + radius?: number): LatLng; + /** + * Returns the location of origin when provided with a LatLng destination, + * meters travelled and original heading. Headings are expressed in + * degrees clockwise from North. This function returns null when no + * solution is available. + */ + static computeOffsetOrigin( + to: LatLng, distance: number, heading: number, + radius?: number): LatLng; + /** + * Returns the signed area of a closed path. The signed area may be used + * to determine the orientation of the path. The computed area uses the + * same units as the radius. The radius defaults to the Earth's radius in + * meters, in which case the area is in square meters. + */ + static computeSignedArea( + loop: LatLng[]|MVCArray, radius?: number): number; + /** + * Returns the LatLng which lies the given fraction of the way between the + * origin LatLng and the destination LatLng. + */ + static interpolate(from: LatLng, to: LatLng, fraction: number): LatLng; } - export class Point { - /** A point on a two-dimensional plane. */ - constructor(x: number, y: number); - /** The X coordinate */ - x: number; - /** The Y coordinate */ - y: number; - /** Compares two Points */ - equals(other: Point): boolean; - /** Returns a string representation of this Point. */ - toString(): string; + export class poly { + static containsLocation(point: LatLng, polygon: Polygon): boolean; + static isLocationOnEdge( + point: LatLng, poly: Polygon|Polyline, tolerance?: number): boolean; + } + } + + /***** AdSense Library *****/ + export module adsense { + export class AdUnit extends MVCObject { + constructor(container: Element, opts: AdUnitOptions); + getBackgroundColor(): string; + getBorderColor(): string; + getChannelNumber(): string; + getContainer(): Element; + getFormat(): AdFormat; + getMap(): Map; + getPosition(): ControlPosition; + getPublisherId(): string; + getTextColor(): string; + getTitleColor(): string; + getUrlColor(): string; + setBackgroundColor(backgroundColor: string): void; + setBorderColor(borderColor: string): void; + setChannelNumber(channelNumber: string): void; + setFormat(format: AdFormat): void; + setMap(map: Map|null): void; + setPosition(position: ControlPosition): void; + setTextColor(textColor: string): void; + setTitleColor(titleColor: string): void; + setUrlColor(urlColor: string): void; } - export class Size { - constructor(width: number, height: number, widthUnit?: string, heightUnit?: string); - height: number; - width: number; - equals(other: Size): boolean; - toString(): string; + export interface AdUnitOptions { + backgroundColor?: string; + borderColor?: string; + channelNumber?: string; + format?: AdFormat; + map?: Map; + position?: ControlPosition; + publisherId?: string; + textColor?: string; + titleColor?: string; + urlColor?: string; } - /***** MVC *****/ - /** Base class implementing KVO. */ - export class MVCObject { - /** - * The MVCObject constructor is guaranteed to be an empty function, and so you may inherit from MVCObject - * by simply writing MySubclass.prototype = new google.maps.MVCObject();. Unless otherwise noted, - * this is not true of other classes in the API, and inheriting from other classes in the API is not supported. - */ - constructor(); - /** - * Adds the given listener function to the given event name. Returns an identifier for this listener - * that can be used with google.maps.event.removeListener. - */ - addListener(eventName: string, handler: (...args: any[]) => void): MapsEventListener; - /** Binds a View to a Model. */ - bindTo(key: string, target: MVCObject, targetKey?: string, noNotify?: boolean): void; - changed(key: string): void; - /** Gets a value. */ - get(key: string): any; - /** - * Notify all observers of a change on this property. This notifies both objects that are bound - * to the object's property as well as the object that it is bound to. - */ - notify(key: string): void; - /** Sets a value. */ - set(key: string, value: any): void; - /** Sets a collection of key-value pairs. */ - setValues(values: any): void; - /** - * Removes a binding. Unbinding will set the unbound property to the current value. - * The object will not be notified, as the value has not changed. - */ - unbind(key: string): void; - /** Removes all bindings. */ - unbindAll(): void; + export enum AdFormat { + BANNER, + BUTTON, + HALF_BANNER, + LARGE_HORIZONTAL_LINK_UNIT, + LARGE_RECTANGLE, + LARGE_VERTICAL_LINK_UNIT, + LEADERBOARD, + MEDIUM_RECTANGLE, + MEDIUM_VERTICAL_LINK_UNIT, + SKYSCRAPER, + SMALL_HORIZONTAL_LINK_UNIT, + SMALL_RECTANGLE, + SMALL_SQUARE, + SMALL_VERTICAL_LINK_UNIT, + SQUARE, + VERTICAL_BANNER, + WIDE_SKYSCRAPER, + X_LARGE_VERTICAL_LINK_UNIT + } + } + + /***** Places Library *****/ + export module places { + export class Autocomplete extends MVCObject { + constructor(inputField: HTMLInputElement, opts?: AutocompleteOptions); + getBounds(): LatLngBounds; + getPlace(): PlaceResult; + setBounds(bounds: LatLngBounds|LatLngBoundsLiteral): void; + setComponentRestrictions(restrictions: ComponentRestrictions): void; + setTypes(types: string[]): void; } - /** This class extends MVCObject. */ - export class MVCArray extends MVCObject { - /** A mutable MVC Array. */ - constructor(array?: T[]); - /** Removes all elements from the array. */ - clear(): void; - /** - * Iterate over each element, calling the provided callback. - * The callback is called for each element like: callback(element, index). - */ - forEach(callback: (elem: T, i: number) => void): void; - /** - * Returns a reference to the underlying Array. - * Warning: if the Array is mutated, no events will be fired by this object. - */ - getArray(): T[]; - /** Returns the element at the specified index. */ - getAt(i: number): T; - /** Returns the number of elements in this array. */ - getLength(): number; - /** Inserts an element at the specified index. */ - insertAt(i: number, elem: T): void; - /** Removes the last element of the array and returns that element. */ - pop(): T; - /** Adds one element to the end of the array and returns the new length of the array. */ - push(elem: T): number; - /** Removes an element from the specified index. */ - removeAt(i: number): T; - /** Sets an element at the specified index. */ - setAt(i: number, elem: T): void; + export interface AutocompleteOptions { + bounds?: LatLngBounds|LatLngBoundsLiteral; + componentRestrictions?: ComponentRestrictions; + placeIdOnly?: boolean; + strictBounds?: boolean; + types?: string[]; + type?: string; } - /***** Geometry Library *****/ - export module geometry { - export class encoding { - static decodePath(encodedPath: string): LatLng[]; - static encodePath(path: LatLng[] | MVCArray): string; - } - - /** - * Utility functions for computing geodesic angles, distances and areas. - * The default radius is Earth's radius of 6378137 meters. - */ - export class spherical { - /** - * Returns the area of a closed path. - * The computed area uses the same units as the radius. - * The radius defaults to the Earth's radius in meters, - * in which case the area is in square meters. - */ - static computeArea(path: LatLng[] | MVCArray, radius?: number): number; - /** - * Returns the distance, in meters, between two LatLngs. - * You can optionally specify a custom radius. - * The radius defaults to the radius of the Earth. - */ - static computeDistanceBetween(from: LatLng, to: LatLng, radius?: number): number; - /** - * Returns the heading from one LatLng to another LatLng. - * Headings are expressed in degrees clockwise from North within the range [-180,180). - */ - static computeHeading(from: LatLng, to: LatLng): number; - /** - * Returns the length of the given path. - */ - static computeLength(path: LatLng[] | MVCArray, radius?: number): number; - /** - * Returns the LatLng resulting from moving a distance from an origin in the - * specified heading (expressed in degrees clockwise from north). - */ - static computeOffset(from: LatLng, distance: number, heading: number, radius?: number): LatLng; - /** - * Returns the location of origin when provided with a LatLng destination, meters - * travelled and original heading. Headings are expressed in degrees clockwise from - * North. This function returns null when no solution is available. - */ - static computeOffsetOrigin(to: LatLng, distance: number, heading: number, radius?: number): LatLng; - /** - * Returns the signed area of a closed path. The signed area may be used to determine - * the orientation of the path. The computed area uses the same units as the radius. - * The radius defaults to the Earth's radius in meters, in which case the area is in - * square meters. - */ - static computeSignedArea(loop: LatLng[] | MVCArray, radius?: number): number; - /** - * Returns the LatLng which lies the given fraction of the way between the origin - * LatLng and the destination LatLng. - */ - static interpolate(from: LatLng, to: LatLng, fraction: number): LatLng; - } - - export class poly { - static containsLocation(point: LatLng, polygon: Polygon): boolean; - static isLocationOnEdge(point: LatLng, poly: Polygon|Polyline, tolerance?: number): boolean; - } + export interface AutocompletePrediction { + description: string; + matched_substrings: PredictionSubstring[]; + place_id: string; + reference: string; + structured_formatting: AutocompleteStructuredFormatting; + terms: PredictionTerm[]; + types: string[]; } - /***** AdSense Library *****/ - export module adsense { - export class AdUnit extends MVCObject { - constructor(container: Element, opts: AdUnitOptions); - getBackgroundColor(): string; - getBorderColor(): string; - getChannelNumber(): string; - getContainer(): Element; - getFormat(): AdFormat; - getMap(): Map; - getPosition(): ControlPosition; - getPublisherId(): string; - getTextColor(): string; - getTitleColor(): string; - getUrlColor(): string; - setBackgroundColor(backgroundColor: string): void; - setBorderColor(borderColor: string): void; - setChannelNumber(channelNumber: string): void; - setFormat(format: AdFormat): void; - setMap(map: Map | null): void; - setPosition(position: ControlPosition): void; - setTextColor(textColor: string): void; - setTitleColor(titleColor: string): void; - setUrlColor(urlColor: string): void; - } - - export interface AdUnitOptions { - backgroundColor?: string; - borderColor?: string; - channelNumber?: string; - format?: AdFormat; - map?: Map; - position?: ControlPosition; - publisherId?: string; - textColor?: string; - titleColor?: string; - urlColor?: string; - } - - export enum AdFormat { - BANNER, - BUTTON, - HALF_BANNER, - LARGE_HORIZONTAL_LINK_UNIT, - LARGE_RECTANGLE, - LARGE_VERTICAL_LINK_UNIT, - LEADERBOARD, - MEDIUM_RECTANGLE, - MEDIUM_VERTICAL_LINK_UNIT, - SKYSCRAPER, - SMALL_HORIZONTAL_LINK_UNIT, - SMALL_RECTANGLE, - SMALL_SQUARE, - SMALL_VERTICAL_LINK_UNIT, - SQUARE, - VERTICAL_BANNER, - WIDE_SKYSCRAPER, - X_LARGE_VERTICAL_LINK_UNIT - } + export interface AutocompleteStructuredFormatting { + main_text: string; + main_text_matched_substrings: PredictionSubstring[]; + secondary_text: string; } - /***** Places Library *****/ - export module places { - export class Autocomplete extends MVCObject { - constructor(inputField: HTMLInputElement, opts?: AutocompleteOptions); - getBounds(): LatLngBounds; - getPlace(): PlaceResult; - setBounds(bounds: LatLngBounds|LatLngBoundsLiteral): void; - setComponentRestrictions(restrictions: ComponentRestrictions): void; - setTypes(types: string[]): void; - } - - export interface AutocompleteOptions { - bounds?: LatLngBounds|LatLngBoundsLiteral; - componentRestrictions?: ComponentRestrictions; - placeIdOnly?: boolean; - strictBounds?: boolean; - types?: string[]; - type?: string; - } - - export interface AutocompletePrediction { - description: string; - matched_substrings: PredictionSubstring[]; - place_id: string; - reference: string; - structured_formatting: AutocompleteStructuredFormatting; - terms: PredictionTerm[]; - types: string[]; - } - - export interface AutocompleteStructuredFormatting { - main_text: string; - main_text_matched_substrings: PredictionSubstring[]; - secondary_text: string; - } - - export interface OpeningHours { - open_now: boolean; - periods: OpeningPeriod[]; - weekday_text: string[]; - } - - export interface OpeningPeriod { - open: OpeningHoursTime; - close?: OpeningHoursTime; - } - - export interface OpeningHoursTime { - day: number; - hours: number; - minutes: number; - nextDate: number; - time: string; - } - - export interface PredictionTerm { - offset: number; - value: string; - } - - export interface PredictionSubstring { - length: number; - offset: number; - } - - export class AutocompleteService { - constructor(); - getPlacePredictions(request: AutocompletionRequest, callback: (result: AutocompletePrediction[], status: PlacesServiceStatus) => void): void; - getQueryPredictions(request: QueryAutocompletionRequest, callback: (result: QueryAutocompletePrediction[], status: PlacesServiceStatus) => void): void; - } - - export class AutocompleteSessionToken { - constructor(); - } - - export interface AutocompletionRequest { - bounds?: LatLngBounds|LatLngBoundsLiteral; - componentRestrictions?: ComponentRestrictions; - input: string; - location?: LatLng; - offset?: number; - radius?: number; - sessionToken?: AutocompleteSessionToken; - types?: string[]; - } - - export interface ComponentRestrictions { - country: string|string[]; - } - - export type LocationBias = LatLng|LatLngLiteral|LatLngBounds|LatLngBoundsLiteral|Circle|CircleLiteral|string; - - export interface PlaceAspectRating { - rating: number; - type: string; - } - - export interface PlaceDetailsRequest { - placeId: string; - fields?: string[]; - sessionToken?: AutocompleteSessionToken; - } - - export interface PlaceGeometry { - location: LatLng; - viewport: LatLngBounds; - } - - export interface PlacePhoto { - height: number; - html_attributions: string[]; - width: number; - getUrl(opts: PhotoOptions): string; - } - - export interface PhotoOptions { - maxHeight?: number; - maxWidth?: number; - } - - export interface PlaceResult { - address_components: GeocoderAddressComponent[]; - adr_address: string; - formatted_address: string; - formatted_phone_number: string; - geometry: PlaceGeometry; - html_attributions: string[]; - icon: string; - id: string; - international_phone_number: string; - name: string; - opening_hours: OpeningHours; - permanently_closed: boolean; - photos: PlacePhoto[]; - place_id: string; - price_level: number; - rating: number; - reviews: PlaceReview[]; - types: string[]; - url: string; - utc_offset: number; - vicinity: string; - website: string; - } - - export interface PlaceReview { - aspects: PlaceAspectRating[]; - author_name: string; - author_url: string; - language: string; - text: string; - } - - export interface PlaceSearchPagination { - nextPage(): void; - hasNextPage: boolean; - } - - export interface PlaceSearchRequest { - bounds?: LatLngBounds|LatLngBoundsLiteral; - keyword?: string; - location?: LatLng|LatLngLiteral; - maxPriceLevel?: number; - minPriceLevel?: number; - name?: string; - openNow?: boolean; - radius?: number; - rankBy?: RankBy; - types?: string[]; /* Deprecated. Will be removed February 16, 2017 */ - type?: string; - } - - export class PlacesService { - constructor(attrContainer: HTMLDivElement|Map); - findPlaceFromPhoneNumber(request: FindPlaceFromPhoneNumberRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void): void; - findPlaceFromQuery(request: FindPlaceFromQueryRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void): void; - getDetails(request: PlaceDetailsRequest, callback: (result: PlaceResult, status: PlacesServiceStatus) => void): void; - nearbySearch(request: PlaceSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus, pagination: PlaceSearchPagination) => void): void; - /** @deprecated Radar search is deprecated as of June 30, 2018. After that time, this feature will no longer be available. */ - radarSearch(request: RadarSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void): void; - textSearch(request: TextSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus, pagination: PlaceSearchPagination) => void): void; - } - - export enum PlacesServiceStatus { - ERROR, - INVALID_REQUEST, - OK, - OVER_QUERY_LIMIT, - NOT_FOUND, - REQUEST_DENIED, - UNKNOWN_ERROR, - ZERO_RESULTS - } - - export interface QueryAutocompletePrediction { - description: string; - matched_substrings: PredictionSubstring[]; - place_id: string; - terms: PredictionTerm[]; - } - - export interface QueryAutocompletionRequest { - bounds?: LatLngBounds|LatLngBoundsLiteral; - input?: string; - location?: LatLng; - offset?: number; - radius?: number; - } - - export interface RadarSearchRequest { - bounds?: LatLngBounds|LatLngBoundsLiteral; - keyword?: string; - location?: LatLng|LatLngLiteral; - name?: string; - radius?: number; - types?: string[]; /* Deprecated. Will be removed February 16, 2017 */ - type?: string; - } - - export enum RankBy { - DISTANCE, - PROMINENCE - } - - export class SearchBox extends MVCObject { - constructor(inputField: HTMLInputElement, opts?: SearchBoxOptions); - getBounds(): LatLngBounds; - getPlaces(): PlaceResult[]; - setBounds(bounds: LatLngBounds|LatLngBoundsLiteral): void; - } - - export interface SearchBoxOptions { - bounds: LatLngBounds|LatLngBoundsLiteral; - } - - export interface TextSearchRequest { - bounds?: LatLngBounds|LatLngBoundsLiteral; - location?: LatLng|LatLngLiteral; - query: string; - radius?: number; - types?: string[]; /* Deprecated. Will be removed February 16, 2017 */ - type?: string; - } - - export interface FindPlaceFromQueryRequest { - fields: string[]; - locationBias?: LocationBias; - query: string; - } - - export interface FindPlaceFromPhoneNumberRequest { - fields: string[]; - locationBias?: LocationBias; - query: string; - } + export interface OpeningHours { + open_now: boolean; + periods: OpeningPeriod[]; + weekday_text: string[]; } - /***** Drawing Library *****/ - export module drawing { - export class DrawingManager extends MVCObject { - constructor(options?: DrawingManagerOptions); - getDrawingMode(): OverlayType; - getMap(): Map; - setDrawingMode(drawingMode: OverlayType | null): void; - setMap(map: Map | null): void; - setOptions(options: DrawingManagerOptions): void; - } - - /** Options for the drawing manager. */ - export interface DrawingManagerOptions { - /** - * Options to apply to any new circles created with this DrawingManager. The center and radius properties - * are ignored, and the map property of a new circle is always set to the DrawingManager's map. - */ - circleOptions?: CircleOptions; - /** The enabled/disabled state of the drawing control. Defaults to true. */ - drawingControl?: boolean; - /** The display options for the drawing control. */ - drawingControlOptions?: DrawingControlOptions; - /** - * The DrawingManager's drawing mode, which defines the type of overlay to be added on the map. - * Accepted values are 'marker', 'polygon', 'polyline', 'rectangle', 'circle', or null. A drawing mode - * of null means that the user can interact with the map as normal, and clicks do not draw anything. - */ - drawingMode?: OverlayType | null; - /** - * The Map to which the DrawingManager is attached, which is the Map on which the overlays created - * will be placed. - */ - map?: Map; - /** - * Options to apply to any new markers created with this DrawingManager. The position property is ignored, - * and the map property of a new marker is always set to the DrawingManager's map. - */ - markerOptions?: MarkerOptions; - /** - * Options to apply to any new polygons created with this DrawingManager. The paths property is ignored, - * and the map property of a new polygon is always set to the DrawingManager's map. - */ - polygonOptions?: PolygonOptions; - /** - * Options to apply to any new polylines created with this DrawingManager. The path property is ignored, - * and the map property of a new polyline is always set to the DrawingManager's map. - */ - polylineOptions?: PolylineOptions; - /** - * Options to apply to any new rectangles created with this DrawingManager. The bounds property is ignored, - * and the map property of a new rectangle is always set to the DrawingManager's map. - */ - rectangleOptions?: RectangleOptions; - } - - export interface DrawingControlOptions { - drawingModes?: OverlayType[]; - position?: ControlPosition; - } - - /** The properties of an overlaycomplete event on a DrawingManager.. */ - export interface OverlayCompleteEvent { - /** The completed overlay. */ - overlay: Marker|Polygon|Polyline|Rectangle|Circle; - /** The completed overlay's type. */ - type: OverlayType; - } - - /** - * The types of overlay that may be created by the DrawingManager. Specify these by value, or by using the - * constant's name. For example, 'polygon' or google.maps.drawing.OverlayType.POLYGON. - */ - export enum OverlayType { - /** - * Specifies that the DrawingManager creates circles, and that the overlay given in the overlaycomplete - * event is a circle. - */ - CIRCLE, - /** - * Specifies that the DrawingManager creates markers, and that the overlay given in the overlaycomplete - * event is a marker. - */ - MARKER, - /** - * Specifies that the DrawingManager creates polygons, and that the overlay given in the overlaycomplete - * event is a polygon. - */ - POLYGON, - /** - * Specifies that the DrawingManager creates polylines, and that the overlay given in the overlaycomplete - * event is a polyline. - */ - POLYLINE, - /** - * Specifies that the DrawingManager creates rectangles, and that the overlay given in the overlaycomplete - * event is a rectangle. - */ - RECTANGLE - } + export interface OpeningPeriod { + open: OpeningHoursTime; + close?: OpeningHoursTime; } - /***** Visualization Library *****/ - export module visualization { - export class MapsEngineLayer extends MVCObject { - constructor(options: MapsEngineLayerOptions); - getLayerId(): string; - getLayerKey(): string; - getMap(): Map; - getMapId(): string; - getOpacity(): number; - getProperties(): MapsEngineLayerProperties; - getStatus(): MapsEngineStatus; - getZIndex(): number; - setLayerId(layerId: string): void; - setLayerKey(layerKey: string): void; - setMap(map: Map | null): void; - setMapId(mapId: string): void; - setOpacity(opacity: number): void; - setOptions(options: MapsEngineLayerOptions): void; - setZIndex(zIndex: number): void; - } - - export interface MapsEngineLayerOptions { - accessToken?: string; - clickable?: boolean; - fitBounds?: boolean; - layerId?: string; - layerKey?: string; - map?: Map; - mapId?: string; - opacity?: number; - suppressInfoWindows?: boolean; - zIndex?: number; - } - - export interface MapsEngineLayerProperties { - name: string; - } - - export interface MapsEngineMouseEvent { - featureId?: string; - infoWindowHtml?: string; - latLng?: LatLng; - pixelOffset?: Size; - } - - export enum MapsEngineStatus { - INVALID_LAYER, - OK, - UNKNOWN_ERROR - } - - export class HeatmapLayer extends MVCObject { - constructor(opts?: HeatmapLayerOptions); - getData(): MVCArray; - getMap(): Map; - setData(data: MVCArray | LatLng[] | WeightedLocation[]): void; - setMap(map: Map | null): void; - } - - export interface HeatmapLayerOptions { - data: any; - dissipating?: boolean; - gradient?: string[]; - map?: Map; - maxIntensity?: number; - opacity?: number; - radius?: number; - } - - export interface WeightedLocation { - location: LatLng; - weight: number; - } - - export class MouseEvent { - stop(): void; - } - - export class MapsEventListener { - - } + export interface OpeningHoursTime { + day: number; + hours: number; + minutes: number; + nextDate: number; + time: string; } + + export interface PredictionTerm { + offset: number; + value: string; + } + + export interface PredictionSubstring { + length: number; + offset: number; + } + + export class AutocompleteService { + constructor(); + getPlacePredictions( + request: AutocompletionRequest, + callback: + (result: AutocompletePrediction[], + status: PlacesServiceStatus) => void): void; + getQueryPredictions( + request: QueryAutocompletionRequest, + callback: + (result: QueryAutocompletePrediction[], + status: PlacesServiceStatus) => void): void; + } + + export class AutocompleteSessionToken { + constructor(); + } + + export interface AutocompletionRequest { + bounds?: LatLngBounds|LatLngBoundsLiteral; + componentRestrictions?: ComponentRestrictions; + input: string; + location?: LatLng; + offset?: number; + radius?: number; + sessionToken?: AutocompleteSessionToken; + types?: string[]; + } + + export interface ComponentRestrictions { + country: string|string[]; + } + + export type LocationBias = LatLng|LatLngLiteral|LatLngBounds| + LatLngBoundsLiteral|Circle|CircleLiteral|string; + + export interface PlaceAspectRating { + rating: number; + type: string; + } + + export interface PlaceDetailsRequest { + placeId: string; + fields?: string[]; + sessionToken?: AutocompleteSessionToken; + } + + export interface PlaceGeometry { + location: LatLng; + viewport: LatLngBounds; + } + + export interface PlacePhoto { + height: number; + html_attributions: string[]; + width: number; + getUrl(opts: PhotoOptions): string; + } + + export interface PhotoOptions { + maxHeight?: number; + maxWidth?: number; + } + + export interface PlaceResult { + address_components: GeocoderAddressComponent[]; + adr_address: string; + formatted_address: string; + formatted_phone_number: string; + geometry: PlaceGeometry; + html_attributions: string[]; + icon: string; + id: string; + international_phone_number: string; + name: string; + opening_hours: OpeningHours; + permanently_closed: boolean; + photos: PlacePhoto[]; + place_id: string; + price_level: number; + rating: number; + reviews: PlaceReview[]; + types: string[]; + url: string; + utc_offset: number; + vicinity: string; + website: string; + } + + export interface PlaceReview { + aspects: PlaceAspectRating[]; + author_name: string; + author_url: string; + language: string; + text: string; + } + + export interface PlaceSearchPagination { + nextPage(): void; + hasNextPage: boolean; + } + + export interface PlaceSearchRequest { + bounds?: LatLngBounds|LatLngBoundsLiteral; + keyword?: string; + location?: LatLng|LatLngLiteral; + maxPriceLevel?: number; + minPriceLevel?: number; + name?: string; + openNow?: boolean; + radius?: number; + rankBy?: RankBy; + types?: string[]; /* Deprecated. Will be removed February 16, 2017 */ + type?: string; + } + + export class PlacesService { + constructor(attrContainer: HTMLDivElement|Map); + findPlaceFromPhoneNumber( + request: FindPlaceFromPhoneNumberRequest, + callback: + (results: PlaceResult[], status: PlacesServiceStatus) => void): + void; + findPlaceFromQuery( + request: FindPlaceFromQueryRequest, + callback: + (results: PlaceResult[], status: PlacesServiceStatus) => void): + void; + getDetails( + request: PlaceDetailsRequest, + callback: (result: PlaceResult, status: PlacesServiceStatus) => void): + void; + nearbySearch( + request: PlaceSearchRequest, + callback: + (results: PlaceResult[], status: PlacesServiceStatus, + pagination: PlaceSearchPagination) => void): void; + /** + * @deprecated Radar search is deprecated as of June 30, 2018. After that + * time, this feature will no longer be available. + */ + radarSearch( + request: RadarSearchRequest, + callback: + (results: PlaceResult[], status: PlacesServiceStatus) => void): + void; + textSearch( + request: TextSearchRequest, + callback: + (results: PlaceResult[], status: PlacesServiceStatus, + pagination: PlaceSearchPagination) => void): void; + } + + export enum PlacesServiceStatus { + ERROR, + INVALID_REQUEST, + OK, + OVER_QUERY_LIMIT, + NOT_FOUND, + REQUEST_DENIED, + UNKNOWN_ERROR, + ZERO_RESULTS + } + + export interface QueryAutocompletePrediction { + description: string; + matched_substrings: PredictionSubstring[]; + place_id: string; + terms: PredictionTerm[]; + } + + export interface QueryAutocompletionRequest { + bounds?: LatLngBounds|LatLngBoundsLiteral; + input?: string; + location?: LatLng; + offset?: number; + radius?: number; + } + + export interface RadarSearchRequest { + bounds?: LatLngBounds|LatLngBoundsLiteral; + keyword?: string; + location?: LatLng|LatLngLiteral; + name?: string; + radius?: number; + types?: string[]; /* Deprecated. Will be removed February 16, 2017 */ + type?: string; + } + + export enum RankBy {DISTANCE, PROMINENCE} + + export class SearchBox extends MVCObject { + constructor(inputField: HTMLInputElement, opts?: SearchBoxOptions); + getBounds(): LatLngBounds; + getPlaces(): PlaceResult[]; + setBounds(bounds: LatLngBounds|LatLngBoundsLiteral): void; + } + + export interface SearchBoxOptions { + bounds: LatLngBounds|LatLngBoundsLiteral; + } + + export interface TextSearchRequest { + bounds?: LatLngBounds|LatLngBoundsLiteral; + location?: LatLng|LatLngLiteral; + query: string; + radius?: number; + types?: string[]; /* Deprecated. Will be removed February 16, 2017 */ + type?: string; + } + + export interface FindPlaceFromQueryRequest { + fields: string[]; + locationBias?: LocationBias; + query: string; + } + + export interface FindPlaceFromPhoneNumberRequest { + fields: string[]; + locationBias?: LocationBias; + query: string; + } + } + + /***** Drawing Library *****/ + export module drawing { + export class DrawingManager extends MVCObject { + constructor(options?: DrawingManagerOptions); + getDrawingMode(): OverlayType; + getMap(): Map; + setDrawingMode(drawingMode: OverlayType|null): void; + setMap(map: Map|null): void; + setOptions(options: DrawingManagerOptions): void; + } + + /** Options for the drawing manager. */ + export interface DrawingManagerOptions { + /** + * Options to apply to any new circles created with this DrawingManager. + * The center and radius properties are ignored, and the map property of a + * new circle is always set to the DrawingManager's map. + */ + circleOptions?: CircleOptions; + /** + * The enabled/disabled state of the drawing control. Defaults to true. + */ + drawingControl?: boolean; + /** The display options for the drawing control. */ + drawingControlOptions?: DrawingControlOptions; + /** + * The DrawingManager's drawing mode, which defines the type of overlay to + * be added on the map. Accepted values are 'marker', 'polygon', + * 'polyline', 'rectangle', 'circle', or null. A drawing mode of null + * means that the user can interact with the map as normal, and clicks do + * not draw anything. + */ + drawingMode?: OverlayType|null; + /** + * The Map to which the DrawingManager is attached, which is the Map on + * which the overlays created will be placed. + */ + map?: Map; + /** + * Options to apply to any new markers created with this DrawingManager. + * The position property is ignored, and the map property of a new marker + * is always set to the DrawingManager's map. + */ + markerOptions?: MarkerOptions; + /** + * Options to apply to any new polygons created with this DrawingManager. + * The paths property is ignored, and the map property of a new polygon is + * always set to the DrawingManager's map. + */ + polygonOptions?: PolygonOptions; + /** + * Options to apply to any new polylines created with this DrawingManager. + * The path property is ignored, and the map property of a new polyline is + * always set to the DrawingManager's map. + */ + polylineOptions?: PolylineOptions; + /** + * Options to apply to any new rectangles created with this + * DrawingManager. The bounds property is ignored, and the map property of + * a new rectangle is always set to the DrawingManager's map. + */ + rectangleOptions?: RectangleOptions; + } + + export interface DrawingControlOptions { + drawingModes?: OverlayType[]; + position?: ControlPosition; + } + + /** The properties of an overlaycomplete event on a DrawingManager.. */ + export interface OverlayCompleteEvent { + /** The completed overlay. */ + overlay: Marker|Polygon|Polyline|Rectangle|Circle; + /** The completed overlay's type. */ + type: OverlayType; + } + + /** + * The types of overlay that may be created by the DrawingManager. Specify + * these by value, or by using the constant's name. For example, 'polygon' + * or google.maps.drawing.OverlayType.POLYGON. + */ + export enum OverlayType { + /** + * Specifies that the DrawingManager creates circles, and that the overlay + * given in the overlaycomplete event is a circle. + */ + CIRCLE, + /** + * Specifies that the DrawingManager creates markers, and that the overlay + * given in the overlaycomplete event is a marker. + */ + MARKER, + /** + * Specifies that the DrawingManager creates polygons, and that the + * overlay given in the overlaycomplete event is a polygon. + */ + POLYGON, + /** + * Specifies that the DrawingManager creates polylines, and that the + * overlay given in the overlaycomplete event is a polyline. + */ + POLYLINE, + /** + * Specifies that the DrawingManager creates rectangles, and that the + * overlay given in the overlaycomplete event is a rectangle. + */ + RECTANGLE + } + } + + /***** Visualization Library *****/ + export module visualization { + export class MapsEngineLayer extends MVCObject { + constructor(options: MapsEngineLayerOptions); + getLayerId(): string; + getLayerKey(): string; + getMap(): Map; + getMapId(): string; + getOpacity(): number; + getProperties(): MapsEngineLayerProperties; + getStatus(): MapsEngineStatus; + getZIndex(): number; + setLayerId(layerId: string): void; + setLayerKey(layerKey: string): void; + setMap(map: Map|null): void; + setMapId(mapId: string): void; + setOpacity(opacity: number): void; + setOptions(options: MapsEngineLayerOptions): void; + setZIndex(zIndex: number): void; + } + + export interface MapsEngineLayerOptions { + accessToken?: string; + clickable?: boolean; + fitBounds?: boolean; + layerId?: string; + layerKey?: string; + map?: Map; + mapId?: string; + opacity?: number; + suppressInfoWindows?: boolean; + zIndex?: number; + } + + export interface MapsEngineLayerProperties { + name: string; + } + + export interface MapsEngineMouseEvent { + featureId?: string; + infoWindowHtml?: string; + latLng?: LatLng; + pixelOffset?: Size; + } + + export enum MapsEngineStatus {INVALID_LAYER, OK, UNKNOWN_ERROR} + + export class HeatmapLayer extends MVCObject { + constructor(opts?: HeatmapLayerOptions); + getData(): MVCArray; + getMap(): Map; + setData(data: MVCArray|LatLng[]| + WeightedLocation[]): void; + setMap(map: Map|null): void; + } + + export interface HeatmapLayerOptions { + data: any; + dissipating?: boolean; + gradient?: string[]; + map?: Map; + maxIntensity?: number; + opacity?: number; + radius?: number; + } + + export interface WeightedLocation { + location: LatLng; + weight: number; + } + + export class MouseEvent { + stop(): void; + } + + export class MapsEventListener {} + } } diff --git a/types/graphql-query-complexity/dist/QueryComplexity.d.ts b/types/graphql-query-complexity/dist/QueryComplexity.d.ts new file mode 100644 index 0000000000..898e2023bb --- /dev/null +++ b/types/graphql-query-complexity/dist/QueryComplexity.d.ts @@ -0,0 +1,26 @@ +/** + * Created by Ivo Meißner on 28.07.17. + */ +import { ValidationContext, FragmentDefinitionNode, OperationDefinitionNode, FieldNode, InlineFragmentNode, GraphQLUnionType, GraphQLObjectType, GraphQLInterfaceType, GraphQLError } from 'graphql'; +export interface QueryComplexityOptions { + maximumComplexity: number; + variables?: object; + onComplete?: (complexity: number) => void; + createError?: (max: number, actual: number) => GraphQLError; +} +export default class QueryComplexity { + context: ValidationContext; + complexity: number; + options: QueryComplexityOptions; + fragments: { + [name: string]: FragmentDefinitionNode; + }; + OperationDefinition: object; + constructor(context: ValidationContext, options: QueryComplexityOptions); + onOperationDefinitionEnter(operation: OperationDefinitionNode): void; + onOperationDefinitionLeave(): GraphQLError | undefined; + nodeComplexity(node: FieldNode | FragmentDefinitionNode | InlineFragmentNode | + OperationDefinitionNode, typeDef: GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType, complexity?: number): number; + createError(): GraphQLError; + getDefaultComplexity(args: object, childScore: number): number; +} diff --git a/types/graphql-query-complexity/dist/index.d.ts b/types/graphql-query-complexity/dist/index.d.ts new file mode 100644 index 0000000000..082f70cc11 --- /dev/null +++ b/types/graphql-query-complexity/dist/index.d.ts @@ -0,0 +1,4 @@ +import { QueryComplexityOptions } from './QueryComplexity'; +export default function createQueryComplexityValidator(options: QueryComplexityOptions): () => void; +export type ComplexityResolver = (args: any, complexity: number) => number; +export type Complexity = number | ComplexityResolver; diff --git a/types/graphql-query-complexity/graphql-query-complexity-tests.ts b/types/graphql-query-complexity/graphql-query-complexity-tests.ts new file mode 100644 index 0000000000..29a3913dbf --- /dev/null +++ b/types/graphql-query-complexity/graphql-query-complexity-tests.ts @@ -0,0 +1,5 @@ +import QueryComplexity from "graphql-query-complexity/dist/QueryComplexity"; +import complexityFunction from "graphql-query-complexity"; +const complexity = new QueryComplexity(null as any, null as any); +complexity.createError().message; // $ExpectType string +complexityFunction({maximumComplexity: 10}); diff --git a/types/graphql-query-complexity/index.d.ts b/types/graphql-query-complexity/index.d.ts new file mode 100644 index 0000000000..4c5954fb4f --- /dev/null +++ b/types/graphql-query-complexity/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for graphql-query-complexity 0.1 +// Project: https://github.com/ivome/graphql-query-complexity +// Definitions by: Abhik Mitra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +import createQueryComplexityValidator from "./dist"; +export default createQueryComplexityValidator; diff --git a/types/graphql-query-complexity/tsconfig.json b/types/graphql-query-complexity/tsconfig.json new file mode 100644 index 0000000000..d706752c48 --- /dev/null +++ b/types/graphql-query-complexity/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dist/index.d.ts", + "dist/QueryComplexity.d.ts", + "graphql-query-complexity-tests.ts" + ] +} \ No newline at end of file diff --git a/types/graphql-query-complexity/tslint.json b/types/graphql-query-complexity/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphql-query-complexity/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/graphql-relay/index.d.ts b/types/graphql-relay/index.d.ts index fc1eb3aa1e..842e1ad4f1 100644 --- a/types/graphql-relay/index.d.ts +++ b/types/graphql-relay/index.d.ts @@ -34,12 +34,12 @@ import { * whose return type is a connection type with forward pagination. */ export interface ForwardConnectionArgs { - after: ConnectionCursor; - first: number; + after?: ConnectionCursor | null; + first?: number | null; } export const forwardConnectionArgs: GraphQLFieldConfigArgumentMap & { - after: ConnectionCursor; - first: number; + after?: ConnectionCursor | null; + first?: number | null; }; /** @@ -47,12 +47,12 @@ export const forwardConnectionArgs: GraphQLFieldConfigArgumentMap & { * whose return type is a connection type with backward pagination. */ export interface BackwardConnectionArgs { - before: ConnectionCursor; - last: number; + before?: ConnectionCursor | null; + last?: number | null; } export const backwardConnectionArgs: GraphQLFieldConfigArgumentMap & { - before: ConnectionCursor; - last: number; + before?: ConnectionCursor | null; + last?: number | null; }; /** @@ -105,10 +105,10 @@ export type ConnectionCursor = string; * A flow type designed to be exposed as `PageInfo` over GraphQL. */ export interface PageInfo { - startCursor: ConnectionCursor; - endCursor: ConnectionCursor; - hasPreviousPage: boolean; - hasNextPage: boolean; + startCursor?: ConnectionCursor | null; + endCursor?: ConnectionCursor | null; + hasPreviousPage?: boolean | null; + hasNextPage?: boolean | null; } /** @@ -131,10 +131,10 @@ export interface Edge { * A flow type describing the arguments a connection field receives in GraphQL. */ export interface ConnectionArguments { - before?: ConnectionCursor; - after?: ConnectionCursor; - first?: number; - last?: number; + before?: ConnectionCursor | null; + after?: ConnectionCursor | null; + first?: number | null; + last?: number | null; } // connection/arrayconnection.js @@ -212,8 +212,8 @@ export function cursorForObjectInConnection( * otherwise it will be the default. */ export function getOffsetWithDefault( - cursor?: ConnectionCursor, - defaultOffset?: number + cursor?: ConnectionCursor | null, + defaultOffset?: number | null ): number; // mutation/mutation.js diff --git a/types/graphql/error/GraphQLError.d.ts b/types/graphql/error/GraphQLError.d.ts index ce31564fb1..2c7c69544b 100644 --- a/types/graphql/error/GraphQLError.d.ts +++ b/types/graphql/error/GraphQLError.d.ts @@ -59,12 +59,12 @@ export class GraphQLError extends Error { /** * The original error thrown from a field resolver during execution. */ - readonly originalError: Maybe; + readonly originalError: Maybe & { readonly extensions: any }; /** * Extension fields to add to the formatted error. */ - readonly extensions: { [key: string]: any } | void; + readonly extensions: { [key: string]: any } | undefined; constructor( message: string, diff --git a/types/graphql/error/formatError.d.ts b/types/graphql/error/formatError.d.ts index 7f13117cf0..2d87c877a9 100644 --- a/types/graphql/error/formatError.d.ts +++ b/types/graphql/error/formatError.d.ts @@ -11,6 +11,5 @@ export interface GraphQLFormattedError { readonly message: string; readonly locations: ReadonlyArray | undefined; readonly path: ReadonlyArray | undefined; - // Extensions - readonly [key: string]: any; + readonly extensions?: { [key: string]: any }; } diff --git a/types/graphql/error/locatedError.d.ts b/types/graphql/error/locatedError.d.ts index 77dd470c63..0d49d5f3a3 100644 --- a/types/graphql/error/locatedError.d.ts +++ b/types/graphql/error/locatedError.d.ts @@ -7,7 +7,7 @@ import { ASTNode } from "../language/ast"; * document responsible for the original Error. */ export function locatedError( - originalError: Error, + originalError: Error | GraphQLError, nodes: ReadonlyArray, path: ReadonlyArray ): GraphQLError; diff --git a/types/graphql/execution/execute.d.ts b/types/graphql/execution/execute.d.ts index 60294abbc7..fc6ad898d1 100644 --- a/types/graphql/execution/execute.d.ts +++ b/types/graphql/execution/execute.d.ts @@ -126,11 +126,6 @@ export function buildExecutionContext( fieldResolver: Maybe> ): ReadonlyArray | ExecutionContext; -/** - * Extracts the root type of the operation from the schema. - */ -export function getOperationRootType(schema: GraphQLSchema, operation: OperationDefinitionNode): GraphQLObjectType; - /** * Given a selectionSet, adds all of the fields in that selection to * the passed in map of fields, and returns it at the end. diff --git a/types/graphql/execution/values.d.ts b/types/graphql/execution/values.d.ts index e3cb7eb4bc..94f462e8b6 100644 --- a/types/graphql/execution/values.d.ts +++ b/types/graphql/execution/values.d.ts @@ -1,5 +1,5 @@ import Maybe from "../tsutils/Maybe"; -import { GraphQLError } from "../error"; +import { GraphQLError } from "../error/GraphQLError"; import { GraphQLInputType, GraphQLField, GraphQLArgument } from "../type/definition"; import { GraphQLDirective } from "../type/directives"; import { GraphQLSchema } from "../type/schema"; diff --git a/types/graphql/graphql.d.ts b/types/graphql/graphql.d.ts index 0b3d52b2d7..60dac7ccb3 100644 --- a/types/graphql/graphql.d.ts +++ b/types/graphql/graphql.d.ts @@ -22,6 +22,11 @@ import { ExecutionResult, ExecutionResultDataDefault } from "./execution/execute * rootValue: * The value provided as the first argument to resolver functions on the top * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. * variableValues: * A mapping of variable name to runtime value to use for all variables * defined in the requestString. diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index 2e9b01d700..4adbf97ab3 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for graphql 0.13 +// Type definitions for graphql 14.0 // Project: https://www.npmjs.com/package/graphql // Definitions by: TonyYang // Caleb Meredith @@ -84,6 +84,8 @@ export { isWrappingType, isNullableType, isNamedType, + isRequiredArgument, + isRequiredInputField, isSpecifiedScalarType, isIntrospectionType, isSpecifiedDirective, @@ -149,6 +151,9 @@ export { GraphQLTypeResolver, GraphQLUnionTypeConfig, GraphQLDirectiveConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, } from "./type"; // Parse and operate on GraphQL language source files. @@ -170,6 +175,16 @@ export { TokenKind, DirectiveLocation, BREAK, + // Predicates + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, // type Lexer, ParseOptions, @@ -227,9 +242,16 @@ export { EnumTypeDefinitionNode, EnumValueDefinitionNode, InputObjectTypeDefinitionNode, - TypeExtensionNode, - ObjectTypeExtensionNode, DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, KindEnum, TokenKindEnum, DirectiveLocationEnum, @@ -268,7 +290,7 @@ export { NoUnusedVariablesRule, OverlappingFieldsCanBeMergedRule, PossibleFragmentSpreadsRule, - ProvidedNonNullArgumentsRule, + ProvidedRequiredArgumentsRule, ScalarLeafsRule, SingleFieldSubscriptionsRule, UniqueArgumentNamesRule, @@ -279,7 +301,6 @@ export { UniqueVariableNamesRule, ValuesOfCorrectTypeRule, VariablesAreInputTypesRule, - VariablesDefaultValueAllowedRule, VariablesInAllowedPositionRule, } from "./validation"; @@ -291,10 +312,12 @@ export { // Produce the GraphQL query recommended for a full schema introspection. // Accepts optional IntrospectionOptions. getIntrospectionQuery, - // Deprecated: use getIntrospectionQuery + // @deprecated: use getIntrospectionQuery - will be removed in v15 introspectionQuery, // Gets the target Operation from a Document getOperationAST, + // Gets the Type for the target Operation AST. + getOperationRootType, // Convert a GraphQLSchema to an IntrospectionQuery introspectionFromSchema, // Build a GraphQLSchema from an introspection result. @@ -303,7 +326,8 @@ export { buildASTSchema, // Build a GraphQLSchema from a GraphQL schema language document. buildSchema, - // Get the description from a schema AST node. + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16 getDescription, // Extends an existing GraphQLSchema from a parsed GraphQL Schema // language AST. @@ -330,9 +354,9 @@ export { TypeInfo, // Coerces a JavaScript value to a GraphQL type, or produces errors. coerceValue, - // @deprecated use coerceValue + // @deprecated use coerceValue - will be removed in v15 isValidJSValue, - // Determine if AST values adhere to a GraphQL type. + // @deprecated use validation - will be removed in v15 isValidLiteralValue, // Concatenates multiple AST together. concatAST, diff --git a/types/graphql/language/ast.d.ts b/types/graphql/language/ast.d.ts index 21601385ff..6a6ee1b3e2 100644 --- a/types/graphql/language/ast.d.ts +++ b/types/graphql/language/ast.d.ts @@ -115,13 +115,14 @@ export type ASTNode = | EnumTypeDefinitionNode | EnumValueDefinitionNode | InputObjectTypeDefinitionNode + | DirectiveDefinitionNode + | SchemaExtensionNode | ScalarTypeExtensionNode | ObjectTypeExtensionNode | InterfaceTypeExtensionNode | UnionTypeExtensionNode | EnumTypeExtensionNode - | InputObjectTypeExtensionNode - | DirectiveDefinitionNode; + | InputObjectTypeExtensionNode; /** * Utility type listing all nodes indexed by their kind. @@ -162,13 +163,14 @@ export interface ASTKindToNode { EnumTypeDefinition: EnumTypeDefinitionNode; EnumValueDefinition: EnumValueDefinitionNode; InputObjectTypeDefinition: InputObjectTypeDefinitionNode; + DirectiveDefinition: DirectiveDefinitionNode; + SchemaExtension: SchemaExtensionNode; ScalarTypeExtension: ScalarTypeExtensionNode; ObjectTypeExtension: ObjectTypeExtensionNode; InterfaceTypeExtension: InterfaceTypeExtensionNode; UnionTypeExtension: UnionTypeExtensionNode; EnumTypeExtension: EnumTypeExtensionNode; InputObjectTypeExtension: InputObjectTypeExtensionNode; - DirectiveDefinition: DirectiveDefinitionNode; } // Name @@ -187,7 +189,7 @@ export interface DocumentNode { readonly definitions: ReadonlyArray; } -export type DefinitionNode = ExecutableDefinitionNode | TypeSystemDefinitionNode; // experimental non-spec addition. +export type DefinitionNode = ExecutableDefinitionNode | TypeSystemDefinitionNode | TypeSystemExtensionNode; export type ExecutableDefinitionNode = OperationDefinitionNode | FragmentDefinitionNode; @@ -209,6 +211,7 @@ export interface VariableDefinitionNode { readonly variable: VariableNode; readonly type: TypeNode; readonly defaultValue?: ValueNode; + readonly directives?: ReadonlyArray; } export interface VariableNode { @@ -372,16 +375,12 @@ export interface NonNullTypeNode { // Type System Definition -export type TypeSystemDefinitionNode = - | SchemaDefinitionNode - | TypeDefinitionNode - | TypeExtensionNode - | DirectiveDefinitionNode; +export type TypeSystemDefinitionNode = SchemaDefinitionNode | TypeDefinitionNode | DirectiveDefinitionNode; export interface SchemaDefinitionNode { readonly kind: "SchemaDefinition"; readonly loc?: Location; - readonly directives: ReadonlyArray; + readonly directives?: ReadonlyArray; readonly operationTypes: ReadonlyArray; } @@ -484,6 +483,28 @@ export interface InputObjectTypeDefinitionNode { readonly fields?: ReadonlyArray; } +// Directive Definitions + +export interface DirectiveDefinitionNode { + readonly kind: "DirectiveDefinition"; + readonly loc?: Location; + readonly description?: StringValueNode; + readonly name: NameNode; + readonly arguments?: ReadonlyArray; + readonly locations: ReadonlyArray; +} + +// Type System Extensions + +export type TypeSystemExtensionNode = SchemaExtensionNode | TypeExtensionNode; + +export type SchemaExtensionNode = { + readonly kind: "SchemaExtension"; + readonly loc?: Location; + readonly directives?: ReadonlyArray; + readonly operationTypes?: ReadonlyArray; +}; + // Type Extensions export type TypeExtensionNode = @@ -541,14 +562,3 @@ export interface InputObjectTypeExtensionNode { readonly directives?: ReadonlyArray; readonly fields?: ReadonlyArray; } - -// Directive Definitions - -export interface DirectiveDefinitionNode { - readonly kind: "DirectiveDefinition"; - readonly loc?: Location; - readonly description?: StringValueNode; - readonly name: NameNode; - readonly arguments?: ReadonlyArray; - readonly locations: ReadonlyArray; -} diff --git a/types/graphql/language/directiveLocation.d.ts b/types/graphql/language/directiveLocation.d.ts index 16c42d7877..d73e9f0e5a 100644 --- a/types/graphql/language/directiveLocation.d.ts +++ b/types/graphql/language/directiveLocation.d.ts @@ -13,6 +13,7 @@ type _DirectiveLocation = { FRAGMENT_DEFINITION: "FRAGMENT_DEFINITION"; FRAGMENT_SPREAD: "FRAGMENT_SPREAD"; INLINE_FRAGMENT: "INLINE_FRAGMENT"; + VARIABLE_DEFINITION: "VARIABLE_DEFINITION"; // Type System Definitions SCHEMA: "SCHEMA"; diff --git a/types/graphql/language/index.d.ts b/types/graphql/language/index.d.ts index e36dcbbb91..508a8063cf 100644 --- a/types/graphql/language/index.d.ts +++ b/types/graphql/language/index.d.ts @@ -66,9 +66,28 @@ export { EnumTypeDefinitionNode, EnumValueDefinitionNode, InputObjectTypeDefinitionNode, - TypeExtensionNode, - ObjectTypeExtensionNode, DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, } from "./ast"; +export { + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from "./predicates"; + export { DirectiveLocation, DirectiveLocationEnum } from "./directiveLocation"; diff --git a/types/graphql/language/kinds.d.ts b/types/graphql/language/kinds.d.ts index 768f00addd..54ad33bf57 100644 --- a/types/graphql/language/kinds.d.ts +++ b/types/graphql/language/kinds.d.ts @@ -12,7 +12,6 @@ type _Kind = { DOCUMENT: "Document"; OPERATION_DEFINITION: "OperationDefinition"; VARIABLE_DEFINITION: "VariableDefinition"; - VARIABLE: "Variable"; SELECTION_SET: "SelectionSet"; FIELD: "Field"; ARGUMENT: "Argument"; @@ -23,6 +22,7 @@ type _Kind = { FRAGMENT_DEFINITION: "FragmentDefinition"; // Values + VARIABLE: "Variable"; INT: "IntValue"; FLOAT: "FloatValue"; STRING: "StringValue"; @@ -56,6 +56,12 @@ type _Kind = { ENUM_VALUE_DEFINITION: "EnumValueDefinition"; INPUT_OBJECT_TYPE_DEFINITION: "InputObjectTypeDefinition"; + // Directive Definitions + DIRECTIVE_DEFINITION: "DirectiveDefinition"; + + // Type System Extensions + SCHEMA_EXTENSION: "SchemaExtension"; + // Type Extensions SCALAR_TYPE_EXTENSION: "ScalarTypeExtension"; OBJECT_TYPE_EXTENSION: "ObjectTypeExtension"; @@ -63,9 +69,6 @@ type _Kind = { UNION_TYPE_EXTENSION: "UnionTypeExtension"; ENUM_TYPE_EXTENSION: "EnumTypeExtension"; INPUT_OBJECT_TYPE_EXTENSION: "InputObjectTypeExtension"; - - // Directive Definitions - DIRECTIVE_DEFINITION: "DirectiveDefinition"; }; /** diff --git a/types/graphql/language/parser.d.ts b/types/graphql/language/parser.d.ts index b07db1ff38..c8117ac955 100644 --- a/types/graphql/language/parser.d.ts +++ b/types/graphql/language/parser.d.ts @@ -19,7 +19,7 @@ export interface ParseOptions { * specification. * * This option is provided to ease adoption of the final SDL specification - * and will be removed in a future major release. + * and will be removed in v16. */ allowLegacySDLEmptyFields?: boolean; @@ -29,7 +29,7 @@ export interface ParseOptions { * current specification. * * This option is provided to ease adoption of the final SDL specification - * and will be removed in a future major release. + * and will be removed in v16. */ allowLegacySDLImplementsInterfaces?: boolean; @@ -50,6 +50,17 @@ export interface ParseOptions { * future. */ experimentalFragmentVariables?: boolean; + + /** + * EXPERIMENTAL: + * + * If enabled, the parser understands directives on variable definitions: + * + * query Foo($var: String = "abc" @variable_definition_directive) { + * ... + * } + */ + experimentalVariableDefinitionDirectives?: boolean; } /** diff --git a/types/graphql/language/predicates.d.ts b/types/graphql/language/predicates.d.ts new file mode 100644 index 0000000000..81d2e02c41 --- /dev/null +++ b/types/graphql/language/predicates.d.ts @@ -0,0 +1,19 @@ +import { ASTNode } from "./ast"; + +export function isDefinitionNode(node: ASTNode): boolean; + +export function isExecutableDefinitionNode(node: ASTNode): boolean; + +export function isSelectionNode(node: ASTNode): boolean; + +export function isValueNode(node: ASTNode): boolean; + +export function isTypeNode(node: ASTNode): boolean; + +export function isTypeSystemDefinitionNode(node: ASTNode): boolean; + +export function isTypeDefinitionNode(node: ASTNode): boolean; + +export function isTypeSystemExtensionNode(node: ASTNode): boolean; + +export function isTypeExtensionNode(node: ASTNode): boolean; diff --git a/types/graphql/language/visitor.d.ts b/types/graphql/language/visitor.d.ts index be50e6e02e..26de8a9699 100644 --- a/types/graphql/language/visitor.d.ts +++ b/types/graphql/language/visitor.d.ts @@ -33,9 +33,9 @@ export type VisitFn = ( parent: TAnyNode | ReadonlyArray | undefined, // The key path to get to this node from the root node. path: ReadonlyArray, - // All nodes and Arrays visited before reaching this node. + // All nodes and Arrays visited before reaching parent of this node. // These correspond to array indices in `path`. - // Note: ancestors includes arrays which contain the visited node. + // Note: ancestors includes arrays which contain the parent of visited node. ancestors: ReadonlyArray> ) => any; diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index ced45be4a2..238446fb4c 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -16,6 +16,10 @@ import { FieldNode, FragmentDefinitionNode, ValueNode, + ScalarTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, } from "../language/ast"; import { GraphQLSchema } from "./schema"; @@ -152,7 +156,7 @@ export function assertAbstractType(type: any): GraphQLAbstractType; */ export class GraphQLList { readonly ofType: T; - constructor(type: T); + constructor(ofType: T); toString(): string; toJSON(): string; inspect(): string; @@ -180,7 +184,7 @@ export class GraphQLList { */ export class GraphQLNonNull { readonly ofType: T; - constructor(type: T); + constructor(ofType: T); toString(): string; toJSON(): string; inspect(): string; @@ -256,30 +260,36 @@ export type Thunk = (() => T) | T; export class GraphQLScalarType { name: string; description: Maybe; - astNode?: Maybe; + serialize: GraphQLScalarSerializer; + parseValue: GraphQLScalarValueParser; + parseLiteral: GraphQLScalarLiteralParser; + astNode: Maybe; + extensionASTNodes: Maybe>; constructor(config: GraphQLScalarTypeConfig); - // Serializes an internal value to include in a response. - serialize(value: any): any; - - // Parses an externally provided value to use as an input. - parseValue(value: any): any; - - // Parses an externally provided literal value to use as an input. - parseLiteral(valueNode: ValueNode, variables?: Maybe<{ [key: string]: any }>): any; - toString(): string; toJSON(): string; inspect(): string; } +export type GraphQLScalarSerializer = (value: any) => Maybe; +export type GraphQLScalarValueParser = (value: any) => Maybe; +export type GraphQLScalarLiteralParser = ( + valueNode: ValueNode, + variables: Maybe<{ [key: string]: any }> +) => Maybe; + export interface GraphQLScalarTypeConfig { name: string; description?: Maybe; + // Serializes an internal value to include in a response. + serialize: GraphQLScalarSerializer; + // Parses an externally provided value to use as an input. + parseValue?: GraphQLScalarValueParser; + // Parses an externally provided literal value to use as an input. + parseLiteral?: GraphQLScalarLiteralParser; astNode?: Maybe; - serialize(value: any): Maybe; - parseValue?(value: any): Maybe; - parseLiteral?(valueNode: ValueNode, variables: Maybe<{ [key: string]: any }>): Maybe; + extensionASTNodes?: Maybe>; } /** @@ -424,6 +434,8 @@ export interface GraphQLArgument { astNode?: Maybe; } +export function isRequiredArgument(arg: GraphQLArgument): boolean; + export type GraphQLFieldMap = { [key: string]: GraphQLField; }; @@ -502,7 +514,8 @@ export interface GraphQLInterfaceTypeConfig { export class GraphQLUnionType { name: string; description: Maybe; - astNode?: Maybe; + astNode: Maybe; + extensionASTNodes: Maybe>; resolveType: Maybe>; constructor(config: GraphQLUnionTypeConfig); @@ -525,6 +538,7 @@ export interface GraphQLUnionTypeConfig { resolveType?: Maybe>; description?: Maybe; astNode?: Maybe; + extensionASTNodes?: Maybe>; } /** @@ -552,6 +566,7 @@ export class GraphQLEnumType { name: string; description: Maybe; astNode: Maybe; + extensionASTNodes: Maybe>; constructor(config: GraphQLEnumTypeConfig); getValues(): GraphQLEnumValue[]; @@ -569,6 +584,7 @@ export interface GraphQLEnumTypeConfig { values: GraphQLEnumValueConfigMap; description?: Maybe; astNode?: Maybe; + extensionASTNodes?: Maybe>; } export type GraphQLEnumValueConfigMap = { [key: string]: GraphQLEnumValueConfig }; @@ -613,6 +629,7 @@ export class GraphQLInputObjectType { name: string; description: Maybe; astNode: Maybe; + extensionASTNodes: Maybe>; constructor(config: GraphQLInputObjectTypeConfig); getFields(): GraphQLInputFieldMap; toString(): string; @@ -625,6 +642,7 @@ export interface GraphQLInputObjectTypeConfig { fields: Thunk; description?: Maybe; astNode?: Maybe; + extensionASTNodes?: Maybe>; } export interface GraphQLInputFieldConfig { @@ -646,4 +664,6 @@ export interface GraphQLInputField { astNode?: Maybe; } +export function isRequiredInputField(field: GraphQLInputField): boolean; + export type GraphQLInputFieldMap = { [key: string]: GraphQLInputField }; diff --git a/types/graphql/type/index.d.ts b/types/graphql/type/index.d.ts index c498f648e4..039062aacf 100644 --- a/types/graphql/type/index.d.ts +++ b/types/graphql/type/index.d.ts @@ -25,6 +25,8 @@ export { isWrappingType, isNullableType, isNamedType, + isRequiredArgument, + isRequiredInputField, // Assertions assertType, assertScalarType, @@ -92,6 +94,9 @@ export { GraphQLScalarTypeConfig, GraphQLTypeResolver, GraphQLUnionTypeConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, } from "./definition"; export { diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index b5ddc9d8d4..7ccb390dbe 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -1,7 +1,7 @@ import Maybe from "../tsutils/Maybe"; import { GraphQLObjectType } from "./definition"; import { GraphQLType, GraphQLNamedType, GraphQLAbstractType } from "./definition"; -import { SchemaDefinitionNode } from "../language/ast"; +import { SchemaDefinitionNode, SchemaExtensionNode } from "../language/ast"; import { GraphQLDirective } from "./directives"; /** @@ -37,6 +37,7 @@ export function isSchema(schema: any): schema is GraphQLSchema; */ export class GraphQLSchema { astNode: Maybe; + extensionASTNodes: Maybe>; constructor(config: GraphQLSchemaConfig); @@ -70,8 +71,7 @@ export interface GraphQLSchemaValidationOptions { * in this list valid, even if they do not adhere to the specification's * schema validation rules. * - * This option is provided to ease adoption and may be removed in a future - * major release. + * This option is provided to ease adoption and will be removed in v15. */ allowedLegacyNames?: Maybe>; } @@ -83,4 +83,5 @@ export interface GraphQLSchemaConfig extends GraphQLSchemaValidationOptions { types?: Maybe; directives?: Maybe; astNode?: Maybe; + extensionASTNodes?: Maybe>; } diff --git a/types/graphql/utilities/buildASTSchema.d.ts b/types/graphql/utilities/buildASTSchema.d.ts index e2406c7ee1..1390601f65 100644 --- a/types/graphql/utilities/buildASTSchema.d.ts +++ b/types/graphql/utilities/buildASTSchema.d.ts @@ -7,8 +7,10 @@ import { NamedTypeNode, DirectiveDefinitionNode, FieldDefinitionNode, + InputValueDefinitionNode, + EnumValueDefinitionNode, } from "../language/ast"; -import { GraphQLNamedType, GraphQLFieldConfig } from "../type/definition"; +import { GraphQLNamedType, GraphQLFieldConfig, GraphQLInputField, GraphQLEnumValueConfig } from "../type/definition"; import { GraphQLDirective } from "../type/directives"; import { Source } from "../language/source"; import { GraphQLSchema, GraphQLSchemaValidationOptions } from "../type/schema"; @@ -20,10 +22,18 @@ interface BuildSchemaOptions extends GraphQLSchemaValidationOptions { * Descriptions are defined as preceding string literals, however an older * experimental version of the SDL supported preceding comments as * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. * * Default: false */ commentDescriptions?: boolean; + + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean; } /** @@ -42,7 +52,7 @@ interface BuildSchemaOptions extends GraphQLSchemaValidationOptions { * Provide true to use preceding comments as the description. * */ -export function buildASTSchema(ast: DocumentNode, options?: BuildSchemaOptions): GraphQLSchema; +export function buildASTSchema(documentAST: DocumentNode, options?: BuildSchemaOptions): GraphQLSchema; type TypeDefinitionsMap = { [key: string]: TypeDefinitionNode }; type TypeResolver = (typeRef: NamedTypeNode) => GraphQLNamedType; @@ -57,10 +67,15 @@ export class ASTDefinitionBuilder { buildDirective(directiveNode: DirectiveDefinitionNode): GraphQLDirective; buildField(field: FieldDefinitionNode): GraphQLFieldConfig; + + buildInputField(value: InputValueDefinitionNode): GraphQLInputField; + + buildEnumValue(value: EnumValueDefinitionNode): GraphQLEnumValueConfig; } /** * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. * * Accepts options as a second argument: * diff --git a/types/graphql/utilities/coerceValue.d.ts b/types/graphql/utilities/coerceValue.d.ts index 081eea4a32..d1fb9eceee 100644 --- a/types/graphql/utilities/coerceValue.d.ts +++ b/types/graphql/utilities/coerceValue.d.ts @@ -1,4 +1,4 @@ -import { GraphQLError } from "../error"; +import { GraphQLError } from "../error/GraphQLError"; import { ASTNode } from "../language/ast"; import { GraphQLInputType } from "../type/definition"; diff --git a/types/graphql/utilities/extendSchema.d.ts b/types/graphql/utilities/extendSchema.d.ts index 7cde767ed7..094a10310d 100644 --- a/types/graphql/utilities/extendSchema.d.ts +++ b/types/graphql/utilities/extendSchema.d.ts @@ -7,10 +7,18 @@ interface Options extends GraphQLSchemaValidationOptions { * Descriptions are defined as preceding string literals, however an older * experimental version of the SDL supported preceding comments as * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. * * Default: false */ commentDescriptions?: boolean; + + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean; } /** diff --git a/types/graphql/utilities/findBreakingChanges.d.ts b/types/graphql/utilities/findBreakingChanges.d.ts index 84f1bea158..4b8111d3a5 100644 --- a/types/graphql/utilities/findBreakingChanges.d.ts +++ b/types/graphql/utilities/findBreakingChanges.d.ts @@ -12,7 +12,7 @@ import { GraphQLDirective } from "../type/directives"; import { GraphQLSchema } from "../type/schema"; import { DirectiveLocationEnum } from "../language/directiveLocation"; -export const BreakingChangeType : _BreakingChangeType; +export const BreakingChangeType: _BreakingChangeType; // @internal type _BreakingChangeType = { @@ -24,13 +24,13 @@ type _BreakingChangeType = { VALUE_REMOVED_FROM_ENUM: "VALUE_REMOVED_FROM_ENUM"; ARG_REMOVED: "ARG_REMOVED"; ARG_CHANGED_KIND: "ARG_CHANGED_KIND"; - NON_NULL_ARG_ADDED: "NON_NULL_ARG_ADDED"; - NON_NULL_INPUT_FIELD_ADDED: "NON_NULL_INPUT_FIELD_ADDED"; + REQUIRED_ARG_ADDED: "REQUIRED_ARG_ADDED"; + REQUIRED_INPUT_FIELD_ADDED: "REQUIRED_INPUT_FIELD_ADDED"; INTERFACE_REMOVED_FROM_OBJECT: "INTERFACE_REMOVED_FROM_OBJECT"; DIRECTIVE_REMOVED: "DIRECTIVE_REMOVED"; DIRECTIVE_ARG_REMOVED: "DIRECTIVE_ARG_REMOVED"; DIRECTIVE_LOCATION_REMOVED: "DIRECTIVE_LOCATION_REMOVED"; - NON_NULL_DIRECTIVE_ARG_ADDED: "NON_NULL_DIRECTIVE_ARG_ADDED"; + REQUIRED_DIRECTIVE_ARG_ADDED: "REQUIRED_DIRECTIVE_ARG_ADDED"; }; export const DangerousChangeType: _DangerousChangeType; @@ -41,8 +41,8 @@ type _DangerousChangeType = { VALUE_ADDED_TO_ENUM: "VALUE_ADDED_TO_ENUM"; INTERFACE_ADDED_TO_OBJECT: "INTERFACE_ADDED_TO_OBJECT"; TYPE_ADDED_TO_UNION: "TYPE_ADDED_TO_UNION"; - NULLABLE_INPUT_FIELD_ADDED: "NULLABLE_INPUT_FIELD_ADDED"; - NULLABLE_ARG_ADDED: "NULLABLE_ARG_ADDED"; + OPTIONAL_INPUT_FIELD_ADDED: "OPTIONAL_INPUT_FIELD_ADDED"; + OPTIONAL_ARG_ADDED: "OPTIONAL_ARG_ADDED"; }; export interface BreakingChange { diff --git a/types/graphql/utilities/getOperationRootType.d.ts b/types/graphql/utilities/getOperationRootType.d.ts new file mode 100644 index 0000000000..e1f88e7e13 --- /dev/null +++ b/types/graphql/utilities/getOperationRootType.d.ts @@ -0,0 +1,11 @@ +import { GraphQLSchema } from "../type/schema"; +import { OperationDefinitionNode, OperationTypeDefinitionNode } from "../language/ast"; +import { GraphQLObjectType } from "../type/definition"; + +/** + * Extracts the root type of the operation from the schema. + */ +export function getOperationRootType( + schema: GraphQLSchema, + operation: OperationDefinitionNode | OperationTypeDefinitionNode +): GraphQLObjectType; diff --git a/types/graphql/utilities/index.d.ts b/types/graphql/utilities/index.d.ts index f571c3ab76..29e90b1fee 100644 --- a/types/graphql/utilities/index.d.ts +++ b/types/graphql/utilities/index.d.ts @@ -1,7 +1,7 @@ // The GraphQL query recommended for a full schema introspection. export { getIntrospectionQuery, - // Deprecated, use getIntrospectionQuery() + // @deprecated, use getIntrospectionQuery() - will be removed in v15 introspectionQuery, } from "./introspectionQuery"; @@ -33,6 +33,9 @@ export { // Gets the target Operation from a Document export { getOperationAST } from "./getOperationAST"; +// Gets the Type for the target Operation AST. +export { getOperationRootType } from "./getOperationRootType"; + // Convert a GraphQLSchema to an IntrospectionQuery export { introspectionFromSchema } from "./introspectionFromSchema"; @@ -40,7 +43,14 @@ export { introspectionFromSchema } from "./introspectionFromSchema"; export { buildClientSchema } from "./buildClientSchema"; // Build a GraphQLSchema from GraphQL Schema language. -export { buildASTSchema, buildSchema, getDescription, BuildSchemaOptions } from "./buildASTSchema"; +export { + buildASTSchema, + buildSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16 + getDescription, + BuildSchemaOptions, +} from "./buildASTSchema"; // Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. export { extendSchema } from "./extendSchema"; @@ -70,10 +80,10 @@ export { TypeInfo } from "./TypeInfo"; // Coerces a JavaScript value to a GraphQL type, or produces errors. export { coerceValue } from "./coerceValue"; -// @deprecated use coerceValue +// @deprecated use coerceValue - will be removed in v15 export { isValidJSValue } from "./isValidJSValue"; -// Determine if AST values adhere to a GraphQL type. +// @deprecated use validation - will be removed in v15 export { isValidLiteralValue } from "./isValidLiteralValue"; // Concatenates multiple AST together. diff --git a/types/graphql/utilities/introspectionFromSchema.d.ts b/types/graphql/utilities/introspectionFromSchema.d.ts index 8733a35087..8b2df44439 100644 --- a/types/graphql/utilities/introspectionFromSchema.d.ts +++ b/types/graphql/utilities/introspectionFromSchema.d.ts @@ -10,4 +10,4 @@ import { IntrospectionQuery, IntrospectionOptions } from "./introspectionQuery"; * This is the inverse of buildClientSchema. The primary use case is outside * of the server context, for instance when doing schema comparisons. */ -export function introspectionFromSchema(schema: GraphQLSchema, options: IntrospectionOptions): IntrospectionQuery; +export function introspectionFromSchema(schema: GraphQLSchema, options?: IntrospectionOptions): IntrospectionQuery; diff --git a/types/graphql/utilities/introspectionQuery.d.ts b/types/graphql/utilities/introspectionQuery.d.ts index f2172595f8..a256f96cd4 100644 --- a/types/graphql/utilities/introspectionQuery.d.ts +++ b/types/graphql/utilities/introspectionQuery.d.ts @@ -9,6 +9,11 @@ export interface IntrospectionOptions { export function getIntrospectionQuery(options?: IntrospectionOptions): string; +/** + * Deprecated, call getIntrospectionQuery directly. + * + * This function will be removed in v15 + */ export const introspectionQuery: string; export interface IntrospectionQuery { diff --git a/types/graphql/utilities/isValidJSValue.d.ts b/types/graphql/utilities/isValidJSValue.d.ts index d45d104ffd..e64a64d768 100644 --- a/types/graphql/utilities/isValidJSValue.d.ts +++ b/types/graphql/utilities/isValidJSValue.d.ts @@ -2,5 +2,7 @@ import { GraphQLInputType } from "../type/definition"; /** * Deprecated. Use coerceValue() directly for richer information. + * + * This function will be removed in v15 */ export function isValidJSValue(value: any, type: GraphQLInputType): string[]; diff --git a/types/graphql/utilities/isValidLiteralValue.d.ts b/types/graphql/utilities/isValidLiteralValue.d.ts index 6a9275bce9..34ee223ba2 100644 --- a/types/graphql/utilities/isValidLiteralValue.d.ts +++ b/types/graphql/utilities/isValidLiteralValue.d.ts @@ -6,5 +6,7 @@ import { GraphQLInputType } from "../type/definition"; * Utility which determines if a value literal node is valid for an input type. * * Deprecated. Rely on validation for documents containing literal values. + * + * This function will be removed in v15 */ export function isValidLiteralValue(type: GraphQLInputType, valueNode: ValueNode): ReadonlyArray; diff --git a/types/graphql/utilities/schemaPrinter.d.ts b/types/graphql/utilities/schemaPrinter.d.ts index 8e3aefe7fc..154d287cc9 100644 --- a/types/graphql/utilities/schemaPrinter.d.ts +++ b/types/graphql/utilities/schemaPrinter.d.ts @@ -2,6 +2,14 @@ import { GraphQLSchema } from "../type/schema"; import { GraphQLType, GraphQLNamedType } from "../type/definition"; export interface Options { + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ commentDescriptions?: boolean; } diff --git a/types/graphql/validation/ValidationContext.d.ts b/types/graphql/validation/ValidationContext.d.ts index 24049decdf..0da635756a 100644 --- a/types/graphql/validation/ValidationContext.d.ts +++ b/types/graphql/validation/ValidationContext.d.ts @@ -18,6 +18,7 @@ import { } from "../type/definition"; import { GraphQLDirective } from "../type/directives"; import { TypeInfo } from "../utilities/TypeInfo"; +import { ASTVisitor } from "../language/visitor"; type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; type VariableUsage = { @@ -31,16 +32,28 @@ type VariableUsage = { * allowing access to commonly useful contextual information from within a * validation rule. */ -export default class ValidationContext { - constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); +export class ASTValidationContext { + constructor(ast: DocumentNode); reportError(error: GraphQLError): undefined; getErrors(): ReadonlyArray; - getSchema(): GraphQLSchema; - getDocument(): DocumentNode; +} + +export class SDLValidationContext extends ASTValidationContext { + constructor(ast: DocumentNode, schema?: Maybe); + + getSchema(): Maybe; +} + +export type SDLValidationRule = (context: SDLValidationContext) => ASTVisitor; + +export class ValidationContext extends ASTValidationContext { + constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); + + getSchema(): GraphQLSchema; getFragment(name: string): Maybe; @@ -66,3 +79,5 @@ export default class ValidationContext { getArgument(): Maybe; } + +export type ValidationRule = (context: ValidationContext) => ASTVisitor; diff --git a/types/graphql/validation/index.d.ts b/types/graphql/validation/index.d.ts index 911c592432..3046930152 100644 --- a/types/graphql/validation/index.d.ts +++ b/types/graphql/validation/index.d.ts @@ -1,7 +1,6 @@ export { validate } from "./validate"; -import ValidationContext from "./ValidationContext"; -export { ValidationContext }; +export { ValidationContext } from "./ValidationContext"; export { specifiedRules } from "./specifiedRules"; @@ -45,7 +44,7 @@ export { OverlappingFieldsCanBeMerged as OverlappingFieldsCanBeMergedRule } from export { PossibleFragmentSpreads as PossibleFragmentSpreadsRule } from "./rules/PossibleFragmentSpreads"; // Spec Section: "Argument Optionality" -export { ProvidedNonNullArguments as ProvidedNonNullArgumentsRule } from "./rules/ProvidedNonNullArguments"; +export { ProvidedRequiredArguments as ProvidedRequiredArgumentsRule } from "./rules/ProvidedRequiredArguments"; // Spec Section: "Leaf Field Selections" export { ScalarLeafs as ScalarLeafsRule } from "./rules/ScalarLeafs"; @@ -77,8 +76,5 @@ export { ValuesOfCorrectType as ValuesOfCorrectTypeRule } from "./rules/ValuesOf // Spec Section: "Variables are Input Types" export { VariablesAreInputTypes as VariablesAreInputTypesRule } from "./rules/VariablesAreInputTypes"; -// Spec Section: "Variables Default Value Is Allowed" -export { VariablesDefaultValueAllowed as VariablesDefaultValueAllowedRule } from "./rules/VariablesDefaultValueAllowed"; - // Spec Section: "All Variable Usages Are Allowed" export { VariablesInAllowedPosition as VariablesInAllowedPositionRule } from "./rules/VariablesInAllowedPosition"; diff --git a/types/graphql/validation/rules/ExecutableDefinitions.d.ts b/types/graphql/validation/rules/ExecutableDefinitions.d.ts index 423e0dcad2..405e140530 100644 --- a/types/graphql/validation/rules/ExecutableDefinitions.d.ts +++ b/types/graphql/validation/rules/ExecutableDefinitions.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ASTValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function nonExecutableDefinitionMessage(defName: string): string; @@ -9,4 +9,4 @@ export function nonExecutableDefinitionMessage(defName: string): string; * A GraphQL document is only valid for execution if all definitions are either * operation or fragment definitions. */ -export function ExecutableDefinitions(context: ValidationContext): ASTVisitor; +export function ExecutableDefinitions(context: ASTValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/FieldsOnCorrectType.d.ts b/types/graphql/validation/rules/FieldsOnCorrectType.d.ts index c5c7f053c2..a2dd533502 100644 --- a/types/graphql/validation/rules/FieldsOnCorrectType.d.ts +++ b/types/graphql/validation/rules/FieldsOnCorrectType.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; /** diff --git a/types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts b/types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts index 7c760e331f..d45212c58b 100644 --- a/types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts +++ b/types/graphql/validation/rules/FragmentsOnCompositeTypes.d.ts @@ -1,10 +1,9 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -import { GraphQLType } from "../../type/definition"; -export function inlineFragmentOnNonCompositeErrorMessage(type: GraphQLType): string; +export function inlineFragmentOnNonCompositeErrorMessage(type: string): string; -export function fragmentOnNonCompositeErrorMessage(fragName: string, type: GraphQLType): string; +export function fragmentOnNonCompositeErrorMessage(fragName: string, type: string): string; /** * Fragments on composite type diff --git a/types/graphql/validation/rules/KnownArgumentNames.d.ts b/types/graphql/validation/rules/KnownArgumentNames.d.ts index 9602c34c43..25bd10ebed 100644 --- a/types/graphql/validation/rules/KnownArgumentNames.d.ts +++ b/types/graphql/validation/rules/KnownArgumentNames.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext, SDLValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function unknownArgMessage( @@ -21,3 +21,6 @@ export function unknownDirectiveArgMessage( * that field. */ export function KnownArgumentNames(context: ValidationContext): ASTVisitor; + +// @internal +export function KnownArgumentNamesOnDirectives(context: ValidationContext | SDLValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/KnownDirectives.d.ts b/types/graphql/validation/rules/KnownDirectives.d.ts index 179e65b9f7..35859f9c2d 100644 --- a/types/graphql/validation/rules/KnownDirectives.d.ts +++ b/types/graphql/validation/rules/KnownDirectives.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext, SDLValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function unknownDirectiveMessage(directiveName: string): string; @@ -11,4 +11,4 @@ export function misplacedDirectiveMessage(directiveName: string, location: strin * A GraphQL document is only valid if all `@directives` are known by the * schema and legally positioned. */ -export function KnownDirectives(context: ValidationContext): ASTVisitor; +export function KnownDirectives(context: ValidationContext | SDLValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/KnownFragmentNames.d.ts b/types/graphql/validation/rules/KnownFragmentNames.d.ts index 40405f67dd..5709ef3e63 100644 --- a/types/graphql/validation/rules/KnownFragmentNames.d.ts +++ b/types/graphql/validation/rules/KnownFragmentNames.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function unknownFragmentMessage(fragName: string): string; diff --git a/types/graphql/validation/rules/KnownTypeNames.d.ts b/types/graphql/validation/rules/KnownTypeNames.d.ts index 6bef3661f9..1fe8885dab 100644 --- a/types/graphql/validation/rules/KnownTypeNames.d.ts +++ b/types/graphql/validation/rules/KnownTypeNames.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function unknownTypeMessage(typeName: string, suggestedTypes: Array): string; diff --git a/types/graphql/validation/rules/LoneAnonymousOperation.d.ts b/types/graphql/validation/rules/LoneAnonymousOperation.d.ts index 881814c4d2..4fa878774c 100644 --- a/types/graphql/validation/rules/LoneAnonymousOperation.d.ts +++ b/types/graphql/validation/rules/LoneAnonymousOperation.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ASTValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function anonOperationNotAloneMessage(): string; @@ -9,4 +9,4 @@ export function anonOperationNotAloneMessage(): string; * A GraphQL document is only valid if when it contains an anonymous operation * (the query short-hand) that it contains only that one operation definition. */ -export function LoneAnonymousOperation(context: ValidationContext): ASTVisitor; +export function LoneAnonymousOperation(context: ASTValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/LoneSchemaDefinition.d.ts b/types/graphql/validation/rules/LoneSchemaDefinition.d.ts new file mode 100644 index 0000000000..66b1844c54 --- /dev/null +++ b/types/graphql/validation/rules/LoneSchemaDefinition.d.ts @@ -0,0 +1,13 @@ +import { SDLValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function schemaDefinitionNotAloneMessage(): string; + +export function canNotDefineSchemaWithinExtensionMessage(): string; + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ +export function LoneSchemaDefinition(context: SDLValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/NoFragmentCycles.d.ts b/types/graphql/validation/rules/NoFragmentCycles.d.ts index f119c5a487..bd9e9b1c1a 100644 --- a/types/graphql/validation/rules/NoFragmentCycles.d.ts +++ b/types/graphql/validation/rules/NoFragmentCycles.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function cycleErrorMessage(fragName: string, spreadNames: Array): string; diff --git a/types/graphql/validation/rules/NoUndefinedVariables.d.ts b/types/graphql/validation/rules/NoUndefinedVariables.d.ts index f340b41ad8..415382149e 100644 --- a/types/graphql/validation/rules/NoUndefinedVariables.d.ts +++ b/types/graphql/validation/rules/NoUndefinedVariables.d.ts @@ -1,5 +1,5 @@ import Maybe from "../../tsutils/Maybe"; -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function undefinedVarMessage(varName: string, opName: Maybe): string; diff --git a/types/graphql/validation/rules/NoUnusedFragments.d.ts b/types/graphql/validation/rules/NoUnusedFragments.d.ts index 6f757c16c2..91978e7875 100644 --- a/types/graphql/validation/rules/NoUnusedFragments.d.ts +++ b/types/graphql/validation/rules/NoUnusedFragments.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function unusedFragMessage(fragName: string): string; diff --git a/types/graphql/validation/rules/NoUnusedVariables.d.ts b/types/graphql/validation/rules/NoUnusedVariables.d.ts index 1846995a1f..f0052f7940 100644 --- a/types/graphql/validation/rules/NoUnusedVariables.d.ts +++ b/types/graphql/validation/rules/NoUnusedVariables.d.ts @@ -1,5 +1,5 @@ import Maybe from "../../tsutils/Maybe"; -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function unusedVariableMessage(varName: string, opName: Maybe): string; diff --git a/types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts b/types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts index 1dfa62a089..dc9993e3f0 100644 --- a/types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts +++ b/types/graphql/validation/rules/OverlappingFieldsCanBeMerged.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function fieldsConflictMessage(responseName: string, reason: ConflictReasonMessage): string; diff --git a/types/graphql/validation/rules/PossibleFragmentSpreads.d.ts b/types/graphql/validation/rules/PossibleFragmentSpreads.d.ts index f318cb189e..cd83879798 100644 --- a/types/graphql/validation/rules/PossibleFragmentSpreads.d.ts +++ b/types/graphql/validation/rules/PossibleFragmentSpreads.d.ts @@ -1,10 +1,9 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -import { GraphQLType } from "../../type/definition"; -export function typeIncompatibleSpreadMessage(fragName: string, parentType: GraphQLType, fragType: GraphQLType): string; +export function typeIncompatibleSpreadMessage(fragName: string, parentType: string, fragType: string): string; -export function typeIncompatibleAnonSpreadMessage(parentType: GraphQLType, fragType: GraphQLType): string; +export function typeIncompatibleAnonSpreadMessage(parentType: string, fragType: string): string; /** * Possible fragment spread diff --git a/types/graphql/validation/rules/ProvidedNonNullArguments.d.ts b/types/graphql/validation/rules/ProvidedNonNullArguments.d.ts deleted file mode 100644 index e442b47f83..0000000000 --- a/types/graphql/validation/rules/ProvidedNonNullArguments.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import ValidationContext from "../ValidationContext"; -import { ASTVisitor } from "../../language/visitor"; -import { GraphQLType } from "../../type/definition"; - -export function missingFieldArgMessage(fieldName: string, argName: string, type: GraphQLType): string; - -export function missingDirectiveArgMessage(directiveName: string, argName: string, type: GraphQLType): string; - -/** - * Provided required arguments - * - * A field or directive is only valid if all required (non-null) field arguments - * have been provided. - */ -export function ProvidedNonNullArguments(context: ValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/ProvidedRequiredArguments.d.ts b/types/graphql/validation/rules/ProvidedRequiredArguments.d.ts new file mode 100644 index 0000000000..000095510f --- /dev/null +++ b/types/graphql/validation/rules/ProvidedRequiredArguments.d.ts @@ -0,0 +1,17 @@ +import { ValidationContext, SDLValidationContext } from "../ValidationContext"; +import { ASTVisitor } from "../../language/visitor"; + +export function missingFieldArgMessage(fieldName: string, argName: string, type: string): string; + +export function missingDirectiveArgMessage(directiveName: string, argName: string, type: string): string; + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ +export function ProvidedRequiredArguments(context: ValidationContext): ASTVisitor; + +// @internal +export function ProvidedRequiredArgumentsOnDirectives(context: ValidationContext | SDLValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/ScalarLeafs.d.ts b/types/graphql/validation/rules/ScalarLeafs.d.ts index 5bbf85043a..c6f73ec047 100644 --- a/types/graphql/validation/rules/ScalarLeafs.d.ts +++ b/types/graphql/validation/rules/ScalarLeafs.d.ts @@ -1,10 +1,9 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -import { GraphQLType } from "../../type/definition"; -export function noSubselectionAllowedMessage(fieldName: string, type: GraphQLType): string; +export function noSubselectionAllowedMessage(fieldName: string, type: string): string; -export function requiredSubselectionMessage(fieldName: string, type: GraphQLType): string; +export function requiredSubselectionMessage(fieldName: string, type: string): string; /** * Scalar leafs diff --git a/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts b/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts index 54b1fec36a..1e473032ce 100644 --- a/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts +++ b/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts @@ -1,5 +1,5 @@ import Maybe from "../../tsutils/Maybe"; -import ValidationContext from "../ValidationContext"; +import { ASTValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function singleFieldOnlyMessage(name: Maybe): string; @@ -9,4 +9,4 @@ export function singleFieldOnlyMessage(name: Maybe): string; * * A GraphQL subscription is valid only if it contains a single root field. */ -export function SingleFieldSubscriptions(context: ValidationContext): ASTVisitor; +export function SingleFieldSubscriptions(context: ASTValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/UniqueArgumentNames.d.ts b/types/graphql/validation/rules/UniqueArgumentNames.d.ts index 47a59c3362..3c6b0d5f02 100644 --- a/types/graphql/validation/rules/UniqueArgumentNames.d.ts +++ b/types/graphql/validation/rules/UniqueArgumentNames.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ASTValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function duplicateArgMessage(argName: string): string; @@ -9,4 +9,4 @@ export function duplicateArgMessage(argName: string): string; * A GraphQL field or directive is only valid if all supplied arguments are * uniquely named. */ -export function UniqueArgumentNames(context: ValidationContext): ASTVisitor; +export function UniqueArgumentNames(context: ASTValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts b/types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts index f3d6327c23..6a3b9e16b6 100644 --- a/types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts +++ b/types/graphql/validation/rules/UniqueDirectivesPerLocation.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ASTValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function duplicateDirectiveMessage(directiveName: string): string; @@ -9,4 +9,4 @@ export function duplicateDirectiveMessage(directiveName: string): string; * A GraphQL document is only valid if all directives at a given location * are uniquely named. */ -export function UniqueDirectivesPerLocation(context: ValidationContext): ASTVisitor; +export function UniqueDirectivesPerLocation(context: ASTValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/UniqueFragmentNames.d.ts b/types/graphql/validation/rules/UniqueFragmentNames.d.ts index 9a2554200c..08504fec6d 100644 --- a/types/graphql/validation/rules/UniqueFragmentNames.d.ts +++ b/types/graphql/validation/rules/UniqueFragmentNames.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ASTValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function duplicateFragmentNameMessage(fragName: string): string; @@ -8,4 +8,4 @@ export function duplicateFragmentNameMessage(fragName: string): string; * * A GraphQL document is only valid if all defined fragments have unique names. */ -export function UniqueFragmentNames(context: ValidationContext): ASTVisitor; +export function UniqueFragmentNames(context: ASTValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/UniqueInputFieldNames.d.ts b/types/graphql/validation/rules/UniqueInputFieldNames.d.ts index 34d5b9845a..d59fdaee1b 100644 --- a/types/graphql/validation/rules/UniqueInputFieldNames.d.ts +++ b/types/graphql/validation/rules/UniqueInputFieldNames.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ASTValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function duplicateInputFieldMessage(fieldName: string): string; @@ -9,4 +9,4 @@ export function duplicateInputFieldMessage(fieldName: string): string; * A GraphQL input object value is only valid if all supplied fields are * uniquely named. */ -export function UniqueInputFieldNames(context: ValidationContext): ASTVisitor; +export function UniqueInputFieldNames(context: ASTValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/UniqueOperationNames.d.ts b/types/graphql/validation/rules/UniqueOperationNames.d.ts index 221b1187c2..8cc4dc03ba 100644 --- a/types/graphql/validation/rules/UniqueOperationNames.d.ts +++ b/types/graphql/validation/rules/UniqueOperationNames.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ASTValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function duplicateOperationNameMessage(operationName: string): string; @@ -8,4 +8,4 @@ export function duplicateOperationNameMessage(operationName: string): string; * * A GraphQL document is only valid if all defined operations have unique names. */ -export function UniqueOperationNames(context: ValidationContext): ASTVisitor; +export function UniqueOperationNames(context: ASTValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/UniqueVariableNames.d.ts b/types/graphql/validation/rules/UniqueVariableNames.d.ts index d0aaf0404e..0f9439b5af 100644 --- a/types/graphql/validation/rules/UniqueVariableNames.d.ts +++ b/types/graphql/validation/rules/UniqueVariableNames.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ASTValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function duplicateVariableMessage(variableName: string): string; @@ -8,4 +8,4 @@ export function duplicateVariableMessage(variableName: string): string; * * A GraphQL operation is only valid if all its variables are uniquely named. */ -export function UniqueVariableNames(context: ValidationContext): ASTVisitor; +export function UniqueVariableNames(context: ASTValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/ValuesOfCorrectType.d.ts b/types/graphql/validation/rules/ValuesOfCorrectType.d.ts index 09314835ad..9896207d33 100644 --- a/types/graphql/validation/rules/ValuesOfCorrectType.d.ts +++ b/types/graphql/validation/rules/ValuesOfCorrectType.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function badValueMessage(typeName: string, valueName: string, message?: string): string; diff --git a/types/graphql/validation/rules/VariablesAreInputTypes.d.ts b/types/graphql/validation/rules/VariablesAreInputTypes.d.ts index 32472e15fd..712e645092 100644 --- a/types/graphql/validation/rules/VariablesAreInputTypes.d.ts +++ b/types/graphql/validation/rules/VariablesAreInputTypes.d.ts @@ -1,4 +1,4 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; export function nonInputTypeOnVarMessage(variableName: string, typeName: string): string; diff --git a/types/graphql/validation/rules/VariablesDefaultValueAllowed.d.ts b/types/graphql/validation/rules/VariablesDefaultValueAllowed.d.ts deleted file mode 100644 index 1961eb645e..0000000000 --- a/types/graphql/validation/rules/VariablesDefaultValueAllowed.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import ValidationContext from "../ValidationContext"; -import { ASTVisitor } from "../../language/visitor"; -import { GraphQLType } from "../../type/definition"; - -export function defaultForRequiredVarMessage(varName: string, type: GraphQLType, guessType: GraphQLType): string; - -/** - * Variable's default value is allowed - * - * A GraphQL document is only valid if all variable default values are allowed - * due to a variable not being required. - */ -export function VariablesDefaultValueAllowed(context: ValidationContext): ASTVisitor; diff --git a/types/graphql/validation/rules/VariablesInAllowedPosition.d.ts b/types/graphql/validation/rules/VariablesInAllowedPosition.d.ts index f21ed5c7fb..2e994a3438 100644 --- a/types/graphql/validation/rules/VariablesInAllowedPosition.d.ts +++ b/types/graphql/validation/rules/VariablesInAllowedPosition.d.ts @@ -1,8 +1,7 @@ -import ValidationContext from "../ValidationContext"; +import { ValidationContext } from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -import { GraphQLType } from "../../type/definition"; -export function badVarPosMessage(varName: string, varType: GraphQLType, expectedType: GraphQLType): string; +export function badVarPosMessage(varName: string, varType: string, expectedType: string): string; /** * Variables passed to field arguments conform to type diff --git a/types/graphql/validation/specifiedRules.d.ts b/types/graphql/validation/specifiedRules.d.ts index 8e9815377f..c7c177b00e 100644 --- a/types/graphql/validation/specifiedRules.d.ts +++ b/types/graphql/validation/specifiedRules.d.ts @@ -1,3 +1,5 @@ +import { ValidationRule, SDLValidationRule } from "./ValidationContext"; + // Spec Section: "Executable Definitions" import { ExecutableDefinitions } from "./rules/ExecutableDefinitions"; @@ -65,10 +67,7 @@ import { UniqueArgumentNames } from "./rules/UniqueArgumentNames"; import { ValuesOfCorrectType } from "./rules/ValuesOfCorrectType"; // Spec Section: "Argument Optionality" -import { ProvidedNonNullArguments } from "./rules/ProvidedNonNullArguments"; - -// Spec Section: "Variables Default Value Is Allowed" -import { VariablesDefaultValueAllowed } from "./rules/VariablesDefaultValueAllowed"; +import { ProvidedRequiredArguments } from "./rules/ProvidedRequiredArguments"; // Spec Section: "All Variable Usages Are Allowed" import { VariablesInAllowedPosition } from "./rules/VariablesInAllowedPosition"; @@ -79,12 +78,15 @@ import { OverlappingFieldsCanBeMerged } from "./rules/OverlappingFieldsCanBeMerg // Spec Section: "Input Object Field Uniqueness" import { UniqueInputFieldNames } from "./rules/UniqueInputFieldNames"; -import ValidationContext from "./ValidationContext"; - /** * This set includes all validation rules defined by the GraphQL spec. * * The order of the rules in this list has been adjusted to lead to the * most clear output when encountering multiple validation errors. */ -export const specifiedRules: Array<(context: ValidationContext) => any>; +export const specifiedRules: ReadonlyArray; + +import { LoneSchemaDefinition } from "./rules/LoneSchemaDefinition"; + +// @internal +export const specifiedSDLRules: ReadonlyArray; diff --git a/types/graphql/validation/validate.d.ts b/types/graphql/validation/validate.d.ts index 9a5092d258..6c0e644ea3 100644 --- a/types/graphql/validation/validate.d.ts +++ b/types/graphql/validation/validate.d.ts @@ -2,6 +2,7 @@ import { GraphQLError } from "../error"; import { DocumentNode } from "../language/ast"; import { GraphQLSchema } from "../type/schema"; import { TypeInfo } from "../utilities/TypeInfo"; +import { ValidationRule } from "./ValidationContext"; /** * Implements the "Validation" section of the spec. @@ -21,7 +22,23 @@ import { TypeInfo } from "../utilities/TypeInfo"; */ export function validate( schema: GraphQLSchema, - ast: DocumentNode, - rules?: ReadonlyArray, + documentAST: DocumentNode, + rules?: ReadonlyArray, typeInfo?: TypeInfo ): ReadonlyArray; + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDL(documentAST: DocumentNode): undefined; + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDLExtension(documentAST: DocumentNode, schema: GraphQLSchema): undefined; diff --git a/types/grasp/grasp-tests.ts b/types/grasp/grasp-tests.ts index 87da0b8d45..0c732e2e21 100644 --- a/types/grasp/grasp-tests.ts +++ b/types/grasp/grasp-tests.ts @@ -17,10 +17,7 @@ grasp({ }); // $ExpectError -grasp({ - args: [], - textFormat: { cyan: "cyan" } -}); +grasp({ args: [], textFormat: { cyan: "cyan" } }); // $ExpectType string grasp.VERSION; diff --git a/types/grpc-error/grpc-error-tests.ts b/types/grpc-error/grpc-error-tests.ts new file mode 100644 index 0000000000..f8f309cb65 --- /dev/null +++ b/types/grpc-error/grpc-error-tests.ts @@ -0,0 +1,7 @@ +import GRPCError = require('grpc-error'); + +const error1 = new GRPCError('test'); +const error2 = new GRPCError({status_code: 'invalid'}); +const error3 = new GRPCError('test', 12); +const error4 = new GRPCError('test', {status_code: 'invalid'}); +const error5 = new GRPCError('test', 12, {status_code: 'invalid'}); diff --git a/types/grpc-error/index.d.ts b/types/grpc-error/index.d.ts new file mode 100644 index 0000000000..6f76d288db --- /dev/null +++ b/types/grpc-error/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for grpc-error 1.0 +// Project: https://github.com/bojand/grpc-error +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare class GRPCError extends Error { + constructor(value: string | object); + constructor(message: string, value: number | object); + constructor(message: string, code: number, metadata: object); + + code: number; + metadata: object; +} + +export = GRPCError; diff --git a/types/grpc-error/tsconfig.json b/types/grpc-error/tsconfig.json new file mode 100644 index 0000000000..51388578e0 --- /dev/null +++ b/types/grpc-error/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "grpc-error-tests.ts" + ] +} diff --git a/types/grpc-error/tslint.json b/types/grpc-error/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/grpc-error/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/gulp-sequence/gulp-sequence-tests.ts b/types/gulp-sequence/gulp-sequence-tests.ts new file mode 100644 index 0000000000..f2c10418c8 --- /dev/null +++ b/types/gulp-sequence/gulp-sequence-tests.ts @@ -0,0 +1,70 @@ +import * as seq from 'gulp-sequence'; +import * as gulp from 'gulp'; + +seq.use(gulp).use(gulp).use(gulp); + +gulp.task('x', seq('foo')); +gulp.task('x', seq('foo', ['foo', 'bar'], 'qux')); +gulp.task('x', seq( + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + '10', + '11', + '12', + '13', + '14', + '15', + '16', + '17', + '18', + '19', + '20', + '21', + '22', + '23', + '24', + '25' +)); + +const noop = () => {}; + +// tslint:disable-next-line:no-void-expression +let r: undefined = seq('foo', noop); +// tslint:disable-next-line:no-void-expression +r = seq('foo', ['foo', 'bar'], 'qux', noop); +// tslint:disable-next-line:no-void-expression +r = seq( + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', + '10', + '11', + '12', + '13', + '14', + '15', + '16', + '17', + '18', + '19', + '20', + '21', + '22', + '23', + '24', + '25', + noop +); diff --git a/types/gulp-sequence/index.d.ts b/types/gulp-sequence/index.d.ts new file mode 100644 index 0000000000..aa236e3a5a --- /dev/null +++ b/types/gulp-sequence/index.d.ts @@ -0,0 +1,391 @@ +// Type definitions for gulp-sequence 1.0 +// Project: https://github.com/teambition/gulp-sequence +// Definitions by: Alorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Gulp, TaskFunction } from 'gulp'; + +declare namespace seq { + type Step = string | string[]; + + type Done = (error?: any) => void; + + function use(gulp: Gulp): typeof seq; +} + +/* +Sequence functions (apart from the one returning TaskFunction) generated using the following (requires lodash for the padding): + +const fnBase = `declare function seq(`; +const argPad = _.pad('', fnBase.length, ' '); +const maxArgs = 25; + +const outDone = []; + +for (let i = 1; i <= maxArgs; i++) { + let def = []; + for (let j = 1; j <= i; j++) { + def.push(`s${j}: seq.Step`); + } + + def.push(`done: seq.Done): void;`); + outDone.push(def.join(`,\n${argPad}`)); +} + +console.log(fnBase + outDone.join(`\n${fnBase}`)); +*/ + +declare function seq(firstTask: seq.Step, ...additionalTasks: seq.Step[]): TaskFunction; + +declare function seq(s1: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + s17: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + s17: seq.Step, + s18: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + s17: seq.Step, + s18: seq.Step, + s19: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + s17: seq.Step, + s18: seq.Step, + s19: seq.Step, + s20: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + s17: seq.Step, + s18: seq.Step, + s19: seq.Step, + s20: seq.Step, + s21: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + s17: seq.Step, + s18: seq.Step, + s19: seq.Step, + s20: seq.Step, + s21: seq.Step, + s22: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + s17: seq.Step, + s18: seq.Step, + s19: seq.Step, + s20: seq.Step, + s21: seq.Step, + s22: seq.Step, + s23: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + s17: seq.Step, + s18: seq.Step, + s19: seq.Step, + s20: seq.Step, + s21: seq.Step, + s22: seq.Step, + s23: seq.Step, + s24: seq.Step, + done: seq.Done): void; +declare function seq(s1: seq.Step, + s2: seq.Step, + s3: seq.Step, + s4: seq.Step, + s5: seq.Step, + s6: seq.Step, + s7: seq.Step, + s8: seq.Step, + s9: seq.Step, + s10: seq.Step, + s11: seq.Step, + s12: seq.Step, + s13: seq.Step, + s14: seq.Step, + s15: seq.Step, + s16: seq.Step, + s17: seq.Step, + s18: seq.Step, + s19: seq.Step, + s20: seq.Step, + s21: seq.Step, + s22: seq.Step, + s23: seq.Step, + s24: seq.Step, + s25: seq.Step, + done: seq.Done): void; + +export = seq; diff --git a/types/gulp-sequence/tsconfig.json b/types/gulp-sequence/tsconfig.json new file mode 100644 index 0000000000..cdfaf33610 --- /dev/null +++ b/types/gulp-sequence/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-sequence-tests.ts" + ] +} diff --git a/types/gulp-sequence/tslint.json b/types/gulp-sequence/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-sequence/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hammerjs/index.d.ts b/types/hammerjs/index.d.ts index 587a3c89a0..d1bb8ffd85 100644 --- a/types/hammerjs/index.d.ts +++ b/types/hammerjs/index.d.ts @@ -263,19 +263,15 @@ interface Recognizer canEmit():boolean; canRecognizeWith( otherRecognizer:Recognizer ):boolean; - dropRecognizeWith( otherRecognizer:Recognizer ):Recognizer; - dropRecognizeWith( otherRecognizer:string ):Recognizer; - dropRequireFailure( otherRecognizer:Recognizer ):Recognizer; - dropRequireFailure( otherRecognizer:string ):Recognizer; + dropRecognizeWith( otherRecognizer:Recognizer | Recognizer[] | string):Recognizer; + dropRequireFailure( otherRecognizer:Recognizer | Recognizer[] | string):Recognizer; emit( input:HammerInput ):void; getTouchAction():any[]; hasRequireFailures():boolean; process( inputData:HammerInput ):string; recognize( inputData:HammerInput ):void; - recognizeWith( otherRecognizer:Recognizer ):Recognizer; - recognizeWith( otherRecognizer:string ):Recognizer; - requireFailure( otherRecognizer:Recognizer ):Recognizer; - requireFailure( otherRecognizer:string ):Recognizer; + recognizeWith( otherRecognizer:Recognizer | Recognizer[] | string):Recognizer; + requireFailure( otherRecognizer:Recognizer | Recognizer[] | string):Recognizer; reset():void; set( options?:RecognizerOptions ):Recognizer; tryEmit( input:HammerInput ):void; diff --git a/types/helmet/helmet-tests.ts b/types/helmet/helmet-tests.ts index afedea6c23..59e5613408 100644 --- a/types/helmet/helmet-tests.ts +++ b/types/helmet/helmet-tests.ts @@ -25,9 +25,10 @@ function helmetTest() { */ function contentSecurityPolicyTest() { const emptyArray: string[] = []; - const config = { + const config: helmet.IHelmetContentSecurityPolicyConfiguration = { directives: { baseUri: ['base.example.com'], + blockAllMixedContent: true, childSrc: ['child.example.com'], connectSrc: ['connect.example.com'], defaultSrc: ['*'], @@ -37,14 +38,20 @@ function contentSecurityPolicyTest() { frameSrc: emptyArray, imgSrc: ['images.example.com'], mediaSrc: ['media.example.com'], + manifestSrc: ['manifest.example.com'], objectSrc: ['objects.example.com'], pluginTypes: emptyArray, + prefetchSrc: ['prefetch.example.com'], reportUri: '/some-url', - sandbox: emptyArray, + reportTo: 'report.example.com', + requireSriFor: emptyArray, + sandbox: ['allow-presentation'], scriptSrc: ['scripts.example.com', function (req: express.Request, res: express.Response) { return "'nonce-abc123'"; }], - styleSrc: ['css.example.com'] + styleSrc: ['css.example.com'], + upgradeInsecureRequests: true, + workerSrc: ['worker.example.com'] }, reportOnly: false, setAllHeaders: false, diff --git a/types/helmet/index.d.ts b/types/helmet/index.d.ts index 6f89728e8a..3625d029a0 100644 --- a/types/helmet/index.d.ts +++ b/types/helmet/index.d.ts @@ -35,8 +35,27 @@ declare namespace helmet { } export type HelmetCspDirectiveValue = string | IHelmetContentSecurityPolicyDirectiveFunction; + export type HelmetCspSandboxDirective = + | string + | 'allow-forms' + | 'allow-modals' + | 'allow-orientation-lock' + | 'allow-pointer-lock' + | 'allow-popups-to-escape-sandbox' + | 'allow-popups' + | 'allow-presentation' + | 'allow-same-origin' + | 'allow-scripts' + | 'allow-top-navigation' + + export type HelmetCspRequireSriForValue = + | string + | 'script' + | 'style' + export interface IHelmetContentSecurityPolicyDirectives { baseUri?: HelmetCspDirectiveValue[]; + blockAllMixedContent?: boolean; childSrc?: HelmetCspDirectiveValue[]; connectSrc?: HelmetCspDirectiveValue[]; defaultSrc?: HelmetCspDirectiveValue[]; @@ -45,13 +64,45 @@ declare namespace helmet { frameAncestors?: HelmetCspDirectiveValue[]; frameSrc?: HelmetCspDirectiveValue[]; imgSrc?: HelmetCspDirectiveValue[]; + manifestSrc?: HelmetCspDirectiveValue[]; mediaSrc?: HelmetCspDirectiveValue[]; objectSrc?: HelmetCspDirectiveValue[]; pluginTypes?: HelmetCspDirectiveValue[]; + prefetchSrc?: HelmetCspDirectiveValue[]; + reportTo?: string; reportUri?: string; - sandbox?: HelmetCspDirectiveValue[]; + requireSriFor?: HelmetCspRequireSriForValue[]; + sandbox?: HelmetCspSandboxDirective[]; scriptSrc?: HelmetCspDirectiveValue[]; styleSrc?: HelmetCspDirectiveValue[]; + upgradeInsecureRequests?: boolean; + workerSrc?: HelmetCspDirectiveValue[]; + } + + export interface IHelmetContentSecurityPolicyDirectives { + 'base-uri'?: HelmetCspDirectiveValue[]; + 'block-all-mixed-content'?: boolean; + 'child-src'?: HelmetCspDirectiveValue[]; + 'connect-src'?: HelmetCspDirectiveValue[]; + 'default-src'?: HelmetCspDirectiveValue[]; + 'font-src'?: HelmetCspDirectiveValue[]; + 'form-action'?: HelmetCspDirectiveValue[]; + 'frame-ancestors'?: HelmetCspDirectiveValue[]; + 'frame-src'?: HelmetCspDirectiveValue[]; + 'img-src'?: HelmetCspDirectiveValue[]; + 'manifest-src'?: HelmetCspDirectiveValue[]; + 'media-src'?: HelmetCspDirectiveValue[]; + 'object-src'?: HelmetCspDirectiveValue[]; + 'plugin-types'?: HelmetCspDirectiveValue[]; + 'prefetch-src'?: HelmetCspDirectiveValue[]; + 'report-to'?: string; + 'report-uri'?: string; + 'require-sri-for'?: HelmetCspRequireSriForValue[]; + 'sandbox'?: HelmetCspSandboxDirective[]; + 'script-src'?: HelmetCspDirectiveValue; + 'style-src'?: HelmetCspDirectiveValue; + 'upgrade-insecure-requests'?: boolean; + 'worker-src'?: HelmetCspDirectiveValue; } export interface IHelmetContentSecurityPolicyConfiguration { diff --git a/types/i18next-node-fs-backend/i18next-node-fs-backend-tests.ts b/types/i18next-node-fs-backend/i18next-node-fs-backend-tests.ts index 924541f7a1..4fbd7f2a07 100644 --- a/types/i18next-node-fs-backend/i18next-node-fs-backend-tests.ts +++ b/types/i18next-node-fs-backend/i18next-node-fs-backend-tests.ts @@ -17,6 +17,25 @@ var options = { i18next.use(Backend).init(options); i18next.use(Backend).init({ backend: options.backend }); +var parseOptions = { + backend: { + // path where resources get loaded from + loadPath: '/locales/{{lng}}/{{ns}}.json', + + // path to post missing resources + addPath: '/locales/{{lng}}/{{ns}}.missing.json', + + // jsonIndent to use when storing json files + jsonIndent: 2, + + parse: (data: any) => { + return data; + }, + } +}; + +i18next.use(Backend).init({ backend: parseOptions }); + var backend = new Backend(null, options.backend); backend = new Backend(); diff --git a/types/i18next-node-fs-backend/index.d.ts b/types/i18next-node-fs-backend/index.d.ts index 9475118c95..442c59ca80 100644 --- a/types/i18next-node-fs-backend/index.d.ts +++ b/types/i18next-node-fs-backend/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for i18next-node-fs-backend // Project: https://github.com/i18next/i18next-node-fs-backend // Definitions by: Cyril Schumacher +// Silas Rech // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 declare namespace I18next { interface I18nextOptions extends i18nextNodeFsBackEnd.I18nextOptions { } @@ -13,7 +15,6 @@ declare namespace i18nextNodeFsBackEnd { * @interface */ interface i18nextNodeFsBackEndOptions { - // path where resources get loaded from /** * @summary Path where resources get loaded from. * @type {string} @@ -30,8 +31,13 @@ declare namespace i18nextNodeFsBackEnd { * @summary jsonIndent to use when storing json files * @type {number} */ - // jsonIndent: number; + + /** + * @summary custom parser + * @type {function} + */ + parse?: (data: any) => any; } /** @@ -47,10 +53,10 @@ declare module "i18next-node-fs-backend" { import * as i18next from "i18next"; class BackEnd { - constructor(services?: any, options?: Object); - init(options?: Object): void; + constructor(services?: any, options?: i18nextNodeFsBackEnd.i18nextNodeFsBackEndOptions); + init(options?: i18nextNodeFsBackEnd.i18nextNodeFsBackEndOptions): void; } - var out: typeof BackEnd; - export = out; + const module: typeof BackEnd; + export = module; } diff --git a/types/ip-address/index.d.ts b/types/ip-address/index.d.ts index 59dbb07d57..295499394b 100644 --- a/types/ip-address/index.d.ts +++ b/types/ip-address/index.d.ts @@ -1,110 +1,266 @@ // Type definitions for ip-address 5.8 // Project: https://github.com/beaugunderson/ip-address -// Definitions by: Daniel Byrne +// Definitions by: Ian Copp +// Daniel Byrne // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace ipAddress; -export interface v6Helpers { - spanAllZeroes(s: string): string; - spanAll(s: string, optionalOffset?: number): string; - spanLeadingZeroes(address: string): string; - simpleGroup(addressString: string, offset?: number): string; -} +import jsbn = require("jsbn"); -export interface TeredoObject { - readonly prefix: string; - readonly server4: string; - readonly client4: string; - readonly flags: string; - readonly coneNat: any; - readonly microsoft: { - readonly reserved: any, - readonly universalLocal: any, - readonly groupIndividual: any, - readonly nonce: any, +export interface TeredoProperties { + prefix: string; + server4: Address4; + client4: Address4; + flags: string; + coneNat: boolean; + microsoft: { + reserved: boolean; + universalLocal: boolean; + groupIndividual: boolean; + nonce: string; }; udpPort: string; } - -export interface SixToFourResponse { - readonly prefix: string; - readonly gateway: string; +export interface SixToFourProperties { + prefix: string; + gateway: string; } +export function group(): string; +export function href(port?: number): string; +export function link(options: any): string; +export function simpleGroup(addressString: string, offset: number): string; +export function spanAll(s: string, offset?: number): string; +export function spanLeadingZeroes(address: string): string; +export function spanAllZeroes(s: string): string; +export type IPv6Scope = + "Reserved" + | "Interface local" + | "Link local" + | "Admin local" + | "Site local" + | "Organization local" + | "Global" + | "Reserved"; +export type IPv6Type = + "Multicast (All nodes on this interface)" + | "Multicast (All routers on this interface)" + | "Multicast (All nodes on this link)" + | "Multicast (All routers on this link)" + | "Multicast (All routers in this site)" + | "Multicast (OSPFv3 AllSPF routers)" + | "Multicast (OSPFv3 AllDR routers)" + | "Multicast (RIP routers)" + | "Multicast (EIGRP routers)" + | "Multicast (PIM routers)" + | "Multicast (MLDv2 reports)" + | "Multicast (mDNSv6)" + | "Multicast (mDNSv6)" + | "Multicast (mDNSv6)" + | "Multicast (All DHCP servers and relay agents on this link)" + | "Multicast (All DHCP servers and relay agents in this site)" + | "Multicast (All DHCP servers on this link)" + | "Multicast (All DHCP servers in this site)" + | "Unspecified" + | "Loopback" + | "Multicast" + | "Link-local unicast"; +/** Represents an IPv4 address */ export class Address4 { - constructor(address: string); + /** Converts a BigInteger to a v4 address object */ + static fromBigInteger(bigInteger: jsbn.BigInteger): Address4; + /** Converts a hex string to an IPv4 address object */ static fromHex(hex: string): Address4; + /** Converts an integer into a IPv4 address object */ static fromInteger(integer: number): Address4; - static fromBigInteger(bigInteger: any): Address4; - - valid: boolean; + constructor(address: string); + readonly groups: number; + readonly subnet: string; + readonly subnetMask: number; + readonly v4: boolean; address: string; - parsedAddress: string; - groups: number; - v4: boolean; - subnet: string; - subnetMask: number; - - isValid(): boolean; + addressMinusSuffix: string; + parsedAddress: string[]; + valid: boolean; + /** Returns the address as a BigInteger */ + bigInteger(): jsbn.BigInteger; + /** Returns a zero-padded base-2 string representation of the address */ + binaryZeroPad(): string; + /** Returns the correct form of an address */ correctForm(): string; - isCorrect(): boolean; - toHex(): string; - toArray(): any; - toGroup6(): string; - bigInteger(): any; - startAddress(): Address4; - startAddressExclusive(): Address4; + /** + * The last address in the range given by this address' subnet, often + * referred to as the Broadcast + */ endAddress(): Address4; + /** + * The last host address in the range given by this address's subnet ie + * the last address prior to the Broadcast Address + */ endAddressExclusive(): Address4; - mask(optionalMask?: number): string; + /** Returns the bits in the given range as a base-2 string */ getBitsBase2(start: number, end: number): string; - isInSubnet(): boolean; - binaryZeroPad(): string; + /** Returns true if the address is correct, false otherwise */ + isCorrect(): boolean; + /** Returns true if the given address is in the subnet of the current address */ + isInSubnet(address: Address4 | Address6): boolean; + /** Return true if the address is valid */ + isValid(): boolean; + /** Returns the first n bits of the address, defaulting to the subnet mask */ + mask(mask?: string): string; + /** Parses a v4 address */ + parse(address: string): string[]; + /** + * The first address in the range given by this address' subnet, often + * referred to as the Network Address. + */ + startAddress(): Address4; + /** + * The first host address in the range given by this address's subnet ie + * the first address after the Network Address + */ + startAddressExclusive(): Address4; + /** Converts an IPv4 address object to an array of bytes */ + toArray(): number[]; + /** Converts an IPv4 address object to an IPv6 address group */ + toGroup6(): string; + /** Converts an IPv4 address object to a hex string */ + toHex(): string; + /** + * Converts an IPv4 address object to an IPv6 address group + * @deprecated + */ + toV6Group(): string; } - +/** + * Represents an IPv6 address + */ export class Address6 { - constructor(address: string, optionalGroups?: number); - static fromBigInteger(bigInteger: any): Address6; - static fromURL(url: string): Address6; + static RE_BAD_ADDRESS: RegExp; + static RE_BAD_CHARACTERS: RegExp; + static RE_SUBNET_STRING: RegExp; + static RE_ZONE_STRING: RegExp; + static SCOPES: string; + static TYPES: string; + /** Create an IPv6-mapped address given an IPv4 address */ static fromAddress4(address4: string): Address6; - static fromArpa(arpaFormAddress: string): Address6; - static fromByteArray(bytes: any): Address6; - static fromUnsignedByteArray(bytes: any): Address6; - + /** Convert a BigInteger to a v6 address object */ + static fromBigInteger(bigInteger: jsbn.BigInteger): Address6; + /** Convert a byte array to an Address6 object */ + static fromByteArray(bytes: number[]): Address6; + /** Convert a URL (with optional port number) to an address object */ + static fromURL(url: string): Address6; + /** Convert an unsigned byte array to an Address6 object */ + static fromUnsignedByteArray(bytes: number[]): Address6; + /** Return an address from ip6.arpa form */ + static fromArpa(ip6arpa: string): Address6; + /** + * @param address An IPv6 address string + * @param groups How many octets to parse (default 8) + */ + constructor(address: string, groups?: number); + readonly groups: number; + readonly subnet: string; + readonly subnetMask: number; + readonly v4: boolean; valid: boolean; address: string; - groups: number; - v4: boolean; - subnet: string; - subnetMask: number; - - microsoftTranscription(): string; - mask(optionalMask?: number): string; - possibleSubnets(optionalSubnetSize?: number): string; - startAddress(): Address6; - startAddressExclusive(): Address6; - endAddress(): Address6; - endAddressExclusive(): Address6; - getScope(): string; - getType(): string; - getBits(start: number, end: number): any; - getBitsBase2(start: number, end: number): string; - getBitsBase16(start: number, end: number): string; - getBitsPastSubnet(): string; - reverseForm(options?: { omitSuffix: boolean }): string; - correctForm(): string; + /** Return the address as a BigInteger */ + bigInteger(): jsbn.BigInteger; + /** Return a zero-padded base-2 string representation of the address */ binaryZeroPad(): string; + /** Return the canonical form of the address */ canonicalForm(): string; + /** Return the correct form of the address */ + correctForm(): string; + /** Return the decimal form of the address */ decimal(): string; - bigInteger(): any; + /** The last address in the range given by this address' subnet */ + endAddress(): Address6; + /** Return the bits in the given range as a BigInteger */ + getBits(start: number, end: number): jsbn.BigInteger; + /** Return the bits in the given range as a base-16 string */ + getBitsBase16(start: number, end: number): string; + /** Return the bits in the given range as a base-2 string */ + getBitsBase2(start: number, end: number): string; + /** Return the bits that are set past the subnet mask length */ + getBitsPastSubnet(): string; + /** Return the scope of the address */ + getScope(): string; + /** Return the type of the address */ + getType(): IPv6Type; + /** Return an object containing the 6to4 properties of the address */ + inspect6to4(): SixToFourProperties; + /** Return an object containing the Teredo properties of the address */ + inspectTeredo(): TeredoProperties; + /** Returns true if the address is a v4-in-v6 address, false otherwise */ + is4(): boolean; + /** Returns true if the address is a 6to4 address, false otherwise */ + is6to4(): boolean; + /** Returns true if the address is in the canonical form, false otherwise */ + isCanonical(): boolean; + /** Returns true if the address is correct, false otherwise */ + isCorrect(): boolean; + /** Returns true if the given address is in the subnet of the current address */ + isInSubnet(address: Address4 | Address6): boolean; + /** Returns true if the address is a link local address, false otherwise */ + isLinkLocal(): boolean; + /** Returns true if the address is a loopback address, false otherwise */ + isLoopback(): boolean; + /** Returns true if the address is a multicast address, false otherwise */ + isMulticast(): boolean; + /** Returns true if the address is a Teredo address, false otherwise */ + isTeredo(): boolean; + /** Returns true if the address is valid, false otherwise */ + isValid(): boolean; + /** Return the first n bits of the address, defaulting to the subnet mask */ + mask(mask?: number): string; + /** Return the Microsoft UNC transcription of the address */ + microsoftTranscription(): string; + parse(address: string): string[]; + parse4in6(address: string): string; + /** Return the number of possible subnets of a given size in the address */ + possibleSubnets(size?: number): string; + regularExpression(substring?: string): RegExp; + regularExpressionString(substring?: string): RegExp; + /** Return the reversed ip6.arpa form of the address */ + reverseForm(options?: {omitSuffix: boolean}): string; + /** The first address in the range given by this address' subnet */ + startAddress(): Address6; + /** Return the last two groups of this address as an IPv4 address string */ to4(): string; + /** Return the v4-in-v6 form of the address */ to4in6(): string; - inspectTeredo(): TeredoObject; - inspect6to4(): SixToFourResponse; + /** Return a v6 6to4 address from a v6 v4inv6 address */ to6to4(): Address6; - toByteArray(): any; - toUnsignedByteArray(): any; + /** Return a byte array */ + toByteArray(): number[]; + /** Return an unsigned byte array */ + toUnsignedByteArray(): number[]; + /** + * Return a v6 6to4 address from a v6 v4inv6 address + * @deprecated + */ + get6to4(): Address6; + /** + * Return an object containing the 6to4 properties of the address + * @deprecated + */ + six2four(): SixToFourProperties; + /** + * Return an object containing the Teredo properties of the address + * @deprecated + */ + toredo(): TeredoProperties; + /** + * Return the last two groups of this address as an IPv4 address string + * @deprecated + */ + tov4(): string; + /** + * Return the v4-in-v6 form of the address + * @deprecated + */ + v4inv6(): string; } - -export const v6: {helpers: v6Helpers}; diff --git a/types/ip-address/ip-address-tests.ts b/types/ip-address/ip-address-tests.ts index 76b4e471aa..d7cbbb5564 100644 --- a/types/ip-address/ip-address-tests.ts +++ b/types/ip-address/ip-address-tests.ts @@ -33,7 +33,7 @@ address4.toGroup6(); // $ExpectType string address4.mask(); // $ExpectType string -address4.mask(0); +address4.mask('0'); // $ExpectType string address4.getBitsBase2(0, 1); // $ExpectType string @@ -44,7 +44,7 @@ address4.isValid(); // $ExpectType boolean address4.isCorrect(); // $ExpectType boolean -address4.isInSubnet(); +address4.isInSubnet(address4); // Test Address6 Typings const address6 = new ipAddress.Address6('127.0.0.1'); @@ -59,12 +59,8 @@ const address6Mask = address6.subnetMask; // $ExpectType Address6 address6.startAddress(); // $ExpectType Address6 -address6.startAddressExclusive(); -// $ExpectType Address6 address6.endAddress(); // $ExpectType Address6 -address6.endAddressExclusive(); -// $ExpectType Address6 address6.to6to4(); // $ExpectType string @@ -79,7 +75,7 @@ address6.possibleSubnets(); address6.possibleSubnets(1); // $ExpectType string address6.getScope(); -// $ExpectType string +// $ExpectType IPv6Type address6.getType(); // $ExpectType string address6.getBitsBase2(0, 1); @@ -101,21 +97,16 @@ address6.decimal(); address6.to4(); // $ExpectType string address6.to4in6(); - -// $ExpectType TeredoObject +// $ExpectType TeredoProperties address6.inspectTeredo(); - -// $ExpectType SixToFourResponse +// $ExpectType SixToFourProperties address6.inspect6to4(); -// Test v6 Typings -const v6 = ipAddress.v6; - // $ExpectType string -v6.helpers.simpleGroup(address6.address); +ipAddress.simpleGroup(address6.address, 1); // $ExpectType string -v6.helpers.spanAll(address6.address); +ipAddress.spanAll(address6.address); // $ExpectType string -v6.helpers.spanAllZeroes(address6.address); +ipAddress.spanAllZeroes(address6.address); // $ExpectType string -v6.helpers.spanLeadingZeroes(address6.address); +ipAddress.spanLeadingZeroes(address6.address); diff --git a/types/jest-plugin-context/index.d.ts b/types/jest-plugin-context/index.d.ts new file mode 100644 index 0000000000..da2698b78e --- /dev/null +++ b/types/jest-plugin-context/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for jest-plugin-context 2.9 +// Project: https://github.com/negativetwelve/jest-plugins/tree/master/packages/jest-plugin-context +// Definitions by: Jonas Heinrich +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +declare var context: jest.Describe; diff --git a/types/jest-plugin-context/jest-plugin-context-tests.ts b/types/jest-plugin-context/jest-plugin-context-tests.ts new file mode 100644 index 0000000000..2683574086 --- /dev/null +++ b/types/jest-plugin-context/jest-plugin-context-tests.ts @@ -0,0 +1 @@ +context(0, () => {}); diff --git a/types/jest-plugin-context/tsconfig.json b/types/jest-plugin-context/tsconfig.json new file mode 100644 index 0000000000..1138a892e9 --- /dev/null +++ b/types/jest-plugin-context/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", + "jest-plugin-context-tests.ts" + ] +} diff --git a/types/jest-plugin-context/tslint.json b/types/jest-plugin-context/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/jest-plugin-context/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jest-plugin-set/index.d.ts b/types/jest-plugin-set/index.d.ts new file mode 100644 index 0000000000..05d96335cb --- /dev/null +++ b/types/jest-plugin-set/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for jest-plugin-set 2.9 +// Project: https://github.com/negativetwelve/jest-plugins/tree/master/packages/jest-plugin-set +// Definitions by: Jonas Heinrich +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function set(name: string, block: () => void): void; diff --git a/types/jest-plugin-set/jest-plugin-set-tests.ts b/types/jest-plugin-set/jest-plugin-set-tests.ts new file mode 100644 index 0000000000..93096eeb19 --- /dev/null +++ b/types/jest-plugin-set/jest-plugin-set-tests.ts @@ -0,0 +1 @@ +set('variableA', () => {}); diff --git a/types/jest-plugin-set/tsconfig.json b/types/jest-plugin-set/tsconfig.json new file mode 100644 index 0000000000..4d7b7d4bbf --- /dev/null +++ b/types/jest-plugin-set/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", + "jest-plugin-set-tests.ts" + ] +} diff --git a/types/jest-plugin-set/tslint.json b/types/jest-plugin-set/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/jest-plugin-set/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jest-when/index.d.ts b/types/jest-when/index.d.ts new file mode 100644 index 0000000000..af62a95830 --- /dev/null +++ b/types/jest-when/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for jest-when 1.1 +// Project: https://github.com/timkindberg/jest-when#readme +// Definitions by: Alden Taylor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export interface PartialMockInstance { + mockReturnValue: jest.MockInstance['mockReturnValue']; +} + +export interface When { + (fn: jest.Mocked | jest.Mock): When; + // due to no-unnecessary-generics lint rule, the generics have been replaced with 'any' + // calledWith(...matchers: any[]): PartialMockInstance; + // expectCalledWith(...matchers: any[]): PartialMockInstance; + calledWith(...matchers: any[]): PartialMockInstance; + expectCalledWith(...matchers: any[]): PartialMockInstance; +} + +export const when: When; diff --git a/types/jest-when/jest-when-tests.ts b/types/jest-when/jest-when-tests.ts new file mode 100644 index 0000000000..13da65928d --- /dev/null +++ b/types/jest-when/jest-when-tests.ts @@ -0,0 +1,57 @@ +import { when } from 'jest-when'; + +describe('mock-when test', () => { + it('basic usage:', () => { + const fn = jest.fn(); + when(fn).calledWith(1).mockReturnValue('yay!'); + + const result = fn(1); + expect(result).toEqual('yay!'); + }); + + it('Supports multiple args:', () => { + const fn = jest.fn(); + when(fn).calledWith(1, true, 'foo').mockReturnValue('yay!'); + + const result = fn(1, true, 'foo'); + expect(result).toEqual('yay!'); + }); + + it('Supports jest matchers:', () => { + const fn = jest.fn(); + when(fn).calledWith( + expect.anything(), + expect.any(Number), + expect.arrayContaining([false]) + ).mockReturnValue('yay!'); + + const result = fn('whatever', 100, [true, false]); + expect(result).toEqual('yay!'); + }); + + it('Supports compound declarations:', () => { + const fn = jest.fn(); + when(fn).calledWith(1).mockReturnValue('no'); + when(fn).calledWith(2).mockReturnValue('way?'); + when(fn).calledWith(3).mockReturnValue('yes'); + when(fn).calledWith(4).mockReturnValue('way!'); + + expect(fn(1)).toEqual('no'); + expect(fn(2)).toEqual('way?'); + expect(fn(3)).toEqual('yes'); + expect(fn(4)).toEqual('way!'); + expect(fn(5)).toEqual(undefined); + }); + + it('Assert the args:', () => { + const fn = jest.fn(); + when(fn).expectCalledWith(1).mockReturnValue('x'); + let testPassed = false; + try { + fn(2); // Will throw a helpful jest assertion error with args diff + } catch (e) { + testPassed = true; + } + expect(testPassed).toBeTruthy(); + }); +}); diff --git a/types/jest-when/tsconfig.json b/types/jest-when/tsconfig.json new file mode 100644 index 0000000000..46c037813f --- /dev/null +++ b/types/jest-when/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", + "jest-when-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jest-when/tslint.json b/types/jest-when/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jest-when/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index a9cbdbc1e3..b663e37076 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -481,6 +481,10 @@ declare namespace jest { * If you know how to test something, `.not` lets you test its opposite. */ not: Matchers; + /** + * Ensure that a mock function is called with specific arguments on an Nth call. + */ + nthCalledWith(nthCall: number, ...params: any[]): R; /** * Ensure that the nth call to a mock function has returned a specified value. */ @@ -504,6 +508,10 @@ declare namespace jest { * Ensures that a mock function is called. */ toBeCalled(): R; + /** + * Ensures that a mock function is called an exact number of times. + */ + toBeCalledTimes(expected: number): R; /** * Ensure that a mock function is called with specific arguments. */ diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 801c6a5a78..2de3cadfd4 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -504,6 +504,9 @@ describe("", () => { expect(jest.fn()).lastReturnedWith("jest"); expect(jest.fn()).lastReturnedWith({}); + expect(jest.fn()).nthCalledWith(0, "jest"); + expect(jest.fn()).nthCalledWith(1, {}); + expect(jest.fn()).nthReturnedWith(0, "jest"); expect(jest.fn()).nthReturnedWith(1, {}); @@ -513,6 +516,8 @@ describe("", () => { expect(jest.fn()).toBeCalled(); + expect(jest.fn()).toBeCalledTimes(1); + expect(jest.fn()).toBeCalledWith(); expect(jest.fn()).toBeCalledWith("jest"); expect(jest.fn()).toBeCalledWith({}, {}); diff --git a/types/js-beautify/index.d.ts b/types/js-beautify/index.d.ts index f3b13767d9..7f5453a1a9 100644 --- a/types/js-beautify/index.d.ts +++ b/types/js-beautify/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js_beautify +// Type definitions for js_beautify 1.8.2 // Project: https://github.com/beautify-web/js-beautify/ // Definitions by: Josh Goldberg , Hans Windhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -13,7 +13,7 @@ interface JsBeautifyOptions { max_preserve_newlines?: number; jslint_happy?: boolean; space_after_anon_function?: boolean; - brace_style?: 'collapse-preserve-inline'|'collapse'|'expand'|'end-expand'|'none'; + brace_style?: 'collapse-preserve-inline' | 'collapse' | 'expand' | 'end-expand' | 'none'; keep_array_indentation?: boolean; keep_function_indentation?: boolean; space_before_conditional?: boolean; @@ -21,29 +21,34 @@ interface JsBeautifyOptions { eval_code?: boolean; unescape_strings?: boolean; wrap_line_length?: number; - wrap_attributes?: 'auto'|'force' ; + wrap_attributes?: 'auto' | 'force'; wrap_attributes_indent_size?: number; end_with_newline?: boolean; } +// See https://github.com/beautify-web/js-beautify/blob/v1.8.2/js/src/html/beautifier.js#L268-L330 interface HTMLBeautifyOptions { + indent_inner_html?: boolean; + indent_body_inner_html?: boolean; + indent_head_inner_html?: boolean; indent_size?: number; indent_char?: string; - indent_with_tabs?: boolean; - indent_handlebars?: boolean; - eol?: string; - end_with_newline?: boolean; + wrap_line_length?: number; preserve_newlines?: boolean; max_preserve_newlines?: number; - indent_inner_html?: boolean; - brace_style?: 'collapse-preserve-inline'|'collapse'|'expand'|'end-expand'|'none'; - indent_scripts?: 'keep'|'separate'|'normal'; - wrap_line_length?: number; - wrap_attributes?: 'auto'|'force' ; + indent_handlebars?: boolean; + wrap_attributes?: 'auto' | 'force' | 'force-expand-multiline' | 'force-aligned' | 'aligned-multiple'; wrap_attributes_indent_size?: number; + end_with_newline?: boolean; + extra_liners?: string[]; + eol?: string; + indent_with_tabs?: boolean; + disabled?: boolean; + inline?: string[]; + void_elements?: string[]; unformatted?: string[]; content_unformatted?: string[]; - extra_liners?: string|string[]; + indent_scripts?: 'keep' | 'separate'; } interface CSSBeautifyOptions { @@ -56,21 +61,19 @@ interface CSSBeautifyOptions { newline_between_rules?: boolean; } -interface jsb{ - (js_source_text: string, options?: JsBeautifyOptions) : string ; - js:(js_source_text: string, options?: JsBeautifyOptions) => string ; - js_beautify:(js_source_text: string, options?: JsBeautifyOptions) => string ; +interface jsb { + (js_source_text: string, options?: JsBeautifyOptions): string; + js: (js_source_text: string, options?: JsBeautifyOptions) => string; + js_beautify: (js_source_text: string, options?: JsBeautifyOptions) => string; - css:(js_source_text: string, options?: CSSBeautifyOptions) => string ; - css_beautify:(js_source_text: string, options?: CSSBeautifyOptions) => string ; + css: (js_source_text: string, options?: CSSBeautifyOptions) => string; + css_beautify: (js_source_text: string, options?: CSSBeautifyOptions) => string; - html:(js_source_text: string, options?: HTMLBeautifyOptions) => string ; - html_beautify:(js_source_text: string, options?: HTMLBeautifyOptions) => string ; + html: (js_source_text: string, options?: HTMLBeautifyOptions) => string; + html_beautify: (js_source_text: string, options?: HTMLBeautifyOptions) => string; } -declare var js_beautify:jsb; -declare module "js-beautify" -{ +declare var js_beautify: jsb; +declare module "js-beautify" { export = js_beautify; } - diff --git a/types/js-beautify/js-beautify-tests.ts b/types/js-beautify/js-beautify-tests.ts index 206499173d..f421052503 100644 --- a/types/js-beautify/js-beautify-tests.ts +++ b/types/js-beautify/js-beautify-tests.ts @@ -1,5 +1,3 @@ - - let bCss = js_beautify.css("body{display:none;}"); bCss = js_beautify.css_beautify("body{display:none;}"); @@ -34,4 +32,5 @@ var full: string = js_beautify( "wrap_attributes": "auto", "wrap_attributes_indent_size": 4, "end_with_newline": false - }); + } +); diff --git a/types/js-cookie/index.d.ts b/types/js-cookie/index.d.ts index f587e1df88..6cd3c89169 100644 --- a/types/js-cookie/index.d.ts +++ b/types/js-cookie/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for js-cookie 2.1 +// Type definitions for js-cookie 2.2 // Project: https://github.com/js-cookie/js-cookie // Definitions by: Theodore Brown // BendingBender +// Antoine Lépée // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -57,7 +58,7 @@ declare namespace Cookies { * Returns the parsed representation of the string * stored in the cookie according to JSON.parse */ - getJSON(name: string): object; + getJSON(name: string): any; /** * Returns the parsed representation of diff --git a/types/js-cookie/js-cookie-tests.ts b/types/js-cookie/js-cookie-tests.ts index 7b68951c87..683b401d8b 100644 --- a/types/js-cookie/js-cookie-tests.ts +++ b/types/js-cookie/js-cookie-tests.ts @@ -24,7 +24,7 @@ Cookies2; // $ExpectType CookiesStatic Cookies.set('name', { foo: 'bar' }); -// $ExpectType object +// $ExpectType any Cookies.getJSON('name'); // $ExpectType { [key: string]: any; } diff --git a/types/jsdom/index.d.ts b/types/jsdom/index.d.ts index cfb54fa25f..1aa9750fbc 100644 --- a/types/jsdom/index.d.ts +++ b/types/jsdom/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for jsdom 11.0 +// Type definitions for jsdom 11.12 // Project: https://github.com/tmpvar/jsdom#readme // Definitions by: Leonard Thieu +// Johan Palmfjord // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -101,6 +102,20 @@ export type ConstructorOptions = Options & { * Values that are not "text/html" or an XML mime type will throw. It defaults to "text/html". */ contentType?: string; + /** + * jsdom does not have the capability to render visual content, and will act like a headless browser by default. + * It provides hints to web pages through APIs such as document.hidden that their content is not visible. + * + * When the pretendToBeVisual option is set to true, jsdom will pretend that it is rendering and displaying + * content. + */ + pretendToBeVisual?: boolean + /** + * The maximum size in code units for the separate storage areas used by localStorage and sessionStorage. + * Attempts to store data larger than this limit will cause a DOMException to be thrown. By default, it is set + * to 5,000,000 code units per origin, as inspired by the HTML specification. + */ + storageQuota?: number }; export interface DOMWindow extends Window { diff --git a/types/jsdom/jsdom-tests.ts b/types/jsdom/jsdom-tests.ts index 2dbbdca601..da82b2db7c 100644 --- a/types/jsdom/jsdom-tests.ts +++ b/types/jsdom/jsdom-tests.ts @@ -68,6 +68,14 @@ function test_beforeParse() { }); } +function test_storageQuota() { + new JSDOM('', { storageQuota: 1337 }); +} + +function test_pretendToBeVisual() { + new JSDOM('', { pretendToBeVisual: true }); +} + function test_serialize() { const dom = new JSDOM(`hello`); diff --git a/types/jsftp/index.d.ts b/types/jsftp/index.d.ts new file mode 100644 index 0000000000..ed543e5bb2 --- /dev/null +++ b/types/jsftp/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for jsftp 2.1 +// Project: https://github.com/sergi/jsftp +// Definitions by: Konrad Księski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Socket } from 'net'; +import { EventEmitter } from 'events'; + +export interface JsftpOpts { + host?: string; + port?: number; + user?: string; + pass?: string; + createSocket?: ({ port, host }: { port: number, host: string }, firstAction: () => {}) => Socket; + useList?: boolean; +} + +export type ErrorCallback = (err: Error) => void; +export type RawCallback = (err: Error, data: { code: number, text: string }) => void; +export type ListCallback = (err: Error, dirContents: string) => void; +export type GetCallback = (err: Error, socket: Socket) => void; +export type LsCallback = (err: Error, res: [{ name: string }]) => void; + +export default class Ftp extends EventEmitter { + constructor(opts: JsftpOpts); + + ls(filePath: string, callback: LsCallback): void; + + list(filePath: string, callback: ListCallback): void; + + get(remotePath: string, callback: GetCallback): void; + get(remotePath: string, localPath: string, callback: ErrorCallback): void; + + put(source: string | Buffer | NodeJS.ReadableStream, remotePath: string, callback: ErrorCallback): void; + + rename(from: string, to: string, callback: ErrorCallback): void; + + // Ftp.raw(command, params, callback) + raw(command: string, callback: RawCallback): void; + raw(command: string, arg1: any, callback: RawCallback): void; + raw(command: string, arg1: any, arg2: any, callback: RawCallback): void; + raw(command: string, arg1: any, arg2: any, arg3: any, callback: RawCallback): void; + raw(command: string, arg1: any, arg2: any, arg3: any, arg4: any, callback: RawCallback): void; + + keepAlive(timeInMs?: number): void; + + destroy(): void; +} diff --git a/types/jsftp/jsftp-tests.ts b/types/jsftp/jsftp-tests.ts new file mode 100644 index 0000000000..94ad47cbd4 --- /dev/null +++ b/types/jsftp/jsftp-tests.ts @@ -0,0 +1,25 @@ +import Ftp from 'jsftp'; + +const connectOpts = { + host: 'localhost', + port: 22222, +}; + +const ftp = new Ftp(connectOpts); // $ExpectType Ftp + +ftp.ls('foo', (err) => { }); // $ExpectType void + +ftp.list('foo', (err) => { }); // $ExpectType void + +ftp.get('foo', (err) => { }); // $ExpectType void +ftp.get('foo', 'bar', (err) => { }); // $ExpectType void + +ftp.put('foo', 'bar', (err) => { }); // $ExpectType void + +ftp.rename('foo', 'bar', (err) => { }); // $ExpectType void + +ftp.raw('foo', 'param', (err) => { }); // $ExpectType void + +ftp.keepAlive(); // $ExpectType void + +ftp.destroy(); // $ExpectType void diff --git a/types/nano/tsconfig.json b/types/jsftp/tsconfig.json similarity index 94% rename from types/nano/tsconfig.json rename to types/jsftp/tsconfig.json index 7586d0b0bf..f5d841a4ef 100644 --- a/types/nano/tsconfig.json +++ b/types/jsftp/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "nano-tests.ts" + "jsftp-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jsftp/tslint.json b/types/jsftp/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsftp/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/karma/index.d.ts b/types/karma/index.d.ts index cc4525566b..4b71c0a723 100644 --- a/types/karma/index.d.ts +++ b/types/karma/index.d.ts @@ -248,6 +248,7 @@ declare namespace karma { * you can specify how many browsers should be running at once at any given point in time. */ concurrency?: number; + customLaunchers?: { [key: string]: CustomLauncher }; /** * @default [] * @description List of files/patterns to exclude from loaded files. @@ -470,6 +471,13 @@ declare namespace karma { */ nocache?: boolean; } + + interface CustomLauncher { + base: string; + browserName?: string; + flags?: string[]; + platform?: string; + } } declare var karma: karma.Karma; diff --git a/types/karma/karma-tests.ts b/types/karma/karma-tests.ts index 6d9b8abd9f..a8adc36f45 100644 --- a/types/karma/karma-tests.ts +++ b/types/karma/karma-tests.ts @@ -106,6 +106,12 @@ module.exports = function(config: karma.Config) { 'Chrome', 'Firefox' ], + customLaunchers: { + ChromiumHeadless_without_security: { + base: 'ChromiumHeadless', + flags: ['--no-sandbox', '--disable-setuid-sandbox'], + }, + }, singleRun: true }); diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index b400af2497..329bf438b2 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -156,7 +156,6 @@ declare namespace Knex { // Others first: Select; - debug(enabled?: boolean): QueryBuilder; pluck(column: string): QueryBuilder; insert(data: any, returning?: string | string[]): QueryBuilder; @@ -169,9 +168,6 @@ declare namespace Knex { delete(returning?: string | string[]): QueryBuilder; truncate(): QueryBuilder; - transacting(trx?: Transaction): QueryBuilder; - connection(connection: any): QueryBuilder; - clone(): QueryBuilder; } @@ -390,12 +386,14 @@ declare namespace Knex { interface ChainableInterface extends Bluebird { toQuery(): string; - options(options: any): QueryBuilder; - stream(callback: (readable: stream.PassThrough) => any): Bluebird; + options(options: { [key: string]: any }): this; + connection(connection: any): this; + debug(enabled: boolean): this; + transacting(trx: Transaction): this; + 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; - stream(options: { [key: string]: any }, callback: (readable: stream.PassThrough) => any): Bluebird; - pipe(writable: any): stream.PassThrough; - exec(callback: Function): QueryBuilder; + pipe(writable: T, options?: { [key: string]: any }): stream.PassThrough; } interface Transaction extends Knex { @@ -408,7 +406,7 @@ declare namespace Knex { // Schema builder // - interface SchemaBuilder extends Bluebird { + interface SchemaBuilder extends ChainableInterface { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; alterTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index e7fb3e1b81..461e1738fe 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -982,19 +982,11 @@ knex.select('name').from('users') .where('id', '>', 20) .andWhere('id', '<', 200) .limit(10) - .offset(x) - .exec(function(err: any, rows: any[]) { - if (err) return console.error(err); - knex.select('id').from('nicknames').whereIn('nickname', rows.map((r: any) => r.name)) - .exec(function(err: any, rows: any[]) { - if (err) return console.error(err); - console.log(rows); - }); - }); + .offset(x); // Retrieve the stream: var stream = knex.select('*').from('users').stream(); -var writableStream: any; +var writableStream: NodeJS.WritableStream; stream.pipe(writableStream); // With options: diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index 215d38e7f1..4e2f3b1519 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -5,7 +5,8 @@ // Clément Bourgeois , // Matt Brooks , // Benjamin Eckardt , -// Mathias Lorenzen +// Mathias Lorenzen , +// Leonardo Lombardi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -22,29 +23,108 @@ interface KnockoutObservableFunctions { interface KnockoutObservableArrayFunctions { // General Array functions + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ indexOf(searchElement: T, fromIndex?: number): number; + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ slice(start: number, end?: number): T[]; + /** + * Removes and returns all the remaining elements starting from a given index. + * @param start The zero-based location in the array from which to start removing elements. + */ splice(start: number): T[]; + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param ...items Elements to insert into the array in place of the deleted elements. + */ splice(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Removes the last value from the array and returns it. + */ pop(): T; + /** + * Adds a new item to the end of array. + * @param ...items Items to be added + */ push(...items: T[]): void; + /** + * Removes the first value from the array and returns it. + */ shift(): T; + /** + * Inserts a new item at the beginning of the array. + * @param ...items Items to be added + */ unshift(...items: T[]): number; + /** + * Reverses the order of the array and returns the observableArray (not the underlying array). + */ reverse(): KnockoutObservableArray; + /** + * Sorts the array contents and returns the observableArray. + */ sort(): KnockoutObservableArray; + /** + * Sorts the array contents and returns the observableArray. + * @param compareFunction A function that returns negative value if first argument is smaller, positive value if second is smaller, or zero to treat them as equal. + */ sort(compareFunction: (left: T, right: T) => number): KnockoutObservableArray; // Ko specific + /** + * Replaces the first value that equals oldItem with newItem + * @param oldItem Item to be replaced + * @param newItem Replacing item + */ replace(oldItem: T, newItem: T): void; - + /** + * Removes all values that equal item and returns them as an array. + * @param item The item to be removed + */ remove(item: T): T[]; + /** + * Removes all values and returns them as an array. + * @param removeFunction A function used to determine true if item should be removed and fasle otherwise + */ remove(removeFunction: (item: T) => boolean): T[]; + /** + * Removes all values that equal any of the supplied items + * @param items Items to be removed + */ removeAll(items: T[]): T[]; + /** + * Removes all values and returns them as an array. + */ removeAll(): T[]; + // Ko specific Usually relevant to Ruby on Rails developers only + /** + * Finds any objects in the array that equal someItem and gives them a special property called _destroy with value true. + * @param item Items to be marked with the property. + */ destroy(item: T): void; + /** + * Finds any objects in the array filtered by a function and gives them a special property called _destroy with value true. + * @param destroyFunction A function used to determine which items should be marked with the property. + */ destroy(destroyFunction: (item: T) => boolean): void; + /** + * Finds any objects in the array that equal suplied items and gives them a special property called _destroy with value true. + * @param items + */ destroyAll(items: T[]): void; + /** + * Gives a special property called _destroy with value true to all objects in the array. + */ destroyAll(): void; } @@ -116,16 +196,16 @@ interface KnockoutObservable extends KnockoutSubscribable, KnockoutObserva (value: T): void; peek(): T; - valueHasMutated?:{(): void;}; - valueWillMutate?:{(): void;}; + valueHasMutated?: { (): void; }; + valueWillMutate?: { (): void; }; extend(requestedExtenders: { [key: string]: any; }): KnockoutObservable; } interface KnockoutComputedDefine { read(): T; - write? (value: T): void; + write?(value: T): void; disposeWhenNodeIsRemoved?: Node; - disposeWhen? (): boolean; + disposeWhen?(): boolean; owner?: any; deferEvaluation?: boolean; pure?: boolean; @@ -206,17 +286,17 @@ interface KnockoutMemoization { parseMemoText(memoText: string): string; } -interface KnockoutVirtualElement {} +interface KnockoutVirtualElement { } interface KnockoutVirtualElements { allowedBindings: { [bindingName: string]: boolean; }; - emptyNode(node: KnockoutVirtualElement ): void; - firstChild(node: KnockoutVirtualElement ): KnockoutVirtualElement; - insertAfter( container: KnockoutVirtualElement, nodeToInsert: Node, insertAfter: Node ): void; + emptyNode(node: KnockoutVirtualElement): void; + firstChild(node: KnockoutVirtualElement): KnockoutVirtualElement; + insertAfter(container: KnockoutVirtualElement, nodeToInsert: Node, insertAfter: Node): void; nextSibling(node: KnockoutVirtualElement): Node; - prepend(node: KnockoutVirtualElement, toInsert: Node ): void; - setDomNodeChildren(node: KnockoutVirtualElement, newChildren: { length: number;[index: number]: Node; } ): void; - childNodes(node: KnockoutVirtualElement ): Node[]; + prepend(node: KnockoutVirtualElement, toInsert: Node): void; + setDomNodeChildren(node: KnockoutVirtualElement, newChildren: { length: number;[index: number]: Node; }): void; + childNodes(node: KnockoutVirtualElement): Node[]; } interface KnockoutExtenders { @@ -365,12 +445,12 @@ interface KnockoutTemplateSources { domElement: { prototype: KnockoutTemplateSourcesDomElement - new (element: Element): KnockoutTemplateSourcesDomElement + new(element: Element): KnockoutTemplateSourcesDomElement }; anonymousTemplate: { prototype: KnockoutTemplateAnonymous; - new (element: Element): KnockoutTemplateAnonymous; + new(element: Element): KnockoutTemplateAnonymous; }; } @@ -478,7 +558,7 @@ interface KnockoutStatic { prototype: KnockoutTemplateEngine; - new (): KnockoutTemplateEngine; + new(): KnockoutTemplateEngine; }; ////////////////////////////////// @@ -503,7 +583,7 @@ interface KnockoutStatic { prototype: KnockoutNativeTemplateEngine; - new (): KnockoutNativeTemplateEngine; + new(): KnockoutNativeTemplateEngine; instance: KnockoutNativeTemplateEngine; }; @@ -572,7 +652,7 @@ interface KnockoutStatic { bindingProvider: { instance: KnockoutBindingProvider; - new (): KnockoutBindingProvider; + new(): KnockoutBindingProvider; } ///////////////////////////////// @@ -631,7 +711,7 @@ declare namespace KnockoutComponentTypes { interface Config { viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule; - template: string | Node[]| DocumentFragment | TemplateElement | AMDModule; + template: string | Node[] | DocumentFragment | TemplateElement | AMDModule; synchronous?: boolean; } @@ -672,16 +752,16 @@ declare namespace KnockoutComponentTypes { } interface Loader { - getConfig? (componentName: string, callback: (result: ComponentConfig | null) => void): void; - loadComponent? (componentName: string, config: ComponentConfig, callback: (result: Definition | null) => void): void; - loadTemplate? (componentName: string, templateConfig: any, callback: (result: Node[] | null) => void): void; - loadViewModel? (componentName: string, viewModelConfig: any, callback: (result: any) => void): void; + getConfig?(componentName: string, callback: (result: ComponentConfig | null) => void): void; + loadComponent?(componentName: string, config: ComponentConfig, callback: (result: Definition | null) => void): void; + loadTemplate?(componentName: string, templateConfig: any, callback: (result: Node[] | null) => void): void; + loadViewModel?(componentName: string, viewModelConfig: any, callback: (result: any) => void): void; suppressLoaderExceptions?: boolean; } interface Definition { template: Node[]; - createViewModel? (params: any, options: { element: Node; }): any; + createViewModel?(params: any, options: { element: Node; }): any; } } diff --git a/types/koa-bunyan-logger/index.d.ts b/types/koa-bunyan-logger/index.d.ts new file mode 100644 index 0000000000..1cf77fec92 --- /dev/null +++ b/types/koa-bunyan-logger/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for koa-bunyan-logger 2.0 +// Project: https://github.com/koajs/bunyan-logger +// Definitions by: Steven McDowall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Middleware } from 'koa'; + +import Logger = require('bunyan'); + +export = koaBunyanLogger; + +declare function koaBunyanLogger(logger?: Logger): Middleware; + +// Extend the Koa context to add the logger.. +declare module 'koa' { + // tslint:disable-next-line: interface-name + interface BaseContext { + log: Logger; + } +} diff --git a/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts b/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts new file mode 100644 index 0000000000..daaf26b7a3 --- /dev/null +++ b/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts @@ -0,0 +1,12 @@ +import Koa = require('koa'); +import koaBunyanLogger = require('koa-bunyan-logger'); + +const app = new Koa(); +app.use(koaBunyanLogger()); + +app.use(async (ctx, next) => { + ctx.log.info('Got a request from %s for %s', ctx.request.ip, ctx.path); + await next(); +}); + +app.listen(8000); diff --git a/types/koa-bunyan-logger/tsconfig.json b/types/koa-bunyan-logger/tsconfig.json new file mode 100644 index 0000000000..67657f2ec2 --- /dev/null +++ b/types/koa-bunyan-logger/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", + "koa-bunyan-logger-tests.ts" + ] +} diff --git a/types/koa-bunyan-logger/tslint.json b/types/koa-bunyan-logger/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-bunyan-logger/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-convert/index.d.ts b/types/koa-convert/index.d.ts index ed5cd38480..498088b4c6 100644 --- a/types/koa-convert/index.d.ts +++ b/types/koa-convert/index.d.ts @@ -7,7 +7,7 @@ import { Context, Middleware } from "koa"; declare function convert( - mw: (context: Context, next: () => void) => Generator + mw: (context: Context, next: () => Promise) => Generator ): Middleware; export = convert; diff --git a/types/koa-passport/index.d.ts b/types/koa-passport/index.d.ts index d00635a462..fe6ab5ee27 100644 --- a/types/koa-passport/index.d.ts +++ b/types/koa-passport/index.d.ts @@ -43,7 +43,7 @@ declare namespace KoaPassport { session(options?: { pauseStream: boolean; }): Middleware; authenticate(strategy: string | string[], callback?: (...args: any[]) => any): Middleware; - authenticate(strategy: string | string[], options: passport.AuthenticateOptions, callback?: (...args: any[]) => any): Middleware; + authenticate(strategy: string | string[], options: passport.AuthenticateOptions | object, callback?: (...args: any[]) => any): Middleware; authorize(strategy: string | string[], callback?: (...args: any[]) => any): Middleware; authorize(strategy: string | string[], options: any, callback?: (...args: any[]) => any): Middleware; diff --git a/types/koa-requestid/index.d.ts b/types/koa-requestid/index.d.ts new file mode 100644 index 0000000000..2fd2feea84 --- /dev/null +++ b/types/koa-requestid/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for koa-requestid 2.0 +// Project: https://github.com/seegno/koa-requestid/ +// Definitions by: Steven McDowall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Middleware } from 'koa'; + +export = requestId; + +declare function requestId(options?: { + expose?: string; + header?: string; + query?: string; +}): Middleware; diff --git a/types/koa-requestid/koa-requestid-tests.ts b/types/koa-requestid/koa-requestid-tests.ts new file mode 100644 index 0000000000..75fc5d0749 --- /dev/null +++ b/types/koa-requestid/koa-requestid-tests.ts @@ -0,0 +1,10 @@ +import Koa = require('koa'); +import requestId = require('koa-requestid'); +const app = new Koa(); + +app.use(requestId()); +app.use(async ctx => { + ctx.body = ctx.state.id; +}); + +app.listen(3000); diff --git a/types/koa-requestid/tsconfig.json b/types/koa-requestid/tsconfig.json new file mode 100644 index 0000000000..74c7711102 --- /dev/null +++ b/types/koa-requestid/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", + "koa-requestid-tests.ts" + ] +} diff --git a/types/koa-requestid/tslint.json b/types/koa-requestid/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-requestid/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/kue/index.d.ts b/types/kue/index.d.ts index 4117ef0a82..9153039ff0 100644 --- a/types/kue/index.d.ts +++ b/types/kue/index.d.ts @@ -78,6 +78,8 @@ export declare class Job extends events.EventEmitter { public failed_at: string | number; public started_at: string | number; public client: redisClientFactory.RedisClient; + public workerId: string; + private _error: string; private _max_attempts; static priorities: Priorities; diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 0822dea605..8402d8bc9b 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -11,10 +11,12 @@ export as namespace L; import * as geojson from 'geojson'; export class Class { - static extend(props: any): any/* how to return constructor of self extended type ? */; - static include(props: any): any /* how to return self extended type ? */; - static mergeOptions(props: any): any /* how to return self extended type ? */; - static addInitHook(initHookFn: () => void): any/* how to return self extended type ? */; + static extend(props: any): {new(...args: any[]): any} & typeof Class; + static include(props: any): any & typeof Class; + static mergeOptions(props: any): any & typeof Class; + + static addInitHook(initHookFn: () => void): any & typeof Class; + static addInitHook(methodName: string, ...args: any[]): any & typeof Class; } export class Transformation { @@ -1532,8 +1534,12 @@ export namespace Browser { } export namespace Util { - function extend(dest: any, src?: any): any; - function create(proto: any, properties?: any): any; + function extend(dest: D, src?: S1): D & S1; + function extend(dest: D, src1: S1, src2: S2): D & S1 & S2; + function extend(dest: D, src1: S1, src2: S2, src3: S3): D & S1 & S2 & S3; + function extend(dest: any, ...src: any[]): any; + + function create(proto: object | null, properties?: PropertyDescriptorMap): any; function bind(fn: () => void, ...obj: any[]): () => void; function stamp(obj: any): number; function throttle(fn: () => void, time: number, context: any): () => void; @@ -1547,7 +1553,7 @@ export namespace Util { function template(str: string, data: any): string; function isArray(obj: any): boolean; function indexOf(array: any[], el: any): number; - function requestAnimFrame(fn: () => void, context?: any, immediate?: boolean): number; + function requestAnimFrame(fn: (timestamp: number) => void, context?: any, immediate?: boolean): number; function cancelAnimFrame(id: number): void; let lastId: number; diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index 66f12fd0ed..d1375fa83f 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -444,10 +444,13 @@ defaultIcon = new L.Icon.Default({imagePath: 'apath'}); const myControlClass = L.Control.extend({}); const myControl = new myControlClass(); +const myOtherControlClass = myControlClass.extend({}); +const myOtherControl = new myOtherControlClass(); L.Control.include({}); L.Control.mergeOptions({}); L.Control.addInitHook(() => {}); +L.Control.addInitHook('method1', 'hello', 1); export class MyNewControl extends L.Control { constructor() { @@ -526,8 +529,35 @@ polyline = new L.Polyline(multiPolylineLatLngs); polyline.setLatLngs(multiPolylineLatLngs); const multiPolylineLatLngs2: L.LatLng[][] = polyline.getLatLngs() as L.LatLng[][]; -L.Util.extend({}); +const obj1 = { + prop1: 1, +}; + +const obj2 = { + prop2: '2', +}; + +const obj3 = { + prop3: 'three', +}; + +const obj4 = { + prop4: 'cuatro', +}; + +const obj5 = { + prop5: 'cinque', +}; + +const extended0: typeof obj1 = L.Util.extend(obj1); +const extended1: typeof obj1 & typeof obj2 = L.Util.extend(obj1, obj2); +const extended2: typeof obj1 & typeof obj2 & typeof obj3 = L.Util.extend(obj1, obj2, obj3); +const extended3: typeof obj1 & typeof obj2 & typeof obj3 & typeof obj4 = L.Util.extend(obj1, obj2, obj3, obj4); +const extended4: typeof obj1 & typeof obj2 & typeof obj3 & typeof obj4 & typeof obj5 = L.Util.extend(obj1, obj2, obj3, obj4, obj5); + L.Util.create({}); +L.Util.create(null, {foo: {writable: true, value: 'bar'}}); + L.Util.bind(() => {}, {}); L.Util.stamp({}); L.Util.throttle(() => {}, 123, {}); @@ -546,7 +576,7 @@ L.Util.template('template', {}); L.Util.isArray({}); L.Util.indexOf([], {}); L.Util.requestAnimFrame(() => {}); -L.Util.requestAnimFrame(() => {}, {}); +L.Util.requestAnimFrame(timestamp => console.log(timestamp), {}); L.Util.requestAnimFrame(() => {}, {}, true); L.Util.cancelAnimFrame(1); L.Util.emptyImageUrl; diff --git a/types/level-codec/index.d.ts b/types/level-codec/index.d.ts new file mode 100644 index 0000000000..a106350215 --- /dev/null +++ b/types/level-codec/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for level-codec 9.0 +// Project: https://github.com/Level/codec +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface CodecEncoder { + encode: (val: any) => any; + decode: (val: any) => any; + buffer: boolean; + type: string; +} +export interface CodecOptions { + keyEncoding?: string | CodecEncoder; + valueEncoding?: string | CodecEncoder; +} +export interface Codec { + encodeKey(key: any, opts?: CodecOptions, batchOpts?: CodecOptions): any; + encodeValue(value: any, opts?: CodecOptions, batchOpts?: CodecOptions): any; + decodeKey(key: any, opts?: CodecOptions): any; + decodeValue(value: any, opts?: CodecOptions): any; + encodeBatch(ops: any, opts?: CodecOptions): any; + encodeLtgt(ltgt: any): any; + createStreamDecoder(opts: CodecOptions): any; + keyAsBuffer(opts?: CodecOptions): any; + valueAsBuffer(opts?: CodecOptions): any; +} +export interface CodecConstructor { + new (options?: CodecOptions): Codec; + (options?: CodecOptions): Codec; +} + +export const Codec: CodecConstructor; diff --git a/types/level-codec/level-codec-tests.ts b/types/level-codec/level-codec-tests.ts new file mode 100644 index 0000000000..371966844f --- /dev/null +++ b/types/level-codec/level-codec-tests.ts @@ -0,0 +1,12 @@ +import { Codec } from "level-codec"; + +const test = (codec: Codec) => { + return codec.keyAsBuffer(); +}; + +test(new Codec({ keyEncoding: "hex" })); +test(new Codec()); + +// new not needed +test(Codec({ keyEncoding: "hex" })); +test(Codec()); diff --git a/types/level-codec/tsconfig.json b/types/level-codec/tsconfig.json new file mode 100644 index 0000000000..0381e4eb12 --- /dev/null +++ b/types/level-codec/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", + "level-codec-tests.ts" + ] +} diff --git a/types/level-codec/tslint.json b/types/level-codec/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/level-codec/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index 4305c662a8..a29a6adeda 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -33,6 +33,7 @@ export class Document { constructor(version?: number, encoding?: string); errors: SyntaxError[]; + validationErrors: ValidationError[]; child(idx: number): Element|null; childNodes(): Element[]; @@ -45,6 +46,7 @@ export class Document { root(newRoot: Node): Node; toString(formatted?: boolean): string; type(): 'document'; + validate(xsdDoc: Document): boolean; version(): string; setDtd(name: string, ext: string, sys: string): void; getDtd(): { @@ -169,3 +171,15 @@ export interface SyntaxError { str3: number|null; int1: number|null; } + +export interface ValidationError extends Error { + domain: number|null; + code: number|null; + level: number|null; + + line: number|null; + /** + * 1-based column number, 0 if not applicable/available. + */ + column: number; +} diff --git a/types/libxmljs/libxmljs-tests.ts b/types/libxmljs/libxmljs-tests.ts index fe720cc242..3975257307 100644 --- a/types/libxmljs/libxmljs-tests.ts +++ b/types/libxmljs/libxmljs-tests.ts @@ -62,3 +62,7 @@ const xmlDocWithNs = libxmljs.parseXml(xmlWithNs); const gchildWithNs = xmlDocWithNs.get('//a:grandchild', {a: 'http://test.com/test'})!; console.log(gchildWithNs.text()); // prints "grandchild content" + +const validated: boolean = doc.validate(doc); +doc.validationErrors[0].message; // inherited from Error +doc.validationErrors[0].line; diff --git a/types/mali-compose/index.d.ts b/types/mali-compose/index.d.ts new file mode 100644 index 0000000000..87b23087d3 --- /dev/null +++ b/types/mali-compose/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for mali 1.1 +// Project: https://github.com/malijs/mali-compose +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { Context } from "mali"; + +declare function compose( + middleware: ReadonlyArray< + (ctx: Context, next: () => Promise) => Promise + > +): (context: Context, next: () => Promise) => Promise; + +export = compose; diff --git a/types/mali-compose/mali-compose-tests.ts b/types/mali-compose/mali-compose-tests.ts new file mode 100644 index 0000000000..190ab46458 --- /dev/null +++ b/types/mali-compose/mali-compose-tests.ts @@ -0,0 +1,39 @@ +import compose = require('mali-compose'); +import { Context } from 'mali'; + +type middleware = (context: Context, next: () => Promise) => Promise; + +const arr: number[] = []; +const stack: middleware[] = []; + +function _sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +stack.push(async (ctx: Context, next: () => Promise) => { + arr.push(1); + await _sleep(1); + await next(); + await _sleep(1); + arr.push(6); + }); + +stack.push(async (ctx: Context, next: () => Promise) => { + arr.push(2); + await _sleep(1); + await next(); + await _sleep(1); + arr.push(5); +}); + +stack.push(async (ctx: Context, next: () => Promise) => { + arr.push(3); + await _sleep(1); + await next(); + await _sleep(1); + arr.push(4); +}); + +compose(stack); +compose([]); +compose([compose(stack)]); diff --git a/types/mali-compose/tsconfig.json b/types/mali-compose/tsconfig.json new file mode 100644 index 0000000000..e0afe50e85 --- /dev/null +++ b/types/mali-compose/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mali-compose-tests.ts" + ] +} diff --git a/types/mali-compose/tslint.json b/types/mali-compose/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/mali-compose/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/mali-onerror/index.d.ts b/types/mali-onerror/index.d.ts new file mode 100644 index 0000000000..c9600d50f0 --- /dev/null +++ b/types/mali-onerror/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for mali-onerror 0.1 +// Project: https://github.com/malijs/onerror +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { Context } from "mali"; + +declare function onError( + fn: (err: Error, ctx: Context) => void +): (ctx: Context, next: () => Promise) => Promise; // ? next (I know it s a function) + +export = onError; diff --git a/types/mali-onerror/mali-onerror-tests.ts b/types/mali-onerror/mali-onerror-tests.ts new file mode 100644 index 0000000000..19c8a5ab55 --- /dev/null +++ b/types/mali-onerror/mali-onerror-tests.ts @@ -0,0 +1,13 @@ +import onError = require('mali-onerror'); +import Mali = require('mali'); +import path = require('path'); + +// Example mali app from Mali docs +const PROTO_PATH = path.resolve(__dirname, '../protos/helloworld.proto'); + +function errorLogger(err: Error, ctx: Mali.Context) { + console.log('Error on %s: %s', ctx.name, err.toString()); +} + +const app = new Mali(PROTO_PATH); +app.use(onError(errorLogger)); diff --git a/types/mali-onerror/tsconfig.json b/types/mali-onerror/tsconfig.json new file mode 100644 index 0000000000..a47d002aab --- /dev/null +++ b/types/mali-onerror/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mali-onerror-tests.ts" + ] +} diff --git a/types/mali-onerror/tslint.json b/types/mali-onerror/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/mali-onerror/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/mali/index.d.ts b/types/mali/index.d.ts new file mode 100644 index 0000000000..8e536d5330 --- /dev/null +++ b/types/mali/index.d.ts @@ -0,0 +1,77 @@ +// Type definitions for mali 0.9 +// Project: https://github.com/malijs/mali +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { EventEmitter } from 'events'; +import { Stream } from 'stream'; + +declare class Mali extends EventEmitter { + constructor(path: any, name?: string | ReadonlyArray, options?: any); + name: string; + env: string; + ports: ReadonlyArray; + silent: boolean; + + addService(path: any, name: string | ReadonlyArray, options?: any): void; + use(service?: any, name?: any, fns?: any): void; + start(port: number | string, creds?: any, options?: any): any; // gnarly type inferring for these functions so Im just gonna let them handle it. + toJSON(): any; + close(): Promise; + inspect(): any; +} + +declare namespace Mali { + interface Context { + name: string; + fullName: string; + service: string; + package: string; + app: any; // ? app + call: any; + request: Request; + response: Response; + req: any; // ? + res: any; // ? + type: string; + metadata: string; + get(field: string): any; + set(field: any, val?: any): void; // do I need `?:` if its of type `any`? + sendMetadata(md: any): void; + getStatus(field: string): any; + setStatus(field: any, val?: any): void; // ^ + } + + class Request { + constructor(call: any, type: string); + call: any; + type: string; + metadata: any; + req: any; // ? + + getMetadata(): any; + get(field: string): any; + } + + class Response { + constructor(call: any, type: string); + call: any; + type: string; + metadata: any; + status: any; + res: any; // ? + set(field: any, val?: any): void; // is `val?:` necessary when its of type `any`? + get(field: string): any; + getMetadata(): any; + sendMetadata(md?: any): void; + getStatus(field: string): any; + setStatus(field: any, val?: any): void; // ^ same as above + } + + function exec(ctx: Context, handler: any, cb?: any): void; +} + +export = Mali; diff --git a/types/mali/mali-tests.ts b/types/mali/mali-tests.ts new file mode 100644 index 0000000000..d6d33a263f --- /dev/null +++ b/types/mali/mali-tests.ts @@ -0,0 +1,16 @@ +// example from https://github.com/malijs/mali#example + +import Mali = require('mali'); +import path = require('path'); + +const PROTO_PATH = path.resolve(__dirname, '../protos/helloworld.proto'); + +async function sayHello(ctx: Mali.Context) { + ctx.res = { message: 'Hello '.concat(ctx.req.name) }; +} + +const app = new Mali(PROTO_PATH); +// $ExpectType void +app.use({sayHello}); +// $ExpectType any +app.start('127.0.0.1:50051'); diff --git a/types/mali/tsconfig.json b/types/mali/tsconfig.json new file mode 100644 index 0000000000..1a4f86d02c --- /dev/null +++ b/types/mali/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mali-tests.ts" + ] +} diff --git a/types/mali/tslint.json b/types/mali/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/mali/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/megajs/index.d.ts b/types/megajs/index.d.ts new file mode 100644 index 0000000000..731c5e5b1e --- /dev/null +++ b/types/megajs/index.d.ts @@ -0,0 +1,116 @@ +// Type definitions for megajs 0.14 +// Project: https://github.com/qgustavor/mega +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import { Readable, Writable, Stream } from 'stream'; + +export interface AccountInfo { + type: string; + spaceUsed: number; + spaceTotal: number; + downloadBandwidthUsed: number; + downloadBandwidthTotal: number; + sharedBandwidthUsed: number; + sharedBandwidthLimit: number; +} + +export interface DownloadOptions { + maxConnections?: number; + initialChunkSize?: number; + chunkSizeIncrement?: number; + maxChunkSize?: number; + returnCiphertext?: boolean; + start?: any; + end?: any; +} + +export interface UploadOptions { + name: string; + attributes?: object; + size?: any; + thumbnailImage?: Buffer | Readable; + previewImage?: Buffer | Readable; +} + +export interface LinkOptions { + noKey?: boolean; + key?: string | Buffer; +} + +export interface MakeDirectoryOptions { + name: string; + attributes?: object; + key?: string | Buffer; +} + +export interface FileOptions { + downloadId: string; + key: string; + directory?: boolean; +} + +export interface StorageOptions { + email: string; + password: string; + keepalive?: boolean; + autologin?: boolean; + autoload?: boolean; +} + +export class File { + constructor(options: FileOptions | string); + static fromURL(options: FileOptions | string): File; + static unpackAttributes(at: any): JSON; + name: string; + attributes: object; + size: number; + key: Buffer; + timestamp: number; + nodeId: string; + downloadId: string; + directory: boolean; + children: ReadonlyArray; + loadAttributes(cb?: any): Readable; + download(options?: DownloadOptions, cb?: any): Readable; +} + +export class Storage { + constructor(options: StorageOptions, callback?: any); + static fromJSON(json: JSON): Storage; + name: string; + key: Buffer; + sid: string; + files: {[id in string]: MutableFile}; + root: MutableFile; + trash: MutableFile; + inbox: MutableFile; + mounts: ReadonlyArray; + upload(options: UploadOptions | string, buffer?: Buffer, cb?: any): Writable; + mkdir(options: MakeDirectoryOptions | string, cb: (err: Error | undefined, file: MutableFile) => void): Readable; + reload(cb: any): Readable; + login(cb: any): Readable; + getAccountInfo(cb: any): AccountInfo; + toJSON(): JSON; +} + +export class MutableFile extends File { + constructor(options: FileOptions | string, storage: Storage); + upload(options: UploadOptions | string, buffer?: Buffer, cb?: any): Writable; + mkdir(options: MakeDirectoryOptions | string, cb?: any): Readable; + importFile(file: File | string, cb: (err: Error | undefined, file: MutableFile) => void): Readable; + link(options: LinkOptions | undefined, cb: (err: Error | undefined, url: string) => void): Readable; + shareFolder(options: LinkOptions | undefined, cb: (err: Error | undefined, url: string) => void): Readable; + delete(permanent: true | undefined, cb: (err: Error | undefined) => void): Readable; + moveTo(target: MutableFile | string, cb: (err: Error | undefined) => void): Readable; + setAttributes(attributes: object, cb: (err: Error | undefined) => void): Readable; + uploadAttribute(type: string | number, opt?: Buffer | Stream, cb?: any): Readable; + rename(newFileName: string, cb: (err: Error | undefined) => void): Readable; + setLabel(label: string, cb: (err: Error | undefined) => void): Readable; + setFavorite(isFavorite: boolean, cb: (err: Error | undefined) => void): Readable; +} + +export default function mega(options: StorageOptions, cb?: any): Storage; diff --git a/types/megajs/megajs-tests.ts b/types/megajs/megajs-tests.ts new file mode 100644 index 0000000000..862373c85a --- /dev/null +++ b/types/megajs/megajs-tests.ts @@ -0,0 +1,9 @@ +import mega from 'megajs'; + +// $ExpectType Storage +mega({email: 'test@test.net', password: '1234'}); + +// tslint:disable-next-line no-duplicate-imports +import { Storage } from 'megajs'; + +const storage = new Storage({email: 'test@test.net', password: '1234'}); diff --git a/types/megajs/tsconfig.json b/types/megajs/tsconfig.json new file mode 100644 index 0000000000..0e6bb53df1 --- /dev/null +++ b/types/megajs/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "megajs-tests.ts" + ] +} diff --git a/types/megajs/tslint.json b/types/megajs/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/megajs/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/memdown/index.d.ts b/types/memdown/index.d.ts new file mode 100644 index 0000000000..ab7b8dfe36 --- /dev/null +++ b/types/memdown/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for memdown 3.0 +// Project: https://github.com/Level/memdown +// Definitions by: Meirion Hughes +// Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { AbstractLevelDOWN } from 'abstract-leveldown'; + +export interface MemDown extends AbstractLevelDOWN {} + +export interface MemDownConstructor { + // tslint:disable-next-line no-unnecessary-generics + new (): MemDown; + // tslint:disable-next-line no-unnecessary-generics + (): MemDown; +} + +export const MemDown: MemDownConstructor; +export default MemDown; diff --git a/types/memdown/memdown-tests.ts b/types/memdown/memdown-tests.ts new file mode 100644 index 0000000000..f93a4bb779 --- /dev/null +++ b/types/memdown/memdown-tests.ts @@ -0,0 +1,16 @@ +import MemDown from 'memdown'; + +const test = (db: MemDown) => { + db.open(() => { + db.put("key", "value", (err?: Error) => { }); + db.get("key", (err?: Error) => { }); + db.get("key", (err: Error | undefined, value: string) => { }); + db.close(() => {}); + }); +}; + +// doesn't need `new` and can be called as a function +test(new MemDown()); +test(new MemDown()); +test(MemDown()); +test(MemDown()); diff --git a/types/delay/tsconfig.json b/types/memdown/tsconfig.json similarity index 94% rename from types/delay/tsconfig.json rename to types/memdown/tsconfig.json index cb0da53652..dd3aa17b6c 100644 --- a/types/delay/tsconfig.json +++ b/types/memdown/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "delay-tests.ts" + "memdown-tests.ts" ] } \ No newline at end of file diff --git a/types/memdown/tslint.json b/types/memdown/tslint.json new file mode 100644 index 0000000000..256ee54775 --- /dev/null +++ b/types/memdown/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/meteor/browser-policy-common.d.ts b/types/meteor/browser-policy-common.d.ts index 4aa3810f45..8926938976 100644 --- a/types/meteor/browser-policy-common.d.ts +++ b/types/meteor/browser-policy-common.d.ts @@ -19,10 +19,13 @@ declare module "meteor/browser-policy-common" { allowStyleOrigin(origin: string): void; allowScriptOrigin(origin: string): void; allowFrameOrigin(origin: string): void; + allowFrameAncestorsOrigin(origin: string): void; allowContentTypeSniffing(): void; allowAllContentOrigin(): void; allowAllContentDataUrl(): void; allowAllContentSameOrigin(): void; + allowConnectOrigin(origin: string): void; + allowObjectOrigin(origin: string): void; disallowAll(): void; disallowInlineStyles(): void; @@ -31,6 +34,7 @@ declare module "meteor/browser-policy-common" { disallowFont(): void; disallowObject(): void; disallowAllContent(): void; + disallowConnect(): void; }; } } diff --git a/types/meteor/index.d.ts b/types/meteor/index.d.ts index 0822bab8e7..dfa14ebc59 100644 --- a/types/meteor/index.d.ts +++ b/types/meteor/index.d.ts @@ -8,6 +8,7 @@ // Arda TANRIKULU // Stefan Holzapfel // Andrey Markeev +// Leon Machens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/meteor/server-render.d.ts b/types/meteor/server-render.d.ts index 0f78cac1c0..9c30def0f8 100644 --- a/types/meteor/server-render.d.ts +++ b/types/meteor/server-render.d.ts @@ -11,6 +11,7 @@ declare module "meteor/server-render" { appendToBody?(html: string): void; appendToElementById?(id: string, html: string): void; renderIntoElementById?(id: string, html: string): void; + renderIntoElementById?(id: string, html: NodeJS.ReadableStream): void; } type Callback = (sink: Sink) => Promise | any; diff --git a/types/meteor/test/meteor-tests-module-only.ts b/types/meteor/test/meteor-tests-module-only.ts index 3591b90635..716d0a7e74 100644 --- a/types/meteor/test/meteor-tests-module-only.ts +++ b/types/meteor/test/meteor-tests-module-only.ts @@ -1,7 +1,6 @@ // This file is for tests that involve modules that don't have corresponding // globals. -import { onPageLoad } from "meteor/server-render"; import { ServiceConfiguration } from "meteor/service-configuration"; import { WebApp } from "meteor/webapp"; diff --git a/types/meteor/test/server-render.tsx b/types/meteor/test/server-render.tsx new file mode 100644 index 0000000000..f6adb72f32 --- /dev/null +++ b/types/meteor/test/server-render.tsx @@ -0,0 +1,15 @@ +import { onPageLoad } from "meteor/server-render"; +import * as React from 'react'; +import { renderToString, renderToNodeStream } from 'react-dom/server'; + +onPageLoad(sink => { + if (sink.renderIntoElementById) { + sink.renderIntoElementById("app", renderToString(
Hello World
)); + } +}); + +onPageLoad(sink => { + if (sink.renderIntoElementById) { + sink.renderIntoElementById("app", renderToNodeStream(
Hello World
)); + } +}); \ No newline at end of file diff --git a/types/meteor/tsconfig.json b/types/meteor/tsconfig.json index 7ad451fd56..ed6a9e0e77 100644 --- a/types/meteor/tsconfig.json +++ b/types/meteor/tsconfig.json @@ -15,7 +15,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" }, "files": [ "accounts-base.d.ts", @@ -61,6 +62,7 @@ "index.d.ts", "test/meteor-tests.ts", "test/globals/meteor-tests.ts", - "test/meteor-tests-module-only.ts" + "test/meteor-tests-module-only.ts", + "test/server-render.tsx" ] } diff --git a/types/minio/index.d.ts b/types/minio/index.d.ts index 53ca4fa6cd..1bb407529d 100644 --- a/types/minio/index.d.ts +++ b/types/minio/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for minio 6.0 +// Type definitions for minio 7.0 // Project: https://github.com/minio/minio-js#readme // Definitions by: Barin Britva // Lubomir Kaplan // Panagiotis Kapros +// Ben Watkins // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -20,7 +21,7 @@ export interface ClientOptions { endPoint: string; accessKey: string; secretKey: string; - secure?: boolean; + useSSL?: boolean; port?: number; region?: Region; transport?: any; diff --git a/types/minio/minio-tests.ts b/types/minio/minio-tests.ts index 46d83201f7..f93ce98af5 100644 --- a/types/minio/minio-tests.ts +++ b/types/minio/minio-tests.ts @@ -4,7 +4,7 @@ import Minio = require('minio'); const minio = new Minio.Client({ endPoint: 'localhost', port: 9000, - secure: false, + useSSL: false, accessKey: 'iV7RAFOtxF', secretKey: 'Go1hhOkXnl', }); diff --git a/types/mirrorx/index.d.ts b/types/mirrorx/index.d.ts index 07b26d494c..443712c325 100644 --- a/types/mirrorx/index.d.ts +++ b/types/mirrorx/index.d.ts @@ -51,8 +51,8 @@ export interface RedirectProps { strict?: boolean; } -export interface RouteComponentProps

{ - match: match

; +export interface RouteComponentProps { + match: match; location: H.Location; history: H.History; staticContext?: any; diff --git a/types/ml-levenberg-marquardt/index.d.ts b/types/ml-levenberg-marquardt/index.d.ts new file mode 100644 index 0000000000..fd2f0d1038 --- /dev/null +++ b/types/ml-levenberg-marquardt/index.d.ts @@ -0,0 +1,76 @@ +// Type definitions for ml-levenberg-marquardt 1.0 +// Project: https://github.com/mljs/levenberg-marquardt#readme +// Definitions by: m93a +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +declare namespace LM { + /** + * Function that receives an array of parameters and returns + * a function with the independent variable as a parameter. + */ + type FittedFunction = (parameters: number[]) => (x: number) => number; + + /** + * Coordinates of points to fit. + */ + interface Data { + x: number[]; + y: number[]; + } + + interface Options { + /** + * The Levenberg-Marquardt lambda parameter. + * Default value: 0 + */ + damping: number; + + /** + * Initial guesses for the parameters. + * Default value: Array(parameters.lengh).fill(1) + */ + initialValues: number[]; + + /** + * Adjustment for decrease the damping parameter. + * Default value: 10e-2 + */ + gradientDifference: number; + + /** + * The maximum number of iterations before halting. + * Default value: 100 + */ + maxIterations: number; + + /** + * Minimum uncertainty allowed for each point. + * Default value: 10e-3 + */ + errorTolerance: number; + + /** + * Maximum values for the parameters. + * Default value: Array(data.x.length).fill(MAX_SAFE_INTEGER) + */ + maxValue: number[]; + + /** + * Minimum values for the parameters. + * Default value: Array(data.x.length).fill(MIN_SAFE_INTEGER) + */ + minValue: number[]; + } + + interface Result { + iterations: number; + parameterError: number; + parameterValues: number[]; + } +} + +/** Implementation of the Levenberg-Marquardt curve fitting method. */ +declare function LM(d: LM.Data, fn: LM.FittedFunction, o?: Partial): LM.Result; + +export default LM; diff --git a/types/ml-levenberg-marquardt/ml-levenberg-marquardt-tests.ts b/types/ml-levenberg-marquardt/ml-levenberg-marquardt-tests.ts new file mode 100644 index 0000000000..514af7f901 --- /dev/null +++ b/types/ml-levenberg-marquardt/ml-levenberg-marquardt-tests.ts @@ -0,0 +1,31 @@ +import LM from 'ml-levenberg-marquardt'; + +function sinFunction([a, b]: number[]) { + return (t: number) => a * Math.sin(b * t); +} + +const data = { + x: [ + 0, Math.PI / 2, Math.PI, Math.PI * 3 / 2 + ], + y: [ + 0, 1, 0, -1 + ] +}; + +const initialValues = [ 2, 4 ]; + +const options = { + damping: 1.5, + initialValues, + gradientDifference: 10e-2, + maxIterations: 100, + errorTolerance: 10e-3 +}; + +const fittedParams = LM(data, sinFunction, options); + +// this doesn't make sense but it uses fittedParams... +if (fittedParams.iterations < 10) { + fittedParams.parameterValues[0] += fittedParams.parameterError; +} diff --git a/types/ml-levenberg-marquardt/tsconfig.json b/types/ml-levenberg-marquardt/tsconfig.json new file mode 100644 index 0000000000..7043dea3b6 --- /dev/null +++ b/types/ml-levenberg-marquardt/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ml-levenberg-marquardt-tests.ts" + ] +} diff --git a/types/ml-levenberg-marquardt/tslint.json b/types/ml-levenberg-marquardt/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ml-levenberg-marquardt/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/moment-timezone/index.d.ts b/types/moment-timezone/index.d.ts index 1d05b96f36..0f2d68cb57 100644 --- a/types/moment-timezone/index.d.ts +++ b/types/moment-timezone/index.d.ts @@ -58,7 +58,7 @@ declare module "moment" { interface Moment { tz(): string | undefined; - tz(timezone: string, keepLocalTime?: boolean): Moment; + tz(timezone: string, keepLocalTime?: boolean): moment.Moment; zoneAbbr(): string; zoneName(): string; } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 5791b906f1..cad52bb88a 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -14,6 +14,8 @@ // Wan Bachtiar // Geraldine Lemeur // Jimmy Shimizu +// Dominik Heigl +// Angela-1 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -22,7 +24,7 @@ /// /// -import { ObjectID } from 'bson'; +import { ObjectID, Timestamp } from 'bson'; import { EventEmitter } from 'events'; import { Readable, Writable } from "stream"; @@ -58,13 +60,136 @@ export class MongoClient extends EventEmitter { logout(options?: { dbName?: string }): Promise; logout(options: { dbName?: string }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#startSession */ - startSession(options?: any): ClientSession; + startSession(options?: SessionOptions): ClientSession; + /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#watch */ + watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; + /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */ + withSession(operation: (session: ClientSession) => Promise): Promise; + /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#withSession */ + withSession(options: SessionOptions, operation: (session: ClientSession) => Promise): Promise; } -declare class ClientSession extends EventEmitter { - endSession(callback?: MongoCallback): void; - endSession(options: any, callback?: MongoCallback): void; +/** + * http://mongodb.github.io/node-mongodb-native/3.1/api/ClientSession.html + */ +export interface ClientSession extends EventEmitter { + /** The server id associated with this session */ + id: any; + /** + * Aborts the currently active transaction in this session. + * @param {MongoCallback} [cb] Optional callback for completion of this operation + */ + abortTransaction(cb?: MongoCallback): Promise; + /** + * Advances the operationTime for a ClientSession. + * @param {mongodb.Timestamp} operationTime + */ + advanceOperationTime(operamtionTime: Timestamp): void; + /** + * Commits the currently active transaction in this session. + * @param {MongoCallback} [cb] Optional callback for completion of this operation + */ + commitTransaction(cb?: MongoCallback): Promise; + + /** + * Ends this session on the server + * @param {MongoCallback} [cb] Optional callback for completion of this operation + */ + endSession(cb?: MongoCallback): void; + /** + * Ends this session on the server + * @param {*} [options] Optional settings. Currently reserved for future use + * @param {MongoCallback} [cb] Optional callback for completion of this operation + */ + endSession(options: any, cb?: MongoCallback): void + + /** + * Used to determine if this session equals another + * + * @param {ClientSession} session A class representing a client session on the server + * @returns {boolean} if the sessions are equal + */ equals(session: ClientSession): boolean; + + /** Increment the transaction number on the internal ServerSession */ + incrementTransactionNumber(): void; + + /** + * @returns {boolean} this session is currently in a transaction or not + */ + inTransaction(): boolean; + + /** + * Starts a new transaction with the given options. + * @param {TransactionOptions} options + * @memberof ClientSession + */ + startTransaction(options?: TransactionOptions): void; + +} + +// http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#ReadConcern +type ReadConcernLevel = 'local' | 'available' | 'majority' | 'linearizable' | 'snapshot'; + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#ReadConcern + */ +export interface ReadConcern { + level: ReadConcernLevel; +} + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#WriteConcern + */ +interface WriteConcern { + /** + * requests acknowledgement that the write operation has + * propagated to a specified number of mongod hosts + * @type {(number | 'majority' | string)} default 1 + */ + w?: number | 'majority' | string; + /** + * requests acknowledgement from MongoDB that the write operation has + * been written to the journal + * @type {boolean} default false + */ + j?: boolean; + /** + * a time limit, in milliseconds, for the write concern + * @type {number} + * @memberof WriteConcern + */ + wtimeout?: number; +} + +/** + * Options to pass when creating a Client Session + * http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#SessionOptions + */ +export interface SessionOptions { + /** + * Whether causal consistency should be enabled on this session + * @type {boolean} default true + */ + causalConsistency?: boolean; + /** + * The default TransactionOptions to use for transactions started on this session. + */ + defaultTransactionOptions?: TransactionOptions; +} + +/** + * Configuration options for a transaction. + * http://mongodb.github.io/node-mongodb-native/3.1/api/global.html#TransactionOptions + */ +export interface TransactionOptions { + readConcern?: ReadConcern; + writeConcern?: WriteConcern; + readPreference?: any; } export interface MongoClientCommonOption { @@ -190,7 +315,7 @@ export interface DbCreateOptions extends CommonOptions { // ES6 compatible promise constructor promiseLibrary?: Object; /** https://docs.mongodb.com/manual/reference/read-concern/#read-concern */ - readConcern?: { level?: Object }; + readConcern?: ReadConcern; // Sets a cap on how many operations the driver will buffer up before giving up on getting a // working connection, default is -1 which is unlimited. bufferMaxEntries?: number; @@ -208,6 +333,10 @@ export interface SocketOptions { keepAliveInitialDelay?: number; // TCP Connection timeout setting. default 0 connectTimeoutMS?: number; + // Version of IP stack. Can be 4, 6 or null. default: null. + // If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + // refer to http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html + family?: 4 | 6 | null; // TCP Socket timeout setting. default 0 socketTimeoutMS?: number; } @@ -328,14 +457,7 @@ export class Db extends EventEmitter { stats(options: { scale?: number }, callback: MongoCallback): void; } -export interface CommonOptions { - /** The write concern. */ - w?: string | number; - /** The write concern timeout. */ - wtimeout?: number; - /** Specify a journal write concern. */ - j?: boolean; - /** Session to use for this operation */ +export interface CommonOptions extends WriteConcern { session?: ClientSession; } @@ -395,7 +517,7 @@ export interface DbCollectionOptions extends CommonOptions { readPreference?: ReadPreference | string; serializeFunctions?: boolean; strict?: boolean; - readConcern?: { level: Object }; + readConcern?: ReadConcern; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */ @@ -485,7 +607,7 @@ export interface Collection { // The current write concern values. writeConcern: any; // The current read concern values. - readConcern: any; + readConcern: ReadConcern; // Get current index hint for collection. hint: any; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#aggregate */ @@ -515,8 +637,8 @@ export interface Collection { createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ */ createIndexes(indexSpecs: Object[], callback: MongoCallback): void; - createIndexes(indexSpecs: Object[], options?: {session?: ClientSession}): Promise; - createIndexes(indexSpecs: Object[], options: {session?: ClientSession}, callback: MongoCallback): void; + createIndexes(indexSpecs: Object[], options?: { session?: ClientSession }): Promise; + createIndexes(indexSpecs: Object[], options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany */ deleteMany(filter: FilterQuery, callback: MongoCallback): void; deleteMany(filter: FilterQuery, options?: CommonOptions): Promise; @@ -530,17 +652,17 @@ export interface Collection { distinct(key: string, query: Object, options?: { readPreference?: ReadPreference | string, maxTimeMS?: number, session?: ClientSession }): Promise; distinct(key: string, query: Object, options: { readPreference?: ReadPreference | string, maxTimeMS?: number, session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#drop */ - drop(options?: {session: ClientSession}): Promise; + drop(options?: { session: ClientSession }): Promise; drop(callback: MongoCallback): void; - drop(options: {session: ClientSession}, callback: MongoCallback): void; + drop(options: { session: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#dropIndex */ dropIndex(indexName: string, callback: MongoCallback): void; dropIndex(indexName: string, options?: CommonOptions & { maxTimeMS?: number }): Promise; dropIndex(indexName: string, options: CommonOptions & { maxTimeMS?: number }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#dropIndexes */ - dropIndexes(options?: {session?: ClientSession, maxTimeMS?: number}): Promise; + dropIndexes(options?: { session?: ClientSession, maxTimeMS?: number }): Promise; dropIndexes(callback?: MongoCallback): void; - dropIndexes(options: {session?: ClientSession, maxTimeMS?: number}, callback: MongoCallback): void; + dropIndexes(options: { session?: ClientSession, maxTimeMS?: number }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount */ estimatedDocumentCount(callback: MongoCallback): void; estimatedDocumentCount(query: Object, callback: MongoCallback): void; @@ -579,13 +701,13 @@ export interface Collection { group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options?: { readPreference?: ReadPreference | string }): Promise; group(keys: Object | Array | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options: { readPreference?: ReadPreference | string }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexes */ - indexes(options?: {session: ClientSession}): Promise; + indexes(options?: { session: ClientSession }): Promise; indexes(callback: MongoCallback): void; - indexes(options: {session?: ClientSession}, callback: MongoCallback): void; + indexes(options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexExists */ indexExists(indexes: string | string[], callback: MongoCallback): void; - indexExists(indexes: string | string[], options?: {session: ClientSession}): Promise; - indexExists(indexes: string | string[], options: {session: ClientSession}, callback: MongoCallback): void; + indexExists(indexes: string | string[], options?: { session: ClientSession }): Promise; + indexExists(indexes: string | string[], options: { session: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#indexInformation */ indexInformation(callback: MongoCallback): void; indexInformation(options?: { full: boolean, session: ClientSession }): Promise; @@ -610,9 +732,9 @@ export interface Collection { insertOne(docs: Object, options?: CollectionInsertOneOptions): Promise; insertOne(docs: Object, options: CollectionInsertOneOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#isCapped */ - isCapped(options?: {session: ClientSession}): Promise; + isCapped(options?: { session: ClientSession }): Promise; isCapped(callback: MongoCallback): void; - isCapped(options: {session: ClientSession}, callback: MongoCallback): void; + isCapped(options: { session: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#listIndexes */ listIndexes(options?: { batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#mapReduce */ @@ -620,17 +742,17 @@ export interface Collection { mapReduce(map: Function | string, reduce: Function | string, options?: MapReduceOptions): Promise; mapReduce(map: Function | string, reduce: Function | string, options: MapReduceOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#options */ - options(options?: {session: ClientSession}): Promise; + options(options?: { session: ClientSession }): Promise; options(callback: MongoCallback): void; - options(options: {session: ClientSession}, callback: MongoCallback): void; + options(options: { session: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#parallelCollectionScan */ parallelCollectionScan(callback: MongoCallback[]>): void; parallelCollectionScan(options?: ParallelCollectionScanOptions): Promise[]>; parallelCollectionScan(options: ParallelCollectionScanOptions, callback: MongoCallback[]>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#reIndex */ - reIndex(options?: {session: ClientSession}): Promise; + reIndex(options?: { session: ClientSession }): Promise; reIndex(callback: MongoCallback): void; - reIndex(options: {session: ClientSession}, callback: MongoCallback): void; + reIndex(options: { session: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove */ /** @deprecated Use use deleteOne, deleteMany or bulkWrite */ remove(selector: Object, callback: MongoCallback): void; @@ -673,7 +795,7 @@ export interface Collection { updateOne(filter: FilterQuery, update: Object, options?: ReplaceOneOptions): Promise; updateOne(filter: FilterQuery, update: Object, options: ReplaceOneOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#watch */ - watch(pipeline?: Object[], options?: ChangeStreamOptions & { session?: ClientSession }): ChangeStream; + watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; } export type FilterQuery = { @@ -713,7 +835,7 @@ export type FilterQuery = { $bitsAnySet?: Object; [key: string]: any; }; -} | { [key:string]: any }; +} | { [key: string]: any }; // Documentation: http://docs.mongodb.org/manual/reference/command/collStats/ export interface CollStats { @@ -896,7 +1018,7 @@ export interface CollectionAggregationOptions { readPreference?: ReadPreference | string; // Return the query as cursor, on 2.6 > it returns as a real cursor // on pre 2.6 it returns as an emulated cursor. - cursor?: { batchSize: number }; + cursor?: { batchSize?: number }; // Explain returns the aggregation execution plan (requires mongodb 2.6 >). explain?: boolean; // lets the server know if it can use disk to store @@ -1152,7 +1274,7 @@ export interface FindOneOptions { export interface InsertWriteOpResult { insertedCount: number; ops: Array; - insertedIds: {[key: number]: ObjectID}; + insertedIds: { [key: number]: ObjectID }; connection: any; result: { ok: number, n: number } } @@ -1500,11 +1622,18 @@ export class GridFSBucketWriteStream extends Writable { /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketWriteStream.html */ export interface GridFSBucketWriteStreamOptions { + /** Custom file id for the GridFS file. */ id?: GridFSBucketWriteStreamId, + /** The chunk size to use, in bytes */ chunkSizeBytes?: number, + /** The write concern */ w?: number, + /** The write concern timeout */ wtimeout?: number, + /** The journal write concern */ j?: number + /** Default false; If true, disables adding an md5 field to file data */ + disableMD5?: boolean } /** http://mongodb.github.io/node-mongodb-native/3.1/api/ChangeStream.html */ @@ -1560,29 +1689,29 @@ export interface LoggerState { export class Logger { constructor(className: string, options?: LoggerOptions) // Log a message at the debug level - debug(message: string, state: LoggerState):void + debug(message: string, state: LoggerState): void // Log a message at the warn level - warn(message: string, state: LoggerState):void + warn(message: string, state: LoggerState): void // Log a message at the info level - info(message: string, state: LoggerState):void + info(message: string, state: LoggerState): void // Log a message at the error level - error(message: string, state: LoggerState):void + error(message: string, state: LoggerState): void // Is the logger set at info level - isInfo():boolean + isInfo(): boolean // Is the logger set at error level - isError():boolean + isError(): boolean // Is the logger set at error level - isWarn():boolean + isWarn(): boolean // Is the logger set at debug level - isDebug():boolean + isDebug(): boolean // Resets the logger to default settings, error and no filtered classes - static reset():void + static reset(): void // Get the current logger function - static currentLogger():log + static currentLogger(): log //Set the current logger function - static setCurrentLogger(log: log):void + static setCurrentLogger(log: log): void // Set what classes to log. - static filter(type: string, values: string[]):void + static filter(type: string, values: string[]): void // Set the current log level - static setLevel(level: string):void + static setLevel(level: string): void } diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index 5ffaf6818f..9151346ea5 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -17,6 +17,7 @@ let options: mongodb.MongoClientOptions = { poolSize: 1, socketOptions: {}, + family: 4, reconnectTries: 123456, reconnectInterval: 123456, @@ -174,5 +175,113 @@ let testFunc = async () => { testClient = await mongodb.connect(connectionString); }; -mongodb.connect(connectionString, (err: mongodb.MongoError, client: mongodb.MongoClient) => {}); -mongodb.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => {}); +mongodb.connect(connectionString, (err: mongodb.MongoError, client: mongodb.MongoClient) => { }); +mongodb.connect(connectionString, options, (err: mongodb.MongoError, client: mongodb.MongoClient) => { }); + +// https://docs.mongodb.com/manual/core/transactions/ + +async function commitWithRetry(session: mongodb.ClientSession) { + try { + await session.commitTransaction(); + console.log('Transaction committed.'); + } catch (error) { + if ( + error.errorLabels && + error.errorLabels.indexOf('UnknownTransactionCommitResult') < 0 + ) { + console.log('UnknownTransactionCommitResult, retrying commit operation ...'); + await commitWithRetry(session); + } else { + console.log('Error during commit ...'); + throw error; + } + } +} + +async function runTransactionWithRetry( + txnFunc: (client: mongodb.MongoClient, session: mongodb.ClientSession) => Promise, + client: mongodb.MongoClient, + session: mongodb.ClientSession) { + try { + await txnFunc(client, session); + } catch (error) { + console.log('Transaction aborted. Caught exception during transaction.'); + + // If transient error, retry the whole transaction + if (error.errorLabels && error.errorLabels.indexOf('TransientTransactionError') < 0) { + console.log('TransientTransactionError, retrying transaction ...'); + await runTransactionWithRetry(txnFunc, client, session); + } else { + throw error; + } + } +} + +async function updateEmployeeInfo(client: mongodb.MongoClient, session: mongodb.ClientSession) { + session.startTransaction({ + readConcern: { level: 'snapshot' }, + writeConcern: { w: 'majority' } + }); + + const employeesCollection = client.db('hr').collection('employees'); + const eventsCollection = client.db('reporting').collection('events'); + + await employeesCollection.updateOne( + { employee: 3 }, + { $set: { status: 'Inactive' } }, + { session } + ); + await eventsCollection.insertOne( + { + employee: 3, + status: { new: 'Inactive', old: 'Active' } + }, + { session } + ); + + try { + await commitWithRetry(session); + } catch (error) { + await session.abortTransaction(); + throw error; + } +} + +async function transfer(client: mongodb.MongoClient, from: any, to: any, amount: number) { + const db = client.db(); + const session = client.startSession(); + session.startTransaction(); + try { + const opts = { session, returnOriginal: false }; + const A = await db.collection('Account'). + findOneAndUpdate({ name: from }, { $inc: { balance: -amount } }, opts). + then(res => res.value); + if (A.balance < 0) { + // If A would have negative balance, fail and abort the transaction + // `session.abortTransaction()` will undo the above `findOneAndUpdate()` + throw new Error('Insufficient funds: ' + (A.balance + amount)); + } + + const B = await db.collection('Account'). + findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts). + then(res => res.value); + + await session.commitTransaction(); + session.endSession(); + return { from: A, to: B }; + } catch (error) { + // If an error occurred, abort the whole transaction and + // undo any changes that might have happened + await session.abortTransaction(); + session.endSession(); + throw error; // Rethrow so calling function sees error + } + } + +mongodb.connect(connectionString).then((client) => { + client.startSession(); + client.withSession(session => + runTransactionWithRetry(updateEmployeeInfo, client, session) + ); +}); + diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 94aacd244e..3534f82f49 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mongoose 5.2.3 +// Type definitions for Mongoose 5.2.13 // Project: http://mongoosejs.com/ // Definitions by: horiuchi // sindrenm @@ -11,6 +11,7 @@ // ondratra // alfirin // Idan Dardikman +// Dominik Heigl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -62,9 +63,9 @@ declare module "mongoose" { * Some mongoose classes have the same name as the native JS classes * Keep references to native classes using a "Native" prefix */ - class NativeBuffer extends global.Buffer {} - class NativeDate extends global.Date {} - class NativeError extends global.Error {} + class NativeBuffer extends global.Buffer { } + class NativeDate extends global.Date { } + class NativeError extends global.Error { } /* * section index.js @@ -72,7 +73,7 @@ declare module "mongoose" { */ export var DocumentProvider: any; // recursive constructor - export var Mongoose: new(...args: any[]) => typeof mongoose; + export var Mongoose: new (...args: any[]) => typeof mongoose; type Mongoose = typeof mongoose; export var SchemaTypes: typeof Schema.Types; @@ -158,6 +159,8 @@ declare module "mongoose" { /** Sets mongoose options */ export function set(key: string, value: any): void; + export function startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise; + class CastError extends Error { /** * The Mongoose CastError constructor @@ -210,16 +213,16 @@ declare module "mongoose" { open(connection_string: string, database?: string, port?: number, options?: ConnectionOpenOptions, callback?: (err: any) => void): any; - /** - * Opens the connection to MongoDB. - * @param mongodb://uri or the host to which you are connecting - * @param database database name - * @param port database port - * @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden. - * Mongoose defaults the server auto_reconnect options to true which can be overridden. - * See the node-mongodb-native driver instance for options that it understands. - * Options passed take precedence over options included in connection strings. - */ + /** + * Opens the connection to MongoDB. + * @param mongodb://uri or the host to which you are connecting + * @param database database name + * @param port database port + * @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden. + * Mongoose defaults the server auto_reconnect options to true which can be overridden. + * See the node-mongodb-native driver instance for options that it understands. + * Options passed take precedence over options included in connection strings. + */ openUri(connection_string: string, database?: string, port?: number, options?: ConnectionOpenOptions, callback?: (err: any) => void): any; @@ -346,7 +349,7 @@ declare module "mongoose" { /** Specify a journal write concern (default: false). */ journal?: boolean; /** The write concern */ - w?: number|string; + w?: number | string; /** The write concern timeout. */ wTimeoutMS?: number; /** The ReadPreference mode as listed here: http://mongodb.github.io/node-mongodb-native/2.1/api/ReadPreference.html */ @@ -425,7 +428,9 @@ declare module "mongoose" { interface ConnectionOptions extends ConnectionOpenOptions, - ConnectionOpenSetOptions {} + ConnectionOpenSetOptions { } + + interface ClientSession extends mongodb.ClientSession { } /* * section drivers/node-mongodb-native/collection.js @@ -460,6 +465,8 @@ declare module "mongoose" { */ useDb(name: string): Connection; + startSession(options?: mongodb.SessionOptions, cb?: (err: any, session: mongodb.ClientSession) => void): Promise; + /** Expose the possible connection states. */ static STATES: any; } @@ -870,7 +877,7 @@ declare module "mongoose" { /** defaults to true */ validateBeforeSave?: boolean; /** defaults to "__v" */ - versionKey?: string|boolean; + versionKey?: string | boolean; /** * skipVersioning allows excluding paths from * versioning (the internal revision will not be @@ -945,9 +952,9 @@ declare module "mongoose" { * to the front of this SchemaType's validators array using unshift(). */ required?: SchemaTypeOpts.RequiredFn | - boolean | [boolean, string] | - string | [string, string] | - any; + boolean | [boolean, string] | + string | [string, string] | + any; /** * Sets default select() behavior for this path. @@ -975,9 +982,11 @@ declare module "mongoose" { * and must return Boolean. Returning false means validation failed. */ validate?: RegExp | [RegExp, string] | - SchemaTypeOpts.ValidateFn | [SchemaTypeOpts.ValidateFn, string] | - SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts | - (SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts)[]; + SchemaTypeOpts.ValidateFn | [SchemaTypeOpts.ValidateFn, string] | + SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts | + SchemaTypeOpts.AsyncPromiseValidationFn | SchemaTypeOpts.AsyncPromiseValidationOpts | + (SchemaTypeOpts.ValidateOpts | SchemaTypeOpts.AsyncValidateOpts | + SchemaTypeOpts.AsyncPromiseValidationFn | SchemaTypeOpts.AsyncPromiseValidationOpts)[]; /** Declares an unique index. */ unique?: boolean | any; @@ -1004,16 +1013,16 @@ declare module "mongoose" { * Sets a minimum date validator. */ min?: number | [number, string] | - Date | [Date, string] | - any; + Date | [Date, string] | + any; /** * Date, Number only - Sets a maximum number validator. * Sets a maximum date validator. */ max?: number | [number, string] | - Date | [Date, string] | - any; + Date | [Date, string] | + any; /** * Date only - Declares a TTL index (rounded to the nearest second) @@ -1060,6 +1069,14 @@ declare module "mongoose" { validator: AsyncValidateFn; } + interface AsyncPromiseValidationFn { + (value: T): Promise; + } + + interface AsyncPromiseValidationOpts extends ValidateOptsBase { + validator: AsyncPromiseValidationFn; + } + interface EnumOpts { values?: T[]; message?: string; @@ -1473,9 +1490,9 @@ declare module "mongoose" { // var objectId: mongoose.Types.ObjectId should reference mongodb.ObjectID not // the ObjectIdConstructor, so we add the interface below - interface ObjectId extends mongodb.ObjectID {} + interface ObjectId extends mongodb.ObjectID { } - class Decimal128 extends mongodb.Decimal128 {} + class Decimal128 extends mongodb.Decimal128 { } /* * section types/embedded.js @@ -1521,7 +1538,7 @@ declare module "mongoose" { * So we save this type as the second type parameter in DocumentQuery. Since people have * been using Query, we set it as an alias of DocumentQuery. */ - class Query extends DocumentQuery {} + class Query extends DocumentQuery { } class DocumentQuery extends mquery { /** * Specifies a javascript function or expression to pass to MongoDBs query system. @@ -1877,6 +1894,12 @@ declare module "mongoose" { */ read(pref: string, tags?: any[]): this; + /** + * Sets the readConcern option for the query. + * @param level one of the listed read concern level or their aliases + */ + readConcern(level: string): this; + /** * Specifies a $regex query condition. * When called with one argument, the most recent path passed to where() is used. @@ -1903,6 +1926,15 @@ declare module "mongoose" { selectedInclusively(): boolean; /** Sets query options. */ setOptions(options: any): this; + /** Sets query conditions to the provided JSON object. */ + setQuery(conditions: any): this; + + /** + * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/) + * associated with this query. Sessions are how you mark a query as part of a + * [transaction](/docs/transactions.html). + */ + session(session: mongodb.ClientSession | null): this; /** * Specifies a $size query condition. @@ -1954,14 +1986,14 @@ declare module "mongoose" { /** Executes this query and returns a promise */ then(resolve?: (res: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): Promise; + reject?: (err: any) => void | TRes | PromiseLike): Promise; /** * Converts this query to a customized, reusable query * constructor with all arguments and options retained. */ - toConstructor(): new(...args: any[]) => Query; - toConstructor(): new(...args: any[]) => DocumentQuery; + toConstructor(): new (...args: any[]) => Query; + toConstructor(): new (...args: any[]) => DocumentQuery; /** * Declare and/or execute this query as an update() operation. @@ -1989,7 +2021,7 @@ declare module "mongoose" { // https://github.com/aheckmann/mquery // mquery currently does not have a type definition please // replace it if one is ever created - class mquery {} + class mquery { } interface QueryFindOneAndRemoveOptions { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ @@ -2336,6 +2368,12 @@ declare module "mongoose" { */ cursor(options: any): this; + /** + * Appends a new $facet operator to this aggregate pipeline. + * @param arg $facet operator contents + */ + facet(arg: { [outputField: string]: object[] }): this; + // If cursor option is on, could return an object /** Executes the aggregate pipeline on the currently bound Model. */ exec(callback?: (err: any, result: T) => void): Promise | any; @@ -2422,6 +2460,7 @@ declare module "mongoose" { */ sample(size: number): this; + session(session: mongodb.ClientSession | null): this; /** * Appends a new $skip operator to this aggregate pipeline. * @param num number of records to skip before next stage @@ -2438,8 +2477,8 @@ declare module "mongoose" { sort(arg: string | any): this; /** Provides promise for aggregate. */ - then(resolve?: (val: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): Promise; + then(resolve?: (val: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): Promise; /** * Appends new custom $unwind operator(s) to this aggregate pipeline. @@ -2576,7 +2615,7 @@ declare module "mongoose" { * This function does not trigger any middleware. In particular, it does not trigger aggregate middleware. * @param options See https://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch */ - watch(options?: mongodb.ChangeStreamOptions & {session?: any}): mongodb.ChangeStream; + watch(options?: mongodb.ChangeStreamOptions & { session?: ClientSession }): mongodb.ChangeStream; /** * Translate any aliases fields/conditions so the final query or document object is pure @@ -2823,9 +2862,9 @@ declare module "mongoose" { * with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. */ insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): Promise; - insertMany(docs: any[], options?: { ordered?: boolean, rawResult?: boolean }, callback?: (error: any, docs: T[]) => void): Promise; + insertMany(docs: any[], options?: { ordered?: boolean, rawResult?: boolean } & ModelOptions, callback?: (error: any, docs: T[]) => void): Promise; insertMany(doc: any, callback?: (error: any, doc: T) => void): Promise; - insertMany(doc: any, options?: { ordered?: boolean, rawResult?: boolean }, callback?: (error: any, doc: T) => void): Promise; + insertMany(doc: any, options?: { ordered?: boolean, rawResult?: boolean } & ModelOptions, callback?: (error: any, doc: T) => void): Promise; /** * Performs any async initialization of this model against MongoDB. @@ -2969,7 +3008,12 @@ declare module "mongoose" { schema: Schema; } - interface ModelFindByIdAndUpdateOptions { + /** https://mongoosejs.com/docs/api.html#query_Query-setOptions */ + interface ModelOptions { + session?: ClientSession | null; + } + + interface ModelFindByIdAndUpdateOptions extends ModelOptions { /** true to return the modified document rather than the original. defaults to false */ new?: boolean; /** creates the object if it doesn't exist. defaults to false. */ @@ -3021,7 +3065,7 @@ declare module "mongoose" { populate?: ModelPopulateOptions | ModelPopulateOptions[]; } - interface ModelUpdateOptions { + interface ModelUpdateOptions extends ModelOptions { /** safe mode (defaults to value set in schema (true)) */ safe?: boolean; /** whether to create the doc if it doesn't match (false) */ diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index af8770dc28..dea144c279 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -524,7 +524,15 @@ new mongoose.Schema({ setImmediate(done, true); } } - } + }, + promiseValidated: { + type: Number, + validate: { + validator: async (val: number) => { + return val === 2; + } + } + }, }); new mongoose.Schema({ name: { type: String, validate: [ { validator: () => {return true}, msg: 'uh oh' }, @@ -1010,6 +1018,7 @@ query.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function kittens[0].execPopulate(); }); query.read('primary', []).read('primary'); +query.readConcern('majority').readConcern('m'); query.regex(/re/).regex('path', /re/); query.remove({}, cb); query.remove({}); @@ -1028,6 +1037,7 @@ query.setOptions({ batchSize: true, lean: false }); +query.setQuery({ age: 5 }); query.size(0).size('age', 0); query.skip(100).skip(100); query.slaveOk().slaveOk(false); @@ -1227,6 +1237,7 @@ aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]); aggregate.collation({ locale: 'en_US', strength: 1 }); aggregate.count('countName'); +aggregate.facet({ fieldA: [{ a: 1 }], fieldB: [{ b: 1 }] }); aggregate.cursor({ batchSize: 1000 }).exec().each(cb); aggregate.exec().then(cb).catch(cb); aggregate.option({foo: 'bar'}).exec(); @@ -1889,3 +1900,64 @@ MyModel.createIndexes((err: any): void => {}).then(() => {}); mongoose.connection.createCollection('foo').then(() => {}); mongoose.connection.createCollection('foo', {wtimeout: 5}).then(() => {}); mongoose.connection.createCollection('foo', {wtimeout: 5}, (err: Error, coll): void => {coll.collectionName}).then(() => {}); + +const db = mongoose.connection; +const User = mongoose.model('User', new mongoose.Schema({ name: String })); + +let session: mongoose.ClientSession; +mongoose.connection.createCollection('users'). + then(() => db.startSession()). + then(_session => { + session = _session; + session.startTransaction(); + User.findOne({ name: 'foo' }).session(session); + session.commitTransaction(); + return User.create({ name: 'foo' }); + }); + +const Event = db.model('Event', new mongoose.Schema({ createdAt: Date }), 'Event'); + +db.createCollection('users'). + then(() => db.startSession()). + then(_session => { + session = _session; + return User.create({ name: 'foo' }); + }). + then(() => { + session.startTransaction(); + return User.findOne({ name: 'foo' }).session(session).exec(); + }). + then(() => { + session.commitTransaction(); + return User.findOne({ name: 'bar' }).exec(); + }). + catch(() => { + session.abortTransaction(); + }); + db.createCollection('Event'). + then(() => db.startSession()). + then(_session => { + session = _session; + session.startTransaction(); + return Event.insertMany([ + { createdAt: new Date('2018-06-01') }, + { createdAt: new Date('2018-06-02') }, + { createdAt: new Date('2017-06-01') }, + { createdAt: new Date('2017-05-31') } + ], { session: session }); + }). + then(() => Event.aggregate([ + { + $group: { + _id: { + month: { $month: '$createdAt' }, + year: { $year: '$createdAt' } + }, + count: { $sum: 1 } + } + }, + { $sort: { count: -1, '_id.year': -1, '_id.month': -1 } } + ]).session(session).exec()). + then((res: any) => { + session.commitTransaction(); + }); \ No newline at end of file diff --git a/types/n3/index.d.ts b/types/n3/index.d.ts index dd2d5ca394..a9438616c2 100644 --- a/types/n3/index.d.ts +++ b/types/n3/index.d.ts @@ -156,6 +156,8 @@ export interface N3Writer { addQuad(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term | RDF.Term[], graph?: RDF.Term, done?: () => void): void; addQuad(quad: RDF.Quad): void; addQuads(quads: RDF.Quad[]): void; + addPrefix(prefix: string, iri: string, done?: () => void): void; + addPrefixes(prefixes: Prefixes, done?: () => void): void; end(err?: ErrorCallback, result?: string): void; blank(predicate: RDF.Term, object: RDF.Term): RDF.Term; blank(triple: BlankTriple | RDF.Quad | BlankTriple[] | RDF.Quad[]): RDF.Term; diff --git a/types/n3/n3-tests.ts b/types/n3/n3-tests.ts index 367b602c8a..d24960a112 100644 --- a/types/n3/n3-tests.ts +++ b/types/n3/n3-tests.ts @@ -3,6 +3,28 @@ import * as RDF from "rdf-js"; import * as fs from "fs"; import * as stream from "stream"; +function test_add_prefix() { + const writer: N3.N3Writer = new N3.Writer(); + + writer.addPrefix('xsd', 'http://www.w3.org/2001/XMLSchema#'); + writer.end((error, result) => { + console.log(result); + }); +} + +function test_add_prefixes() { + const writer: N3.N3Writer = new N3.Writer(); + + writer.addPrefixes({ + freebase: N3.DataFactory.namedNode("http://rdf.freebase.com/ns/"), + xsd: N3.DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#") + }); + + writer.end((error, result) => { + console.log(result); + }); +} + function test_serialize() { const writer: N3.N3Writer = new N3.Writer( { diff --git a/types/nano/index.d.ts b/types/nano/index.d.ts deleted file mode 100644 index 3e3faeb3cb..0000000000 --- a/types/nano/index.d.ts +++ /dev/null @@ -1,1142 +0,0 @@ -// Type definitions for nano 6.4 -// Project: https://github.com/apache/couchdb-nano -// Definitions by: Tim Jacobi -// Kovács Vince -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -/// - -import { EventEmitter } from "events"; -import { CoreOptions, Request } from "request"; - -declare function nano( - config: nano.Configuration | string -): nano.ServerScope | nano.DocumentScope; - -declare namespace nano { - interface Configuration { - url: string; - cookie?: string; - requestDefaults?: CoreOptions; - log?(id: string, args: any): void; - parseUrl?: boolean; - request?(params: any): void; - } - - type Callback = (error: any, response: R, headers?: any) => void; - - interface ServerScope { - readonly config: ServerConfig; - db: DatabaseScope; - use(db: string): DocumentScope; - scope(db: string): DocumentScope; - request: RequestFunction; - relax: RequestFunction; - dinosaur: RequestFunction; - // http://docs.couchdb.org/en/latest/api/server/authn.html#cookie-authentication - auth(username: string, userpass: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/server/authn.html#get--_session - session(callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates - updates(callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates - updates(params: UpdatesParams, callback?: Callback): Request; - followUpdates(callback?: Callback): EventEmitter; - followUpdates(params: any, callback?: Callback): EventEmitter; - uuids(num: number, callback: Callback): Request; - } - - interface DatabaseScope { - // http://docs.couchdb.org/en/latest/api/database/common.html#put--db - create(name: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/common.html#get--db - get(name: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/common.html#delete--db - destroy(name: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/server/common.html#get--_all_dbs - list(callback?: Callback): Request; - use(db: string): DocumentScope; - compact(name: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/compact.html#post--db-_compact - compact(name: string, designname: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate - replicate( - source: string | DocumentScope, - target: string | DocumentScope, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate - replicate( - source: string | DocumentScope, - target: string | DocumentScope, - options: DatabaseReplicateOptions, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes - changes(name: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/compact.html#post--db-_compact - changes(name: string, params: DatabaseChangesParams, callback?: Callback): Request; - follow(source: string, callback?: Callback): EventEmitter; - follow(source: string, params: DatabaseScopeFollowUpdatesParams, callback?: Callback): EventEmitter; - followUpdates(params?: any, callback?: Callback): EventEmitter; - // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates - updates(callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates - updates(params: UpdatesParams, callback?: Callback): Request; - } - - interface DocumentScope { - readonly config: ServerConfig; - // http://docs.couchdb.org/en/latest/api/database/common.html#get--db - info(callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate - replicate( - target: string | DocumentScope, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate - replicate( - target: string | DocumentScope, - options: any, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/database/compact.html#post--db-_compact - compact(callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes - changes(callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes - changes(params: DatabaseChangesParams, callback?: Callback): Request; - follow(callback?: Callback): EventEmitter; - follow(params: DocumentScopeFollowUpdatesParams, callback?: Callback): EventEmitter; - // http://docs.couchdb.org/en/latest/api/server/authn.html#cookie-authentication - auth(username: string, userpass: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/server/authn.html#get--_session - session(callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/common.html#post--db - // http://docs.couchdb.org/en/latest/api/document/common.html#put--db-docid - insert(document: ViewDocument | D & MaybeDocument, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/common.html#post--db - // http://docs.couchdb.org/en/latest/api/document/common.html#put--db-docid - insert( - document: ViewDocument | D & MaybeDocument, - params: DocumentInsertParams | string | null, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/document/common.html#get--db-docid - get(docname: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/document/common.html#get--db-docid - get(docname: string, params?: DocumentGetParams, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/document/common.html#head--db-docid - head(docname: string, callback: Callback): Request; - // http://docs.couchdb.org/en/latest/api/document/common.html#copy--db-docid - copy(src_document: string, dst_document: string, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/document/common.html#copy--db-docid - copy( - src_document: string, - dst_document: string, - options: DocumentCopyOptions, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/document/common.html#delete--db-docid - destroy(docname: string, rev: string, callback?: Callback): Request; - bulk(docs: BulkModifyDocsWrapper, callback?: Callback): Request; - bulk(docs: BulkModifyDocsWrapper, params: any, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#get--db-_all_docs - list(callback?: Callback>): Request; - // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#get--db-_all_docs - list(params: DocumentListParams, callback?: Callback>): Request; - // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs - fetch(docnames: BulkFetchDocsWrapper, callback?: Callback>): Request; - // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs - fetch( - docnames: BulkFetchDocsWrapper, - params: DocumentFetchParams, - callback?: Callback> - ): Request; - // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs - fetchRevs(docnames: BulkFetchDocsWrapper, callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs - fetchRevs( - docnames: BulkFetchDocsWrapper, - params: DocumentFetchParams, - callback?: Callback - ): Request; - multipart: Multipart; - attachment: Attachment; - // http://docs.couchdb.org/en/latest/api/ddoc/render.html#get--db-_design-ddoc-_show-func - show( - designname: string, - showname: string, - doc_id: string, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/ddoc/render.html#get--db-_design-ddoc-_show-func - show( - designname: string, - showname: string, - doc_id: string, - params: any, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/ddoc/render.html#put--db-_design-ddoc-_update-func-docid - atomic( - designname: string, - updatename: string, - docname: string, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/ddoc/render.html#put--db-_design-ddoc-_update-func-docid - atomic( - designname: string, - updatename: string, - docname: string, - body: any, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/ddoc/render.html#put--db-_design-ddoc-_update-func-docid - updateWithHandler( - designname: string, - updatename: string, - docname: string, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/ddoc/render.html#put--db-_design-ddoc-_update-func-docid - updateWithHandler( - designname: string, - updatename: string, - docname: string, - body: any, - callback?: Callback - ): Request; - search( - designname: string, - searchname: string, - callback?: Callback - ): Request; - search( - designname: string, - searchname: string, - params: any, - callback?: Callback - ): Request; - spatial( - ddoc: string, - viewname: string, - callback?: Callback - ): Request; - spatial( - ddoc: string, - viewname: string, - params: any, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/ddoc/views.html#get--db-_design-ddoc-_view-view - // http://docs.couchdb.org/en/latest/api/ddoc/views.html#post--db-_design-ddoc-_view-view - view( - designname: string, - viewname: string, - callback?: Callback> - ): Request; - // http://docs.couchdb.org/en/latest/api/ddoc/views.html#get--db-_design-ddoc-_view-view - // http://docs.couchdb.org/en/latest/api/ddoc/views.html#post--db-_design-ddoc-_view-view - view( - designname: string, - viewname: string, - params: DocumentViewParams, - callback?: Callback> - ): Request; - // http://docs.couchdb.org/en/latest/api/ddoc/render.html#db-design-design-doc-list-list-name-view-name - viewWithList( - designname: string, - viewname: string, - listname: string, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/ddoc/render.html#db-design-design-doc-list-list-name-view-name - viewWithList( - designname: string, - viewname: string, - listname: string, - params: DocumentViewParams, - callback?: Callback - ): Request; - // http://docs.couchdb.org/en/latest/api/database/find.html#db-find - find(query: MangoQuery, callback?: Callback>): Request; - server: ServerScope; - } - - interface AttachmentData { - name: string; - data: any; - content_type: any; - } - - interface Multipart { - // http://docs.couchdb.org/en/latest/api/document/common.html#creating-multiple-attachments - insert(doc: D, attachments: AttachmentData[], callback?: Callback): Request; - // http://docs.couchdb.org/en/latest/api/document/common.html#creating-multiple-attachments - insert(doc: D, attachments: AttachmentData[], params: any, callback?: Callback): Request; - get(docname: string, callback?: Callback): Request; - get(docname: string, params: any, callback?: Callback): Request; - } - - interface Attachment { - insert(docname: string, attname: string, att: null, contenttype: string, params?: any): NodeJS.WritableStream; - insert( - docname: string, - attname: string, - att: any, - contenttype: string, - callback?: Callback - ): Request; - insert( - docname: string, - attname: string, - att: any, - contenttype: string, - params: any, - callback?: Callback - ): Request; - get(docname: string, attname: string): NodeJS.ReadableStream; - get(docname: string, attname: string, callback?: Callback): Request; - get( - docname: string, - attname: string, - params: any, - callback?: Callback - ): Request; - destroy(docname: string, attname: string, callback?: Callback): Request; - destroy( - docname: string, - attname: string, - params: any, - callback?: Callback - ): Request; - } - - interface ServerConfig { - url: string; - db: string; - } - - type RequestFunction = ( - options?: RequestOptions | string, - callback?: Callback - ) => void; - - interface RequestOptions { - db?: string; - method?: string; - path?: string; - doc?: string; - att?: string; - qs?: any; - content_type?: string; - headers?: any; - body?: any; - encoding?: string; - multipart?: any[]; - } - - // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates - interface UpdatesParams { - feed: "longpoll" | "continuous" | "eventsource"; - timeout: number; - heartbeat: boolean; - since: string; - } - - interface DocumentScopeFollowUpdatesParams { - include_docs?: boolean; - since?: string; - heartbeat?: number; - feed?: "continuous"; - filter?: string | FollowUpdatesParamsFilterFunction; - query_params?: any; - headers?: any; - inactivity_ms?: number; - max_retry_seconds?: number; - initial_retry_delay?: number; - response_grace_time?: number; - } - - interface DatabaseScopeFollowUpdatesParams - extends DocumentScopeFollowUpdatesParams { - db: string; - } - - type FollowUpdatesParamsFilterFunction = (doc: any, req: any) => boolean; - - interface BulkModifyDocsWrapper { - docs: any[]; - } - - interface BulkFetchDocsWrapper { - keys: string[]; - } - - // ------------------------------------- - // Document - // ------------------------------------- - - interface MaybeIdentifiedDocument { - _id?: string; - } - - interface IdentifiedDocument { - _id: string; - } - - interface MaybeRevisionedDocument { - _rev?: string; - } - - interface RevisionedDocument { - _rev: string; - } - - interface MaybeDocument extends MaybeIdentifiedDocument, MaybeRevisionedDocument { - } - - interface Document extends IdentifiedDocument, RevisionedDocument { - } - - // ------------------------------------- - // View - // ------------------------------------- - - interface View { - map?(doc: D & Document): void; - reduce?(doc: D & Document): void; - } - - interface ViewDocument extends IdentifiedDocument { - views: { - [name: string]: View - }; - } - - // ------------------------------------- - // Database scope request and response - // ------------------------------------- - - // http://docs.couchdb.org/en/latest/api/database/common.html#put--db - interface DatabaseCreateResponse { - // Operation status. Available in case of success - ok?: boolean; - - // Error type. Available if response code is 4xx - error?: string; - - // Error description. Available if response code is 4xx - reason?: string; - } - - // http://docs.couchdb.org/en/latest/api/database/common.html#get--db - interface DatabaseGetResponse { - // Set to true if the database compaction routine is operating on this database. - compact_running: boolean; - - // The name of the database. - db_name: string; - - // The version of the physical format used for the data when it is stored on disk. - disk_format_version: number; - - // The number of bytes of live data inside the database file. - data_size: number; - - // The length of the database file on disk. Views indexes are not included in the calculation. - disk_size: number; - - // A count of the documents in the specified database. - doc_count: number; - - // Number of deleted documents - doc_del_count: number; - - // Timestamp of when the database was opened, expressed in microseconds since the epoch. - instance_start_time: string; - - // The number of purge operations on the database. - purge_seq: number; - - sizes: { - // The size of live data inside the database, in bytes. - active: number; - - // The uncompressed size of database contents in bytes. - external: number; - - // The size of the database file on disk in bytes. Views indexes - file: number; - }; - - // The current number of updates to the database. - update_seq: number; - } - - // http://docs.couchdb.org/en/latest/api/database/common.html#delete--db - // http://docs.couchdb.org/en/latest/api/database/compact.html#post--db-_compact - interface OkResponse { - // Operation status - ok: boolean; - } - - // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate - interface DatabaseReplicateOptions { - // Cancels the replication - cancel?: boolean; - - // Configure the replication to be continuous - continuous?: boolean; - - // Creates the target database. Required administrator’s privileges on target server. - create_target?: boolean; - - // Array of document IDs to be synchronized - doc_ids?: string[]; - - // The name of a filter function. - filter ?: string; - - // Address of a proxy server through which replication should occur (protocol can be “http” or “socks5”) - proxy ?: string; - - // Source database name or URL - source?: string; - - // Target database name or URL - target?: string; - } - - // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate - interface DatabaseReplicationHistoryItem { - // Number of document write failures - doc_write_failures: number; - - // Number of documents read - docs_read: number; - - // Number of documents written to target - docs_written: number; - - // Last sequence number in changes stream - end_last_seq: number; - - // Date/Time replication operation completed in RFC 2822 format - end_time: string; - - // Number of missing documents checked - missing_checked: number; - - // Number of missing documents found - missing_found: number; - - // Last recorded sequence number - recorded_seq: number; - - // Session ID for this replication operation - session_id: string; - - // First sequence number in changes stream - start_last_seq: number; - - // Date/Time replication operation started in RFC 2822 format - start_time: string; - } - - // http://docs.couchdb.org/en/latest/api/server/common.html#post--_replicate - interface DatabaseReplicateResponse { - // Replication history - history: DatabaseReplicationHistoryItem[]; - - // Replication status - ok: boolean; - - // Replication protocol version - replication_id_version: number; - - // Unique session ID - session_id: string; - - // Last sequence number read from source database - source_last_seq: number; - } - - // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes - interface DatabaseChangesParams { - // List of document IDs to filter the changes feed as valid JSON array. Used with _doc_ids filter. Since length of - // URL is limited, it is better to use POST /{db}/_changes instead. - doc_ids?: string[]; - - // Includes conflicts information in response. Ignored if include_docs isn’t true. Default is false. - conflicts?: boolean; - - // Return the change results in descending sequence order (most recent change first). Default is false. - descending?: boolean; - - // - normal Specifies Normal Polling Mode. All past changes are returned immediately. Default. - // - longpoll Specifies Long Polling Mode. Waits until at least one change has occurred, sends the change, then - // closes the connection. Most commonly used in conjunction with since=now, to wait for the next change. - // - continuous Sets Continuous Mode. Sends a line of JSON per event. Keeps the socket open until timeout. - // - eventsource Sets Event Source Mode. Works the same as Continuous Mode, but sends the events in EventSource - // format. - feed?: "normal" | "longpoll" | "continuous" | "eventsource"; - - // Reference to a filter function from a design document that will filter whole stream emitting only filtered - // events. See the section Change Notifications in the book CouchDB The Definitive Guide for more information. - filter?: string; - - // Period in milliseconds after which an empty line is sent in the results. Only applicable for longpoll, - // continuous, and eventsource feeds. Overrides any timeout to keep the feed alive indefinitely. Default is 60000. - // May be true to use default value. - heartbeat?: number; - - // Include the associated document with each result. If there are conflicts, only the winning revision is returned. - // Default is false. - include_docs?: boolean; - - // Include the Base64-encoded content of attachments in the documents that are included if include_docs is true. - // Ignored if include_docs isn’t true. Default is false. - attachments?: boolean; - - // Include encoding information in attachment stubs if include_docs is true and the particular attachment is - // compressed. Ignored if include_docs isn’t true. Default is false. - att_encoding_info?: boolean; - - // Limit number of result rows to the specified value (note that using 0 here has the same effect as 1). - limit?: number; - - // Start the results from the change immediately after the given update sequence. Can be valid update sequence or - // now value. Default is 0. - since?: number; - - // Specifies how many revisions are returned in the changes array. The default, main_only, will only return the - // current “winning” revision; all_docs will return all leaf revisions (including conflicts and deleted former - // conflicts). - style?: string; - - // Maximum period in milliseconds to wait for a change before the response is sent, even if there are no results. - // Only applicable for longpoll or continuous feeds. Default value is specified by httpd/changes_timeout - // configuration option. Note that 60000 value is also the default maximum timeout to prevent undetected dead - // connections. - timeout?: number; - - // Allows to use view functions as filters. Documents counted as “passed” for view filter in case if map function - // emits at least one record for them. See _view for more info. - view?: string; - } - - // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes - interface DatabaseChangesResultItem { - // List of document’s leaves with single field rev. - changes: Array<{ rev: string }>; - - // Document ID. - id: string; - - // Update sequence. - seq: any; - - // true if the document is deleted. - deleted: boolean; - } - - // http://docs.couchdb.org/en/latest/api/database/changes.html#get--db-_changes - interface DatabaseChangesResponse { - // Last change update sequence - last_seq: any; - - // Count of remaining items in the feed - pending: number; - - // Changes made to a database - results: DatabaseChangesResultItem[]; - } - - // http://docs.couchdb.org/en/latest/api/server/authn.html#cookie-authentication - interface DatabaseAuthResponse { - // Operation status - ok: boolean; - - // Username - name: string; - - // List of user roles - roles: string[]; - } - - // http://docs.couchdb.org/en/latest/api/server/authn.html#get--_session - interface DatabaseSessionResponse { - // Operation status - ok: boolean; - - // User context for the current user - userCtx: any; - - // Server authentication configuration - info: any; - } - - // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates - interface DatabaseUpdatesResultItem { - // Database name. - db_name: string; - - // A database event is one of created, updated, deleted. - type: string; - - // Update sequence of the event. - seq: any; - } - - // http://docs.couchdb.org/en/latest/api/server/common.html#get--_db_updates - interface DatabaseUpdatesResponse { - // An array of database events. For longpoll and continuous modes, the entire response is the contents of the - // results array. - results: DatabaseUpdatesResultItem[]; - - // The last sequence ID reported. - last_seq: string; - } - - // ------------------------------------- - // Document scope request and response - // ------------------------------------- - - interface DocumentResponseRowMeta { - id: string; - key: string; - value: { - rev: string; - }; - } - - interface DocumentResponseRow extends DocumentResponseRowMeta { - doc?: D & Document; - } - - // http://docs.couchdb.org/en/latest/api/database/common.html#post--db - // http://docs.couchdb.org/en/latest/api/document/common.html#put--db-docid - interface DocumentInsertParams { - // Document’s revision if updating an existing document. Alternative to If-Match header or document key. - rev?: string; - - // Stores document in batch mode. - batch?: "ok"; - - // Prevents insertion of a conflicting document. Possible values: true (default) and false. If false, a - // well-formed _rev must be included in the document. new_edits=false is used by the replicator to insert - // documents into the target database even if that leads to the creation of conflicts. - new_edits?: boolean; - } - - // http://docs.couchdb.org/en/latest/api/database/common.html#post--db - // http://docs.couchdb.org/en/latest/api/document/common.html#put--db-docid - interface DocumentInsertResponse { - // Document ID - id: string; - - // Operation status - ok: boolean; - - // Revision MVCC token - rev: string; - } - - // http://docs.couchdb.org/en/latest/api/document/common.html#delete--db-docid - interface DocumentDestroyResponse { - // Document ID - id: string; - - // Operation status - ok: boolean; - - // Revision MVCC token - rev: string; - } - - // http://docs.couchdb.org/en/latest/api/document/common.html#get--db-docid - interface DocumentGetParams { - // Includes attachments bodies in response. Default is false. - attachments?: boolean; - - // Includes encoding information in attachment stubs if the particular attachment is compressed. Default is - // false. - att_encoding_info?: boolean; - - // Includes attachments only since specified revisions. Doesn’t includes attachments for specified revisions. - atts_since?: any[]; - - // Includes information about conflicts in document. Default is false. - conflicts?: boolean; - - // Includes information about deleted conflicted revisions. Default is false. - deleted_conflicts?: boolean; - - // Forces retrieving latest “leaf” revision, no matter what rev was requested. Default is false. - latest?: boolean; - - // Includes last update sequence for the document. Default is false. - local_seq?: boolean; - - // Acts same as specifying all conflicts, deleted_conflicts and revs_info query parameters. Default is false. - meta?: boolean; - - // Retrieves documents of specified leaf revisions. Additionally, it accepts value as all to return all leaf - // revisions. - open_revs?: any[]; - - // Retrieves document of specified revision. - rev?: string; - - // Includes list of all known document revisions. - revs?: boolean; - - // Includes detailed information for all known document revisions. Default is false. - revs_info?: boolean; - } - - // http://docs.couchdb.org/en/latest/api/document/common.html#get--db-docid - interface DocumentGetResponse { - // Document ID. - _id: string; - - // Revision MVCC token. - _rev: string; - - // Deletion flag. Available if document was removed. - _deleted?: boolean; - - // Attachment’s stubs. Available if document has any attachments. - _attachments?: any; - - // List of conflicted revisions. Available if requested with conflicts=true query parameter. - _conflicts?: any[]; - - // List of deleted conflicted revisions. Available if requested with deleted_conflicts=true query parameter. - _deleted_conflicts?: any[]; - - // Document’s update sequence in current database. Available if requested with local_seq=true query parameter. - _local_seq?: string; - - // List of objects with information about local revisions and their status. Available if requested with - // open_revs query parameter. - _revs_info?: any[]; - - // List of local revision tokens without. Available if requested with revs=true query parameter. - _revisions?: any; - } - - interface DocumentCopyOptions { - overwrite?: boolean; - } - - // http://docs.couchdb.org/en/latest/api/document/common.html#copy--db-docid - interface DocumentCopyResponse { - // Document ID - id: string; - - // Operation status - ok: boolean; - - // Revision MVCC token - rev: string; - } - - // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#get--db-_all_docs - interface DocumentListParams { - // Includes conflicts information in response. Ignored if include_docs isn’t true. Default is false. - conflicts?: boolean; - - // Return the documents in descending by key order. Default is false. - descending?: boolean; - - // Stop returning records when the specified key is reached. - endkey?: string; - - // Stop returning records when the specified key is reached. end_key is an alias for endkey - end_key?: string; - - // Stop returning records when the specified document ID is reached. - end_key_doc_id?: string; - - // Include the full content of the documents in the return. Default is false. - include_docs?: boolean; - - // Specifies whether the specified end key should be included in the result. Default is true. - inclusive_end?: boolean; - - // Return only documents that match the specified key. - key?: string; - - // Return only documents that match the specified keys. - keys?: string; // This can be string[] too ??? - - // Limit the number of the returned documents to the specified number. - limit?: number; - - // Skip this number of records before starting to return the results. Default is 0. - skip?: number; - - // Allow the results from a stale view to be used, without triggering a rebuild of all views within the - // encompassing design doc. Supported values: ok and update_after. - stale?: string; - - // Return records starting with the specified key. - startkey?: string; - - // Return records starting with the specified key. start_key is an alias for startkey - start_key?: string; - - // Return records starting with the specified document ID. - start_key_doc_id?: string; - - // Response includes an update_seq value indicating which sequence id of the underlying database the view - // reflects. Default is false. - update_seq?: boolean; - } - - // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#get--db-_all_docs - interface DocumentListResponse { - // Offset where the document list started. - offset: number; - - // Array of view row objects. By default the information returned contains only the document ID and revision. - rows: Array>; - - // Number of documents in the database/view. Note that this is not the number of rows returned in the actual - // query. - total_rows: number; - - // Current update sequence for the database. - update_seq?: number; - } - - interface DocumentFetchParams { - conflicts?: boolean; - descending?: boolean; - end_key?: string; - end_key_doc_id?: string; - inclusive_end?: boolean; - key?: string; - keys?: string; // This can be string[] too ??? - limit?: number; - skip?: number; - stale?: string; - start_key?: string; - start_key_doc_id?: string; - update_seq?: boolean; - } - - interface DocumentFetchResponse { - offset: number; - rows: Array>; - total_rows: number; - update_seq?: number; - } - - interface DocumentFetchRevsResponse { - offset: number; - rows: DocumentResponseRowMeta[]; - total_rows: number; - update_seq?: number; - } - - // http://docs.couchdb.org/en/latest/api/ddoc/views.html#get--db-_design-ddoc-_view-view - interface DocumentViewParams { - // Includes conflicts information in response. Ignored if include_docs isn’t true. Default is false. - conflicts?: boolean; - - // Return the documents in descending by key order. Default is false. - descending?: boolean; - - // Stop returning records when the specified key is reached. - endkey?: any; - - // Alias for endkey param. - end_key?: any; - - // Stop returning records when the specified document ID is reached. Requires endkey to be specified for this - // to have any effect. - endkey_docid?: string; - - // Alias for endkey_docid param. - end_key_doc_id?: string; - - // Group the results using the reduce function to a group or single row. Default is false. - group?: boolean; - - // Specify the group level to be used. - group_level?: number; - - // Include the associated document with each row. Default is false. - include_docs?: boolean; - - // Include the Base64-encoded content of attachments in the documents that are included if include_docs is - // true. Ignored if include_docs isn’t true. Default is false. - attachments?: boolean; - - // Include encoding information in attachment stubs if include_docs is true and the particular attachment is - // compressed. Ignored if include_docs isn’t true. Default is false. - att_encoding_info?: boolean; - - // Specifies whether the specified end key should be included in the result. Default is true. - inclusive_end?: boolean; - - // Return only documents that match the specified key. - key?: any; - - // Return only documents where the key matches one of the keys specified in the array. - keys?: any[]; - - // Limit the number of the returned documents to the specified number. - limit?: number; - - // Use the reduction function. Default is true. - reduce?: boolean; - - // Skip this number of records before starting to return the results. Default is 0. - skip?: number; - - // Sort returned rows. Setting this to false offers a performance boost. The total_rows and offset fields are - // not available when this is set to false. Default is true. - sorted?: boolean; - - // Whether or not the view results should be returned from a stable set of shards. Default is false. - stable?: boolean; - // Allow the results from a stale view to be used. Supported values: ok, update_after and false. ok is - // equivalent to stable=true&update=false. update_after is equivalent to stable=true&update=lazy. false is - // equivalent to stable=false&update=true. - stale?: string; - - // Return records starting with the specified key. - startkey?: any; - - // Alias for startkey param - start_key?: any; - - // Return records starting with the specified document ID. Requires startkey to be specified for this to have - // any effect. - startkey_docid?: string; - - // Alias for startkey_docid param - start_key_doc_id?: string; - - // Whether or not the view in question should be updated prior to responding to the user. Supported values: - // true, false, lazy. Default is true. - update?: string; - - // Response includes an update_seq value indicating which sequence id of the database the view reflects. - // Default is false. - update_seq?: boolean; - } - - // http://docs.couchdb.org/en/latest/api/ddoc/views.html#get--db-_design-ddoc-_view-view - interface DocumentViewResponse { - // Offset where the document list started. - offset: number; - - // Array of view row objects. By default the information returned contains only the document ID and revision. - rows: Array<{ - id: string; - key: string; - value: V; - }>; - - // Number of documents in the database/view. - total_rows: number; - - // Current update sequence for the database - update_seq: any; - } - - type MangoValue = number | string | Date | boolean; - - // http://docs.couchdb.org/en/latest/api/database/find.html#selector-syntax - interface MangoSelector { - [key: string]: MangoSelector | MangoValue | MangoValue[]; - } - - // http://docs.couchdb.org/en/latest/api/database/find.html#sort-syntax - type SortOrder = string | string[] | { [key: string]: 'asc' | 'desc' }; - - interface MangoQuery { - // JSON object describing criteria used to select documents. - selector: MangoSelector; - - // Maximum number of results returned. Default is 25. - limit?: number; - - // Skip the first 'n' results, where 'n' is the value specified. - skip?: number; - - // JSON array following sort syntax. - sort?: SortOrder[]; - - // JSON array specifying which fields of each object should be returned. If it is omitted, - // the entire object is returned. - // http://docs.couchdb.org/en/latest/api/database/find.html#filtering-fields - fields?: string[]; - - // Instruct a query to use a specific index. - // Specified either as "" or ["", ""]. - use_index?: string | [string, string]; - - // Read quorum needed for the result. This defaults to 1. - r?: number; - - // A string that enables you to specify which page of results you require. Used for paging through result sets. - bookmark?: string; - - // Whether to update the index prior to returning the result. Default is true. - update?: boolean; - - // Whether or not the view results should be returned from a “stable” set of shards. - stable?: boolean; - - // Combination of update = false and stable = true options.Possible options: "ok", false (default). - stale?: 'ok' | false; - - // Include execution statistics in the query response. Optional, default: false. - execution_stats?: boolean; - } - - interface MangoResponse { - // Array of documents matching the search. In each matching document, the fields specified in - // the fields part of the request body are listed, along with their values. - docs: D[]; - - // A string that enables you to specify which page of results you require. Used for paging through result sets. - bookmark?: string; - - // Execution warnings - warning?: string; - - // Basic execution statistics for a specific request. - execution_stats?: MangoExecutionStats; - } - - // http://docs.couchdb.org/en/latest/api/database/find.html#execution-statistics - interface MangoExecutionStats { - // Number of index keys examined. Currently always 0. - total_keys_examined: number; - - // Number of documents fetched from the database / index, equivalent to using include_docs = true in a view. - total_docs_examined: number; - - // Number of documents fetched from the database using an out - of - band document fetch. - // This is only non - zero when read quorum > 1 is specified in the query parameters. - total_quorum_docs_examined: number; - - // Number of results returned from the query. - results_returned: number; - - // Total execution time in milliseconds as measured by the database. - execution_time_ms: number; - } -} - -export = nano; diff --git a/types/nano/nano-tests.ts b/types/nano/nano-tests.ts deleted file mode 100644 index 0556f2b8fe..0000000000 --- a/types/nano/nano-tests.ts +++ /dev/null @@ -1,191 +0,0 @@ -import * as fs from "fs"; -import nano = require("nano"); - -/* - * Instantiate with configuration object - */ -const config: nano.Configuration = { - url: "http://localhost:5984/foo", - cookie: "someAuthSession", - requestDefaults: { proxy: "http://someproxy" } -}; - -const cfgInstance = nano(config); - -/* - * Server Scope - */ -const instance: nano.ServerScope = nano( - "http://localhost:5984/emails" -); - -instance.dinosaur("", (err, response) => {}); -const url = instance.config.url; - -instance.relax( - { - method: "POST", - path: "_users", - body: { - _id: "org.couchdb.user:", - type: "user", - name: "ss", - roles: ["admin"], - password: "rf" - } - }, - (err: any) => {} -); -instance.session((error, session) => {}); -instance.request( - { - db: "shared_headers", - doc: "new", - headers: { "If-None-Match": JSON.stringify({}) } - }, - (error, helloWorld, rh) => {} -); -instance.relax( - { db: "document_list", doc: "_all_docs", method: "GET", qs: { limit: 1 } }, - (error, docs) => {} -); -instance.auth("", "", (err: any, _: any, headers: any) => {}); -instance.uuids(3, (error, data) => {}); - -/* - * Database Scope - */ -const db: nano.DatabaseScope = instance.db; - -db.create("az09_$()+-/", err => {}); -db.get("database_get", (err, response) => {}); -db.destroy("_users", () => {}); -db.list((error, list) => {}); -db.replicate(instance.use("a"), instance.use("b"), (error: any) => {}); -db.replicate("a", "b", (error: any) => {}); - -/* - * Document Scope - */ -interface SomeDocument { - name: string; -} - -const mydb: nano.DocumentScope = instance.use("mydb"); - -mydb.insert({ name: "baz" }, null, (err, response) => {}); -mydb.insert({ name: "baz" }, "foobar", (error, foo) => {}); -mydb.insert({ name: "baz" }, { new_edits: true }, (error, foo) => {}); -mydb.get("foobaz", { revs_info: true }, (error, foobaz) => {}); -mydb.head("foobaz", (error, body, headers) => {}); -mydb.copy( - "foo_src", - "foo_dest", - { overwrite: true }, - (error, response, headers) => {} -); -mydb.destroy("x", "x", (err, response) => {}); -mydb.bulk( - { docs: [{ key: "baz", name: "bazzel" }, { key: "bar", name: "barry" }] }, - (error: any, response: any) => {} -); -mydb.list((error: any, docs: any) => {}); -mydb.fetch({ keys: ["foobar"] }, (error: any, docs: any) => {}); -mydb.fetchRevs({ keys: ["foobar"] }, (error: any, docs: any) => {}); -mydb.changes({ since: 0 }, (err, response) => {}); -mydb.compact(error => {}); -const feed = mydb.follow({ since: "0" }); -feed.on("change", (change: any) => {}); -mydb.atomic("update", "addbaz", "baz", (error: any, response: any) => {}); -mydb.viewWithList( - "people", - "by_name_and_city", - "my_list", - { key: ["Derek", "San Francisco"] }, - (error, list) => {} -); -mydb.view( - "alice", - "by_id", - { keys: ["foobar", "barfoo"], include_docs: true }, - (err, view) => {} -); -mydb.show( - "people", - "singleDoc", - "p_clemens", - (error: any, doc: any, rh: any) => {} -); -mydb.replicate("database_replica", (error: any) => {}); - -const req = mydb.find({ - selector: { - userId: 1234, - name: 'Paul', - status: { $ne: 'suspended' }, - age: { $gt: 69 }, - building: { - number: { - $in: [101, 203, 205] - } - } - }, - skip: 10, - limit: 1, - use_index: "user_index_doc", - fields: ['name', 'age'], - sort: [{ age: 'desc' }, { name: 'asc' }], - r: 2, - stale: 'ok', - execution_stats: true -}, (resp: nano.MangoResponse, error: any) => { - for (const doc of resp.docs) { - console.log(doc.name); - } - - if (resp.warning) { - console.error(resp.warning); - } - - if (resp.execution_stats) { - console.log(`Execution time: ${resp.execution_stats.execution_time_ms} ms.`); - } -}); - -req.abort(); - -/* - * Attachments - */ -mydb.attachment.insert( - "new", - "att", - "Hello World!", - "text/plain", - (error: any, att: any) => {} -); -const attInsert: NodeJS.WritableStream = mydb.attachment.insert( - "new", - "att", - null, - "text/plain" -); -mydb.attachment.destroy("new", "att", { rev: "123" }, (err, response) => {}); -mydb.attachment.get("new_string", "att", (error: any, helloWorld: any) => {}); -const attGet: NodeJS.ReadableStream = mydb.attachment.get("new_string", "att"); - -/* - * Multipart - */ -const attachment = { name: 'rabbit.png', data: 'some data', content_type: 'image/png' }; - -mydb.multipart.insert({ name: "baz" }, [attachment], "foobaz", (error, foo) => {}); -mydb.multipart.get("foobaz", (error: any, foobaz: any, headers: any) => {}); - -/* - * Piping - */ -const rs = fs.createReadStream(""); -const is = mydb.attachment.insert("nodejs", "logo.png", null, "image/png"); -is.on("end", () => {}); -rs.pipe(is); diff --git a/types/nano/tslint.json b/types/nano/tslint.json deleted file mode 100644 index e6dc9b7f2f..0000000000 --- a/types/nano/tslint.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - // TODO - "no-any-union": false, - "no-unnecessary-generics": false - } -} diff --git a/types/native-toast/index.d.ts b/types/native-toast/index.d.ts new file mode 100644 index 0000000000..1b9e532255 --- /dev/null +++ b/types/native-toast/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for native-toast 2.0 +// Project: https://github.com/egoist/native-toast +// Definitions by: Michael Nahkies +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const toast: { + (options: ToastOptions): Toast, + success: (options: ToastOptions) => Toast, + warning: (options: ToastOptions) => Toast, + info: (options: ToastOptions) => Toast, + error: (options: ToastOptions) => Toast, +}; + +export default toast; + +export interface ToastOptions { + message?: string; + position?: "center" | "west" | "east" | "south" | "south-west" | "south-east" | "north" | "north-west" | "north-east"; + timeout?: number; + el?: HTMLElement; + rounded?: boolean; + type?: "success" | "warning" | "info" | "error"; + debug?: boolean; + edge?: boolean; + icon?: boolean; + closeOnClick?: boolean; + elements?: HTMLElement[]; +} + +export interface Toast { + show(): void; + hide(): void; + destroy(): void; +} diff --git a/types/native-toast/native-toast-tests.ts b/types/native-toast/native-toast-tests.ts new file mode 100644 index 0000000000..73d6890549 --- /dev/null +++ b/types/native-toast/native-toast-tests.ts @@ -0,0 +1,20 @@ +import toast, { Toast, ToastOptions } from "native-toast"; + +let t: Toast; + +t = toast({ + message: "Team created", + position: "north-east", + timeout: 5000, + type: "success", +}); + +t.hide(); +t.show(); + +const o: ToastOptions = { + message: "test", + position: "west" +}; + +toast.success(o); diff --git a/types/native-toast/tsconfig.json b/types/native-toast/tsconfig.json new file mode 100644 index 0000000000..d36ee00fd9 --- /dev/null +++ b/types/native-toast/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "native-toast-tests.ts" + ] +} diff --git a/types/native-toast/tslint.json b/types/native-toast/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/native-toast/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/next/document.d.ts b/types/next/document.d.ts index 0b21fb53c8..e6ba38b6c9 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -57,6 +57,6 @@ export interface NextScriptProps { export class Head extends React.Component {} export class Main extends React.Component {} export class NextScript extends React.Component {} -export default class extends React.Component { +export default class Document extends React.Component { static getInitialProps(ctx: NextDocumentContext): Promise | DocumentProps; } diff --git a/types/node-gcm/index.d.ts b/types/node-gcm/index.d.ts index 61c7ae70dc..c2bca37a37 100644 --- a/types/node-gcm/index.d.ts +++ b/types/node-gcm/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for node-gcm 0.14.0 +// Type definitions for node-gcm 1.0.2 // Project: https://www.npmjs.org/package/node-gcm // Definitions by: Hiroki Horiuchi +// BWYou // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,12 +15,17 @@ export interface INotificationOptions { tag?: string; color?: string; click_action?: string; + body_loc_key?: string; + body_loc_args?: string; + title_loc_args?: string; + title_loc_key?: string; } export interface IMessageOptions { collapseKey?: string; priority?: string; contentAvailable?: boolean; + mutableContent?: boolean; delayWhileIdle?: boolean; timeToLive?: number; restrictedPackageName?: string; @@ -57,6 +63,7 @@ export interface ISenderSendOptions { export interface IRecipient { to?: string, topic?: string, + condition?: string, notificationKey?: string, registrationIds?: string[], registrationTokens?: string[] diff --git a/types/node-localstorage/index.d.ts b/types/node-localstorage/index.d.ts new file mode 100644 index 0000000000..960d40f1da --- /dev/null +++ b/types/node-localstorage/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for node-localstorage 1.3 +// Project: https://github.com/lmaccherone/node-localstorage +// Definitions by: Allen Gammel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { EventEmitter } from 'events'; + +/** + * A drop-in substitute for the browser native localStorage API that runs on node.js. + * Copyright (c) 2012, Lawrence S. Maccherone, Jr. -- https://github.com/lmaccherone/node-localstorage + * (MIT License) + */ +export class LocalStorage extends EventEmitter { + /** + * The number of keys in the local storage. + */ + length: number; + /** + * Clears the local storage + */ + clear(): void; + /** + * Gets the value of the given [key] + * @param key The key whose value you want to retrieve. + */ + getItem(key: string): string | null; + /** + * Retrieves the value of the key at the [index]. + * @param index The index of the key in which you want to return the value of. + */ + key(index: number): string; + /** + * Removes the specified [key] from local storage. + * @param key The key you want to remove. + */ + removeItem(key: string): void; + /** + * Stores a `key` and it's `value` in to the local store. + * @param key Unique identifier for the new local storage item + * @param value The value of the item + */ + setItem(key: string, value: string): void; + /** + * Internal event `storage` is fired on the `removeItem`, `setItem` and `clear` methods, if subscribed. + * @param eventName The only `eventName` that is supported is `storage`. + * @param callback The call back type is of `StorageEvent`. + */ + on(eventName: 'storage', callback: (event: StorageEvent) => void): this; + /** + * Creates a new LocalStorage instance + * @param location The location in which the local storage resides + * @param quota The partitioned size of the local storage + */ + constructor(location: string, quota?: number); +} +export class JSONStorage extends LocalStorage { + /** + * Gets the value of the given `key`. This method performs a `JSON.parse` on the `value` before returning it. + * @param key The key whose value you want to retrieve. + * @returns `Array of Objects` or an `Object`. This `getItem` method performs a `JSON.parse` on the `value` before returning it. + */ + getItem(key: string): any; + /** + * Stores a `key` and it's `value` in to the local store. The given `value` will have `JSON.stringify` performed on it prior to storing. + * @param key Unique identifier for the new local storage item + * @param value The value associated with the `key`. This `setItem` method performs a `JSON.stringify` on the value before storage. The `value` *must* be a valid `JSON` object. + */ + setItem(key: string, value: any): void; + /** + * Creates a new LocalStorage instance + * @param location The location in which the local storage resides + * @param quota The partitioned size of the local storage + */ + constructor(location: string, quota?: number); +} + +/** + * Contains information regarding a `storage` event. + */ +export class StorageEvent { + /** + * Affected `key`. + */ + key: string; + /** + * Previous `value` associated with the `key`. + */ + oldValue: string; + /** + * Current `value` associated with the `key`. + */ + newValue: string; + /** + * The current `process.pid` for the calling process. + */ + url: string; + /** + * The location of the storage area. Defaults to `localStorage`. + */ + storageArea: string; + /** + * Creates an object containing information regarding a `storage` event. + * @param key Affected `key`. + * @param oldValue Previous `value` associated with the `key`. + * @param newValue Current `value` associated with the `key`. + * @param url The current `process.pid` for the calling process. + * @param storageArea The location of the storage area. Defaults to `localStorage`. + */ + constructor(key: string, oldValue: string, newValue: string, url: string, storageArea: string); +} + +/** + * Provides a specific `Error` object for **Quota Exceeded Errors**. + */ +export class QUOTA_EXCEEDED_ERR extends Error { + /** + * Message explaining the error. + */ + message: string; + /** + * Creates a specific `Error` object for **Quota Exceeded Errors**. + * @param message Message explaining the error. + */ + constructor(message: string); +} diff --git a/types/node-localstorage/node-localstorage-tests.ts b/types/node-localstorage/node-localstorage-tests.ts new file mode 100644 index 0000000000..25c27e622c --- /dev/null +++ b/types/node-localstorage/node-localstorage-tests.ts @@ -0,0 +1,58 @@ +import { LocalStorage, JSONStorage } from 'node-localstorage'; + +const jsonStore = new JSONStorage('./jsonStore'); +const textStore = new LocalStorage('./textStore'); + +interface Person { + givenName: string; + middleName: string; + familyName: string; +} + +const mjkModel: Person = { + givenName: 'Maynard', + middleName: 'James', + familyName: 'Keenan', +}; + +textStore.clear(); +jsonStore.clear(); + +textStore.on('storage', (event) => { + if (textStore.getItem(event.key) !== event.newValue) { + throw new Error('textStore: An error occurred with the event handler.'); + } +}); + +jsonStore.on('storage', (event) => { + if (jsonStore.getItem(event.key) !== event.newValue) { + throw new Error('jsonStore: An error occurred with the event handler.'); + } +}); + +textStore.setItem('tool', '46&2'); + +if (textStore.getItem('tool') !== '46&2') { + throw new Error('.setItem method is not working!'); +} + +jsonStore.setItem('mjk', mjkModel); + +if (jsonStore.getItem('mjk') === null) { + throw new Error('.getItem failed.'); +} + +const mjkTest: Person = jsonStore.getItem('mjk'); + +if (mjkTest === null || mjkTest.givenName !== mjkModel.givenName || mjkTest.middleName !== mjkModel.middleName || mjkTest.familyName !== mjkModel.familyName) { + throw new Error('.setItem method is not working!'); +} + +const keyCheck = textStore.key(0); + +if (keyCheck && keyCheck !== 'tool') { + throw new Error('.key method has failed.'); +} + +textStore.clear(); +jsonStore.clear(); diff --git a/types/node-localstorage/tsconfig.json b/types/node-localstorage/tsconfig.json new file mode 100644 index 0000000000..9411b285e2 --- /dev/null +++ b/types/node-localstorage/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", + "node-localstorage-tests.ts" + ] +} \ No newline at end of file diff --git a/types/node-localstorage/tslint.json b/types/node-localstorage/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/node-localstorage/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/node-resque/index.d.ts b/types/node-resque/index.d.ts new file mode 100644 index 0000000000..4b09807ee5 --- /dev/null +++ b/types/node-resque/index.d.ts @@ -0,0 +1,131 @@ +// Type definitions for node-resque 5.4 +// Project: http://github.com/taskrabbit/node-resque +// Definitions by: Gordey Doronin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export interface ConnectionOptions { + pkg?: string; + host?: string; + port?: number; + database?: number; + namespace?: string; + looping?: boolean; + options?: any; +} + +export class Connection extends NodeJS.EventEmitter { + constructor(options: ConnectionOptions); + + connect(): Promise; + end(): Promise; +} + +export interface Job { + plugins?: string[]; + pluginOptions?: { [pluginName: string]: any }; + perform: (...args: any[]) => Promise; +} + +export interface JobsHash { + [jobName: string]: Job; +} + +export interface QueueOptions { + connection?: ConnectionOptions; +} + +export class Queue extends NodeJS.EventEmitter { + constructor(options: QueueOptions, jobs?: JobsHash); + + connect(): Promise; + enqueue(queue: string, jobName: string, args: ReadonlyArray): Promise; + enqueueIn(milliseconds: number, queue: string, jobName: string, args: ReadonlyArray): Promise; + end(): Promise; + + on(event: 'error', cb: (error: Error, queue: string) => void): this; + once(event: 'error', cb: (error: Error, queue: string) => void): this; +} + +export interface WorkerOptions { + connection?: ConnectionOptions; + queues: string[]; + name?: string; + timeout?: number; + looping?: boolean; +} + +export type WorkerEvent = 'start' | 'end' | 'cleaning_worker' | 'poll' | 'ping' | 'job' | 'reEnqueue' | 'success' | 'failure' | 'error' | 'pause'; + +export class Worker extends NodeJS.EventEmitter { + constructor(options: WorkerOptions, jobs?: JobsHash); + + connect(): Promise; + start(): Promise; + end(): Promise; + + on(event: 'start' | 'end' | 'pause', cb: () => void): this; + on(event: 'cleaning_worker', cb: (worker: string, pid: string) => void): this; + on(event: 'poll', cb: (queue: string) => void): this; + on(event: 'ping', cb: (time: number) => void): this; + on(event: 'job', cb: (queue: string, job: Job) => void): this; + on(event: 'reEnqueue', cb: (queue: string, job: Job, plugin: string) => void): this; + on(event: 'success', cb: (queue: string, job: Job, result: any) => void): this; + on(event: 'failure', cb: (queue: string, job: Job, failure: any) => void): this; + on(event: 'error', cb: (error: Error, queue: string, job: Job) => void): this; + + once(event: 'start' | 'end' | 'pause', cb: () => void): this; + once(event: 'cleaning_worker', cb: (worker: string, pid: string) => void): this; + once(event: 'poll', cb: (queue: string) => void): this; + once(event: 'ping', cb: (time: number) => void): this; + once(event: 'job', cb: (queue: string, job: Job) => void): this; + once(event: 'reEnqueue', cb: (queue: string, job: Job, plugin: string) => void): this; + once(event: 'success', cb: (queue: string, job: Job, result: any) => void): this; + once(event: 'failure', cb: (queue: string, job: Job, failure: any) => void): this; + once(event: 'error', cb: (error: Error, queue: string, job: Job) => void): this; + + removeAllListeners(event: WorkerEvent): this; +} + +export interface SchedulerOptions { + connection?: ConnectionOptions; + name?: string; + timeout?: number; + stuckWorkerTimeout?: number; + masterLockTimeout?: number; +} + +export type SchedulerEvent = 'start' | 'end' | 'poll' | 'master' | 'cleanStuckWorker' | 'error' | 'workingTimestamp' | 'transferredJob'; + +export class Scheduler extends NodeJS.EventEmitter { + constructor(options: SchedulerOptions, jobs?: JobsHash); + + connect(): Promise; + start(): Promise; + end(): Promise; + + on(event: 'start' | 'end' | 'poll' | 'master', cb: () => void): this; + on(event: 'cleanStuckWorker', cb: (workerName: string, errorPayload: ErrorPayload, delta: number) => void): this; + on(event: 'error', cb: (error: Error, queue: string) => void): this; + on(event: 'workingTimestamp', cb: (timestamp: number) => void): this; + on(event: 'transferredJob', cb: (timestamp: number, job: Job) => void): this; + + once(event: 'start' | 'end' | 'poll' | 'master', cb: () => void): this; + once(event: 'cleanStuckWorker', cb: (workerName: string, errorPayload: ErrorPayload, delta: number) => void): this; + once(event: 'error', cb: (error: Error, queue: string) => void): this; + once(event: 'workingTimestamp', cb: (timestamp: number) => void): this; + once(event: 'transferredJob', cb: (timestamp: number, job: Job) => void): this; + + removeAllListeners(event: SchedulerEvent): this; +} + +export interface ErrorPayload { + worker: string; + queue: string; + payload: any; + exception: string; + error: string; + backtrace: string[]; + failed_at: string; +} diff --git a/types/node-resque/node-resque-tests.ts b/types/node-resque/node-resque-tests.ts new file mode 100644 index 0000000000..4e09b54851 --- /dev/null +++ b/types/node-resque/node-resque-tests.ts @@ -0,0 +1,72 @@ +import { ConnectionOptions, Worker, Queue, Job, JobsHash, Scheduler } from 'node-resque'; + +class AddJob implements Job { + plugins: string[] = ['JobLock']; + + pluginOptions = { + JobLock: {} + }; + + perform(...args: number[]): Promise { + const answer = args[0] + args[1]; + return new Promise((resolve) => { setTimeout(resolve, 1000); }) + .then(() => answer); + } +} + +class SubtractJob implements Job { + perform(...args: number[]): Promise { + const answer = args[0] - args[1]; + return Promise.resolve(answer); + } +} + +const connection: ConnectionOptions = { host: 'localhost', port: 6379 }; +const queues = ['math', 'otherQueue']; +const jobs: JobsHash = { + add: new AddJob(), + subtract: new SubtractJob() +}; + +const worker = new Worker({ connection, queues }, jobs); +const queue = new Queue({ connection }, jobs); +const scheduler = new Scheduler({ connection }); + +// register for worker events +worker.on('start', () => { console.log('worker started'); }); +worker.on('end', () => { console.log('worker ended'); }); +worker.on('cleaning_worker', (worker) => { console.log(`cleaning old worker ${worker}`); }); +worker.on('poll', (queue) => { console.log(`worker polling ${queue}`); }); +worker.on('ping', (time) => { console.log(`worker check in @ ${time}`); }); +worker.on('job', (queue, job) => { console.log(`working job ${queue} ${JSON.stringify(job)}`); }); +worker.on('reEnqueue', (queue, job, plugin) => { console.log(`reEnqueue job (${plugin}) ${queue} ${JSON.stringify(job)}`); }); +worker.on('success', (queue, job, result) => { console.log(`job success ${queue} ${JSON.stringify(job)} >> ${result}`); }); +worker.on('failure', (queue, job, failure) => { console.log(`job failure ${queue} ${JSON.stringify(job)} >> ${failure}`); }); +worker.on('error', (error, queue, job) => { console.log(`error ${queue} ${JSON.stringify(job)} >> ${error}`); }); +worker.on('pause', () => { console.log('worker paused'); }); + +// register for scheduler events +scheduler.on('start', () => { console.log('scheduler started'); }); +scheduler.on('end', () => { console.log('scheduler ended'); }); +scheduler.on('poll', () => { console.log('scheduler polling'); }); +scheduler.on('master', () => { console.log('scheduler became master'); }); +scheduler.on('cleanStuckWorker', (workerName, errorPayload, delta) => { console.log(`failing ${workerName} (stuck for ${delta}s) and failing job ${errorPayload}`); }); +scheduler.on('error', (error) => { console.log(`scheduler error >> ${error}`); }); +scheduler.on('workingTimestamp', (timestamp) => { console.log(`scheduler working timestamp ${timestamp}`); }); +scheduler.on('transferredJob', (timestamp, job) => { console.log(`scheduler enquing job ${timestamp} >> ${JSON.stringify(job)}`); }); + +// register for queue events +queue.on('error', (error) => { console.log(error); }); + +// start worker +worker.connect().then(() => worker.start()); + +// start scheduler +scheduler.connect().then(() => scheduler.start()); + +queue.connect().then(() => { + queue.enqueue('math', 'add', [1, 2]); + queue.enqueue('math', 'add', [1, 2]); + queue.enqueue('math', 'add', [2, 3]); + queue.enqueueIn(3000, 'math', 'subtract', [2, 1]); +}); diff --git a/types/node-resque/tsconfig.json b/types/node-resque/tsconfig.json new file mode 100644 index 0000000000..6cdce9ca44 --- /dev/null +++ b/types/node-resque/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", + "node-resque-tests.ts" + ] +} diff --git a/types/node-resque/tslint.json b/types/node-resque/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/node-resque/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/node-telegram-bot-api/index.d.ts b/types/node-telegram-bot-api/index.d.ts index 934daa3fe3..9d9616b813 100644 --- a/types/node-telegram-bot-api/index.d.ts +++ b/types/node-telegram-bot-api/index.d.ts @@ -371,7 +371,7 @@ declare namespace TelegramBot { mime_type?: string; } - interface Video { + interface Video extends FileBase { width: number; height: number; duration: number; diff --git a/types/nodemailer/lib/addressparser.d.ts b/types/nodemailer/lib/addressparser.d.ts index be42c1deed..a687a21560 100644 --- a/types/nodemailer/lib/addressparser.d.ts +++ b/types/nodemailer/lib/addressparser.d.ts @@ -16,7 +16,6 @@ declare namespace addressparser { * * [{name: 'Name', address: 'address@domain'}] * - * @param str Address field * @return An array of address objects */ declare function addressparser(address: string): addressparser.Address[]; diff --git a/types/nodemailer/lib/mailer/index.d.ts b/types/nodemailer/lib/mailer/index.d.ts index 00cf40839c..ece591e30e 100644 --- a/types/nodemailer/lib/mailer/index.d.ts +++ b/types/nodemailer/lib/mailer/index.d.ts @@ -47,9 +47,9 @@ declare namespace Mail { /** optional content type for the attachment, if not set will be derived from the filename property */ contentType?: string; /** optional transfer encoding for the attachment, if not set it will be derived from the contentType property. Example values: quoted-printable, base64. If it is unset then base64 encoding is used for the attachment. If it is set to false then previous default applies (base64 for most, 7bit for text). */ - contentTransferEncoding?: string; + contentTransferEncoding?: '7bit' | 'base64' | 'quoted-printable' | false; /** optional content disposition type for the attachment, defaults to ‘attachment’ */ - contentDisposition?: string; + contentDisposition?: 'attachment' | 'inline'; /** is an object of additional headers */ headers?: Headers; /** an optional value that overrides entire node content in the mime message. If used then all other options set for this node are ignored. */ diff --git a/types/nodemailer/lib/smtp-connection.d.ts b/types/nodemailer/lib/smtp-connection.d.ts index 1215409b46..61cc227583 100644 --- a/types/nodemailer/lib/smtp-connection.d.ts +++ b/types/nodemailer/lib/smtp-connection.d.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'events'; import * as net from 'net'; -import { Writable } from 'stream'; +import { Readable } from 'stream'; import * as tls from 'tls'; import * as shared from './shared'; @@ -173,17 +173,17 @@ declare class SMTPConnection extends EventEmitter { constructor(options?: SMTPConnection.Options); /** Creates a connection to a SMTP server and sets up connection listener */ - connect(callback: () => void): void; + connect(callback: (err?: SMTPConnection.SMTPError) => void): void; /** Sends QUIT */ quit(): void; /** Closes the connection to the server */ close(): void; /** Authenticate user */ - login(auth: SMTPConnection.AuthenticationCredentials | SMTPConnection.AuthenticationOAuth2 | SMTPConnection.Credentials, callback: (err: SMTPConnection.SMTPError | null) => void): void; + login(auth: SMTPConnection.AuthenticationCredentials | SMTPConnection.AuthenticationOAuth2 | SMTPConnection.Credentials, callback: (err?: SMTPConnection.SMTPError) => void): void; /** Sends a message */ - send(envelope: SMTPConnection.Envelope, message: string | Buffer | Writable, callback: (err: SMTPConnection.SMTPError | null, info: SMTPConnection.SentMessageInfo) => void): void; + send(envelope: SMTPConnection.Envelope, message: string | Buffer | Readable, callback: (err: SMTPConnection.SMTPError | null, info: SMTPConnection.SentMessageInfo) => void): void; /** Resets connection state */ - reset(callback: (err: Error | null) => void): void; + reset(callback: (err?: SMTPConnection.SMTPError) => void): void; addListener(event: 'connect' | 'end', listener: () => void): this; addListener(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this; @@ -191,6 +191,14 @@ declare class SMTPConnection extends EventEmitter { emit(event: 'connect' | 'end'): boolean; emit(event: 'error', error: Error): boolean; + listenerCount(event: 'connect' | 'end' | 'error'): number; + + listeners(event: 'connect' | 'end'): Array<() => void>; + listeners(event: 'error'): Array<(err: SMTPConnection.SMTPError) => void>; + + off(event: 'connect' | 'end', listener: () => void): this; + off(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this; + on(event: 'connect' | 'end', listener: () => void): this; on(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this; @@ -203,8 +211,13 @@ declare class SMTPConnection extends EventEmitter { prependOnceListener(event: 'connect' | 'end', listener: () => void): this; prependOnceListener(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this; - listeners(event: 'connect' | 'end'): Array<() => void>; - listeners(event: 'error'): Array<(err: SMTPConnection.SMTPError) => void>; + rawListeners(event: 'connect' | 'end'): Array<() => void>; + rawListeners(event: 'error'): Array<(err: SMTPConnection.SMTPError) => void>; + + removeAllListener(event: 'connect' | 'end' | 'error'): this; + + removeListener(event: 'connect' | 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this; } export = SMTPConnection; diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index 140b351c6b..18661a8ff6 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -123,7 +123,7 @@ function message_attachments_test() { attachments: [ { // utf-8 string as an attachment filename: 'text1.txt', - content: 'hello world!' + content: 'hello world!', }, { // binary buffer as an attachment filename: 'text2.txt', @@ -138,12 +138,15 @@ function message_attachments_test() { }, { // stream as an attachment filename: 'text4.txt', - content: fs.createReadStream('file.txt') + content: fs.createReadStream('file.txt'), + contentTransferEncoding: 'quoted-printable' }, { // define custom content type for the attachment filename: 'text.bin', content: 'hello world!', - contentType: 'text/plain' + contentType: 'text/plain', + contentTransferEncoding: '7bit', + contentDisposition: 'attachment' }, { // use URL as an attachment filename: 'license.txt', @@ -152,10 +155,13 @@ function message_attachments_test() { { // encoded string as an attachment filename: 'text1.txt', content: 'aGVsbG8gd29ybGQh', - encoding: 'base64' + encoding: 'base64', + contentTransferEncoding: 'base64' }, { // data uri as an attachment - path: 'data:text/plain;base64,aGVsbG8gd29ybGQ=' + path: 'data:text/plain;base64,aGVsbG8gd29ybGQ=', + contentDisposition: 'inline', + contentTransferEncoding: false }, { // use pregenerated MIME node @@ -1053,7 +1059,8 @@ function dkim_specific_header_key_test() { function smtp_connection_test() { const connection = new SMTPConnection(); - connection.connect(() => { + connection.connect((err) => { + if (err) throw err; connection.login({ user: 'user', pass: 'pass' }, (err) => { if (err) throw err; connection.send({ from: 'a@example.com', to: 'b@example.net' }, 'message', (err, info) => { diff --git a/types/numeric/index.d.ts b/types/numeric/index.d.ts new file mode 100644 index 0000000000..d17791d7f6 --- /dev/null +++ b/types/numeric/index.d.ts @@ -0,0 +1,1199 @@ +// Type definitions for numeric 1.2 +// Project: https://github.com/sloisel/numeric +// Definitions by: Sasha Grin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +// Documentation: http://www.numericjs.com/documentation.html + +type NonNullPrimitive = number | string | boolean | undefined; +type Scalar = number; +type Vector = number[]; +type VectorBoolean = boolean[]; +type Matrix = number[][]; +type SparseMatrix = [Vector, Vector, Vector]; +type DeprecatedSparseMatrix = Array>; +type DeprecatedSparseVector = Array; +type CCSComparisonResult = [Vector, Vector, VectorBoolean]; +type ShapeFunction = (i: number, j: number) => boolean; +interface LUPP { + L: SparseMatrix; + U: SparseMatrix; + P: Vector; + Pinv: Vector; +} +interface LU { + L: Matrix; + U: Matrix; +} +type MultidimensionalArray = + | T[][] + | T[][][] + | T[][][][] + | T[][][][][] + | T[][][][][][] + | T[][][][][][][] + | T[][][][][][][][] + | T[][][][][][][][][][] + | T[][][][][][][][][][][] + | T[][][][][][][][][][][][] + | T[][][][][][][][][][][][][] + | T[][][][][][][][][][][][][][] + | T[][][][][][][][][][][][][][][] + | T[][][][][][][][][][][][][][][][]; +type MultidimensionalMatrix = MultidimensionalArray; + +type TensorValue = Scalar | Vector | MultidimensionalMatrix; +type NonScalar = Vector | MultidimensionalMatrix; + +declare class Tensor { + x: TensorValue; + y?: TensorValue; + + add(tensor: Tensor | TensorValue): Tensor; + sub(tensor: Tensor | TensorValue): Tensor; + mul(tensor: Tensor | TensorValue): Tensor; + // it's buggy. https://github.com/sloisel/numeric/pull/59 + reciprocal(): Tensor; + div(tensor: Tensor | TensorValue): Tensor; + dot(tensor: Tensor | TensorValue): Tensor; + transpose(): Tensor; + transjugate(): Tensor; + exp(): Tensor; + conj(): Tensor; + neg(): Tensor; + sin(): Tensor; + cos(): Tensor; + abs(): Tensor; + log(): Tensor; + norm2(): Tensor; + inv(): Tensor; + get(i: Vector): Tensor; + set(i: Vector, value: Tensor): Tensor; + getRows(i0: number, i1: number): Tensor; + setRows(i0: number, i1: number, tensor: Tensor): Tensor; + getRow(k: number): Tensor; + setRow(i: number, tensor: Tensor): Tensor; + getBlock(from: Vector, to: Vector): Tensor; + setBlock(from: Vector, to: Vector, tensor: Tensor): Tensor; + rep(s: Vector, value: Tensor | TensorValue): Tensor; + diag(d: Tensor | TensorValue): Tensor; + eig(): { lambda: Tensor; E: Tensor }; + identity(n: number): Tensor; + getDiag(): Tensor; + // fast fourier transforms + fft(): Tensor; + ifft(): Tensor; +} + +declare class Spline { + x: Vector; + yl: Vector; + yr: Vector; + kl: Vector; + kr: Vector; + + at(x0: Vector | Scalar): Vector | Scalar; + diff(): Spline; + roots(): Vector; +} + +declare class Dopri { + x: Vector; + y: Vector; + f: Vector; + ymid: Vector; + iterations: number; + msg: string; + events?: boolean | VectorBoolean; + + at(x: Vector): Vector | Matrix; +} + +interface Numeric { + readonly epsilon: number; + largeArray: number; + precision: number; + readonly version: string; + + seedrandom: { + seedrandom(seed: number | string, useEntropy?: boolean): string; + random(): number; + }; + + // utility functions + // Benchmarking routine + bench(func: () => any, interval?: number): number; + prettyPrint(x?: any): string; + parseDate(date: string): number; + parseDate(dates: string[]): number[]; + parseFloat(input: string): number; + parseFloat(inputs: string[]): number[]; + parseCSV(csv: string): string[][]; + // toCSV is buggy. + // https://github.com/sloisel/numeric/pull/51 + toCSV(csvArray: any[][]): string; + // Encode a matrix as an image URL + imageURL(img: number[][]): string; + getURL(url: string): any; + + // linear algebra with arrays + // Get Array dimensions + dim(arr: any): Vector; + // x and y are entrywise identical + same(x: any, y: any): boolean; + // Create an Array by duplicating values + rep(scale: Vector, value: T, key?: number): MultidimensionalArray; + + // Matrix-Matrix, Matrix-Vector, Vector-Matrix and Vector-Vector product + dot( + x: Vector | Matrix | Scalar, + y: Vector | Matrix | Scalar + ): Vector | Matrix | Scalar; + dotMMsmall(x: Matrix, y: Matrix): Matrix; + dotMMbig(x: Matrix, y: Matrix): Matrix; + dotMV(x: Matrix, y: Vector): Vector; + dotVM(x: Vector, y: Matrix): Vector; + dotVV(x: Vector, y: Vector): Scalar; + + // Create diagonal matrix + diag(diagonal: Vector): Matrix; + // Get the diagonal of a Matrix + getDiag(matrix: Matrix): Vector; + // Identity matrix + identity(num: number): Matrix; + + // Pointwise Math.abs(x) + abs(x: T): T; + absV(x: Vector): Vector; + abseqV(x: Vector): Vector; + abseq(x: T): T; + + // Pointwise arc-cosine + acos(x: T): T; + acosV(x: Vector): Vector; + acoseqV(x: Vector): Vector; + acoseq(x: T): T; + + // Pointwise arc-sine + asin(x: T): T; + asinV(x: Vector): Vector; + asineqV(x: Vector): Vector; + asineq(x: T): T; + + // Pointwise arc-tangent + atan(x: T): T; + atanV(x: Vector): Vector; + ataneqV(x: Vector): Vector; + ataneq(x: T): T; + + // Pointwise Math.ceil(x) + ceil(x: T): T; + ceilV(x: Vector): Vector; + ceileqV(x: Vector): Vector; + ceileq(x: T): T; + + // Pointwise Math.cos(x) + cos(x: T): T; + cosV(x: Vector): Vector; + coseqV(x: Vector): Vector; + coseq(x: T): T; + + // Pointwise Math.exp(x) + exp(x: T): T; + expV(x: Vector): Vector; + expeqV(x: Vector): Vector; + expeq(x: T): T; + + // Poinwise Math.floor(x) + floor(x: T): T; + floorV(x: Vector): Vector; + flooreqV(x: Vector): Vector; + flooreq(x: T): T; + + // Pointwise Math.log(x) + log(x: T): T; + logV(x: Vector): Vector; + logeqV(x: Vector): Vector; + logeq(x: T): T; + + // Pointwise Math.round(x) + round(x: T): T; + roundV(x: Vector): Vector; + roundeqV(x: Vector): Vector; + roundeq(x: T): T; + + // Pointwise Math.sin(x) + sin(x: T): T; + sinV(x: Vector): Vector; + sineqV(x: Vector): Vector; + sineq(x: T): T; + + // Pointwise Math.sqrt(x) + sqrt(x: T): T; + sqrtV(x: Vector): Vector; + sqrteqV(x: Vector): Vector; + sqrteq(x: T): T; + + // Pointwise tangent + tan(x: T): T; + tanV(x: Vector): Vector; + taneqV(x: Vector): Vector; + taneq(x: T): T; + + // Pointwise Number.isNan(x) + isNaN(x: Vector): VectorBoolean; + isNaN(x: MultidimensionalMatrix): MultidimensionalArray; + isNaNV(x: Vector): VectorBoolean; + isNaNeqV(x: Vector): VectorBoolean; + isNaNeq(x: Vector): VectorBoolean; + isNaNeq(x: MultidimensionalMatrix): MultidimensionalArray; + + // Pointwise Number.isFinite(x) + isFinite(x: Vector): VectorBoolean; + isFinite(x: MultidimensionalMatrix): MultidimensionalArray; + isFiniteV(x: Vector): VectorBoolean; + isFiniteeqV(x: Vector): VectorBoolean; + isFiniteeq(x: Vector): VectorBoolean; + isFiniteeq(x: MultidimensionalMatrix): MultidimensionalArray; + + // Pointwise -x + neg(x: T): T; + negV(x: Vector): Vector; + negeq(x: T): T; + negeqV(x: Vector): Vector; + + // Pointwise logical negation !x + not(x: NonNullPrimitive): boolean; + not(x: NonNullPrimitive[]): VectorBoolean; + not( + x: MultidimensionalArray + ): MultidimensionalArray; + notV(x: NonNullPrimitive[]): VectorBoolean; + noteq(x: NonNullPrimitive): boolean; + noteq(x: NonNullPrimitive[]): VectorBoolean; + noteq( + x: MultidimensionalArray + ): MultidimensionalArray; + noteqV(x: NonNullPrimitive[]): VectorBoolean; + + // Pointwise binary negation ~x + bnot(x: T): T; + bnotV(x: Vector): Vector; + bnoteq(x: T): T; + bnoteqV(x: Vector): Vector; + + // Deep copy of Array + clone< + T extends NonNullPrimitive[] | MultidimensionalArray + >( + x: T + ): T; + cloneV(x: NonNullPrimitive[]): NonNullPrimitive[]; + cloneeq(x: NonNullPrimitive[]): NonNullPrimitive[]; + cloneeq< + T extends NonNullPrimitive[] | MultidimensionalArray + >( + x: T + ): T; + cloneeqV(x: NonNullPrimitive[]): NonNullPrimitive[]; + + // Pointwise sum x+y + add(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + add( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + add( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "+"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "+"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "+"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + addVV(x: Vector, y: Vector): Vector; + addSV(x: Scalar, y: Vector): Vector; + addVS(x: Vector, y: Scalar): Vector; + addeq(x: Vector, y: Vector | Scalar): Vector; + addeqV(x: Vector, y: Vector): Vector; + addeqS(x: Vector, y: Scalar): Vector; + + // Pointwise x-y + sub(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + sub( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + sub( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "-"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "-"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "-"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + subVV(x: Vector, y: Vector): Vector; + subSV(x: Scalar, y: Vector): Vector; + subVS(x: Vector, y: Scalar): Vector; + subeq(x: Vector, y: Vector | Scalar): Vector; + subeqV(x: Vector, y: Vector): Vector; + subeqS(x: Vector, y: Scalar): Vector; + + // Pointwise x*y + mul(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + mul( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + mul( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "*"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "*"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "*"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + mulVV(x: Vector, y: Vector): Vector; + mulSV(x: Scalar, y: Vector): Vector; + mulVS(x: Vector, y: Scalar): Vector; + muleq(x: Vector, y: Vector | Scalar): Vector; + muleqV(x: Vector, y: Vector): Vector; + muleqS(x: Vector, y: Scalar): Vector; + + // Pointwise x/y + div(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + div( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + div( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "/"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "/"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "/"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + divVV(x: Vector, y: Vector): Vector; + divSV(x: Scalar, y: Vector): Vector; + divVS(x: Vector, y: Scalar): Vector; + diveq(x: Vector, y: Vector | Scalar): Vector; + diveqV(x: Vector, y: Vector): Vector; + diveqS(x: Vector, y: Scalar): Vector; + + // Pointwise x%y + mod(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + mod( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + mod( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "%"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "%"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "%"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + modVV(x: Vector, y: Vector): Vector; + modSV(x: Scalar, y: Vector): Vector; + modVS(x: Vector, y: Scalar): Vector; + modeq(x: Vector, y: Vector | Scalar): Vector; + modeqV(x: Vector, y: Vector): Vector; + modeqS(x: Vector, y: Scalar): Vector; + + // Pointwise x && y + and(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + and( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + and( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "&&"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "&&"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "&&"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + andVV(x: Vector, y: Vector): Vector; + andSV(x: Scalar, y: Vector): Vector; + andVS(x: Vector, y: Scalar): Vector; + andeq(x: Vector, y: Vector | Scalar): Vector; + andeqV(x: Vector, y: Vector): Vector; + andeqS(x: Vector, y: Scalar): Vector; + + // Pointwise logical or x||y + or(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + or( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + or( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "||"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "||"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "||"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + orVV(x: Vector, y: Vector): Vector; + orSV(x: Scalar, y: Vector): Vector; + orVS(x: Vector, y: Scalar): Vector; + oreq(x: Vector, y: Vector | Scalar): Vector; + oreqV(x: Vector, y: Vector): Vector; + oreqS(x: Vector, y: Scalar): Vector; + + // Pointwise comparison x === y + eq(x: Scalar, y: Scalar): boolean; + eq(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + eq( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + "==="(x: Scalar, y: Scalar, ...args: Scalar[]): boolean; + "==="(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + "==="( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + eqVV(x: Vector, y: Vector): VectorBoolean; + eqSV(x: Scalar, y: Vector): VectorBoolean; + eqVS(x: Vector, y: Scalar): VectorBoolean; + eqeq(x: Vector, y: Vector | Scalar): VectorBoolean; + eqeqV(x: Vector, y: Vector): VectorBoolean; + eqeqS(x: Vector, y: Scalar): VectorBoolean; + + // Pointwise x!==y + neq(x: Scalar, y: Scalar): boolean; + neq(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + neq( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + "!=="(x: Scalar, y: Scalar, ...args: Scalar[]): boolean; + "!=="(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + "!=="( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + neqVV(x: Vector, y: Vector): VectorBoolean; + neqSV(x: Scalar, y: Vector): VectorBoolean; + neqVS(x: Vector, y: Scalar): VectorBoolean; + neqeq(x: Vector, y: Vector | Scalar): VectorBoolean; + neqeqV(x: Vector, y: Vector): VectorBoolean; + neqeqS(x: Vector, y: Scalar): VectorBoolean; + + // Pointwise x; + "<"(x: Scalar, y: Scalar, ...args: Scalar[]): boolean; + "<"(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + "<"( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + ltVV(x: Vector, y: Vector): VectorBoolean; + ltSV(x: Scalar, y: Vector): VectorBoolean; + ltVS(x: Vector, y: Scalar): VectorBoolean; + lteq(x: Vector, y: Vector | Scalar): VectorBoolean; + lteqV(x: Vector, y: Vector): VectorBoolean; + lteqS(x: Vector, y: Scalar): VectorBoolean; + + // Pointwise x>y + gt(x: Scalar, y: Scalar): boolean; + gt(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + gt( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + ">"(x: Scalar, y: Scalar, ...args: Scalar[]): boolean; + ">"(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + ">"( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + gtVV(x: Vector, y: Vector): VectorBoolean; + gtSV(x: Scalar, y: Vector): VectorBoolean; + gtVS(x: Vector, y: Scalar): VectorBoolean; + gteq(x: Vector, y: Vector | Scalar): VectorBoolean; + gteqV(x: Vector, y: Vector): VectorBoolean; + gteqS(x: Vector, y: Scalar): VectorBoolean; + + // Pointwise x<=y + leq(x: Scalar, y: Scalar): boolean; + leq(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + leq( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + "<="(x: Scalar, y: Scalar, ...args: Scalar[]): boolean; + "<="(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + "<="( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + leqVV(x: Vector, y: Vector): VectorBoolean; + leqSV(x: Scalar, y: Vector): VectorBoolean; + leqVS(x: Vector, y: Scalar): VectorBoolean; + leqeq(x: Vector, y: Vector | Scalar): VectorBoolean; + leqeqV(x: Vector, y: Vector): VectorBoolean; + leqeqS(x: Vector, y: Scalar): VectorBoolean; + + // Pointwise x>=y + geq(x: Scalar, y: Scalar): boolean; + geq(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + geq( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + ">="(x: Scalar, y: Scalar, ...args: Scalar[]): boolean; + ">="(x: Scalar | Vector, y: Scalar | Vector): VectorBoolean; + ">="( + x: MultidimensionalMatrix, + y: MultidimensionalMatrix + ): MultidimensionalArray; + geqVV(x: Vector, y: Vector): VectorBoolean; + geqSV(x: Scalar, y: Vector): VectorBoolean; + geqVS(x: Vector, y: Scalar): VectorBoolean; + geqeq(x: Vector, y: Vector | Scalar): VectorBoolean; + geqeqV(x: Vector, y: Vector): VectorBoolean; + geqeqS(x: Vector, y: Scalar): VectorBoolean; + + // Pointwise x & y + band(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + band( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + band( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "&"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "&"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "&"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + bandVV(x: Vector, y: Vector): Vector; + bandSV(x: Scalar, y: Vector): Vector; + bandVS(x: Vector, y: Scalar): Vector; + bandeq(x: Vector, y: Vector | Scalar): Vector; + bandeqV(x: Vector, y: Vector): Vector; + bandeqS(x: Vector, y: Scalar): Vector; + + // Pointwise binary or x|y + bor(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + bor( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + bor( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "|"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "|"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "|"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + borVV(x: Vector, y: Vector): Vector; + borSV(x: Scalar, y: Vector): Vector; + borVS(x: Vector, y: Scalar): Vector; + boreq(x: Vector, y: Vector | Scalar): Vector; + boreqV(x: Vector, y: Vector): Vector; + boreqS(x: Vector, y: Scalar): Vector; + + // Pointwise binary xor x^y + bxor(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + bxor( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + bxor( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "^"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "^"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "^"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + bxorVV(x: Vector, y: Vector): Vector; + bxorSV(x: Scalar, y: Vector): Vector; + bxorVS(x: Vector, y: Scalar): Vector; + bxoreq(x: Vector, y: Vector | Scalar): Vector; + bxoreqV(x: Vector, y: Vector): Vector; + bxoreqS(x: Vector, y: Scalar): Vector; + + // Pointwise x< + ): Vector; + lshift( + x: T, + y: T | Scalar, + ...args: Array + ): T; + "<<"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + "<<"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + "<<"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + lshiftVV(x: Vector, y: Vector): Vector; + lshiftSV(x: Scalar, y: Vector): Vector; + lshiftVS(x: Vector, y: Scalar): Vector; + lshifteq(x: Vector, y: Vector | Scalar): Vector; + lshifteqV(x: Vector, y: Vector): Vector; + lshifteqS(x: Vector, y: Scalar): Vector; + + // Pointwise x>>y + rshift(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + rshift( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + rshift( + x: T, + y: T | Scalar, + ...args: Array + ): T; + ">>"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + ">>"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + ">>"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + rshiftVV(x: Vector, y: Vector): Vector; + rshiftSV(x: Scalar, y: Vector): Vector; + rshiftVS(x: Vector, y: Scalar): Vector; + rshifteq(x: Vector, y: Vector | Scalar): Vector; + rshifteqV(x: Vector, y: Vector): Vector; + rshifteqS(x: Vector, y: Scalar): Vector; + + // Pointwise x>>>y + rrshift(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + rrshift( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + rrshift( + x: T, + y: T | Scalar, + ...args: Array + ): T; + ">>>"(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + ">>>"( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + ">>>"( + x: T, + y: T | Scalar, + ...args: Array + ): T; + rrshiftVV(x: Vector, y: Vector): Vector; + rrshiftSV(x: Scalar, y: Vector): Vector; + rrshiftVS(x: Vector, y: Scalar): Vector; + rrshifteq(x: Vector, y: Vector | Scalar): Vector; + rrshifteqV(x: Vector, y: Vector): Vector; + rrshifteqS(x: Vector, y: Scalar): Vector; + + // Pointwise arc-tangent (two parameters) + atan2(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + atan2( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + atan2( + x: T, + y: T | Scalar, + ...args: Array + ): T; + atan2VV(x: Vector, y: Vector): Vector; + atan2SV(x: Scalar, y: Vector): Vector; + atan2VS(x: Vector, y: Scalar): Vector; + atan2eq(x: Vector, y: Vector | Scalar): Vector; + atan2eqV(x: Vector, y: Vector): Vector; + atan2eqS(x: Vector, y: Scalar): Vector; + + // Pointwise x**y + pow(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + pow( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + pow( + x: T, + y: T | Scalar, + ...args: Array + ): T; + powVV(x: Vector, y: Vector): Vector; + powSV(x: Scalar, y: Vector): Vector; + powVS(x: Vector, y: Scalar): Vector; + poweq(x: Vector, y: Vector | Scalar): Vector; + poweqV(x: Vector, y: Vector): Vector; + poweqS(x: Vector, y: Scalar): Vector; + + // Pointwise max(x,y) + max(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + max( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + max( + x: T, + y: T | Scalar, + ...args: Array + ): T; + maxVV(x: Vector, y: Vector): Vector; + maxSV(x: Scalar, y: Vector): Vector; + maxVS(x: Vector, y: Scalar): Vector; + maxeq(x: Vector, y: Vector | Scalar): Vector; + maxeqV(x: Vector, y: Vector): Vector; + maxeqS(x: Vector, y: Scalar): Vector; + + // Pointwise min(x,y) + min(x: Scalar, y: Scalar, ...args: Scalar[]): Scalar; + min( + x: Scalar | Vector, + y: Scalar | Vector, + ...args: Array + ): Vector; + min( + x: T, + y: T | Scalar, + ...args: Array + ): T; + minVV(x: Vector, y: Vector): Vector; + minSV(x: Scalar, y: Vector): Vector; + minVS(x: Vector, y: Scalar): Vector; + mineq(x: Vector, y: Vector | Scalar): Vector; + mineqV(x: Vector, y: Vector): Vector; + mineqS(x: Vector, y: Scalar): Vector; + + // One or more of the components of x are true + any(x: any): boolean; + anyV(x: any[]): boolean; + + // All the components of x are true + all(x: any): boolean; + allV(x: any[]): boolean; + + // Sum all the entries of x + sum(x: Scalar | Vector | MultidimensionalMatrix): number; + sumV(x: Vector): number; + + // Product of all the entries of x + prod(x: Scalar | Vector | MultidimensionalMatrix): number; + prodV(x: Vector): number; + + // Sum of squares of entries of x + norm2Squared(x: Scalar | Vector | MultidimensionalMatrix): number; + norm2SquaredV(x: Vector): number; + + // Largest modulus entry of x + norminf(x: Scalar | Vector | MultidimensionalMatrix): number; + norminfV(x: Vector): number; + + // Sum all absolute values of entries + norm1(x: Scalar | Vector | MultidimensionalMatrix): number; + norm1V(x: Vector): number; + + // Largest value of entries (not modulus) + sup(x: Scalar | Vector | MultidimensionalMatrix): number; + supV(x: Vector): number; + + // Smallest value of entries (not modulus) + inf(x: Scalar | Vector | MultidimensionalMatrix): number; + infV(x: Vector): number; + + // Round the values of entries + truncVV(x: Vector, y: Vector): Vector; + truncVS(x: Vector, y: number): Vector; + truncSV(x: number, y: Vector): Vector; + trunc(x: number | Vector, y: number | Vector): Vector; + + // Matrix inverse + inv(x: Matrix): Matrix; + // Determinant + det(x: Matrix): number; + // Matrix transpose + transpose(x: Matrix): Matrix; + // Negate matrix and transpose + negtranspose(x: Matrix): Matrix; + // Create an Array of random numbers + random(s: Vector): Vector | MultidimensionalMatrix; + // Square root of the sum of the square of the entries of x + norm2(x: Scalar | Vector | MultidimensionalMatrix): number; + // Generate evenly spaced values + linspace(from: number, to: number, numberOfValues?: number): Vector; + // Extract a block from a matrix + getBlock( + x: T, + from: Vector, + to: Vector + ): T; + // Set a block of a matrix + setBlock( + x: T, + from: Vector, + to: Vector, + b: T + ): T; + // create two-dimensional matrix + blockMatrix(x: Scalar | Vector | MultidimensionalMatrix): Matrix; + // x * y + tensor(x: Scalar, y: Scalar): Scalar; + // TensorValue product ret[i][j] = x[i]*y[j] + tensor(x: Vector, y: Vector): Matrix; + + // return instance of Tensor class. X — real value, y — imaginary part. + t(x: TensorValue, y?: TensorValue): Tensor; + + // Eigenvalues of real matrices + house(x: Vector): Vector; + toUpperHessenberg(matrix: Matrix): { H: Matrix; Q: Matrix }; + QRFrancis(x: Matrix, maxiter?: number): { Q: Matrix; B: Matrix }; + eig(A: Matrix, maxiter?: number): { lambda: Tensor; E: Tensor }; + + // Compressed Column Storage matrices + ccsSparse(matrix: Matrix): SparseMatrix; + ccsFull(matrix: SparseMatrix): Matrix; + ccsTSolve( + matrix: SparseMatrix, + b: Vector, + x?: Vector, + bj?: Vector, + xj?: Vector + ): Vector; + ccsDot(A: SparseMatrix, B: SparseMatrix): SparseMatrix; + ccsLUP(matrix: SparseMatrix, threshold?: number): LUPP; + ccsDim(matrix: SparseMatrix): Vector; + ccsGetBlock( + matrix: SparseMatrix, + i?: Vector | Scalar, + j?: Vector | Scalar + ): SparseMatrix; + ccsLUPSolve(lup: LUPP, B: SparseMatrix): Vector; + ccsScatter(matrix: SparseMatrix): SparseMatrix; + ccsGather(matrix: SparseMatrix): SparseMatrix; + + ccsadd(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsadd(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsaddMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccssub(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccssub(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccssubMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccsmul(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsmul(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsmulMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccsdiv(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsdiv(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsdivMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccsmod(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsmod(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsmodMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccsand(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsand(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsandMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccsor(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsor(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsorMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccseq(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult; + ccseq(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult; + ccseqMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult; + + ccsneq(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult; + ccsneq(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult; + ccsneqMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult; + + ccslt(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult; + ccslt(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult; + ccsltMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult; + + ccsgt(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult; + ccsgt(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult; + ccsgtMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult; + + ccsleq(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult; + ccsleq(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult; + ccsleqMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult; + + ccsgeq(x: SparseMatrix, y: Scalar | SparseMatrix): CCSComparisonResult; + ccsgeq(x: Scalar | SparseMatrix, y: SparseMatrix): CCSComparisonResult; + ccsgeqMM(x: SparseMatrix, y: SparseMatrix): CCSComparisonResult; + + ccsband(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsband(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsbandMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccsbor(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsbor(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsborMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccsbxor(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsbxor(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsbxorMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccslshift(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccslshift(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccslshiftMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccsrshift(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsrshift(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsrshiftMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + ccsrrshift(x: SparseMatrix, y: Scalar | SparseMatrix): SparseMatrix; + ccsrrshift(x: Scalar | SparseMatrix, y: SparseMatrix): SparseMatrix; + ccsrrshiftMM(x: SparseMatrix, y: SparseMatrix): SparseMatrix; + + /** @deprecated */ + sdim(matrix: any, ret?: Vector, k?: number): Vector; + /** @deprecated */ + sclone(matrix: T, k?: number, n?: number): T; + /** @deprecated */ + sdiag(d: Vector): DeprecatedSparseMatrix; + /** @deprecated */ + sidentity(n: Scalar): DeprecatedSparseMatrix; + /** @deprecated */ + stranspose(matrix: DeprecatedSparseMatrix): DeprecatedSparseMatrix; + /** @deprecated */ + sdotMM( + a: DeprecatedSparseMatrix, + b: DeprecatedSparseMatrix + ): DeprecatedSparseMatrix; + /** @deprecated */ + sdotMV( + matrix: DeprecatedSparseMatrix, + vector: DeprecatedSparseVector + ): DeprecatedSparseVector; + /** @deprecated */ + sdotVM( + vector: DeprecatedSparseVector, + matrix: DeprecatedSparseMatrix + ): DeprecatedSparseMatrix; + /** @deprecated */ + sdotVV(x: DeprecatedSparseVector, y: DeprecatedSparseVector): number; + /** @deprecated */ + sdot( + x: Scalar | DeprecatedSparseVector | DeprecatedSparseMatrix, + y: Scalar | DeprecatedSparseVector | DeprecatedSparseMatrix + ): Scalar | DeprecatedSparseVector | DeprecatedSparseMatrix; + /** @deprecated */ + sscatter(matrix: DeprecatedSparseMatrix): DeprecatedSparseMatrix; + /** @deprecated */ + sgather( + matrix: DeprecatedSparseMatrix, + ret?: DeprecatedSparseVector, + k?: DeprecatedSparseVector + ): DeprecatedSparseMatrix; + + // Coordinate matrices + cLU(matrix: Matrix): LU; + cLUSolve(lu: LU, b: Vector): Vector; + cgrid(n: number | [number, number], shape?: "L" | ShapeFunction): Matrix; + cdelsq(g: Matrix): Matrix; + cdotmv(matrix: Matrix, x: Vector): Vector; + + // Splines + spline( + x: Vector, + y: Vector | Matrix, + k1?: "periodic" | Scalar, + kn?: "periodic" | Scalar + ): Spline; + + // Unconstrained optimisations + uncmin( + f: (x: Vector) => Scalar, + x0: Vector, + tol?: number, + gradient?: any, + maxit?: number, + callback?: ( + it: number, + x0: Vector, + f0: Scalar, + g0: Vector, + h1: Matrix + ) => any, + options?: { Hinv: Matrix } + ): { + solution: Vector; + f: Scalar; + gradient: Vector; + invHessian: Matrix; + iterations: number; + message: string; + }; + gradient(f: (x: Vector) => Scalar, x: Vector): Vector; + + // Ode solver (Dormand-Prince) + dopri( + x0: Scalar, + x1: Scalar, + y0: Scalar, + f: (x: Vector | Scalar, y: Vector | Scalar) => Vector | Scalar, + tol?: number, + maxit?: number, + event?: (x: Vector | Scalar, y: Vector | Scalar) => Vector | Scalar + ): Dopri; + + // Solving the linear problem Ax=b + solve(matrix: Matrix, vector: Vector): Vector; + LU(matrix: Matrix, fast?: boolean): { LU: Matrix; P: Vector }; + LUsolve(lup: { LU: Matrix; P: Vector }, vector: Vector): Vector; + + // Linear programming + echelonize(matrix: Matrix): { I: Matrix; A: Matrix; P: Vector }; + solveLP( + c: Vector, + A: Matrix, + b: Vector, + Aeq?: Matrix, + beq?: Matrix, + tol?: number, + maxit?: number + ): { solution: Scalar | Vector; message: string; iterations: number }; + + solveQP( + Dmat: Matrix, + dvec: Vector, + Amat: Matrix, + bvec: Vector, + meq?: number, + factorized?: any + ): { + solution: Vector; + value: Vector; + unconstrained_solution: Vector; + iterations: Vector; + iact: Vector; + message: string; + }; + + svd(matrix: Matrix): { U: Matrix; S: Vector; V: Matrix }; +} + +declare const numeric: Numeric; +export = numeric; diff --git a/types/numeric/numeric-tests.ts b/types/numeric/numeric-tests.ts new file mode 100644 index 0000000000..017f3ae6cd --- /dev/null +++ b/types/numeric/numeric-tests.ts @@ -0,0 +1,630 @@ +import numeric = require("numeric"); + +const vector = [2, 5]; +const matrix = [vector, vector]; +const threeDimensionalMatrix = [[[2, 3], [2, 3], [3, 5]]]; +const sparseMatrix: [number[], number[], number[]] = [vector, vector, vector]; + +numeric.bench(() => null, 150); // $ExpectType number +numeric.prettyPrint(vector); // $ExpectType string +numeric.parseDate("08-08-17"); // $ExpectType number +numeric.parseDate(["08-05-87", "08-05-75"]); // $ExpectType number[] +numeric.parseFloat("55.24"); // $ExpectType number +numeric.parseFloat(["25.15", "44.25", "as"]); // $ExpectType number[] +numeric.parseCSV("car, bike"); // $ExpectType string[][] +numeric.toCSV([[25, 52, 62, 66], ["car", "bad", "bike", {}]]); // $ExpectType string +numeric.imageURL([[25, 50], [52, 52]]); // $ExpectType string +numeric.getURL('sdf'); // $ExpectType any + +numeric.dim(matrix); // $ExpectType number[] +numeric.same(25, [25]); // $ExpectType boolean +numeric.rep([2, 5], true); +numeric.dotMMsmall(matrix, matrix); // $ExpectType number[][] +numeric.dotMMbig(matrix, matrix); // $ExpectType number[][] +numeric.dotMV(matrix, vector); // $ExpectType number[] +numeric.dotVM(vector, matrix); // $ExpectType number[] +numeric.dotVV(vector, vector); // $ExpectType number +numeric.dot(vector, matrix); // $ExpectType number | number[] | number[][] +numeric.diag([25, 52]); // $ExpectType number[][] +numeric.getDiag(matrix); // $ExpectType number[] +numeric.identity(24); // $ExpectType number[][] + +numeric.abs(matrix); // $ExpectType number[][] +numeric.absV(vector); // $ExpectType number[] +numeric.abseqV(vector); // $ExpectType number[] +numeric.abseq(matrix); // $ExpectType number[][] + +numeric.acos(matrix); // $ExpectType number[][] +numeric.acosV(vector); // $ExpectType number[] +numeric.acoseqV(vector); // $ExpectType number[] +numeric.acoseq(matrix); // $ExpectType number[][] + +numeric.asin(matrix); // $ExpectType number[][] +numeric.asinV(vector); // $ExpectType number[] +numeric.asineqV(vector); // $ExpectType number[] +numeric.asineq(matrix); // $ExpectType number[][] + +numeric.atan(matrix); // $ExpectType number[][] +numeric.atanV(vector); // $ExpectType number[] +numeric.ataneqV(vector); // $ExpectType number[] +numeric.ataneq(matrix); // $ExpectType number[][] + +numeric.ceil(matrix); // $ExpectType number[][] +numeric.ceilV(vector); // $ExpectType number[] +numeric.ceileqV(vector); // $ExpectType number[] +numeric.ceileq(matrix); // $ExpectType number[][] + +numeric.cos(matrix); // $ExpectType number[][] +numeric.cosV(vector); // $ExpectType number[] +numeric.coseqV(vector); // $ExpectType number[] +numeric.coseq(matrix); // $ExpectType number[][] + +numeric.exp(matrix); // $ExpectType number[][] +numeric.expV(vector); // $ExpectType number[] +numeric.expeqV(vector); // $ExpectType number[] +numeric.expeq(matrix); // $ExpectType number[][] + +numeric.floor(matrix); // $ExpectType number[][] +numeric.floorV(vector); // $ExpectType number[] +numeric.flooreqV(vector); // $ExpectType number[] +numeric.flooreq(matrix); // $ExpectType number[][] + +numeric.log(matrix); // $ExpectType number[][] +numeric.logV(vector); // $ExpectType number[] +numeric.logeqV(vector); // $ExpectType number[] +numeric.logeq(matrix); // $ExpectType number[][] + +numeric.round(matrix); // $ExpectType number[][] +numeric.roundV(vector); // $ExpectType number[] +numeric.roundeqV(vector); // $ExpectType number[] +numeric.roundeq(matrix); // $ExpectType number[][] + +numeric.sin(matrix); // $ExpectType number[][] +numeric.sinV(vector); // $ExpectType number[] +numeric.sineqV(vector); // $ExpectType number[] +numeric.sineq(matrix); // $ExpectType number[][] + +numeric.sqrt(matrix); // $ExpectType number[][] +numeric.sqrtV(vector); // $ExpectType number[] +numeric.sqrteqV(vector); // $ExpectType number[] +numeric.sqrteq(matrix); // $ExpectType number[][] + +numeric.tan(matrix); // $ExpectType number[][] +numeric.tanV(vector); // $ExpectType number[] +numeric.taneqV(vector); // $ExpectType number[] +numeric.taneq(matrix); // $ExpectType number[][] + +numeric.isNaN(vector); // $ExpectType boolean[] +numeric.isNaN(threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.isNaNV(vector); // $ExpectType boolean[] +numeric.isNaNeqV(vector); // $ExpectType boolean[] +numeric.isNaNeq(vector); // $ExpectType boolean[] +numeric.isNaNeq(threeDimensionalMatrix); // $ExpectType MultidimensionalArray + +numeric.isFinite(vector); // $ExpectType boolean[] +numeric.isFinite(threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.isFiniteV(vector); // $ExpectType boolean[] +numeric.isFiniteeqV(vector); // $ExpectType boolean[] +numeric.isFiniteeq(vector); // $ExpectType boolean[] +numeric.isFiniteeq(threeDimensionalMatrix); // $ExpectType MultidimensionalArray + +numeric.neg(matrix); // $ExpectType number[][] +numeric.negV(vector); // $ExpectType number[] +numeric.negeqV(vector); // $ExpectType number[] +numeric.negeq(matrix); // $ExpectType number[][] + +numeric.bnot(matrix); // $ExpectType number[][] +numeric.bnotV(vector); // $ExpectType number[] +numeric.bnoteqV(vector); // $ExpectType number[] +numeric.bnoteq(matrix); // $ExpectType number[][] + +numeric.not(2); // $ExpectType boolean +numeric.not(vector); // $ExpectType boolean[] +numeric.not(threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.notV(vector); // $ExpectType boolean[] +numeric.noteq(2); // $ExpectType boolean +numeric.noteq(vector); // $ExpectType boolean[] +numeric.noteq(threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.noteqV(vector); // $ExpectType boolean[] + +numeric.clone(vector); // $ExpectType number[] +numeric.cloneV(vector); // $ExpectType NonNullPrimitive[] +numeric.cloneeq(vector); // $ExpectType NonNullPrimitive[] +numeric.cloneeqV(vector); // $ExpectType NonNullPrimitive[] + +numeric.add(2, 5, 6); // $ExpectType number +numeric.add(2, 3, vector); // $ExpectType number[] +numeric.add(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["+"](2, 5, 6); // $ExpectType number +numeric["+"](2, 3, vector); // $ExpectType number[] +numeric["+"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.addVV(vector, vector); // $ExpectType number[] +numeric.addSV(2, vector); // $ExpectType number[] +numeric.addVS(vector, 2); // $ExpectType number[] +numeric.addeq(vector, 3); // $ExpectType number[] +numeric.addeqV(vector, vector); // $ExpectType number[] +numeric.addeqS(vector, 3); // $ExpectType number[] + +numeric.sub(2, 5, 6); // $ExpectType number +numeric.sub(2, 3, vector); // $ExpectType number[] +numeric.sub(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["-"](2, 5, 6); // $ExpectType number +numeric["-"](2, 3, vector); // $ExpectType number[] +numeric["-"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.subVV(vector, vector); // $ExpectType number[] +numeric.subSV(2, vector); // $ExpectType number[] +numeric.subVS(vector, 2); // $ExpectType number[] +numeric.subeq(vector, 3); // $ExpectType number[] +numeric.subeqV(vector, vector); // $ExpectType number[] +numeric.subeqS(vector, 3); // $ExpectType number[] + +numeric.mul(2, 5, 6); // $ExpectType number +numeric.mul(2, 3, vector); // $ExpectType number[] +numeric.mul(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["*"](2, 5, 6); // $ExpectType number +numeric["*"](2, 3, vector); // $ExpectType number[] +numeric["*"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.mulVV(vector, vector); // $ExpectType number[] +numeric.mulSV(2, vector); // $ExpectType number[] +numeric.mulVS(vector, 2); // $ExpectType number[] +numeric.muleq(vector, 3); // $ExpectType number[] +numeric.muleqV(vector, vector); // $ExpectType number[] +numeric.muleqS(vector, 3); // $ExpectType number[] + +numeric.div(2, 5, 6); // $ExpectType number +numeric.div(2, 3, vector); // $ExpectType number[] +numeric.div(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["/"](2, 5, 6); // $ExpectType number +numeric["/"](2, 3, vector); // $ExpectType number[] +numeric["/"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.divVV(vector, vector); // $ExpectType number[] +numeric.divSV(2, vector); // $ExpectType number[] +numeric.divVS(vector, 2); // $ExpectType number[] +numeric.diveq(vector, 3); // $ExpectType number[] +numeric.diveqV(vector, vector); // $ExpectType number[] +numeric.diveqS(vector, 3); // $ExpectType number[] + +numeric.mod(2, 5, 6); // $ExpectType number +numeric.mod(2, 3, vector); // $ExpectType number[] +numeric.mod(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["%"](2, 5, 6); // $ExpectType number +numeric["%"](2, 3, vector); // $ExpectType number[] +numeric["%"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.modVV(vector, vector); // $ExpectType number[] +numeric.modSV(2, vector); // $ExpectType number[] +numeric.modVS(vector, 2); // $ExpectType number[] +numeric.modeq(vector, 3); // $ExpectType number[] +numeric.modeqV(vector, vector); // $ExpectType number[] +numeric.modeqS(vector, 3); // $ExpectType number[] + +numeric.and(2, 5, 6); // $ExpectType number +numeric.and(2, 3, vector); // $ExpectType number[] +numeric.and(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["&&"](2, 5, 6); // $ExpectType number +numeric["&&"](2, 3, vector); // $ExpectType number[] +numeric["&&"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.andVV(vector, vector); // $ExpectType number[] +numeric.andSV(2, vector); // $ExpectType number[] +numeric.andVS(vector, 2); // $ExpectType number[] +numeric.andeq(vector, 3); // $ExpectType number[] +numeric.andeqV(vector, vector); // $ExpectType number[] +numeric.andeqS(vector, 3); // $ExpectType number[] + +numeric.or(2, 5, 6); // $ExpectType number +numeric.or(2, 3, vector); // $ExpectType number[] +numeric.or(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["||"](2, 5, 6); // $ExpectType number +numeric["||"](2, 3, vector); // $ExpectType number[] +numeric["||"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.orVV(vector, vector); // $ExpectType number[] +numeric.orSV(2, vector); // $ExpectType number[] +numeric.orVS(vector, 2); // $ExpectType number[] +numeric.oreq(vector, 3); // $ExpectType number[] +numeric.oreqV(vector, vector); // $ExpectType number[] +numeric.oreqS(vector, 3); // $ExpectType number[] + +numeric.eq(2, 5); // $ExpectType boolean +numeric.eq(2, vector); // $ExpectType boolean[] +numeric.eq(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric["==="](2, 5); // $ExpectType boolean +numeric["==="](2, vector); // $ExpectType boolean[] +numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.eqVV(vector, vector); // $ExpectType boolean[] +numeric.eqSV(2, vector); // $ExpectType boolean[] +numeric.eqVS(vector, 2); // $ExpectType boolean[] +numeric.eqeq(vector, 3); // $ExpectType boolean[] +numeric.eqeqV(vector, vector); // $ExpectType boolean[] +numeric.eqeqS(vector, 3); // $ExpectType boolean[] + +numeric.neq(2, 5); // $ExpectType boolean +numeric.neq(2, vector); // $ExpectType boolean[] +numeric.neq(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric["==="](2, 5); // $ExpectType boolean +numeric["==="](2, vector); // $ExpectType boolean[] +numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.neqVV(vector, vector); // $ExpectType boolean[] +numeric.neqSV(2, vector); // $ExpectType boolean[] +numeric.neqVS(vector, 2); // $ExpectType boolean[] +numeric.neqeq(vector, 3); // $ExpectType boolean[] +numeric.neqeqV(vector, vector); // $ExpectType boolean[] +numeric.neqeqS(vector, 3); // $ExpectType boolean[] + +numeric.lt(2, 5); // $ExpectType boolean +numeric.lt(2, vector); // $ExpectType boolean[] +numeric.lt(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric["==="](2, 5); // $ExpectType boolean +numeric["==="](2, vector); // $ExpectType boolean[] +numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.ltVV(vector, vector); // $ExpectType boolean[] +numeric.ltSV(2, vector); // $ExpectType boolean[] +numeric.ltVS(vector, 2); // $ExpectType boolean[] +numeric.lteq(vector, 3); // $ExpectType boolean[] +numeric.lteqV(vector, vector); // $ExpectType boolean[] +numeric.lteqS(vector, 3); // $ExpectType boolean[] + +numeric.gt(2, 5); // $ExpectType boolean +numeric.gt(2, vector); // $ExpectType boolean[] +numeric.gt(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric["==="](2, 5); // $ExpectType boolean +numeric["==="](2, vector); // $ExpectType boolean[] +numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.gtVV(vector, vector); // $ExpectType boolean[] +numeric.gtSV(2, vector); // $ExpectType boolean[] +numeric.gtVS(vector, 2); // $ExpectType boolean[] +numeric.gteq(vector, 3); // $ExpectType boolean[] +numeric.gteqV(vector, vector); // $ExpectType boolean[] +numeric.gteqS(vector, 3); // $ExpectType boolean[] + +numeric.leq(2, 5); // $ExpectType boolean +numeric.leq(2, vector); // $ExpectType boolean[] +numeric.leq(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric["==="](2, 5); // $ExpectType boolean +numeric["==="](2, vector); // $ExpectType boolean[] +numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.leqVV(vector, vector); // $ExpectType boolean[] +numeric.leqSV(2, vector); // $ExpectType boolean[] +numeric.leqVS(vector, 2); // $ExpectType boolean[] +numeric.leqeq(vector, 3); // $ExpectType boolean[] +numeric.leqeqV(vector, vector); // $ExpectType boolean[] +numeric.leqeqS(vector, 3); // $ExpectType boolean[] + +numeric.geq(2, 5); // $ExpectType boolean +numeric.geq(2, vector); // $ExpectType boolean[] +numeric.geq(threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric["==="](2, 5); // $ExpectType boolean +numeric["==="](2, vector); // $ExpectType boolean[] +numeric["==="](threeDimensionalMatrix, threeDimensionalMatrix); // $ExpectType MultidimensionalArray +numeric.geqVV(vector, vector); // $ExpectType boolean[] +numeric.geqSV(2, vector); // $ExpectType boolean[] +numeric.geqVS(vector, 2); // $ExpectType boolean[] +numeric.geqeq(vector, 3); // $ExpectType boolean[] +numeric.geqeqV(vector, vector); // $ExpectType boolean[] +numeric.geqeqS(vector, 3); // $ExpectType boolean[] + +numeric.band(2, 5, 6); // $ExpectType number +numeric.band(2, 3, vector); // $ExpectType number[] +numeric.band(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["&"](2, 5, 6); // $ExpectType number +numeric["&"](2, 3, vector); // $ExpectType number[] +numeric["&"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.bandVV(vector, vector); // $ExpectType number[] +numeric.bandSV(2, vector); // $ExpectType number[] +numeric.bandVS(vector, 2); // $ExpectType number[] +numeric.bandeq(vector, 3); // $ExpectType number[] +numeric.bandeqV(vector, vector); // $ExpectType number[] +numeric.bandeqS(vector, 3); // $ExpectType number[] + +numeric.bor(2, 5, 6); // $ExpectType number +numeric.bor(2, 3, vector); // $ExpectType number[] +numeric.bor(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["|"](2, 5, 6); // $ExpectType number +numeric["|"](2, 3, vector); // $ExpectType number[] +numeric["|"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.borVV(vector, vector); // $ExpectType number[] +numeric.borSV(2, vector); // $ExpectType number[] +numeric.borVS(vector, 2); // $ExpectType number[] +numeric.boreq(vector, 3); // $ExpectType number[] +numeric.boreqV(vector, vector); // $ExpectType number[] +numeric.boreqS(vector, 3); // $ExpectType number[] + +numeric.bxor(2, 5, 6); // $ExpectType number +numeric.bxor(2, 3, vector); // $ExpectType number[] +numeric.bxor(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["^"](2, 5, 6); // $ExpectType number +numeric["^"](2, 3, vector); // $ExpectType number[] +numeric["^"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.bxorVV(vector, vector); // $ExpectType number[] +numeric.bxorSV(2, vector); // $ExpectType number[] +numeric.bxorVS(vector, 2); // $ExpectType number[] +numeric.bxoreq(vector, 3); // $ExpectType number[] +numeric.bxoreqV(vector, vector); // $ExpectType number[] +numeric.bxoreqS(vector, 3); // $ExpectType number[] + +numeric.lshift(2, 5, 6); // $ExpectType number +numeric.lshift(2, 3, vector); // $ExpectType number[] +numeric.lshift(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric["<<"](2, 5, 6); // $ExpectType number +numeric["<<"](2, 3, vector); // $ExpectType number[] +numeric["<<"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.lshiftVV(vector, vector); // $ExpectType number[] +numeric.lshiftSV(2, vector); // $ExpectType number[] +numeric.lshiftVS(vector, 2); // $ExpectType number[] +numeric.lshifteq(vector, 3); // $ExpectType number[] +numeric.lshifteqV(vector, vector); // $ExpectType number[] +numeric.lshifteqS(vector, 3); // $ExpectType number[] + +numeric.rshift(2, 5, 6); // $ExpectType number +numeric.rshift(2, 3, vector); // $ExpectType number[] +numeric.rshift(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric[">>"](2, 5, 6); // $ExpectType number +numeric[">>"](2, 3, vector); // $ExpectType number[] +numeric[">>"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.rshiftVV(vector, vector); // $ExpectType number[] +numeric.rshiftSV(2, vector); // $ExpectType number[] +numeric.rshiftVS(vector, 2); // $ExpectType number[] +numeric.rshifteq(vector, 3); // $ExpectType number[] +numeric.rshifteqV(vector, vector); // $ExpectType number[] +numeric.rshifteqS(vector, 3); // $ExpectType number[] + +numeric.rrshift(2, 5, 6); // $ExpectType number +numeric.rrshift(2, 3, vector); // $ExpectType number[] +numeric.rrshift(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric[">>>"](2, 5, 6); // $ExpectType number +numeric[">>>"](2, 3, vector); // $ExpectType number[] +numeric[">>>"](threeDimensionalMatrix, 2, 4); // $ExpectType number[][][] +numeric.rrshiftVV(vector, vector); // $ExpectType number[] +numeric.rrshiftSV(2, vector); // $ExpectType number[] +numeric.rrshiftVS(vector, 2); // $ExpectType number[] +numeric.rrshifteq(vector, 3); // $ExpectType number[] +numeric.rrshifteqV(vector, vector); // $ExpectType number[] +numeric.rrshifteqS(vector, 3); // $ExpectType number[] + +numeric.atan2(2, 5, 6); // $ExpectType number +numeric.atan2(2, 3, vector); // $ExpectType number[] +numeric.atan2(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric.atan2VV(vector, vector); // $ExpectType number[] +numeric.atan2SV(2, vector); // $ExpectType number[] +numeric.atan2VS(vector, 2); // $ExpectType number[] +numeric.atan2eq(vector, 3); // $ExpectType number[] +numeric.atan2eqV(vector, vector); // $ExpectType number[] +numeric.atan2eqS(vector, 3); // $ExpectType number[] + +numeric.pow(2, 5, 6); // $ExpectType number +numeric.pow(2, 3, vector); // $ExpectType number[] +numeric.pow(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric.powVV(vector, vector); // $ExpectType number[] +numeric.powSV(2, vector); // $ExpectType number[] +numeric.powVS(vector, 2); // $ExpectType number[] +numeric.poweq(vector, 3); // $ExpectType number[] +numeric.poweqV(vector, vector); // $ExpectType number[] +numeric.poweqS(vector, 3); // $ExpectType number[] + +numeric.max(2, 5, 6); // $ExpectType number +numeric.max(2, 3, vector); // $ExpectType number[] +numeric.max(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric.maxVV(vector, vector); // $ExpectType number[] +numeric.maxSV(2, vector); // $ExpectType number[] +numeric.maxVS(vector, 2); // $ExpectType number[] +numeric.maxeq(vector, 3); // $ExpectType number[] +numeric.maxeqV(vector, vector); // $ExpectType number[] +numeric.maxeqS(vector, 3); // $ExpectType number[] + +numeric.min(2, 5, 6); // $ExpectType number +numeric.min(2, 3, vector); // $ExpectType number[] +numeric.min(threeDimensionalMatrix, 2, threeDimensionalMatrix); // $ExpectType number[][][] +numeric.minVV(vector, vector); // $ExpectType number[] +numeric.minSV(2, vector); // $ExpectType number[] +numeric.minVS(vector, 2); // $ExpectType number[] +numeric.mineq(vector, 3); // $ExpectType number[] +numeric.mineqV(vector, vector); // $ExpectType number[] +numeric.mineqS(vector, 3); // $ExpectType number[] + +numeric.any(23); // $ExpectType boolean +numeric.anyV(vector); // $ExpectType boolean + +numeric.all(23); // $ExpectType boolean +numeric.allV(vector); // $ExpectType boolean + +numeric.sum(threeDimensionalMatrix); // $ExpectType number +numeric.sumV(vector); // $ExceptType number + +numeric.prod(threeDimensionalMatrix); // $ExpectType number +numeric.prodV(vector); // $ExceptType number + +numeric.norm2Squared(threeDimensionalMatrix); // $ExpectType number +numeric.norm2SquaredV(vector); // $ExceptType number + +numeric.norminf(threeDimensionalMatrix); // $ExpectType number +numeric.norminfV(vector); // $ExceptType number + +numeric.norm1(threeDimensionalMatrix); // $ExpectType number +numeric.norm1V(vector); // $ExceptType number + +numeric.sup(threeDimensionalMatrix); // $ExpectType number +numeric.supV(vector); // $ExceptType number + +numeric.inf(threeDimensionalMatrix); // $ExpectType number +numeric.infV(vector); // $ExceptType number + +numeric.trunc(vector, 3); // $ExpectType number[] +numeric.truncVV(vector, vector); // $ExpectType number[] +numeric.truncVS(vector, 4); // $ExpectType number[] +numeric.truncSV(3, vector); // $ExpectType number[] + +numeric.inv(matrix); // $ExpectType number[][] +numeric.det(matrix); // $ExpectType number +numeric.transpose(matrix); // $ExpectType number[][] +numeric.negtranspose(matrix); // $ExpectType number[][] +numeric.random(vector); // $ExpectType NonScalar +numeric.norm2(threeDimensionalMatrix); // $ExpectType number +numeric.linspace(1, 3, 5); // $ExpectType number[] +numeric.getBlock(threeDimensionalMatrix, vector, vector); // $ExpectType number[][][] +const block: number[][][] = numeric.setBlock( + threeDimensionalMatrix, + vector, + vector, + threeDimensionalMatrix +); +numeric.blockMatrix(matrix); // $ExpectType number[][] +numeric.tensor(3, 5); // $ExpectType number +numeric.tensor(vector, vector); // $ExpectType number[][] + +const tensor = numeric.t(vector, vector); +tensor + .add(tensor) + .sub(tensor) + .mul(tensor) + .reciprocal() + .div(tensor) + .dot(tensor) + .transpose() + .transjugate() + .exp() + .conj() + .neg() + .sin() + .cos() + .abs() + .log() + .norm2() + .inv() + .get(vector) + .set(vector, tensor) + .getRow(2) + .setRow(2, tensor) + .getRows(10, 10) + .setRows(10, 10, tensor) + .getBlock(vector, vector) + .setBlock(vector, vector, tensor) + .rep(vector, tensor) + .diag(tensor) + .identity(3) + .getDiag() + .fft() + .ifft() + .eig(); + +numeric.house(vector); // $ExpectType number[] +numeric.toUpperHessenberg(matrix); // $ExpectType { H: number[][]; Q: number[][]; } +numeric.QRFrancis(matrix, 25); // $ExpectType { Q: number[][]; B: number[][]; } +numeric.eig(matrix); // $ExpectType { lambda: Tensor; E: Tensor; } + +numeric.ccsSparse(matrix); // $ExpectType [number[], number[], number[]] +numeric.ccsFull(sparseMatrix); // $ExpectType number[][] +numeric.ccsTSolve(sparseMatrix, vector, vector, vector, vector); // $ExpectType number[] +numeric.ccsDot(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +const lup = numeric.ccsLUP(sparseMatrix, 4); +numeric.ccsDim(sparseMatrix); // $ExpectType number[] +numeric.ccsGetBlock(sparseMatrix, vector, 3); // $ExpectType [number[], number[], number[]] +numeric.ccsLUPSolve(lup, sparseMatrix); // $ExpectType number[] +numeric.ccsScatter(sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsGather(sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsadd(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsadd(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsaddMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccssub(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccssub(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccssubMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsmul(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsmul(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsmulMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsdiv(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsdiv(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsdivMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsmod(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsmod(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsmodMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsand(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsand(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsandMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsor(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsor(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsorMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccseq(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccseq(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccseqMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] + +numeric.ccsneq(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccsneq(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccsneqMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] + +numeric.ccslt(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccslt(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccsltMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] + +numeric.ccsgt(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccsgt(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccsgtMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] + +numeric.ccsleq(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccsleq(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccsleqMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] + +numeric.ccsgeq(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccsgeq(2, sparseMatrix); // $ExpectType [number[], number[], boolean[]] +numeric.ccsgeqMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], boolean[]] + +numeric.ccsband(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsband(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsbandMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsbor(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsbor(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsborMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsbxor(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsbxor(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsbxorMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccslshift(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccslshift(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccslshiftMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsrshift(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsrshift(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsrshiftMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +numeric.ccsrrshift(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsrrshift(2, sparseMatrix); // $ExpectType [number[], number[], number[]] +numeric.ccsrrshiftMM(sparseMatrix, sparseMatrix); // $ExpectType [number[], number[], number[]] + +const lu = numeric.cLU(matrix); +numeric.cLUSolve(lu, vector); // $ExpectType number[] +numeric.cgrid(2, "L"); // $ExpectType number[][] +numeric.cdelsq(matrix); // $ExpectType number[][] +numeric.cdotmv(matrix, vector); // $ExpectType number[] + +const spline = numeric.spline(vector, matrix, "periodic", 3); +spline.diff().roots(); // $ExpectType number[] +spline.at(vector); // $ExpectType number | number[] + +numeric.uncmin((x: number[]) => 23, vector, 2, null, 3, () => undefined, { + Hinv: matrix +}); +numeric.gradient((x: number[]) => 44, vector); // $ExpectType number[] + +const dopri = numeric.dopri( + 1, + 1, + 1, + (x = 23, y = 44) => 44, + 2, + 3, + (x = 23, y = 44) => 44 +); +dopri.at(vector); // $ExpectType number[] | number[][] + +numeric.echelonize(matrix); // $ExpectType { I: number[][]; A: number[][]; P: number[]; } +numeric.solveLP(vector, matrix, vector, matrix, matrix, 3, 4); // $ExpectType { solution: number | number[]; message: string; iterations: number; } + +numeric.solveQP(matrix, vector, matrix, vector, 3, 44); // $ExpectType { solution: number[]; value: number[]; unconstrained_solution: number[]; iterations: number[]; iact: number[]; message: string; } + +numeric.svd(matrix); // $ExpectType { U: number[][]; S: number[]; V: number[][]; } diff --git a/types/numeric/tsconfig.json b/types/numeric/tsconfig.json new file mode 100644 index 0000000000..797af40d6b --- /dev/null +++ b/types/numeric/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "numeric-tests.ts" + ] +} diff --git a/types/numeric/tslint.json b/types/numeric/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/numeric/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/object-keys-mapping/index.d.ts b/types/object-keys-mapping/index.d.ts new file mode 100644 index 0000000000..f40ca48769 --- /dev/null +++ b/types/object-keys-mapping/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for object-keys-mapping 3.0 +// Project: https://github.com/coderhaoxin/object-keys-mapping#readme +// Definitions by: newraina +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export function trim(origin: object, ignore?: (v: any) => boolean): object; +export function trim(origin: ReadonlyArray, ignore?: (v: any) => boolean): object[]; + +export function toCamelcase(origin: object): object; +export function toCamelcase(origin: ReadonlyArray): object[]; + +export function reverseCamelcase(origin: object): object; +export function reverseCamelcase(origin: ReadonlyArray): object[]; + +export interface OperatorOptions { + camelcase?: boolean; + mapping?: object; +} + +export class Operator { + constructor(opts?: { camelcase?: boolean }); + + map(origin: object): object; + map(origin: ReadonlyArray): object[]; + + mapField(path: string): string; + + mapObject(origin: object, path: string): object; + + mapArray(origin: ReadonlyArray): object[]; +} diff --git a/types/object-keys-mapping/object-keys-mapping-tests.ts b/types/object-keys-mapping/object-keys-mapping-tests.ts new file mode 100644 index 0000000000..2235b1a48f --- /dev/null +++ b/types/object-keys-mapping/object-keys-mapping-tests.ts @@ -0,0 +1,11 @@ +import { trim, toCamelcase, reverseCamelcase, Operator } from 'object-keys-mapping'; + +trim({ name: '' }); + +toCamelcase({ will_be_camelcase: '' }); + +reverseCamelcase({ willBeUnderlined: '' }); + +const operator = new Operator({ camelcase: true }); + +operator.map({}); diff --git a/types/object-keys-mapping/tsconfig.json b/types/object-keys-mapping/tsconfig.json new file mode 100644 index 0000000000..398625df1d --- /dev/null +++ b/types/object-keys-mapping/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", + "object-keys-mapping-tests.ts" + ] +} diff --git a/types/object-keys-mapping/tslint.json b/types/object-keys-mapping/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/object-keys-mapping/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 024a72f6e9..3383d70350 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -639,10 +639,6 @@ declare namespace Office { *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
*/ interface Context { - /** - * Provides information and access to the signed-in user. - */ - auth: Auth; /** * True, if the current platform allows the add-in to display a UI for selling or upgrading; otherwise returns False. * @@ -1131,60 +1127,6 @@ declare namespace Office { */ asyncContext?: any } - /** - * The Office Auth namespace, Office.context.auth, provides a method that allows the Office host to obtain an access token to the add-in's web application. - * Indirectly, this also enables the add-in to access the signed-in user's Microsoft Graph data without requiring the user to sign in a second time. - * - * @beta - */ - interface Auth { - /** - * Calls the Azure Active Directory V 2.0 endpoint to get an access token to your add-in's web application. Enables add-ins to identify users. - * Server side code can use this token to access Microsoft Graph for the add-in's web application by using the - * {@link https://docs.microsoft.com/azure/active-directory/develop/active-directory-v2-protocols-oauth-on-behalf-of | "on behalf of" OAuth flow}. - * - * Important: In Outlook, this API is not supported if the add-in is loaded in an Outlook.com or Gmail mailbox. - * - * @remarks - * - * - *
HostsExcel, OneNote, Outlook, PowerPoint, Word
Requirement sets{@link https://docs.microsoft.com/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements | IdentityAPI}
- * - * @param options - Optional. Accepts an AuthOptions object to define sign-on behaviors. - * @param callback - Optional. Accepts a callback method that can parse the token for the user's ID or use the token in the "on behalf of" flow to get access to Microsoft Graph. - * If AsyncResult.status is "succeeded", then AsyncResult.value is the raw AAD v. 2.0-formatted access token. - * - * @beta - */ - getAccessTokenAsync(options?: AuthOptions, callback?: (result: AsyncResult) => void): void; - - } - /** - * Provides options for the user experience when Office obtains an access token to the add-in from AAD v. 2.0 with the getAccessTokenAsync method. - */ - interface AuthOptions { - /** - * Causes Office to display the add-in consent experience. Useful if the add-in's Azure permissions have changed or if the user's consent has - * been revoked. - */ - forceConsent?: boolean, - /** - * Prompts the user to add their Office account (or to switch to it, if it is already added). - */ - forceAddAccount?: boolean, - /** - * Causes Office to prompt the user to provide the additional factor when the tenancy being targeted by Microsoft Graph requires multifactor - * authentication. The string value identifies the type of additional factor that is required. In most cases, you won't know at development - * time whether the user's tenant requires an additional factor or what the string should be. So this option would be used in a "second try" - * call of getAccessTokenAsync after Microsoft Graph has sent an error requesting the additional factor and containing the string that should - * be used with the authChallenge option. - */ - authChallenge?: 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. - */ - asyncContext?: any - } /** * Provides an option for preserving context data of any type, unchanged, for use in a callback. */ @@ -1875,7 +1817,7 @@ declare namespace Office { */ ActiveViewChanged, /** - * Triggers when the appointment date or time of the selected series was changed in Outlook. + * Triggers when the appointment date or time of the selected series is changed in Outlook. * * [Api set: Mailbox Preview] * @@ -1934,11 +1876,11 @@ declare namespace Office { */ DialogMessageReceived, /** - * Triggers when Dialog has a event, such as dialog closed, dialog navigation failed. + * Triggers when Dialog has an event, such as dialog closed or dialog navigation failed. */ DialogEventReceived, /** - * Triggers when a document level selection happens + * Triggers when a document-level selection happens. * * **Support details** * @@ -1957,25 +1899,33 @@ declare namespace Office { */ DocumentSelectionChanged, /** - * Triggers when the selected Outlook item was changed. + * Triggers when the selected Outlook item is changed. * * [Api set: Mailbox 1.1] */ ItemChanged, /** - * Triggers when a customXmlPart node was deleted. + * Triggers when a customXmlPart node is deleted. */ NodeDeleted, /** - * Triggers when a customXmlPart node was inserted. + * Triggers when a customXmlPart node is inserted. */ NodeInserted, /** - * Triggers when a customXmlPart node was replaced. + * Triggers when a customXmlPart node is replaced. */ NodeReplaced, /** - * Triggers when the recipient list of the selected item was changed in Outlook. + * Triggers when the OfficeTheme is changed in Outlook. + * + * [Api set: Mailbox Preview] + * + * @beta + */ + OfficeThemeChanged, + /** + * Triggers when the recipient list of the selected item is changed in Outlook. * * [Api set: Mailbox Preview] * @@ -1983,7 +1933,7 @@ declare namespace Office { */ RecipientsChanged, /** - * Triggers when the recurrence pattern of the selected series was changed in Outlook. + * Triggers when the recurrence pattern of the selected series is changed in Outlook. * * [Api set: Mailbox Preview] * @@ -11346,6 +11296,36 @@ declare namespace Office { * @beta */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; + + /** + * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. + * + * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * for Office 365. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee
+ * + * In addition to this signature, the method also has the following signature: + * + * `getInitializationContextAsync(callback?: (result: AsyncResult) => void): void;` + * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property + * set to 9020 and its name property set to GenericResponseError. + * + * @beta + */ + getInitializationContextAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Asynchronously loads custom properties for this add-in on the selected item. @@ -14752,9 +14732,7 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the only supported event type is Office.EventType.ItemChanged, which is invoked when the user selects a new item. - * This event is used by add-ins that implement a pinnable taskpane, and allows the add-in to refresh the taskpane UI based on the currently - * selected item. + * Currently, the supported event types are `Office.EventType.ItemChanged` and `Office.EventType.OfficeThemeChanged`. * * [Api set: Mailbox 1.5] * @@ -16887,11 +16865,11 @@ declare namespace OfficeExtension { */ interface LoadOption { /** - * A comma-delimited string, or array of strings, that specifies the properties/relationships to load. + * A comma-delimited string, or array of strings, that specifies the properties to load. */ select?: string | string[]; /** - * A comma-delimited string, or array of strings, that specifies the relationships to load. + * A comma-delimited string, or array of strings, that specifies the navigation properties to load. */ expand?: string | string[]; /** @@ -16958,7 +16936,7 @@ declare namespace OfficeExtension { * Queues up a command to load the specified properties of the object. You must call `context.sync()` before reading the properties. * * @param object The object whose properties are loaded. - * @param option A comma-delimited string, or array of strings, that specifies the properties/relationships to load, or an + * @param option A comma-delimited string, or array of strings, that specifies the properties to load, or an * {@link OfficeExtension.LoadOption} object. */ load(object: ClientObject, option?: string | string[] | LoadOption): void; @@ -17917,9 +17895,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Application` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Application` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Application` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Application` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Application` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -18073,9 +18051,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Workbook` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Workbook` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Workbook` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Workbook` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Workbook` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -18137,9 +18115,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.WorkbookProtection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.WorkbookProtection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.WorkbookProtection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.WorkbookProtection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.WorkbookProtection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -18158,6 +18136,9 @@ declare namespace Excel { * An Excel worksheet is a grid of cells. It can contain data, tables, charts, etc. * * [Api set: ExcelApi 1.1] + * + * @remarks + * Our {@link https://docs.microsoft.com/office/dev/add-ins/excel/excel-add-ins-worksheets | how-to guide on working with worksheets} has detailed walkthroughs and code samples. */ class Worksheet extends OfficeExtension.ClientObject { /** @@ -18403,9 +18384,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Worksheet` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Worksheet` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Worksheet` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Worksheet` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Worksheet` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -18532,9 +18513,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.WorksheetCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.WorksheetCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.WorksheetCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.WorksheetCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.WorksheetCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -18628,9 +18609,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.WorksheetProtection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.WorksheetProtection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.WorksheetProtection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.WorksheetProtection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.WorksheetProtection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -18815,6 +18796,9 @@ declare namespace Excel { * Range represents a set of one or more contiguous cells such as a cell, a row, a column, block of cells, etc. * * [Api set: ExcelApi 1.1] + * + * @remarks + * Our {@link https://docs.microsoft.com/office/dev/add-ins/excel/excel-add-ins-ranges | how-to guide on working with ranges} has detailed walkthroughs, images, and code samples. */ class Range extends OfficeExtension.ClientObject { /** @@ -19314,9 +19298,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Range` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Range` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Range` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Range` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Range` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -19508,9 +19492,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.RangeView` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.RangeView` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.RangeView` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.RangeView` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.RangeView` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -19556,9 +19540,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.RangeViewCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.RangeViewCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.RangeViewCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.RangeViewCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.RangeViewCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -19620,9 +19604,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.SettingCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.SettingCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.SettingCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.SettingCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.SettingCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -19694,9 +19678,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Setting` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Setting` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Setting` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Setting` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Setting` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -19775,9 +19759,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.NamedItemCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.NamedItemCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.NamedItemCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.NamedItemCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.NamedItemCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -19907,9 +19891,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.NamedItem` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.NamedItem` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.NamedItem` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.NamedItem` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.NamedItem` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -19951,9 +19935,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.NamedItemArrayValues` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.NamedItemArrayValues` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.NamedItemArrayValues` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.NamedItemArrayValues` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.NamedItemArrayValues` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -20023,9 +20007,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Binding` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Binding` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Binding` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Binding` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Binding` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -20182,9 +20166,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.BindingCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.BindingCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.BindingCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.BindingCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.BindingCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -20262,9 +20246,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.TableCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.TableCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.TableCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.TableCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.TableCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -20289,6 +20273,9 @@ declare namespace Excel { * Represents an Excel table. * * [Api set: ExcelApi 1.1] + * + * @remarks + * Our {@link https://docs.microsoft.com/office/dev/add-ins/excel/excel-add-ins-tables | how-to guide on working with tables} has detailed walkthroughs, images, and code samples. */ class Table extends OfficeExtension.ClientObject { /** @@ -20466,9 +20453,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Table` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Table` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Table` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Table` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Table` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -20568,9 +20555,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.TableColumnCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.TableColumnCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.TableColumnCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.TableColumnCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.TableColumnCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -20679,9 +20666,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.TableColumn` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.TableColumn` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.TableColumn` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.TableColumn` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.TableColumn` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -20759,9 +20746,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.TableRowCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.TableRowCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.TableRowCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.TableRowCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.TableRowCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -20833,9 +20820,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.TableRow` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.TableRow` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.TableRow` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.TableRow` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.TableRow` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -20983,9 +20970,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.RangeFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.RangeFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.RangeFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.RangeFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.RangeFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21041,9 +21028,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.FormatProtection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.FormatProtection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.FormatProtection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.FormatProtection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.FormatProtection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21099,9 +21086,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.RangeFill` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.RangeFill` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.RangeFill` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.RangeFill` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.RangeFill` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21171,9 +21158,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.RangeBorder` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.RangeBorder` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.RangeBorder` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.RangeBorder` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.RangeBorder` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21237,9 +21224,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.RangeBorderCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.RangeBorderCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.RangeBorderCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.RangeBorderCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.RangeBorderCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21320,9 +21307,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.RangeFont` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.RangeFont` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.RangeFont` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.RangeFont` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.RangeFont` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21416,9 +21403,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21434,6 +21421,9 @@ declare namespace Excel { * Represents a chart object in a workbook. * * [Api set: ExcelApi 1.1] + * + * @remarks + * Our {@link https://docs.microsoft.com/office/dev/add-ins/excel/excel-add-ins-charts | how-to guide on working with charts} has detailed walkthroughs, images, and code samples. */ class Chart extends OfficeExtension.ClientObject { /** @@ -21623,9 +21613,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Chart` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Chart` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Chart` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Chart` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Chart` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21688,9 +21678,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartAreaFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartAreaFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartAreaFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartAreaFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartAreaFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21753,9 +21743,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartSeriesCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartSeriesCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartSeriesCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartSeriesCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartSeriesCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -21942,9 +21932,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartSeries` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartSeries` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartSeries` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartSeries` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartSeries` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22000,9 +21990,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartSeriesFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartSeriesFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartSeriesFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartSeriesFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartSeriesFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22055,9 +22045,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartPointsCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartPointsCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartPointsCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartPointsCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartPointsCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22152,9 +22142,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartPoint` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartPoint` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartPoint` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartPoint` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartPoint` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22210,9 +22200,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartPointFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartPointFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartPointFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartPointFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartPointFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22295,9 +22285,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartAxes` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartAxes` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxes` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxes` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartAxes` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22567,9 +22557,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartAxis` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartAxis` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxis` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxis` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartAxis` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22625,9 +22615,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartAxisFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartAxisFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxisFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxisFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartAxisFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22690,9 +22680,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartAxisTitle` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartAxisTitle` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxisTitle` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxisTitle` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartAxisTitle` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22741,9 +22731,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartAxisTitleFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartAxisTitleFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxisTitleFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartAxisTitleFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartAxisTitleFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22848,9 +22838,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartDataLabels` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartDataLabels` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartDataLabels` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartDataLabels` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartDataLabels` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -22948,9 +22938,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartDataLabel` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartDataLabel` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartDataLabel` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartDataLabel` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartDataLabel` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23006,9 +22996,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartDataLabelFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartDataLabelFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartDataLabelFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartDataLabelFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartDataLabelFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23064,9 +23054,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartGridlines` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartGridlines` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartGridlines` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartGridlines` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartGridlines` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23115,9 +23105,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartGridlinesFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartGridlinesFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartGridlinesFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartGridlinesFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartGridlinesFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23229,9 +23219,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartLegend` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartLegend` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartLegend` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartLegend` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartLegend` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23280,9 +23270,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartLegendEntry` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartLegendEntry` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartLegendEntry` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartLegendEntry` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartLegendEntry` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23328,9 +23318,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartLegendEntryCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartLegendEntryCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartLegendEntryCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartLegendEntryCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartLegendEntryCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23383,9 +23373,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartLegendFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartLegendFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartLegendFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartLegendFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartLegendFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23537,9 +23527,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartTitle` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartTitle` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartTitle` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartTitle` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartTitle` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23588,9 +23578,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartFormatString` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartFormatString` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartFormatString` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartFormatString` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartFormatString` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23653,9 +23643,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartTitleFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartTitleFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartTitleFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartTitleFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartTitleFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23749,9 +23739,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartBorder` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartBorder` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartBorder` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartBorder` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartBorder` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23821,9 +23811,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartLineFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartLineFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartLineFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartLineFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartLineFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -23907,9 +23897,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartFont` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartFont` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartFont` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartFont` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartFont` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24000,9 +23990,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartTrendline` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartTrendline` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartTrendline` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartTrendline` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartTrendline` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24066,9 +24056,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartTrendlineCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartTrendlineCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartTrendlineCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartTrendlineCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartTrendlineCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24114,9 +24104,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ChartTrendlineFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ChartTrendlineFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ChartTrendlineFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ChartTrendlineFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ChartTrendlineFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24238,9 +24228,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.TableSort` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.TableSort` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.TableSort` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.TableSort` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.TableSort` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24453,9 +24443,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Filter` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Filter` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Filter` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Filter` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Filter` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24640,9 +24630,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.CustomXmlPartScopedCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.CustomXmlPartScopedCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.CustomXmlPartScopedCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.CustomXmlPartScopedCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.CustomXmlPartScopedCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24713,9 +24703,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.CustomXmlPartCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.CustomXmlPartCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.CustomXmlPartCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.CustomXmlPartCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.CustomXmlPartCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24777,9 +24767,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.CustomXmlPart` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.CustomXmlPart` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.CustomXmlPart` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.CustomXmlPart` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.CustomXmlPart` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24841,9 +24831,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.PivotTableCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.PivotTableCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.PivotTableCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.PivotTableCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.PivotTableCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -24859,6 +24849,9 @@ declare namespace Excel { * Represents an Excel PivotTable. * * [Api set: ExcelApi 1.3] + * + * @remarks + * Our {@link https://docs.microsoft.com/office/dev/add-ins/excel/excel-add-ins-pivottables | how-to guide on working with PivotTables} has detailed walkthroughs, images, and code samples. */ class PivotTable extends OfficeExtension.ClientObject { /** @@ -24910,9 +24903,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.PivotTable` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.PivotTable` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.PivotTable` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.PivotTable` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.PivotTable` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25038,9 +25031,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.DocumentProperties` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.DocumentProperties` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.DocumentProperties` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.DocumentProperties` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.DocumentProperties` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25110,9 +25103,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.CustomProperty` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.CustomProperty` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.CustomProperty` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.CustomProperty` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.CustomProperty` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25184,9 +25177,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.CustomPropertyCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.CustomPropertyCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.CustomPropertyCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.CustomPropertyCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.CustomPropertyCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25264,9 +25257,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalFormatCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalFormatCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalFormatCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalFormatCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalFormatCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25477,9 +25470,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25578,9 +25571,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.DataBarConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.DataBarConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.DataBarConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.DataBarConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.DataBarConditionalFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25644,9 +25637,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalDataBarPositiveFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalDataBarPositiveFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalDataBarPositiveFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalDataBarPositiveFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalDataBarPositiveFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25717,9 +25710,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalDataBarNegativeFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalDataBarNegativeFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalDataBarNegativeFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalDataBarNegativeFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalDataBarNegativeFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25797,9 +25790,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.CustomConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.CustomConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.CustomConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.CustomConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.CustomConditionalFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25862,9 +25855,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalFormatRule` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalFormatRule` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalFormatRule` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalFormatRule` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalFormatRule` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -25934,9 +25927,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.IconSetConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.IconSetConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.IconSetConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.IconSetConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.IconSetConditionalFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26028,9 +26021,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ColorScaleConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ColorScaleConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ColorScaleConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ColorScaleConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ColorScaleConditionalFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26144,9 +26137,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.TopBottomConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.TopBottomConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.TopBottomConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.TopBottomConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.TopBottomConditionalFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26224,9 +26217,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.PresetCriteriaConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.PresetCriteriaConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.PresetCriteriaConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.PresetCriteriaConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.PresetCriteriaConditionalFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26297,9 +26290,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.TextConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.TextConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.TextConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.TextConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.TextConditionalFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26377,9 +26370,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.CellValueConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.CellValueConditionalFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.CellValueConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.CellValueConditionalFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.CellValueConditionalFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26478,9 +26471,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalRangeFormat` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalRangeFormat` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeFormat` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeFormat` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalRangeFormat` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26564,9 +26557,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalRangeFont` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalRangeFont` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeFont` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeFont` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalRangeFont` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26622,9 +26615,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalRangeFill` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalRangeFill` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeFill` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeFill` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalRangeFill` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26687,9 +26680,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalRangeBorder` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalRangeBorder` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeBorder` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeBorder` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalRangeBorder` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26781,9 +26774,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.ConditionalRangeBorderCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.ConditionalRangeBorderCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeBorderCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.ConditionalRangeBorderCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.ConditionalRangeBorderCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -26976,9 +26969,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.Style` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.Style` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.Style` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.Style` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Style` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -27026,9 +27019,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Excel.StyleCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Excel.StyleCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Excel.StyleCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Excel.StyleCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.StyleCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -28353,9 +28346,9 @@ declare namespace Excel { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): FunctionResult` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): FunctionResult` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): FunctionResult` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): FunctionResult` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): FunctionResult` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -42669,9 +42662,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.Body` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.Body` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.Body` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.Body` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.Body` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -43180,9 +43173,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.ContentControl` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.ContentControl` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.ContentControl` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.ContentControl` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.ContentControl` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -43288,9 +43281,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.ContentControlCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.ContentControlCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.ContentControlCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.ContentControlCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.ContentControlCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -43365,9 +43358,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.CustomProperty` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.CustomProperty` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.CustomProperty` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.CustomProperty` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.CustomProperty` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -43447,9 +43440,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.CustomPropertyCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.CustomPropertyCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.CustomPropertyCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.CustomPropertyCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.CustomPropertyCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -43545,9 +43538,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.Document` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.Document` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.Document` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.Document` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.Document` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -43646,9 +43639,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.DocumentCreated` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.DocumentCreated` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.DocumentCreated` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.DocumentCreated` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.DocumentCreated` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -43824,9 +43817,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.DocumentProperties` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.DocumentProperties` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.DocumentProperties` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.DocumentProperties` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.DocumentProperties` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -43953,9 +43946,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.Font` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.Font` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.Font` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.Font` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.Font` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -44307,9 +44300,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.InlinePicture` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.InlinePicture` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.InlinePicture` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.InlinePicture` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.InlinePicture` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -44361,9 +44354,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.InlinePictureCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.InlinePictureCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.InlinePictureCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.InlinePictureCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.InlinePictureCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -44549,9 +44542,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.List` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.List` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.List` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.List` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.List` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -44630,9 +44623,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.ListCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.ListCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.ListCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.ListCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.ListCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -44727,9 +44720,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.ListItem` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.ListItem` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.ListItem` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.ListItem` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.ListItem` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -45315,9 +45308,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.Paragraph` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.Paragraph` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.Paragraph` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.Paragraph` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.Paragraph` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -45383,9 +45376,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.ParagraphCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.ParagraphCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.ParagraphCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.ParagraphCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.ParagraphCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -45905,9 +45898,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.Range` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.Range` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.Range` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.Range` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.Range` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -45959,9 +45952,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.RangeCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.RangeCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.RangeCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.RangeCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.RangeCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -46058,9 +46051,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.SearchOptions` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.SearchOptions` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.SearchOptions` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.SearchOptions` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.SearchOptions` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -46163,9 +46156,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.Section` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.Section` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.Section` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.Section` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.Section` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -46217,9 +46210,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.SectionCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.SectionCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.SectionCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.SectionCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.SectionCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -46770,9 +46763,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.Table` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.Table` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.Table` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.Table` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.Table` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -46824,9 +46817,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.TableCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.TableCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.TableCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.TableCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.TableCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -47092,9 +47085,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.TableRow` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.TableRow` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.TableRow` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.TableRow` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.TableRow` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -47146,9 +47139,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.TableRowCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.TableRowCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.TableRowCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.TableRowCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.TableRowCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -47400,9 +47393,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.TableCell` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.TableCell` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.TableCell` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.TableCell` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.TableCell` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -47454,9 +47447,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.TableCellCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.TableCellCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.TableCellCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.TableCellCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.TableCellCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -47524,9 +47517,9 @@ declare namespace Word { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Word.TableBorder` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Word.TableBorder` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Word.TableBorder` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Word.TableBorder` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Word.TableBorder` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -53424,9 +53417,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.Application` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.Application` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.Application` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.Application` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Application` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -53482,9 +53475,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkAnalysis` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkAnalysis` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysis` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysis` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysis` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -53555,9 +53548,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkAnalysisParagraph` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkAnalysisParagraph` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisParagraph` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisParagraph` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisParagraph` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -53620,9 +53613,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkAnalysisParagraphCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkAnalysisParagraphCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisParagraphCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisParagraphCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisParagraphCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -53690,9 +53683,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkAnalysisLine` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkAnalysisLine` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisLine` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisLine` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisLine` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -53755,9 +53748,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkAnalysisLineCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkAnalysisLineCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisLineCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisLineCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisLineCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -53839,9 +53832,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkAnalysisWord` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkAnalysisWord` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisWord` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisWord` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisWord` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -53904,9 +53897,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkAnalysisWordCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkAnalysisWordCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisWordCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkAnalysisWordCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkAnalysisWordCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -53960,9 +53953,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.FloatingInk` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.FloatingInk` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.FloatingInk` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.FloatingInk` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.FloatingInk` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54012,9 +54005,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkStroke` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkStroke` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkStroke` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkStroke` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkStroke` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54077,9 +54070,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkStrokeCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkStrokeCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkStrokeCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkStrokeCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkStrokeCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54140,9 +54133,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkWord` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkWord` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkWord` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkWord` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkWord` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54205,9 +54198,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.InkWordCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.InkWordCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.InkWordCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.InkWordCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.InkWordCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54314,9 +54307,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.Notebook` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.Notebook` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.Notebook` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.Notebook` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Notebook` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54388,9 +54381,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.NotebookCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.NotebookCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.NotebookCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.NotebookCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.NotebookCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54504,9 +54497,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.SectionGroup` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.SectionGroup` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.SectionGroup` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.SectionGroup` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.SectionGroup` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54578,9 +54571,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.SectionGroupCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.SectionGroupCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.SectionGroupCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.SectionGroupCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.SectionGroupCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54737,9 +54730,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.Section` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.Section` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.Section` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.Section` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Section` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -54811,9 +54804,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.SectionCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.SectionCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.SectionCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.SectionCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.SectionCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55000,9 +54993,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.Page` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.Page` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.Page` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.Page` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Page` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55074,9 +55067,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.PageCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.PageCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.PageCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.PageCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.PageCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55186,9 +55179,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.PageContent` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.PageContent` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.PageContent` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.PageContent` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.PageContent` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55251,9 +55244,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.PageContentCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.PageContentCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.PageContentCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.PageContentCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.PageContentCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55354,9 +55347,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.Outline` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.Outline` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.Outline` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.Outline` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Outline` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55612,9 +55605,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.Paragraph` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.Paragraph` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.Paragraph` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.Paragraph` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Paragraph` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55677,9 +55670,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.ParagraphCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.ParagraphCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.ParagraphCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.ParagraphCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.ParagraphCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55733,9 +55726,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.NoteTag` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.NoteTag` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.NoteTag` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.NoteTag` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.NoteTag` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55807,9 +55800,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.RichText` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.RichText` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.RichText` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.RichText` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.RichText` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -55923,9 +55916,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.Image` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.Image` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.Image` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.Image` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Image` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -56080,9 +56073,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.Table` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.Table` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.Table` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.Table` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.Table` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -56188,9 +56181,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.TableRow` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.TableRow` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.TableRow` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.TableRow` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.TableRow` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -56253,9 +56246,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.TableRowCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.TableRowCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.TableRowCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.TableRowCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.TableRowCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -56391,9 +56384,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.TableCell` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.TableCell` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.TableCell` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.TableCell` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.TableCell` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -56456,9 +56449,9 @@ declare namespace OneNote { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): OneNote.TableCellCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): OneNote.TableCellCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): OneNote.TableCellCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): OneNote.TableCellCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): OneNote.TableCellCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -59752,9 +59745,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.Application` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.Application` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.Application` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.Application` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Application` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -59840,9 +59833,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.Document` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.Document` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.Document` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.Document` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Document` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -59966,9 +59959,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.DocumentView` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.DocumentView` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.DocumentView` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.DocumentView` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.DocumentView` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60080,9 +60073,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.Page` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.Page` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.Page` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.Page` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Page` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60179,9 +60172,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.PageView` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.PageView` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.PageView` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.PageView` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.PageView` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60227,9 +60220,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.PageCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.PageCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.PageCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.PageCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.PageCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60272,9 +60265,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.ShapeCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.ShapeCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.ShapeCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.ShapeCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.ShapeCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60383,9 +60376,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.Shape` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.Shape` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.Shape` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.Shape` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Shape` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60471,9 +60464,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.ShapeView` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.ShapeView` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.ShapeView` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.ShapeView` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.ShapeView` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60599,9 +60592,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.ShapeDataItemCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.ShapeDataItemCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.ShapeDataItemCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.ShapeDataItemCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.ShapeDataItemCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60654,9 +60647,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.ShapeDataItem` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.ShapeDataItem` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.ShapeDataItem` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.ShapeDataItem` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.ShapeDataItem` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60702,9 +60695,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.HyperlinkCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.HyperlinkCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.HyperlinkCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.HyperlinkCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.HyperlinkCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60757,9 +60750,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.Hyperlink` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.Hyperlink` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.Hyperlink` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.Hyperlink` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Hyperlink` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60805,9 +60798,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.CommentCollection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.CommentCollection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.CommentCollection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.CommentCollection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.CommentCollection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60867,9 +60860,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.Comment` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.Comment` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.Comment` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.Comment` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Comment` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * @@ -60904,9 +60897,9 @@ declare namespace Visio { * * In addition to this signature, this method has the following signatures: * - * `load(option?: string | string[]): Visio.Selection` - Where option is a comma-delimited string or an array of strings that specify the properties/relationships to load. + * `load(option?: string | string[]): Visio.Selection` - Where option is a comma-delimited string or an array of strings that specify the properties to load. * - * `load(option?: { select?: string; expand?: string; }): Visio.Selection` - Where option.select is a comma-delimited string that specifies the properties/relationships to load, and options.expand is a comma-delimited string that specifies the relationships to load. + * `load(option?: { select?: string; expand?: string; }): Visio.Selection` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. * * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Visio.Selection` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. * diff --git a/types/office-js/office-js-tests.ts b/types/office-js/office-js-tests.ts index 43249712e1..f04f19fe34 100644 --- a/types/office-js/office-js-tests.ts +++ b/types/office-js/office-js-tests.ts @@ -250,22 +250,6 @@ function test_word() { } -function test_shared() { - Office.context.auth.getAccessTokenAsync({ forceConsent: false }, - function (result) { - if (result.status === Office.AsyncResultStatus.Succeeded) { - // result.value is the raw access token - console.log(result.value) - } - else { - console.log("Code: " + result.error.code); - console.log("Message: " + result.error.message); - console.log("name: " + result.error.name); - } - } - ); -} - async function test_visio() { const url = "someurl"; diff --git a/types/ontime/index.d.ts b/types/ontime/index.d.ts new file mode 100644 index 0000000000..6af9872e06 --- /dev/null +++ b/types/ontime/index.d.ts @@ -0,0 +1,83 @@ +// Type definitions for ontime 0.0 +// Project: http://code.woong.org/ontime +// Definitions by: Jan Pilzer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface OntimeSchedule { + /** + * ontime determines the cycle of a job based on the format of time expressions. The time expression basically has + * the form of an ISO-8601 Date Format, YYYY-MM-DDThh:mm:ss where YYYY indicates a year, MM a month, DD a day of the + * month, hh an hour, mm a minute and ss a second, except that: + * + * * A unit can be omitted only when units greater than that are also omitted, which means the day part(DD) cannot be + * omitted unless the year and month parts(YYYY-MM-) are. This makes ontime's time expression differ from the + * original ISO-8601 format because the later allows smaller units to be omitted in times. For example, 12 and 12:00 + * denote hh and hh:mm respectively in the ISO-8601 format while ss and mm:ss respectively in the ontime's format; + * * A space can be used to separate the time part from the date part instead of T as in 2010-01-09 11:00:00; + * * and ontime allows digits not to be zero-padded; for example, it accepts 2014-5-4T0:0:0 as well as + * 2014-05-04T00:00:00 + * + * The time expression is given to ontime through the cycle option. You can give a single expression of the string + * type like '01-01T12:00:00' or multiple ones as an array of strings like [ '01-01T12:00:00', '7-1T0:0:0' ] + */ + cycle: string | string[]; + + /** + * It is sometimes necessary to run a job on the last day of each month, which have been replaced with doing it on + * the first day of each month instead. By setting the keepLast option to true, ontime automatically adjusts the + * date part(DD) to the last day according to the value of the month part(MM) if necessary. + * + * Default: false + */ + keepLast?: boolean; + + /** + * The step option enables a job to be skipped periodically.Setting it to n forces ontime to skip a given job n-1 + * times after a run, which leads to launching the job eveny n cycles. + * + * Default: 1 + */ + step?: number; + + /** + * Setting the utc option to true changes ontime to interpret the time expressions as UTC. + * + * Default: false + */ + utc?: boolean; + + /** + * ontime launches a job on its scheduled time. If the job takes longer than the time interval of the cycle, more + * than one instance of the job may run at the same time. The single option keeps another instance of a job from + * starting if there is already a running one. + * + * Default: false + */ + single?: boolean; + + /** + * ontime has a very simple form of logging that is useful when checking if your configuration works as intended. + * It can be turned on by setting the log option to true. + * + * Default: false + */ + log?: boolean; +} + +export interface OntimeReport { + /** + * Should be called after the job has been finished. + * This is important especially when single is set to true because scheduling the next run is done in the method. + */ + done(): void; + + /** + * Clears timers for scheduling jobs that the ontime instance knows. + * This does not terminate the current execution of a job; you still need to call ot.done() for that purpose. + */ + cancel(): void; +} + +export type OntimeJob = (ot: OntimeReport) => void; + +export function ontime(sched: OntimeSchedule, job: OntimeJob): void; diff --git a/types/ontime/ontime-tests.ts b/types/ontime/ontime-tests.ts new file mode 100644 index 0000000000..4b9db88973 --- /dev/null +++ b/types/ontime/ontime-tests.ts @@ -0,0 +1,37 @@ +import { ontime } from "ontime"; + +ontime({ + cycle: ['04:30:00', '9:00:00'] +}, (ot) => { + ot.done(); +}); + +ontime({ + cycle: '2-9T00:00:00' +}, (ot) => { + ot.done(); +}); + +ontime({ + cycle: '31T00:00:00', + keepLast: true, + step: 3 +}, (ot) => { + ot.done(); +}); + +ontime({ + cycle: '31T00:00:00', + single: false +}, (ot) => { + ot.cancel(); + ot.done(); +}); + +ontime({ + cycle: '31T00:00:00', + utc: true, + log: true +}, (ot) => { + ot.done(); +}); diff --git a/types/ontime/tsconfig.json b/types/ontime/tsconfig.json new file mode 100644 index 0000000000..fd10fa5e88 --- /dev/null +++ b/types/ontime/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", + "ontime-tests.ts" + ] +} diff --git a/types/ontime/tslint.json b/types/ontime/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ontime/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-progress/index.d.ts b/types/p-progress/index.d.ts new file mode 100644 index 0000000000..8eb745683c --- /dev/null +++ b/types/p-progress/index.d.ts @@ -0,0 +1,175 @@ +// Type definitions for p-progress 0.2 +// Project: https://github.com/sindresorhus/p-progress#readme +// Definitions by: icopp +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +declare namespace pProgress { + interface Options { + /** + * Number of concurrently pending promises. + * + * To run the promises in series, set it to 1. + * + * When this option is set, the first argument must be an array of + * promise-returning functions. + * + * Minimum 1. + * + * @default {Infinity} + */ + concurrency?: number; + } +} + +type PromiseFactory = () => Promise | PromiseLike; + +declare class PProgress extends Promise { + /** + * The current progress percentage of the promise as a number between 0 and + * 1. + */ + progress: number; + + /** + * Convenience method to run multiple promises and get a total progress of + * all of them. It counts normal promises with progress `0` when pending and + * progress `1` when resolved. For PProgress type promises, it listens to + * their onProgress() method for more fine grained progress reporting. You + * can mix and match normal promises and PProgress promises. + * + * @param promises Array of promises or promise-returning functions. + * @throws {TypeError} + */ + static all( + promises: [ + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory + ], + options?: pProgress.Options + ): PProgress<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + static all( + promises: [ + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory + ], + options?: pProgress.Options + ): PProgress<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + static all( + promises: [ + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory + ], + options?: pProgress.Options + ): PProgress<[T1, T2, T3, T4, T5, T6, T7, T8]>; + static all( + promises: [ + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory + ], + options?: pProgress.Options + ): PProgress<[T1, T2, T3, T4, T5, T6, T7]>; + static all( + promises: [ + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory + ], + options?: pProgress.Options + ): PProgress<[T1, T2, T3, T4, T5, T6]>; + static all( + promises: [ + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory + ], + options?: pProgress.Options + ): PProgress<[T1, T2, T3, T4, T5]>; + static all( + promises: [ + PromiseFactory, + PromiseFactory, + PromiseFactory, + PromiseFactory + ], + options?: pProgress.Options + ): PProgress<[T1, T2, T3, T4]>; + static all( + promises: [PromiseFactory, PromiseFactory, PromiseFactory], + options?: pProgress.Options + ): PProgress<[T1, T2, T3]>; + static all( + promises: [PromiseFactory, PromiseFactory], + options?: pProgress.Options + ): PProgress<[T1, T2]>; + static all( + promises: [PromiseFactory], + options?: pProgress.Options + ): PProgress<[T1]>; + static all( + promises: Array>, + options?: pProgress.Options + ): PProgress; + + /** + * Same as the Promise constructor, but with an appended `progress` + * parameter in `executor`. + * + * @param progress + * Call this with progress updates. It expects a number between 0 and 1. + * + * Multiple calls with the same number will result in only one + * `onProgress()` event. + * + * Progress percentage `1` is reported for you when the promise resolves. + * If you set it yourself, it will simply be ignored. + */ + constructor( + executor: ( + resolve: (value?: T | PromiseLike) => void, + reject: (reason?: any) => void, + progress: (progress: number) => void + ) => void + ); + + /** + * Accepts a function that gets `instance.progress` as an argument and is + * called for every progress event. + * + * @throws {TypeError} + */ + onProgress(cb: (progress: number) => void): void; +} + +export = PProgress; diff --git a/types/p-progress/p-progress-tests.ts b/types/p-progress/p-progress-tests.ts new file mode 100644 index 0000000000..eb70dec355 --- /dev/null +++ b/types/p-progress/p-progress-tests.ts @@ -0,0 +1,31 @@ +import PProgress = require("p-progress"); + +new PProgress(async (resolve, reject, progress) => { + try { + await Promise.resolve("sindresorhus.com"); + progress(0.5); + + await Promise.resolve("ava.li"); + progress(1); + + resolve(); + } catch (e) { + reject(e); + } +}).onProgress(progress => { + progress; +}); + +PProgress.all( + [ + () => Promise.resolve("sindresorhus.com"), + () => Promise.resolve("ava.li"), + () => Promise.resolve(), + () => Promise.resolve(1) + ], + { concurrency: 2 } +).then(result => { + const str: string = result[0]; + const str2: string = result[1]; + const num: number = result[3]; +}); diff --git a/types/p-progress/tsconfig.json b/types/p-progress/tsconfig.json new file mode 100644 index 0000000000..1cd7ff1976 --- /dev/null +++ b/types/p-progress/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", + "p-progress-tests.ts" + ] +} diff --git a/types/p-progress/tslint.json b/types/p-progress/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-progress/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/page/index.d.ts b/types/page/index.d.ts index ef56afdc9b..afd42e0f43 100644 --- a/types/page/index.d.ts +++ b/types/page/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for page v1.5.0 +// Type definitions for page v1.8.6 // Project: http://visionmedia.github.io/page.js/ // Definitions by: Alan Norbauer // James Garbutt @@ -285,8 +285,8 @@ declare namespace PageJS { } declare module "page" { - var page: PageJS.Static; - export = page; + const page: PageJS.Static; + export default page; } declare var page: PageJS.Static; diff --git a/types/page/page-tests.ts b/types/page/page-tests.ts index 5d5b421d7e..cf22ecfc64 100644 --- a/types/page/page-tests.ts +++ b/types/page/page-tests.ts @@ -1,6 +1,4 @@ - - -import page = require("page"); +import page from 'page'; //*********************************************************************** // Basic Example diff --git a/types/parity-pmd/parity-pmd-tests.ts b/types/parity-pmd/parity-pmd-tests.ts index 3645e7598c..d538b5f353 100644 --- a/types/parity-pmd/parity-pmd-tests.ts +++ b/types/parity-pmd/parity-pmd-tests.ts @@ -22,6 +22,4 @@ format({}); // Invalid sub type // $ExpectError -format({ - messageType: 1 -}); +format({ messageType: 1 }); diff --git a/types/parity-pmr/parity-pmr-tests.ts b/types/parity-pmr/parity-pmr-tests.ts index 03bcc3534d..4fbb2b31b4 100644 --- a/types/parity-pmr/parity-pmr-tests.ts +++ b/types/parity-pmr/parity-pmr-tests.ts @@ -17,9 +17,7 @@ format({}); // Invalid sub type // $ExpectError -format({ - messageType: 1 -}); +format({ messageType: 1 }); // $ExpectType PMRMessage parse(buffer); diff --git a/types/parity-poe/parity-poe-tests.ts b/types/parity-poe/parity-poe-tests.ts index c5b50d5189..fb9c267572 100644 --- a/types/parity-poe/parity-poe-tests.ts +++ b/types/parity-poe/parity-poe-tests.ts @@ -21,9 +21,7 @@ formatInbound({}); // Invalid sub type // $ExpectError -formatInbound({ - messageType: 1 -}); +formatInbound({ messageType: 1 }); /** * parseInbound tests @@ -52,9 +50,7 @@ formatOutbound({}); // Invalid sub type // $ExpectError -formatOutbound({ - messageType: 1 -}); +formatOutbound({ messageType: 1 }); /** * parseOutbound tests diff --git a/types/parse5-html-rewriting-stream/index.d.ts b/types/parse5-html-rewriting-stream/index.d.ts new file mode 100644 index 0000000000..42e0ef9734 --- /dev/null +++ b/types/parse5-html-rewriting-stream/index.d.ts @@ -0,0 +1,80 @@ +// Type definitions for parse5-html-rewriting-stream 5.1 +// Project: https://github.com/inikulin/parse5/tree/master/packages/parse5-html-rewriting-stream +// Definitions by: Sam Li +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as parse5 from 'parse5-sax-parser'; +import * as stream from 'stream'; + +/** + * Streaming SAX-style HTML rewriter. A transform stream (which means you can + * pipe through it, see example). Rewriter uses raw source representation of + * tokens if they are not modified by the user, therefore resulting HTML is + * not affected by parser error-recovery mechanisms as in the classical + * parsing-serialization roundtrip. + */ +export default class RewritingStream extends stream.Transform { + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Raised when the rewriter encounters a start tag. + */ + on(type: 'startTag', + callback: (startTag: parse5.StartTagToken, rawHtml: string) => void): + this; + + /** + * Raised when rewriter encounters an end tag. + */ + on(type: 'endTag', + callback: (endTag: parse5.EndTagToken, rawHtml: string) => void): this; + + /** + * Raised when rewriter encounters a comment. + */ + on(type: 'comment', + callback: (comment: parse5.CommentToken, rawHtml: string) => void): this; + + /** + * Raised when rewriter encounters text content. + */ + on(type: 'text', + callback: (text: parse5.TextToken, rawHtml: string) => void): this; + + /** + * Raised when rewriter encounters a document type declaration. + */ + on(type: 'doctype', + callback: (doctype: parse5.DoctypeToken, rawHtml: string) => void): this; + + /** + * Emits serialized start tag token into the output stream. + */ + emitStartTag(startTag: parse5.StartTagToken): void; + + /** + * Emits serialized end tag token into the output stream. + */ + emitEndTag(endTag: parse5.EndTagToken): void; + + /** + * Emits serialized text token into the output stream. + */ + emitText(text: parse5.TextToken): void; + + /** + * Emits serialized comment token into the output stream. + */ + emitComment(text: parse5.CommentToken): void; + + /** + * Emits serialized document type token into the output stream. + */ + emitDoctype(text: parse5.DoctypeToken): void; + + /** + * Emits raw HTML string into the output stream. + */ + emitRaw(html: string): void; +} diff --git a/types/parse5-html-rewriting-stream/parse5-html-rewriting-stream-tests.ts b/types/parse5-html-rewriting-stream/parse5-html-rewriting-stream-tests.ts new file mode 100644 index 0000000000..f134e4807b --- /dev/null +++ b/types/parse5-html-rewriting-stream/parse5-html-rewriting-stream-tests.ts @@ -0,0 +1,10 @@ +import RewritingStream from 'parse5-html-rewriting-stream'; + +const rewritingStream = new RewritingStream(); +rewritingStream.on('startTag', (startTag, rawHtml) => { + startTag.tagName; // $ExpectType string + startTag.selfClosing; // $ExpectType boolean + rawHtml; // $ExpectType string + + rewritingStream.emitStartTag(startTag); // $ExpectType void +}); diff --git a/types/parse5-html-rewriting-stream/tsconfig.json b/types/parse5-html-rewriting-stream/tsconfig.json new file mode 100644 index 0000000000..604400ba20 --- /dev/null +++ b/types/parse5-html-rewriting-stream/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", + "parse5-html-rewriting-stream-tests.ts" + ] +} diff --git a/types/parse5-html-rewriting-stream/tslint.json b/types/parse5-html-rewriting-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/parse5-html-rewriting-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/passport-kakao/index.d.ts b/types/passport-kakao/index.d.ts index b005b45d98..dbb4c2f07b 100644 --- a/types/passport-kakao/index.d.ts +++ b/types/passport-kakao/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for passport-kakao 0.1 +// Type definitions for passport-kakao 0.2 // Project: https://github.com/rotoshine/passport-kakao // Definitions by: Park9eon +// ZeroCho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -24,11 +25,18 @@ export interface StrategyOption { customHeaders?: string; } +export interface StrategyOptionWithRequest extends StrategyOption { + passReqToCallback: boolean; +} + export type VerifyFunction = (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; +export type VerifyFunctionWithRequest = + (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; export class Strategy extends passport.Strategy { constructor(options: StrategyOption, verify: VerifyFunction); + constructor(options: StrategyOptionWithRequest, verify: VerifyFunctionWithRequest); authenticate(req: express.Request, options?: any): void; userProfile: (accessToken: string, done: (error: any, user?: any) => void) => void; diff --git a/types/passport-kakao/passport-kakao-tests.ts b/types/passport-kakao/passport-kakao-tests.ts index 595404cc5b..5f104f6c41 100644 --- a/types/passport-kakao/passport-kakao-tests.ts +++ b/types/passport-kakao/passport-kakao-tests.ts @@ -1,10 +1,11 @@ -import {Strategy as KakaoStrategy } from 'passport-kakao'; +import { Strategy as KakaoStrategy } from 'passport-kakao'; new KakaoStrategy({ clientID: 'client', clientSecret: 'clientSecret', - callbackURL: 'callbackUrl' + callbackURL: 'callbackUrl', }, (accessToken: string, refreshToken: string, profile: any, done: any) => { // signUp or signIn - }); + }, +); diff --git a/types/passport-naver/index.d.ts b/types/passport-naver/index.d.ts index 8bd022cd21..1366a4b791 100644 --- a/types/passport-naver/index.d.ts +++ b/types/passport-naver/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for passport-naver 0.1 +// Type definitions for passport-naver 0.2 // Project: https://github.com/naver/passport-naver // Definitions by: Park9eon +// ZeroCho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -34,11 +35,16 @@ export interface StrategyOption { profileURL?: string; } -export type VerifyFunction = - (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; +export interface StrategyOptionWithRequest extends StrategyOption { + passReqToCallback: boolean; +} + +export type VerifyFunction = (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; +export type VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; export class Strategy extends passport.Strategy { constructor(options: StrategyOption, verify: VerifyFunction); + constructor(options: StrategyOptionWithRequest, verify: VerifyFunctionWithRequest); authenticate(req: express.Request, options?: any): void; authorizationParams: (options: any) => any; diff --git a/types/passport-naver/passport-naver-tests.ts b/types/passport-naver/passport-naver-tests.ts index 72e76d32e7..d2bfe26fc6 100644 --- a/types/passport-naver/passport-naver-tests.ts +++ b/types/passport-naver/passport-naver-tests.ts @@ -1,10 +1,11 @@ -import {Strategy as NaverStrategy } from 'passport-naver'; +import { Strategy as NaverStrategy } from 'passport-naver'; new NaverStrategy({ clientID: 'client', clientSecret: 'clientSecret', - callbackURL: 'callbackUrl' + callbackURL: 'callbackUrl', }, (accessToken: string, refreshToken: string, profile: any, done: any) => { // signUp or signIn - }); + }, +); diff --git a/types/passport-saml/index.d.ts b/types/passport-saml/index.d.ts index d9c86a9b23..cc2faafe5c 100644 --- a/types/passport-saml/index.d.ts +++ b/types/passport-saml/index.d.ts @@ -19,11 +19,11 @@ export interface CacheProvider { remove(key: string, callback: (err: Error | null, key: string) => void | null): void; } -export type VerifiedCallback = (err: Error | null, user: {}, info: {}) => void; +export type VerifiedCallback = (err: Error | null, user: object, info: object) => void; -export type VerifyWithRequest = (req: express.Request, profile: {}, done: VerifiedCallback) => void; +export type VerifyWithRequest = (req: express.Request, profile: object, done: VerifiedCallback) => void; -export type VerifyWithoutRequest = (profile: {}, done: VerifiedCallback) => void; +export type VerifyWithoutRequest = (profile: object, done: VerifiedCallback) => void; export class Strategy extends passport.Strategy { constructor(config: SamlConfig, verify: VerifyWithRequest | VerifyWithoutRequest); @@ -41,13 +41,13 @@ export interface SamlConfig { entryPoint: string; issuer: string; privateCert?: string; - cert?: {}; + cert?: string; decryptionPvk?: string; signatureAlgorithm?: 'sha1' | 'sha256' | 'sha512'; // Additional SAML behaviors - additionalParams?: {}; - additionalAuthorizeParams?: {}; + additionalParams?: any; + additionalAuthorizeParams?: any; identifierFormat?: string; acceptedClockSkewMs?: number; attributeConsumingServiceIndex?: string; @@ -68,12 +68,12 @@ export interface SamlConfig { // Logout logoutUrl?: string; - additionalLogoutParams?: {}; + additionalLogoutParams?: any; logoutCallbackUrl?: string; } export interface AuthenticateOptions extends passport.AuthenticateOptions { - additionalParams?: {}; + additionalParams?: object; } export interface AuthorizeOptions extends AuthenticateOptions { diff --git a/types/payment/index.d.ts b/types/payment/index.d.ts index fbd3f5ba65..7a1426e7d6 100644 --- a/types/payment/index.d.ts +++ b/types/payment/index.d.ts @@ -11,6 +11,10 @@ interface Fns { * * Validates length */ validateCardNumber(cardNumber: string): boolean; + /** + * Formats a card number + */ + formatCardNumber(cardNumber: string): string; /** * Validates a card expiry: * * Validates numbers diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index fa312dbb0f..8e6ae187e1 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -318,17 +318,21 @@ export interface Axis { export type Calendar = 'gregorian' | 'chinese' | 'coptic' | 'discworld' | 'ethiopian' | 'hebrew' | 'islamic' | 'julian' | 'mayan' | 'nanakshahi' | 'nepali' | 'persian' | 'jalali' | 'taiwan' | 'thai' | 'ummalqura'; +export type AxisName = + | 'x' | 'x2' | 'x3' | 'x4' | 'x5' | 'x6' | 'x7' | 'x8' | 'x9' + | 'y' | 'y2' | 'y3' | 'y4' | 'y5' | 'y6' | 'y7' | 'y8' | 'y9'; + export interface LayoutAxis extends Axis { fixedrange: boolean; - scaleanchor: '/^x([2-9]|[1-9][0-9]+)?$/' | '/^y([2-9]|[1-9][0-9]+)?$/'; + scaleanchor: AxisName; scaleratio: number; constrain: 'range' | 'domain'; constraintoward: 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom'; spikedash: string; spikemode: string; - anchor: 'free' | '/^x([2-9]|[1-9][0-9]+)?$/' | '/^y([2-9]|[1-9][0-9]+)?$/'; + anchor: 'free' | AxisName; side: 'top' | 'bottom' | 'left' | 'right'; - overlaying: 'free' | '/^x([2-9]|[1-9][0-9]+)?$/' | '/^y([2-9]|[1-9][0-9]+)?$/'; + overlaying: 'free' | AxisName; layer: 'above traces' | 'below traces'; domain: number[]; position: number; @@ -434,6 +438,25 @@ export interface ModeBarButton { export type Datum = string | number | Date | null; export type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array; +export interface ErrorOptions { + visible: boolean; + symmetric: boolean; + color: Color; + thickness: number; + width: number; + opacity: number; +} + +export type ErrorBar = Partial & ({ + type: 'constant' | 'percent', + value: number, + valueminus?: number +} | { + type: 'data', + array: Datum[], + arrayminus?: Datum[] +}); + export type Dash = 'solid' | 'dot' | 'dash' | 'longdash' | 'dashdot' | 'longdashdot'; export type Data = Partial; @@ -447,6 +470,8 @@ export interface PlotData { y: Datum[] | Datum[][] | TypedArray; z: Datum[] | Datum[][] | Datum[][][] | TypedArray; xy: Float32Array; + error_x: ErrorBar; + error_y: ErrorBar; xaxis: string; yaxis: string; text: string | string[]; diff --git a/types/plur/index.d.ts b/types/plur/index.d.ts new file mode 100644 index 0000000000..3f94e66fef --- /dev/null +++ b/types/plur/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for plur 3.0 +// Project: https://github.com/sindresorhus/plur#readme +// Definitions by: Kyle Roach +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function plur( + word: string, + plural: string | number, + count?: number +): string; + +export = plur; diff --git a/types/plur/plur-tests.ts b/types/plur/plur-tests.ts new file mode 100644 index 0000000000..be509830df --- /dev/null +++ b/types/plur/plur-tests.ts @@ -0,0 +1,5 @@ +import plur = require('plur'); + +const word = 'chicken'; + +plur(word, 2); diff --git a/types/plur/tsconfig.json b/types/plur/tsconfig.json new file mode 100644 index 0000000000..cb98c338e3 --- /dev/null +++ b/types/plur/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "plur-tests.ts"] +} diff --git a/types/plur/tslint.json b/types/plur/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/plur/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/prometheus-gc-stats/index.d.ts b/types/prometheus-gc-stats/index.d.ts new file mode 100644 index 0000000000..007cf28bed --- /dev/null +++ b/types/prometheus-gc-stats/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for prometheus-gc-stats 0.6 +// Project: https://github.com/SimenB/node-prometheus-gc-stats +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// register is typeof require('prom-client').Registry which has its own .d.ts +declare function gcStats(register: any): () => void; + +export = gcStats; diff --git a/types/prometheus-gc-stats/prometheus-gc-stats-tests.ts b/types/prometheus-gc-stats/prometheus-gc-stats-tests.ts new file mode 100644 index 0000000000..abc7542aa0 --- /dev/null +++ b/types/prometheus-gc-stats/prometheus-gc-stats-tests.ts @@ -0,0 +1,5 @@ +import gcStats = require('prometheus-gc-stats'); + +const testFunc = gcStats('something'); +// $ExpectType void +testFunc(); diff --git a/types/prometheus-gc-stats/tsconfig.json b/types/prometheus-gc-stats/tsconfig.json new file mode 100644 index 0000000000..1fcdb90ce8 --- /dev/null +++ b/types/prometheus-gc-stats/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prometheus-gc-stats-tests.ts" + ] +} diff --git a/types/prometheus-gc-stats/tslint.json b/types/prometheus-gc-stats/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/prometheus-gc-stats/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index a5e85f802e..e66ee97dfa 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -585,6 +585,11 @@ export interface ScreenshotOptions { * @default false */ omitBackground?: boolean; + /** + * The encoding of the image, can be either base64 or binary. Defaults to binary + * @default binary + */ + encoding?: "base64" | "binary"; } /** Options for `addStyleTag` */ @@ -1223,7 +1228,7 @@ export interface Page extends EventEmitter, FrameBase { bringToFront(): Promise; /** Get the browser the page belongs to. */ - browser(): Promise; + browser(): Browser; /** Closes the current page. */ close(options?: PageCloseOptions): Promise; @@ -1341,7 +1346,7 @@ export interface Page extends EventEmitter, FrameBase { * Captures a screenshot of the page. * @param options The screenshot options. */ - screenshot(options?: ScreenshotOptions): Promise; + screenshot(options?: ScreenshotOptions): Promise; /** * Triggers a `change` and `input` event once all the provided options have been selected. @@ -1647,6 +1652,35 @@ export interface LaunchOptions { * Useful so that you can see what is going on. */ slowMo?: number; + /** + * Sets a consistent viewport for each page. Defaults to an 800x600 viewport. null disables the default viewport. + */ + defaultViewport?: { + /** + * page width in pixels. + */ + width?: number; + /** + * page height in pixels. + */ + height?: number; + /** + * Specify device scale factor (can be thought of as dpr). Defaults to 1. + */ + deviceScaleFactor?: number; + /** + * Whether the meta viewport tag is taken into account. Defaults to false. + */ + isMobile?: boolean; + /** + * Specifies if viewport supports touch events. Defaults to false. + */ + hasTouch?: boolean; + /** + * Specifies if viewport is in landscape mode. Defaults to false. + */ + isLandscape?: boolean; + }; /** * Additional arguments to pass to the Chromium instance. List of Chromium * flags can be found here. diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index e883157fec..1e3d35737b 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -167,6 +167,7 @@ puppeteer.launch().then(async browser => { '--no-sandbox', '--disable-setuid-sandbox', ], + defaultViewport: { width: 800, height: 600 }, handleSIGINT: true, handleSIGHUP: true, handleSIGTERM: true, @@ -396,3 +397,14 @@ puppeteer.launch().then(async browser => { ); index; // $ExpectType number }); + +// Test screenshot with an encoding option +(async () => { + const browser = await puppeteer.launch(); + const page = await browser.newPage(); + await page.goto("https://example.com"); + const base64string: string = (await page.screenshot({ encoding: "base64" })) as string; + const buffer: Buffer = (await page.screenshot({ encoding: "binary" })) as Buffer; + + browser.close(); +})(); diff --git a/types/q/index.d.ts b/types/q/index.d.ts index bdcd3c68ca..7926965cf8 100644 --- a/types/q/index.d.ts +++ b/types/q/index.d.ts @@ -61,7 +61,7 @@ declare namespace Q { * The then method from the Promises/A+ specification, with an additional progress handler. */ then(onFulfill?: ((value: T) => IWhenable) | null, onReject?: ((error: any) => IWhenable) | null, onProgress?: ((progress: any) => any) | null): Promise; - + then(onFulfill?: ((value: T) => IWhenable) | null, onReject?: ((error: any) => IWhenable) | null, onProgress?: ((progress: any) => any) | null): Promise; /** * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so * without modifying the final value. This is useful for collecting resources regardless of whether a job succeeded, diff --git a/types/q/q-tests.ts b/types/q/q-tests.ts index 226d86ced8..62160614e4 100644 --- a/types/q/q-tests.ts +++ b/types/q/q-tests.ts @@ -245,6 +245,9 @@ Q.try(() => { }) .catch((error) => console.error("Couldn't sync to the cloud", error)); +// ensure Q.Promise is compatible with PromiseLike +const p7: PromiseLike = Q.Promise((resolve) => resolve()); + // thenReject, returning a Promise of the same type as the Promise it is called on function thenRejectSameType(arg: any): Q.Promise { if (!arg) { diff --git a/types/quill/index.d.ts b/types/quill/index.d.ts index 0eda9a4eff..d1fd85f4ba 100644 --- a/types/quill/index.d.ts +++ b/types/quill/index.d.ts @@ -186,7 +186,8 @@ export class Quill implements EventEmitter { blur(): void; focus(): void; getBounds(index: number, length?: number): BoundsStatic; - getSelection(focus?: boolean): RangeStatic; + getSelection(focus: true): RangeStatic; + getSelection(focus?: false): RangeStatic | null; hasFocus(): boolean; setSelection(index: number, length: number, source?: Sources): void; setSelection(range: RangeStatic, source?: Sources): void; diff --git a/types/qunit/index.d.ts b/types/qunit/index.d.ts index c5e677d187..120c61d667 100644 --- a/types/qunit/index.d.ts +++ b/types/qunit/index.d.ts @@ -7,14 +7,14 @@ interface Assert { /** * Instruct QUnit to wait for an asynchronous operation. - * + * * The callback returned from `assert.async()` will throw an Error if it is * invoked more than once (or more often than the accepted call count, if * provided). * * This replaces functionality previously provided by `QUnit.stop()` and * `QUnit.start()`. - * + * * @param {number} [acceptCallCount=1] Number of expected callbacks before the test is done. */ async(acceptCallCount?: number): () => void; @@ -22,179 +22,179 @@ interface Assert { /** * A deep recursive comparison, working on primitive types, arrays, objects, * regular expressions, dates and functions. - * + * * The `deepEqual()` assertion can be used just like `equal()` when comparing * the value of objects, such that `{ key: value }` is equal to * `{ key: value }`. For non-scalar values, identity will be disregarded by * deepEqual. - * + * * `notDeepEqual()` can be used to explicitly test deep, strict inequality. - * + * * @param actual Object or Expression being tested * @param expected Known comparision value - * @param {string} [message] A short description of the assertion + * @param {string} [message] A short description of the assertion */ - deepEqual(actual: any, expected: any, message?: string): void; - + deepEqual(actual: T, expected: T, message?: string): void; + /** * A non-strict comparison, roughly equivalent to JUnit's assertEquals. - * + * * The `equal` assertion uses the simple comparison operator (`==`) to * compare the actual and expected arguments. When they are equal, the * assertion passes; otherwise, it fails. When it fails, both actual and * expected values are displayed in the test result, in addition to a given * message. - * + * * `notEqual()` can be used to explicitly test inequality. - * + * * `strictEqual()` can be used to test strict equality. - * + * * @param actual Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ equal(actual: any, expected: any, message?: string): void; - + /** * Specify how many assertions are expected to run within a test. - * + * * To ensure that an explicit number of assertions are run within any test, * use `assert.expect( number )` to register an expected count. If the * number of assertions run does not match the expected count, the test will * fail. - * + * * @param {number} amount Number of assertions in this test. */ expect(amount: number): void; - + /** * An inverted deep recursive comparison, working on primitive types, * arrays, objects, regular expressions, dates and functions. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ notDeepEqual(actual: any, expected: any, message?: string): void; - + /** * A non-strict comparison, checking for inequality. - * + * * The `notEqual` assertion uses the simple inverted comparison operator * (`!=`) to compare the actual and expected arguments. When they aren't * equal, the assertion passes; otherwise, it fails. When it fails, both * actual and expected values are displayed in the test result, in addition * to a given message. - * + * * `equal()` can be used to test equality. - * + * * `notStrictEqual()` can be used to test strict inequality. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ notEqual(actual: any, expected: any, message?: string): void; - + /** * A boolean check, inverse of `ok()` and CommonJS's `assert.ok()`, and * equivalent to JUnit's `assertFalse()`. Passes if the first argument is * falsy. - * + * * `notOk()` requires just one argument. If the argument evaluates to false, * the assertion passes; otherwise, it fails. If a second message argument * is provided, it will be displayed in place of the result. - * + * * @param state Expression being tested * @param {string} [message] A short description of the assertion */ notOk(state: any, message?: string): void; - + /** * A strict comparison of an object's own properties, checking for inequality. - * + * * The `notPropEqual` assertion uses the strict inverted comparison operator * (`!==`) to compare the actual and expected arguments as Objects regarding * only their properties but not their constructors. - * + * * When they aren't equal, the assertion passes; otherwise, it fails. When * it fails, both actual and expected values are displayed in the test * result, in addition to a given message. - * + * * `equal()` can be used to test equality. - * + * * `propEqual()` can be used to test strict equality of an Object properties. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ notPropEqual(actual: any, expected: any, message?: string): void; - + /** * A strict comparison, checking for inequality. - * + * * The `notStrictEqual` assertion uses the strict inverted comparison * operator (`!==`) to compare the actual and expected arguments. When they * aren't equal, the assertion passes; otherwise, it fails. When it fails, * both actual and expected values are displayed in the test result, in * addition to a given message. - * + * * `equal()` can be used to test equality. - * + * * `strictEqual()` can be used to test strict equality. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ notStrictEqual(actual: any, expected: any, message?: string): void; - + /** * A boolean check, equivalent to CommonJS's assert.ok() and JUnit's * assertTrue(). Passes if the first argument is truthy. - * + * * The most basic assertion in QUnit, ok() requires just one argument. If * the argument evaluates to true, the assertion passes; otherwise, it * fails. If a second message argument is provided, it will be displayed in * place of the result. - * + * * @param state Expression being tested * @param {string} message A short description of the assertion */ ok(state: any, message?: string): void; - + /** * A strict type and value comparison of an object's own properties. - * + * * The `propEqual()` assertion provides strictly (`===`) comparison of * Object properties. Unlike `deepEqual()`, this assertion can be used to * compare two objects made with different constructors and prototype. - * + * * `strictEqual()` can be used to test strict equality. - * + * * `notPropEqual()` can be used to explicitly test strict inequality of * Object properties. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ propEqual(actual: any, expected: any, message?: string): void; - + /** * Report the result of a custom assertion - * + * * Some test suites may need to express an expectation that is not defined * by any of QUnit's built-in assertions. This need may be met by * encapsulating the expectation in a JavaScript function which returns a * `Boolean` value representing the result; this value can then be passed * into QUnit's `ok` assertion. - * + * * A more readable solution would involve defining a custom assertion. If * the expectation function invokes `pushResult`, QUnit will be notified of * the result and report it accordingly. - * + * * @param assertionResult The assertion result */ pushResult(assertResult: { @@ -203,31 +203,31 @@ interface Assert { expected: any; message: string; }): void; - + /** * A strict type and value comparison. - * + * * The `strictEqual()` assertion provides the most rigid comparison of type * and value with the strict equality operator (`===`). - * + * * `equal()` can be used to test non-strict equality. - * + * * `notStrictEqual()` can be used to explicitly test strict inequality. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ - strictEqual(actual: any, expected: any, message?: string): void; - + strictEqual(actual: T, expected: T, message?: string): void; + /** * Test if a callback throws an exception, and optionally compare the thrown * error. - * + * * When testing code that is expected to throw an exception based on a * specific set of circumstances, use assert.throws() to catch the error * object for testing and comparison. - * + * * In very few environments, like Closure Compiler, throws is considered a * reserved word and will cause an error. For that case, an alias is bundled * called `raises`. It has the same signature and behaviour, just a @@ -238,30 +238,30 @@ interface Assert { /** * A marker for progress in a given test. - * - * The `step()` assertion registers a passing assertion with a provided message. This makes - * it easy to check that specific portions of code are being executed, especially in - * asynchronous test cases and when used with `verifySteps()`. - * + * + * The `step()` assertion registers a passing assertion with a provided message. This makes + * it easy to check that specific portions of code are being executed, especially in + * asynchronous test cases and when used with `verifySteps()`. + * * Together with the `verifySteps()` method, `step()` assertions give you an easy way * to verify both the count and order of code execution. - * + * * @param message Message to display for the step */ step(message: string): void; /** * A helper assertion to verify the order and number of steps in a test. - * + * * The assert.verifySteps() assertion compares a given array of string values (representing steps) * with the order and values of previous step() calls. This assertion is helpful for verifying * the order and count of portions of code paths, especially asynchronous ones. - * + * * @param steps Array of strings representing steps to verify * @param message A short description of the assertion */ verifySteps(steps: string[], message?: string): void; - + } interface Config { @@ -296,7 +296,7 @@ interface Hooks { /** * Runs after the last test. If additional tests are defined after the * module's queue has emptied, it will not run this hook again. - */ + */ after?: (assert: Assert) => void; /** @@ -320,7 +320,7 @@ interface NestedHooks { /** * Runs after the last test. If additional tests are defined after the * module's queue has emptied, it will not run this hook again. - */ + */ after: (fn: (assert: Assert) => void) => void; /** @@ -337,7 +337,7 @@ interface NestedHooks { * Runs before each test. */ beforeEach: (fn: (assert: Assert) => void) => void; - + } declare namespace QUnit { @@ -373,30 +373,30 @@ declare namespace QUnit { } interface QUnit { - + /** * Namespace for QUnit assertions - * + * * QUnit's built-in assertions are defined on the `QUnit.assert` object. An * instance of this object is passed as the only argument to the `QUnit.test` * function callback. - * + * * This object has properties for each of QUnit's built-in assertion methods. */ assert: Assert; /** * Register a callback to fire whenever the test suite begins. - * + * * `QUnit.begin()` is called once before running any tests. - * + * * @callback callback Callback to execute. */ begin(callback: (details: QUnit.BeginDetails) => void): void; /** * Configuration for QUnit - * + * * QUnit has a bunch of internal configuration defaults, some of which are * useful to override. Check the description for each option for details. */ @@ -404,23 +404,23 @@ interface QUnit { /** * Register a callback to fire whenever the test suite ends. - * + * * @param callback Callback to execute */ done(callback: (details: QUnit.DoneDetails) => void): void; /** * Advanced and extensible data dumping for JavaScript. - * + * * This method does string serialization by parsing data structures and * objects. It parses DOM elements to a string representation of their outer * HTML. By default, nested structures will be displayed up to five levels * deep. Anything beyond that is replaced by `[object Object]` and * `[object Array]` placeholders. - * + * * If you need more or less output, change the value of `QUnit.dump.maxDepth`, * representing how deep the elements should be parsed. - * + * * Note: This method used to be in QUnit.jsDump, which was changed to * QUnit.dump. The old property will be removed in QUnit 3.0. */ @@ -431,12 +431,12 @@ interface QUnit { /** * Copy the properties defined by the `mixin` object into the `target` object. - * + * * This method will modify the `target` object to contain the "own" properties * defined by the `mixin`. If the `mixin` object specifies the value of any * attribute as undefined, this property will instead be removed from the * `target` object. - * + * * @param target An object whose properties are to be modified * @param mixin An object describing which properties should be modified */ @@ -444,12 +444,12 @@ interface QUnit { /** * Register a callback to fire whenever an assertion completes. - * + * * This is one of several callbacks QUnit provides. Its intended for * integration scenarios like PhantomJS or Jenkins. The properties of the * details argument are listed below as options. - * - * @param callback Callback to execute + * + * @param callback Callback to execute */ log(callback: (details: QUnit.LogDetails) => void): void; @@ -457,36 +457,36 @@ interface QUnit { * Group related tests under a single label. * * You can use the module name to organize, select, and filter tests to run. - * + * * All tests inside a module callback function will be grouped into that * module. The test names will all be preceded by the module name in the * test results. Other modules can be nested inside this callback function, * where their tests' names will be labeled by their names recursively * prefixed by their parent modules. - * + * * If `QUnit.module` is defined without a `nested` callback argument, all * subsequently defined tests will be grouped into the module until another * module is defined. - * + * * Modules with test group functions allow you to define nested modules, and * QUnit will run tests on the parent module before going deep on the nested * ones, even if they're declared first. Additionally, any hook callbacks on * a parent module will wrap the hooks on a nested module. In other words, * `before` and `beforeEach` callbacks will form a queue while the * `afterEach` and `after` callbacks will form a stack. - * + * * You can specify code to run before and after tests using the hooks * argument, and also to create properties that will be shared on the * testing context. Any additional properties on the `hooks` object will be * added to that context. The `hooks` argument is still optional if you call * `QUnit.module` with a callback argument. - * + * * The module's callback is invoked with the test environment as its `this` * context, with the environment's properties copied to the module's tests, * hooks, and nested modules. Note that changes on tests' `this` are not * preserved between sibling tests, where `this` will be reset to the initial * value for each test. - * + * * @param {string} name Label for this group of tests * @param hookds Callbacks to run during test execution * @param nested A callback with grouped tests and nested modules to run under the current module label @@ -496,31 +496,31 @@ interface QUnit { /** * Register a callback to fire whenever a module ends. - * + * * @param callback Callback to execute */ moduleDone(callback: (details: QUnit.ModuleDoneDetails) => void): void; /** * Register a callback to fire whenever a module begins. - * + * * @param callback Callback to execute */ moduleStart(callback: (details: QUnit.ModuleStartDetails) => void): void; /** * Adds a test to exclusively run, preventing all other tests from running. - * + * * Use this method to focus your test suite on a specific test. QUnit.only * will cause any other tests in your suite to be ignored. - * + * * Note, that if more than one QUnit.only is present only the first instance * will run. - * + * * This is an alternative to filtering tests to run in the HTML reporter. It * is especially useful when you use a console reporter or in a codebase * with a large set of long running tests. - * + * * @param {string} name Title of unit being tested * @param callback Function to close over assertions */ @@ -528,48 +528,48 @@ interface QUnit { /** * DEPRECATED: Report the result of a custom assertion. - * + * * This method is deprecated and it's recommended to use pushResult on its * direct reference in the assertion context. - * + * * QUnit.push reflects to the current running test, and it may leak * assertions in asynchronous mode. Checkout assert.pushResult() to set a * proper custom assertion. - * + * * Invoking QUnit.push allows to create a readable expectation that is not * defined by any of QUnit's built-in assertions. - * + * * @deprecated */ push(result: boolean, actual: any, expected: any, message: string): void; /** * Adds a test like object to be skipped. - * + * * Use this method to replace QUnit.test() instead of commenting out entire * tests. - * + * * This test's prototype will be listed on the suite as a skipped test, * ignoring the callback argument and the respective global and module's * hooks. - * + * * @param {string} Title of unit being tested */ skip(name: string, callback?: (assert: Assert) => void): void; /** * Returns a single line string representing the stacktrace (call stack). - * + * * This method returns a single line string representing the stacktrace from * where it was called. According to its offset argument, `QUnit.stack()` will * return the correspondent line from the call stack. - * + * * The default `offset` is `0` and will return the current location where it * was called. - * + * * Not all browsers support retrieving stracktraces. In those, `QUnit.stack()` * will return undefined. - * + * * @param {number} offset Set the stacktrace line offset. */ stack(offset?: number): string; @@ -577,10 +577,10 @@ interface QUnit { /** * `QUnit.start()` must be used to start a test run that has * `QUnit.config.autostart` set to `false`. - * + * * This method was previously used to control async tests on text contexts * along with QUnit.stop. For asynchronous tests, use assert.async instead. - * + * * When your async test has multiple exit points, call `QUnit.start()` for the * corresponding number of `QUnit.stop()` increments. */ @@ -588,16 +588,16 @@ interface QUnit { /** * Add a test to run. - * + * * Add a test to run using `QUnit.test()`. - * + * * The `assert` argument to the callback contains all of QUnit's assertion * methods. Use this argument to call your test assertions. * * `QUnit.test()` can automatically handle the asynchronous resolution of a * Promise on your behalf if you return a thenable Promise as the result of * your callback function. - * + * * @param {string} Title of unit being tested * @param callback Function to close over assertions */ @@ -605,7 +605,7 @@ interface QUnit { /** * Register a callback to fire whenever a test ends. - * + * * @param callback Callback to execute */ testDone(callback: (details: { @@ -619,7 +619,7 @@ interface QUnit { /** * Register a callback to fire whenever a test begins. - * + * * @param callback Callback to execute */ testStart(callback: (details: QUnit.TestStartDetails) => void): void; @@ -649,7 +649,7 @@ interface QUnit { /** * Are the test running from the server or not. - */ + */ isLocal: boolean; /** diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index a33fde5f5f..59f3b7860b 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -346,8 +346,8 @@ declare namespace R { * `chain` maps a function over a list and concatenates the results. * This implementation is compatible with the Fantasy-land Chain spec */ - chain(fn: (n: T) => U[], list: ReadonlyArray): U[]; - chain(fn: (n: T) => U[]): (list: ReadonlyArray) => U[]; + chain(fn: (n: T) => ReadonlyArray, list: ReadonlyArray): U[]; + chain(fn: (n: T) => ReadonlyArray): (list: ReadonlyArray) => U[]; /** * Restricts a number to be within a range. @@ -745,7 +745,7 @@ declare namespace R { * Returns a new list by pulling every item out of it (and all its sub-arrays) and putting * them in a new array, depth-first. */ - flatten(x: ReadonlyArray | ReadonlyArray): T[]; + flatten(x: ReadonlyArray | ReadonlyArray | ReadonlyArray>): T[]; /** * Returns a new function much like the supplied one, except that the first two arguments' diff --git a/types/random-js/index.d.ts b/types/random-js/index.d.ts index ff1417b681..86926b9beb 100644 --- a/types/random-js/index.d.ts +++ b/types/random-js/index.d.ts @@ -27,7 +27,7 @@ interface Random { sample(population: T[], sampleSize: number): T[]; die(sideCount: number): number; dice(sideCount: number, dieCount: number): number[]; - uuid4(engine: Random.Engine): string; + uuid4(engine?: Random.Engine): string; string(engine: Random.Engine, length: number): string; string(length?: number, pool?: string): string; hex(length?: number, upperCase?: boolean): string; diff --git a/types/random-js/random-js-tests.ts b/types/random-js/random-js-tests.ts index ef438e18c5..936a2a4693 100644 --- a/types/random-js/random-js-tests.ts +++ b/types/random-js/random-js-tests.ts @@ -86,7 +86,8 @@ sampled = random.sample(customTypeArray, 2); numeric = random.die(5); dieValues = random.dice(5, 2); -uuid = Random.uuid4(engine); +uuid = random.uuid4(engine); +uuid = random.uuid4(); str = random.string(); str = random.string(10); diff --git a/types/react-beautiful-dnd/index.d.ts b/types/react-beautiful-dnd/index.d.ts index 780a854751..40a2fb9e73 100644 --- a/types/react-beautiful-dnd/index.d.ts +++ b/types/react-beautiful-dnd/index.d.ts @@ -73,6 +73,7 @@ export interface DroppableStateSnapshot { export interface DroppableProps { droppableId: DroppableId; type?: TypeId; + ignoreContainerClipping?: boolean; isDropDisabled?: boolean; direction?: 'vertical' | 'horizontal'; children(provided: DroppableProvided, snapshot: DroppableStateSnapshot): React.ReactElement; diff --git a/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx b/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx index 4aed203ea6..bfa5d8b8f5 100644 --- a/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx +++ b/types/react-beautiful-dnd/react-beautiful-dnd-tests.tsx @@ -73,7 +73,7 @@ class App extends React.Component<{}, AppState> { render() { return ( - + {(provided, snapshot) => (
{this.state.items.map((item, index) => ( diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index 60db9a20f9..b4d23c1e49 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -4,6 +4,7 @@ // Austin Turner // Krzysztof Bezrąk // Sebastian Silbermann +// Paul Potsides // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -14,76 +15,85 @@ export type View = 'month' | 'week' | 'work_week' | 'day' | 'agenda'; export type Navigate = 'PREV' | 'NEXT' | 'TODAY' | 'DATE'; export type Event = object; -export interface Format { +export interface DateRange { + start: Date; + end: Date; +} + +export type DateFormatFunction = (date: Date, culture?: string, localizer?: object) => string; +export type DateRangeFormatFunction = (range: DateRange, culture?: string, localizer?: object) => string; +export type DateFormat = string | DateFormatFunction; + +export interface Formats { /** * Format for the day of the month heading in the Month view. * e.g. "01", "02", "03", etc */ - dateFormat?: string; + dateFormat?: DateFormat; /** * A day of the week format for Week and Day headings, * e.g. "Wed 01/04" * */ - dayFormat?: string; + dayFormat?: DateFormat; /** * Week day name format for the Month week day headings, * e.g: "Sun", "Mon", "Tue", etc * */ - weekdayFormat?: string; + weekdayFormat?: DateFormat; /** * The timestamp cell formats in Week and Time views, e.g. "4:00 AM" */ - timeGutterFormat?: string; + timeGutterFormat?: DateFormat; /** * Toolbar header format for the Month view, e.g "2015 April" * */ - monthHeaderFormat?: string; + monthHeaderFormat?: DateFormat; /** * Toolbar header format for the Week views, e.g. "Mar 29 - Apr 04" */ - dayRangeHeaderFormat?: string; + dayRangeHeaderFormat?: DateRangeFormatFunction; /** * Toolbar header format for the Day view, e.g. "Wednesday Apr 01" */ - dayHeaderFormat?: string; + dayHeaderFormat?: DateFormat; /** * Toolbar header format for the Agenda view, e.g. "4/1/2015 — 5/1/2015" */ - agendaHeaderFormat?: string; + agendaHeaderFormat?: DateFormat; /** * A time range format for selecting time slots, e.g "8:00am — 2:00pm" */ - selectRangeFormat?: string; + selectRangeFormat?: DateRangeFormatFunction; - agendaDateFormat?: string; - agendaTimeFormat?: string; - agendaTimeRangeFormat?: string; + agendaDateFormat?: DateFormat; + agendaTimeFormat?: DateFormat; + agendaTimeRangeFormat?: DateRangeFormatFunction; /** * Time range displayed on events. */ - eventTimeRangeFormat?: string; + eventTimeRangeFormat?: DateRangeFormatFunction; /** * An optional event time range for events that continue onto another day */ - eventTimeRangeStartFormat?: string; + eventTimeRangeStartFormat?: DateRangeFormatFunction; /** * An optional event time range for events that continue from another day */ - eventTimeRangeEndFormat?: string; + eventTimeRangeEndFormat?: DateRangeFormatFunction; } export interface HeaderProps { @@ -179,7 +189,7 @@ export interface BigCalendarProps extends React.Props string); diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index fe0ba7fe7c..3f2ec34c39 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -1,7 +1,7 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; import * as ReactDOMServer from "react-dom/server"; -import BigCalendar, { BigCalendarProps, Navigate, View } from "react-big-calendar"; +import BigCalendar, { BigCalendarProps, Navigate, View, DateRange } from "react-big-calendar"; // Don't want to add this as a dependency, because it is only used for tests. declare const moment: any; @@ -81,7 +81,11 @@ class FullAPIExample extends React.Component> { min={new Date()} max={new Date()} scrollToTime={new Date()} - formats={{}} + formats={{ + dateFormat: "h a", + agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format", + dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format" + }} messages={{}} timeslots={24} defaultView={'month'} diff --git a/types/react-currency-formatter/index.d.ts b/types/react-currency-formatter/index.d.ts new file mode 100644 index 0000000000..d0f8e217ad --- /dev/null +++ b/types/react-currency-formatter/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for react-currency-formatter 1.1 +// Project: https://github.com/xDae/react-currency-formatter; +// Definitions by: Yury Pastushenko +// Evgeniy Vasiliev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +interface CurrencyFormatterProps { + quantity: number; + currency?: string; + locale?: string; + pattern?: string; + decimal?: string; + group?: string; +} + +declare const reactCurrencyFormatter: React.ComponentClass; +export = reactCurrencyFormatter; diff --git a/types/react-currency-formatter/react-currency-formatter-tests.tsx b/types/react-currency-formatter/react-currency-formatter-tests.tsx new file mode 100644 index 0000000000..06cc4ec9a2 --- /dev/null +++ b/types/react-currency-formatter/react-currency-formatter-tests.tsx @@ -0,0 +1,13 @@ +import * as React from 'react'; +import * as CurrencyFormatter from 'react-currency-formatter'; + +interface Props { + price: number; + currency: string; +} + +const ProductionPrice: React.SFC = (props: Props) => ( + +); + +export default ProductionPrice; diff --git a/types/redux-little-router/tsconfig.json b/types/react-currency-formatter/tsconfig.json similarity index 91% rename from types/redux-little-router/tsconfig.json rename to types/react-currency-formatter/tsconfig.json index 30884e8741..2dee5017b3 100644 --- a/types/redux-little-router/tsconfig.json +++ b/types/react-currency-formatter/tsconfig.json @@ -5,11 +5,11 @@ "es6", "dom" ], + "jsx": "react", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, - "jsx": "react", "baseUrl": "../", "typeRoots": [ "../" @@ -20,6 +20,6 @@ }, "files": [ "index.d.ts", - "redux-little-router-tests.tsx" + "react-currency-formatter-tests.tsx" ] } \ No newline at end of file diff --git a/types/react-currency-formatter/tslint.json b/types/react-currency-formatter/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-currency-formatter/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-data-grid/index.d.ts b/types/react-data-grid/index.d.ts index bfa4ea979f..b41c2c2501 100644 --- a/types/react-data-grid/index.d.ts +++ b/types/react-data-grid/index.d.ts @@ -1,24 +1,43 @@ -// Type definitions for react-data-grid 2.0 +// Type definitions for react-data-grid 4.0 // Project: https://github.com/adazzle/react-data-grid.git -// Definitions by: Simon Gellis , Kieran Peat , Martin Novak +// Definitions by: Simon Gellis , Kieran Peat , Martin Novak , Sebastijan Grabar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// declare namespace AdazzleReactDataGrid { - - interface SelectionParams { - rowIdx: number, - row: any + interface ExcelColumn { + editable: boolean; + name: any; + key: string; + width: number; + resizeable: boolean; + filterable: boolean; } - interface GridProps { + interface EditorBaseProps { + value: any; + column: ExcelColumn; + height: number; + onBlur: () => void; + onCommit: () => void; + onCommitCancel: () => void; + rowData: any; + rowMetaData: any; + } + + interface SelectionParams { + rowIdx: number; + row: T; + } + + interface GridProps { /** * Gets the data to render in each row. Required. * Can be an array or a function that takes an index and returns an object. */ - rowGetter: Array | ((rowIdx: number) => object) + rowGetter: Array | ((rowIdx: number) => T) /** * The total number of rows to render. Required. */ @@ -26,14 +45,14 @@ declare namespace AdazzleReactDataGrid { /** * The columns to render. */ - columns?: Array + columns?: Array> /** * Invoked when the user changes the value of a single cell. * Should update that cell's value. * @param e Information about the event */ - onRowUpdated?: (e: RowUpdateEvent) => void + onRowUpdated?: (e: RowUpdateEvent) => void /** * Invoked when the user pulls down the drag handle of an editable cell. * Should update the values of the selected cells. @@ -45,7 +64,7 @@ declare namespace AdazzleReactDataGrid { * Should update the values of the cells beneath the selected cell. * @param e Information about the event */ - onDragHandleDoubleClick?: (e: DragHandleDoubleClickEvent) => void + onDragHandleDoubleClick?: (e: DragHandleDoubleClickEvent) => void /** * Invoked when the user copies a value from one cell and pastes it into another (in the same column). * Should update the value of the cell in row e.toRow. @@ -56,7 +75,7 @@ declare namespace AdazzleReactDataGrid { * Invoked after the user updates the grid rows in any way. * @param e Information about the event */ - onGridRowsUpdated?: (e: GridRowsUpdatedEvent) => void + onGridRowsUpdated?: (e: GridRowsUpdatedEvent) => void /** * A toolbar to display above the grid. @@ -164,7 +183,7 @@ declare namespace AdazzleReactDataGrid { * Called when a row is selected. * @param rows The (complete) current selection of rows. */ - onRowSelect?: (rows: Array) => void + onRowSelect?: (rows: Array) => void /** * A property that's unique to every row. * This property is required to enable row selection. @@ -206,8 +225,8 @@ declare namespace AdazzleReactDataGrid { rowSelection?: { showCheckbox?: boolean enableShiftSelect?: boolean - onRowsSelected?: (rows: Array) => void, - onRowsDeselected?: (rows: Array) => void, + onRowsSelected?: (rows: Array>) => void, + onRowsDeselected?: (rows: Array>) => void, selectBy?: { indexes?: Array; keys?: { rowKey: string, values: Array }; @@ -230,7 +249,7 @@ declare namespace AdazzleReactDataGrid { * @param rowIdx zero index number of row clicked * @param row object behind the row */ - onRowClick?: (rowIdx : number, row : object) => void + onRowClick?: (rowIdx: number, row: T) => void /** * An event function called when a row is expanded with the toggle @@ -246,12 +265,12 @@ declare namespace AdazzleReactDataGrid { */ getValidFilterValues?: (columnKey: string) => Array - getCellActions?: (column: Column, row: object) => (ActionButton | ActionMenu)[] + getCellActions?: (column: Column, row: T) => (ActionButton | ActionMenu)[] } type ActionButton = { icon: string; - callback: () => void; + callback: () => void; } type ActionMenu = { @@ -266,7 +285,7 @@ declare namespace AdazzleReactDataGrid { /** * Information about a specific column to be rendered. */ - interface Column { + interface Column { /** * A unique key for this column. Required. * Each row should have a property with this name, which contains this column's value. @@ -314,7 +333,10 @@ declare namespace AdazzleReactDataGrid { * The editor for this column. Several editors are available in "react-data-grid/addons". * @default A simple text editor */ - editor?: React.ReactElement | React.ComponentClass | React.StatelessComponent + editor?: + | React.ReactElement + | React.ComponentClass + | React.StatelessComponent; /** * A custom read-only formatter for this column. An image formatter is available in "react-data-grid/addons". */ @@ -331,11 +353,11 @@ declare namespace AdazzleReactDataGrid { */ events?: { [name: string]: ColumnEventCallback - } + }; /** * Retrieve meta data about the row, optionally provide column as a second argument */ - getRowMetaData?: (rowdata: any, column?: Column) => any; + getRowMetaData?: (rowdata: T, column?: Column) => any; /** * A class name to be applied to the cells in the column */ @@ -357,9 +379,10 @@ declare namespace AdazzleReactDataGrid { } /** - * Information about a row update + * Information about a row update. Generic event type returns untyped row, use parameterized type with the row type as the parameter + * @default T = any */ - interface RowUpdateEvent { + interface RowUpdateEvent { /** * The index of the updated row. */ @@ -367,7 +390,7 @@ declare namespace AdazzleReactDataGrid { /** * The columns that were updated and their values. */ - updated: object + updated: T /** * The name of the column that was updated. */ @@ -401,9 +424,10 @@ declare namespace AdazzleReactDataGrid { } /** - * Information about a drag handle double click + * Information about a drag handle double click. Generic event type returns untyped row, use parameterized type with the row type as the parameter + * @default T = any */ - interface DragHandleDoubleClickEvent { + interface DragHandleDoubleClickEvent { /** * The row where the double click occurred. */ @@ -415,7 +439,7 @@ declare namespace AdazzleReactDataGrid { /** * The values of the row. */ - rowData: object + rowData: T /** * The double click event. */ @@ -449,9 +473,10 @@ declare namespace AdazzleReactDataGrid { } /** - * Information about some update to the grid's contents + * Information about some update to the grid's contents. Generic event type returns untyped row, use parameterized type with the row type as the parameter + * @default T = any */ - interface GridRowsUpdatedEvent { + interface GridRowsUpdatedEvent { /** * The key of the column where the event occurred. */ @@ -467,7 +492,7 @@ declare namespace AdazzleReactDataGrid { /** * The columns that were updated and their values. */ - updated: object + updated: T /** * The action that occurred to trigger this event. * One of 'cellUpdate', 'cellDrag', 'columnFill', or 'copyPaste'. @@ -511,7 +536,7 @@ declare namespace AdazzleReactDataGrid { * Excel-like grid component built with React, with editors, keyboard navigation, copy & paste, and the like * http://adazzle.github.io/react-data-grid/ */ - export class ReactDataGrid extends React.Component { + export class ReactDataGrid extends React.Component> { /** * Opens the editor for the cell (idx) in the given row (rowIdx). If the column is not editable then nothing will happen. */ @@ -531,6 +556,18 @@ declare namespace AdazzleReactDataGrid { export import GridRowsUpdatedEvent = AdazzleReactDataGrid.GridRowsUpdatedEvent; export import OnRowExpandToggle = AdazzleReactDataGrid.OnRowExpandToggle; + export namespace editors { + class EditorBase

extends React.Component

{ + getStyle(): { width: string }; + + getValue(): any; + + getInputNode(): Element | null | Text; + + inheritContainerStyles(): boolean; + } + } + // Actual classes exposed on module.exports /** * A react component that renders a row of the grid @@ -541,15 +578,48 @@ declare namespace AdazzleReactDataGrid { */ export class Cell extends React.Component { } } -} + } + + declare namespace AdazzleReactDataGridPlugins { + interface AutoCompleteEditorProps { + onCommit?: () => void; + options?: Array<{ id: number; title: string }>; + label?: any; + value?: any; + height?: number; + valueParams?: string[]; + column?: AdazzleReactDataGrid.ExcelColumn; + resultIdentifier?: string; + search?: string; + onKeyDown?: () => void; + onFocus?: () => void; + editorDisplayValue?: (column: AdazzleReactDataGrid.ExcelColumn, value: any) => string; + } + + interface AutoCompleteTokensEditorProps { + options: Array; + column?: AdazzleReactDataGrid.ExcelColumn; + value?: any[]; + } + + interface DropDownEditorProps { + options: + Array; + } -declare namespace AdazzleReactDataGridPlugins { - // TODO: refine types for these addons export namespace Editors { - export class AutoComplete extends React.Component { } - export class DropDownEditor extends React.Component { } - export class SimpleTextEditor extends React.Component { } - export class CheckboxEditor extends React.Component { } + export class AutoComplete extends React.Component {} + export class AutoCompleteTokensEditor extends React.Component {} + export class DropDownEditor extends React.Component {} + + // TODO: refine types for these addons + export class SimpleTextEditor extends React.Component {} + export class CheckboxEditor extends React.Component {} } export namespace Filters { export class NumericFilter extends React.Component { } @@ -589,16 +659,16 @@ declare namespace AdazzleReactDataGridPlugins { configure?: (props: any) => any ): (Component: any) => any } -} + } -declare module "react-data-grid" { + declare module "react-data-grid" { import ReactDataGrid = AdazzleReactDataGrid.ReactDataGrid; // commonjs export export = ReactDataGrid; -} + } -declare module "react-data-grid-addons" { + declare module "react-data-grid-addons" { import Plugins = AdazzleReactDataGridPlugins; import Editors = Plugins.Editors; import Filters = Plugins.Filters; @@ -633,4 +703,4 @@ declare module "react-data-grid-addons" { } } } -} + } diff --git a/types/react-data-grid/react-data-grid-tests.tsx b/types/react-data-grid/react-data-grid-tests.tsx index aa09041846..201e53a3ca 100644 --- a/types/react-data-grid/react-data-grid-tests.tsx +++ b/types/react-data-grid/react-data-grid-tests.tsx @@ -131,7 +131,7 @@ var counties = [ var titles = ['Dr.', 'Mr.', 'Mrs.', 'Miss', 'Ms.']; -var columns:ReactDataGrid.Column[] = [ +var columns:ReactDataGrid.Column[] = [ { key: 'id', name: 'ID', @@ -152,7 +152,7 @@ var columns:ReactDataGrid.Column[] = [ editor: , width: 200, resizable: true, - getRowMetaData: (rowdata: any, column: ReactDataGrid.Column) => { + getRowMetaData: (rowdata: any, column: ReactDataGrid.Column) => { return {}; } }, @@ -262,7 +262,7 @@ class Example extends React.Component { return clonedColumns; } - handleGridRowsUpdated(updatedRowData:ReactDataGrid.GridRowsUpdatedEvent) { + handleGridRowsUpdated(updatedRowData:ReactDataGrid.GridRowsUpdatedEvent) { var rows = this.state.rows; for (var i = updatedRowData.fromRow; i <= updatedRowData.toRow; i++) { @@ -315,12 +315,12 @@ class Example extends React.Component { return this.state.rows.length; } - onRowsSelected(rows: Array) { + onRowsSelected(rows: Array>) { var selectedIndexes = this.state.selectedIndexes as Array; this.setState({selectedIndexes: selectedIndexes.concat(rows.map(r => r.rowIdx))}); } - onRowsDeselected(rows: Array) { + onRowsDeselected(rows: Array>) { var rowIndexes = rows.map(r => r.rowIdx); var selectedIndexes = this.state.selectedIndexes as Array; this.setState({selectedIndexes: selectedIndexes.filter(i => rowIndexes.indexOf(i) === -1 )}); diff --git a/types/react-data-grid/v1/tsconfig.json b/types/react-data-grid/v1/tsconfig.json index c2602fd049..6919c8eb55 100644 --- a/types/react-data-grid/v1/tsconfig.json +++ b/types/react-data-grid/v1/tsconfig.json @@ -20,11 +20,14 @@ "paths": { "react-data-grid": [ "react-data-grid/v1" - ] + ], + "react-data-grid/*": [ + "react-data-grid/v1/*" + ] } }, "files": [ "index.d.ts", "react-data-grid-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/react-data-grid/v2/index.d.ts b/types/react-data-grid/v2/index.d.ts new file mode 100644 index 0000000000..bfa4ea979f --- /dev/null +++ b/types/react-data-grid/v2/index.d.ts @@ -0,0 +1,636 @@ +// Type definitions for react-data-grid 2.0 +// Project: https://github.com/adazzle/react-data-grid.git +// Definitions by: Simon Gellis , Kieran Peat , Martin Novak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +declare namespace AdazzleReactDataGrid { + + interface SelectionParams { + rowIdx: number, + row: any + } + + interface GridProps { + /** + * Gets the data to render in each row. Required. + * Can be an array or a function that takes an index and returns an object. + */ + rowGetter: Array | ((rowIdx: number) => object) + /** + * The total number of rows to render. Required. + */ + rowsCount: number + /** + * The columns to render. + */ + columns?: Array + + /** + * Invoked when the user changes the value of a single cell. + * Should update that cell's value. + * @param e Information about the event + */ + onRowUpdated?: (e: RowUpdateEvent) => void + /** + * Invoked when the user pulls down the drag handle of an editable cell. + * Should update the values of the selected cells. + * @param e Information about the event + */ + onCellsDragged?: (e: CellDragEvent) => void + /** + * Invoked when the user double clicks on the drag handle of an editable cell. + * Should update the values of the cells beneath the selected cell. + * @param e Information about the event + */ + onDragHandleDoubleClick?: (e: DragHandleDoubleClickEvent) => void + /** + * Invoked when the user copies a value from one cell and pastes it into another (in the same column). + * Should update the value of the cell in row e.toRow. + * @param e Information about the event + */ + onCellCopyPaste?: (e: CellCopyPasteEvent) => void + /** + * Invoked after the user updates the grid rows in any way. + * @param e Information about the event + */ + onGridRowsUpdated?: (e: GridRowsUpdatedEvent) => void + + /** + * A toolbar to display above the grid. + * Consider using the toolbar included in "react-data-grid/addons". + */ + toolbar?: React.ReactElement + /** + * A context menu to disiplay when the user right-clicks a cell. + * Consider using "react-contextmenu", included in "react-data-grid/addons". + */ + contextMenu?: React.ReactElement + /** + * A react component to customize how rows are rendered. + * If you want to define your own, consider extending ReactDataGrid.Row. + */ + rowRenderer?: React.ReactElement | React.ComponentClass | React.StatelessComponent + /** + * A component to display when there are no rows to render. + */ + emptyRowsView?: React.ComponentClass | React.StatelessComponent + + /** + * The minimum width of the entire grid in pixels. + */ + minWidth?: number + /** + * The minimum height of the entire grid in pixels. + * @default 350 + */ + minHeight?: number + /** + * The height of each individual row in pixels. + * @default 35 + */ + rowHeight?: number + /** + * The height of the header row in pixels. + * @default rowHeight + */ + headerRowHeight?: number + /** + * The height of the header filter row in pixels. + * @default 45 + */ + headerFiltersHeight?: number + /** + * The minimum width of each column in pixels. + * @default 80 + */ + minColumnWidth?: number + /** + * Invoked when a column has been resized. + * @param index The index of the column + * @param width The new width of the column + */ + onColumnResize?: (index: number, width: number) => void + + /** + * Controls what happens when the user navigates beyond the first or last cells. + * 'loopOverRow' will navigate to the beginning/end of the current row. + * 'changeRow' will navigate to the beginning of the next row or the end of the last. + * 'none' will do nothing. + * @default none + */ + cellNavigationMode?: 'none' | 'loopOverRow' | 'changeRow' + + /** + * Called when the user sorts the grid by some column. + * Should update the order of the rows returned by rowGetter. + * @param sortColumn The name of the column being sorted by + * @param sortDirection The direction to sort ('ASC'/'DESC'/'NONE') + */ + onGridSort?: (sortColumn: string, sortDirection: 'ASC' | 'DESC' | 'NONE') => void + + /** + * Initial sorting direction + */ + sortDirection?: 'ASC' | 'DESC' | 'NONE' + + /** + * key of the initial sorted column + */ + sortColumn?: string + + /** + * Called when the user filters a column by some value. + * Should restrict the rows in rowGetter to only things that match the filter. + * @param filter The filter being added + */ + onAddFilter?: (filter: Filter) => void + /** + * Called when the user clears all filters. + * Should restore the rows in rowGetter to their original state. + */ + onClearFilters?: () => void + + /** + * When set to true or 'multi', enables multiple row select. + * When set to 'single', enables single row select. + * When set to false or not set, disables row select. + * @default false + */ + enableRowSelect?: boolean | 'single' | 'multi' + /** + * Called when a row is selected. + * @param rows The (complete) current selection of rows. + */ + onRowSelect?: (rows: Array) => void + /** + * A property that's unique to every row. + * This property is required to enable row selection. + * @default 'id' + */ + rowKey?: string + + /** + * Enables cells to be selected when clicked. + * @default false + */ + enableCellSelect?: boolean + + /** + * Enables cells to be dragged and dropped + * @default false + */ + enableDragAndDrop?: boolean + + /** + * Called when a cell is selected. + * @param coordinates The row and column indices of the selected cell. + */ + onCellSelected?: (coordinates: {rowIdx: number, idx: number}) => void + /** + * Called when a cell is deselected. + * @param coordinates The row and column indices of the deselected cell. + */ + onCellDeSelected?: (coordinates: {rowIdx: number, idx: number}) => void + + /** + * How long to wait before rendering a new row while scrolling in milliseconds. + * @default 0 + */ + rowScrollTimeout?: number + /** + * Options object for selecting rows + */ + rowSelection?: { + showCheckbox?: boolean + enableShiftSelect?: boolean + onRowsSelected?: (rows: Array) => void, + onRowsDeselected?: (rows: Array) => void, + selectBy?: { + indexes?: Array; + keys?: { rowKey: string, values: Array }; + isSelectedKey?: string; + } + } + /** + * A custom formatter for the select all checkbox cell + * @default react-data-grid/src/formatters/SelectAll.js + */ + selectAllRenderer?: React.ComponentClass | React.StatelessComponent; + /** + * A custom formatter for select row column + * @default AdazzleReactDataGridPlugins.Editors.CheckboxEditor + */ + rowActionsCell?: React.ComponentClass | React.StatelessComponent; + /** + * An event function called when a row is clicked. + * Clicking the header row will trigger a call with -1 for the rowIdx. + * @param rowIdx zero index number of row clicked + * @param row object behind the row + */ + onRowClick?: (rowIdx : number, row : object) => void + + /** + * An event function called when a row is expanded with the toggle + * @param props OnRowExpandToggle object + */ + onRowExpandToggle?: (props: OnRowExpandToggle ) => void + + /** + * Responsible for returning an Array of values that can be used for filtering + * a column that is column.filterable and using a column.filterRenderer that + * displays a list of options. + * @param columnKey the column key that we are looking to pull values from + */ + getValidFilterValues?: (columnKey: string) => Array + + getCellActions?: (column: Column, row: object) => (ActionButton | ActionMenu)[] + } + + type ActionButton = { + icon: string; + callback: () => void; + } + + type ActionMenu = { + icon: string; + actions: { + icon: string; + text: string; + callback: () => void; + }[]; + } + + /** + * Information about a specific column to be rendered. + */ + interface Column { + /** + * A unique key for this column. Required. + * Each row should have a property with this name, which contains this column's value. + */ + key: string + /** + * This column's display name. Required. + */ + name: string + /** + * A custom width for this specific column. + * @default minColumnWidth from the ReactDataGrid + */ + width?: number + /** + * Whether this column can be resized by the user. + * @default false + */ + resizable?: boolean + /** + * Whether this column should stay fixed on the left as the user scrolls horizontally. + * @default false + */ + locked?: boolean + /** + * Whether this column can be edited. + * @default false + */ + editable?: boolean + /** + * Whether the rows in the grid can be sorted by this column. + * @default false + */ + sortable?: boolean + /** + * Whether the rows in the grid can be filtered by this column. + * @default false + */ + filterable?: boolean; + /** + * A custom formatter for this column's filter. + */ + filterRenderer?: React.ReactElement | React.ComponentClass | React.StatelessComponent; + /** + * The editor for this column. Several editors are available in "react-data-grid/addons". + * @default A simple text editor + */ + editor?: React.ReactElement | React.ComponentClass | React.StatelessComponent + /** + * A custom read-only formatter for this column. An image formatter is available in "react-data-grid/addons". + */ + formatter?: React.ReactElement | React.ComponentClass | React.StatelessComponent + /** + * A custom formatter for this column's header. + */ + headerRenderer?: React.ReactElement | React.ComponentClass | React.StatelessComponent + /** + * Events to be bound to the cells in this specific column. + * Each event must respect this standard in order to work correctly: + * @example + * function onXxx(ev :SyntheticEvent, (rowIdx, idx, name): args) + */ + events?: { + [name: string]: ColumnEventCallback + } + /** + * Retrieve meta data about the row, optionally provide column as a second argument + */ + getRowMetaData?: (rowdata: any, column?: Column) => any; + /** + * A class name to be applied to the cells in the column + */ + cellClass?: string; + /** + * Whether this column can be dragged (re-arranged). + * @default false + */ + draggable?: boolean; + } + + interface ColumnEventCallback { + /** + * A callback for a native react event on a specific cell. + * @param ev The react event + * @param args The row and column coordinates of the cell, and the name of the event. + */ + (ev: React.SyntheticEvent, args: {rowIdx: number, idx: number, name: string}): void + } + + /** + * Information about a row update + */ + interface RowUpdateEvent { + /** + * The index of the updated row. + */ + rowIdx: number + /** + * The columns that were updated and their values. + */ + updated: object + /** + * The name of the column that was updated. + */ + cellKey: string + /** + * The name of the key pressed to trigger the event ('Tab', 'Enter', etc.). + */ + key: string + } + + /** + * Information about a cell drag + */ + interface CellDragEvent { + /** + * The name of the column that was dragged. + */ + cellKey: string + /** + * The row where the drag began. + */ + fromRow: number + /** + * The row where the drag ended. + */ + toRow: number + /** + * The value of the cell that was dragged. + */ + value: any + } + + /** + * Information about a drag handle double click + */ + interface DragHandleDoubleClickEvent { + /** + * The row where the double click occurred. + */ + rowIdx: number + /** + * The column where the double click occurred. + */ + idx: number + /** + * The values of the row. + */ + rowData: object + /** + * The double click event. + */ + e: React.SyntheticEvent + } + + /** + * Information about a copy paste + */ + interface CellCopyPasteEvent { + /** + * The row that was pasted to. + */ + rowIdx: number + /** + * The value that was pasted. + */ + value: any + /** + * The row that was copied from. + */ + fromRow: number + /** + * The row that was pasted to. + */ + toRow: number + /** + * The key of the column where the copy paste occurred. + */ + cellKey: string + } + + /** + * Information about some update to the grid's contents + */ + interface GridRowsUpdatedEvent { + /** + * The key of the column where the event occurred. + */ + cellKey: string + /** + * The top row affected by the event. + */ + fromRow: number + /** + * The bottom row affected by the event. + */ + toRow: number + /** + * The columns that were updated and their values. + */ + updated: object + /** + * The action that occurred to trigger this event. + * One of 'cellUpdate', 'cellDrag', 'columnFill', or 'copyPaste'. + */ + action: 'cellUpdate' | 'cellDrag' | 'columnFill' | 'copyPaste' + } + + /** + * Information about the row toggler + */ + interface OnRowExpandToggle { + /** + * The name of the column group the row is in + */ + columnGroupName: string + /** + * The name of the expanded row + */ + name: string + /** + * If it should expand or not + */ + shouldExpand: boolean + } + + /** + * Some filter to be applied to the grid's contents + */ + interface Filter { + /** + * The key of the column being filtered. + */ + columnKey: string + /** + * The term to filter by. + */ + filterTerm: string + } + + /** + * Excel-like grid component built with React, with editors, keyboard navigation, copy & paste, and the like + * http://adazzle.github.io/react-data-grid/ + */ + export class ReactDataGrid extends React.Component { + /** + * Opens the editor for the cell (idx) in the given row (rowIdx). If the column is not editable then nothing will happen. + */ + openCellEditor(rowIdx: number, idx: number): void; + } + export namespace ReactDataGrid { + // Useful types + export import Column = AdazzleReactDataGrid.Column; + export import Filter = AdazzleReactDataGrid.Filter; + + // Various events + export import RowUpdateEvent = AdazzleReactDataGrid.RowUpdateEvent; + export import SelectionParams = AdazzleReactDataGrid.SelectionParams; + export import CellDragEvent = AdazzleReactDataGrid.CellDragEvent; + export import DragHandleDoubleClickEvent = AdazzleReactDataGrid.DragHandleDoubleClickEvent; + export import CellCopyPasteEvent = AdazzleReactDataGrid.CellCopyPasteEvent; + export import GridRowsUpdatedEvent = AdazzleReactDataGrid.GridRowsUpdatedEvent; + export import OnRowExpandToggle = AdazzleReactDataGrid.OnRowExpandToggle; + + // Actual classes exposed on module.exports + /** + * A react component that renders a row of the grid + */ + export class Row extends React.Component { } + /** + * A react coponent that renders a cell of the grid + */ + export class Cell extends React.Component { } + } +} + +declare namespace AdazzleReactDataGridPlugins { + // TODO: refine types for these addons + export namespace Editors { + export class AutoComplete extends React.Component { } + export class DropDownEditor extends React.Component { } + export class SimpleTextEditor extends React.Component { } + export class CheckboxEditor extends React.Component { } + } + export namespace Filters { + export class NumericFilter extends React.Component { } + export class AutoCompleteFilter extends React.Component { } + export class MultiSelectFilter extends React.Component { } + export class SingleSelectFilter extends React.Component { } + } + export namespace Formatters { + export class ImageFormatter extends React.Component { } + export class DropDownFormatter extends React.Component { } + } + export class Toolbar extends React.Component {} + export namespace DraggableHeader { + export class DraggableContainer extends React.Component{ } + } + export namespace Data { + export const Selectors: { + getRows: (state: object) => object[]; + getSelectedRowsByKey: (state: object) => object[]; + } + } + // TODO: re-export the react-contextmenu typings once those exist + // https://github.com/vkbansal/react-contextmenu/issues/10 + export namespace Menu { + export class ContextMenu extends React.Component { } + export class MenuHeader extends React.Component { } + export class MenuItem extends React.Component { } + export class SubMenu extends React.Component { } + export const monitor: { + getItem(): any + getPosition(): any + hideMenu(): void + }; + export function connect(Menu: any): any; + export function ContextMenuLayer( + identifier: any, + configure?: (props: any) => any + ): (Component: any) => any + } +} + +declare module "react-data-grid" { + import ReactDataGrid = AdazzleReactDataGrid.ReactDataGrid; + + // commonjs export + export = ReactDataGrid; +} + +declare module "react-data-grid-addons" { + import Plugins = AdazzleReactDataGridPlugins; + import Editors = Plugins.Editors; + import Filters = Plugins.Filters; + import Formatters = Plugins.Formatters; + import Toolbar = Plugins.Toolbar; + import Menu = Plugins.Menu; + import Data = Plugins.Data; + import DraggableHeader = Plugins.DraggableHeader; + + // ES6 named exports + export { + Editors, + Filters, + Formatters, + Toolbar, + Menu, + Data, + DraggableHeader + } + + // attach to window + global { + interface Window { + ReactDataGridPlugins: { + Editors: typeof Editors, + Filters: typeof Filters, + Formatters: typeof Formatters, + Toolbar: typeof Toolbar, + Menu: typeof Menu, + Data: typeof Data, + DraggableHeader: typeof DraggableHeader + } + } + } +} diff --git a/types/react-data-grid/v2/react-data-grid-tests.tsx b/types/react-data-grid/v2/react-data-grid-tests.tsx new file mode 100644 index 0000000000..aa09041846 --- /dev/null +++ b/types/react-data-grid/v2/react-data-grid-tests.tsx @@ -0,0 +1,362 @@ +import * as React from 'react'; +import ReactDataGrid = require('react-data-grid'); +import * as ReactDataGridPlugins from 'react-data-grid-addons'; +import faker = require('faker'); + +var Editors = ReactDataGridPlugins.Editors; +var Toolbar = ReactDataGridPlugins.Toolbar; +var AutoCompleteEditor = Editors.AutoComplete; +var DropDownEditor = Editors.DropDownEditor; +var { Selectors } = ReactDataGridPlugins.Data; + +class CustomFilterHeaderCell extends React.Component { + state = { + filterTerm: "" + }; + handleChange(e: any) { + let val = e.target.value; + this.setState({filterTerm: val}); + this.props.onChange({filterTerm: val, column: this.props.column}); + } + render() { + return ( +
+ this.handleChange(e)} /> +
+ ); + } +} + +class CustomRowSelectorCell extends ReactDataGridPlugins.Editors.CheckboxEditor { + render(){ + return super.render(); + } +} + +export interface ICustomSelectAllProps { + onChange: any; + inputRef: any; +} + +class CustomSelectAll extends React.Component { + render() { + return ( +
+ + +
+ ); + } +} + +faker.locale = 'en_GB'; + +function createFakeRowObjectData(index:number):Object { + return { + id: 'id_' + index, + avartar: faker.image.avatar(), + county: faker.address.county(), + email: faker.internet.email(), + title: faker.name.prefix(), + firstName: faker.name.firstName(), + lastName: faker.name.lastName(), + street: faker.address.streetName(), + zipCode: faker.address.zipCode(), + date: faker.date.past().toLocaleDateString(), + bs: faker.company.bs(), + catchPhrase: faker.company.catchPhrase(), + companyName: faker.company.companyName(), + words: faker.lorem.words(), + sentence: faker.lorem.sentence() + }; +} + +function createRows(numberOfRows:number) { + var rows:Object[] = []; + for (var i = 0; i < numberOfRows; i++) { + rows[i] = createFakeRowObjectData(i); + } + return rows; +} + +var counties = [ + {id: 0, title: 'Bedfordshire'}, + {id: 1, title: 'Berkshire'}, + {id: 2, title: 'Buckinghamshire'}, + {id: 3, title: 'Cambridgeshire'}, + {id: 4, title: 'Cheshire'}, + {id: 5, title: 'Cornwall'}, + {id: 6, title: 'Cumbria, (Cumberland)'}, + {id: 7, title: 'Derbyshire'}, + {id: 8, title: 'Devon'}, + {id: 9, title: 'Dorset'}, + {id: 10, title: 'Durham'}, + {id: 11, title: 'Essex'}, + {id: 12, title: 'Gloucestershire'}, + {id: 13, title: 'Hampshire'}, + {id: 14, title: 'Hertfordshire'}, + {id: 15, title: 'Huntingdonshire'}, + {id: 16, title: 'Kent'}, + {id: 17, title: 'Lancashire'}, + {id: 18, title: 'Leicestershire'}, + {id: 19, title: 'Lincolnshire'}, + {id: 20, title: 'Middlesex'}, + {id: 21, title: 'Norfolk'}, + {id: 22, title: 'Northamptonshire'}, + {id: 23, title: 'Northumberland'}, + {id: 24, title: 'Nottinghamshire'}, + {id: 25, title: 'Northamptonshire'}, + {id: 26, title: 'Oxfordshire'}, + {id: 27, title: 'Northamptonshire'}, + {id: 28, title: 'Rutland'}, + {id: 29, title: 'Shropshire'}, + {id: 30, title: 'Somerset'}, + {id: 31, title: 'Staffordshire'}, + {id: 32, title: 'Suffolk'}, + {id: 33, title: 'Surrey'}, + {id: 34, title: 'Sussex'}, + {id: 35, title: 'Warwickshire'}, + {id: 36, title: 'Westmoreland'}, + {id: 37, title: 'Wiltshire'}, + {id: 38, title: 'Worcestershire'}, + {id: 39, title: 'Yorkshire'} +]; + +var titles = ['Dr.', 'Mr.', 'Mrs.', 'Miss', 'Ms.']; + +var columns:ReactDataGrid.Column[] = [ + { + key: 'id', + name: 'ID', + width: 80, + resizable: true + }, + { + key: 'avartar', + name: 'Avartar', + width: 60, + formatter: ReactDataGridPlugins.Formatters.ImageFormatter, + resizable: true, + headerRenderer: + }, + { + key: 'county', + name: 'County', + editor: , + width: 200, + resizable: true, + getRowMetaData: (rowdata: any, column: ReactDataGrid.Column) => { + return {}; + } + }, + { + key: 'title', + name: 'Title', + editor: , + width: 200, + resizable: true, + events: { + onDoubleClick: function () { + console.log("The user double clicked on title column"); + } + } + }, + { + key: 'firstName', + name: 'First Name', + editable: true, + width: 200, + resizable: true + }, + { + key: 'lastName', + name: 'Last Name', + editable: true, + width: 200, + resizable: true + }, + { + key: 'email', + name: 'Email', + editable: true, + width: 200, + resizable: true + }, + { + key: 'street', + name: 'Street', + editable: true, + width: 200, + resizable: true + }, + { + key: 'zipCode', + name: 'ZipCode', + editable: true, + width: 200, + resizable: true + }, + { + key: 'date', + name: 'Date', + editable: true, + width: 200, + resizable: true + }, + { + key: 'bs', + name: 'bs', + editable: true, + width: 200, + resizable: true + }, + { + key: 'catchPhrase', + name: 'Catch Phrase', + editable: true, + width: 200, + resizable: true + }, + { + key: 'companyName', + name: 'Company Name', + editable: true, + width: 200, + resizable: true, + filterable: true, + filterRenderer: CustomFilterHeaderCell + }, + { + key: 'sentence', + name: 'Sentence', + editable: true, + width: 200, + resizable: true, + cellClass: 'sentence-class' + } +]; + +class Example extends React.Component { + getInitialState() { + var fakeRows = createRows(2000); + return {rows: fakeRows}; + } + + getColumns() { + var clonedColumns = columns.slice(); + clonedColumns[2].events = { + onClick: function (ev:React.SyntheticEvent, args:{idx:number, rowIdx:number}) { + var idx = args.idx; + var rowIdx = args.rowIdx; + this.refs.grid.openCellEditor(rowIdx, idx); + }.bind(this) + }; + + return clonedColumns; + } + + handleGridRowsUpdated(updatedRowData:ReactDataGrid.GridRowsUpdatedEvent) { + var rows = this.state.rows; + + for (var i = updatedRowData.fromRow; i <= updatedRowData.toRow; i++) { + var rowToUpdate = rows[i]; + var updatedRow = Object.assign({}, rowToUpdate, updatedRowData.updated); + rows[i] = updatedRow; + } + + this.setState({rows: rows}); + } + + onRowExpandToggle = ({ columnGroupName, name, shouldExpand }:ReactDataGrid.OnRowExpandToggle ) => { + let expandedRows = Object.assign({}, this.state.expandedRows); + expandedRows[columnGroupName] = Object.assign({}, expandedRows[columnGroupName]); + expandedRows[columnGroupName][name] = {isExpanded: shouldExpand}; + this.setState({expandedRows: expandedRows}); + } + + onRowClick(rowIdx:number, row: Object) { + // Do nothing, just test that it accepts an event + } + + getRows() { + const rows = Selectors.getRows(this.state); + console.log(rows); + return rows; + } + + handleAddRow(e:any) { + var newRow = { + value: e.newRowIndex, + userStory: '', + developer: '', + epic: '' + }; + var rows = this.state.rows; + rows.push(newRow); + this.setState({rows: rows}); + } + + getRowAt(index:number) { + this.getRows(); + if (index < 0 || index > this.getSize()) { + return undefined; + } + return this.state.rows[index]; + } + + getSize() { + return this.state.rows.length; + } + + onRowsSelected(rows: Array) { + var selectedIndexes = this.state.selectedIndexes as Array; + + this.setState({selectedIndexes: selectedIndexes.concat(rows.map(r => r.rowIdx))}); + } + onRowsDeselected(rows: Array) { + var rowIndexes = rows.map(r => r.rowIdx); + var selectedIndexes = this.state.selectedIndexes as Array; + this.setState({selectedIndexes: selectedIndexes.filter(i => rowIndexes.indexOf(i) === -1 )}); + } + + render() { + let selectedRows = ['id1', 'id2']; + return ( + } + enableRowSelect={true} + rowHeight={50} + minHeight={600} + rowScrollTimeout={200} + rowSelection={{ + showCheckbox: true, + enableShiftSelect: true, + onRowsSelected: this.onRowsSelected, + onRowsDeselected: this.onRowsDeselected, + selectBy: { + keys: {rowKey: 'id', values: selectedRows} + } + }} + rowActionsCell={CustomRowSelectorCell} + selectAllRenderer={CustomSelectAll} + onRowClick={this.onRowClick} + /> + + ); + } +} diff --git a/types/react-data-grid/v2/tsconfig.json b/types/react-data-grid/v2/tsconfig.json new file mode 100644 index 0000000000..1f5bd63312 --- /dev/null +++ b/types/react-data-grid/v2/tsconfig.json @@ -0,0 +1,33 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "jsx": "react", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "react-data-grid": [ + "react-data-grid/v2" + ], + "react-data-grid/*": [ + "react-data-grid/v2/*" + ] + } + }, + "files": [ + "index.d.ts", + "react-data-grid-tests.tsx" + ] +} diff --git a/types/react-data-grid/v2/tslint.json b/types/react-data-grid/v2/tslint.json new file mode 100644 index 0000000000..637071b426 --- /dev/null +++ b/types/react-data-grid/v2/tslint.json @@ -0,0 +1,80 @@ +{ + "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-object-spread": 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/react-daterange-picker/index.d.ts b/types/react-daterange-picker/index.d.ts index 86ada23508..4b6f5eef45 100644 --- a/types/react-daterange-picker/index.d.ts +++ b/types/react-daterange-picker/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for React Daterange Picker 1.1 +// Type definitions for React Daterange Picker 2.0 // Project: https://github.com/onefinestay/react-daterange-picker // Definitions by: UNCOVER TRUTH Inc. // MartynasZilinskas +// Donald Ford // Definitions: https://github.com/borisyankov/DefinitelyTyped // TypeScript Version: 2.8 @@ -33,7 +34,7 @@ export interface Props extends React.Props { onHighlightRange?(date: Date): void; onSelect?(value: Props): void; onSelectStart?(value: momentRange.MomentRangeExtends): void; - paginationArrowComponent?: PaginationArrow; + paginationArrowComponent?: React.ComponentClass | React.SFC; selectedLabel?: string; selectionType?: 'single' | 'range'; singleDateRange?: boolean; @@ -57,10 +58,8 @@ export interface StateDefinition { selectable?: boolean; } -export interface PaginationArrowProps extends React.Props { +export interface PaginationArrowProps extends React.Props { disabled?: boolean; onTrigger?(): void; direction?: 'next' | 'previous'; } - -export class PaginationArrow extends React.Component { } diff --git a/types/react-daterange-picker/react-daterange-picker-tests.tsx b/types/react-daterange-picker/react-daterange-picker-tests.tsx index b891f6a589..4e79aa1c7a 100644 --- a/types/react-daterange-picker/react-daterange-picker-tests.tsx +++ b/types/react-daterange-picker/react-daterange-picker-tests.tsx @@ -11,6 +11,24 @@ const moment = MomentRange.extendMoment(Moment); type AppProps = ReactDateRangePicker.Props; +const CustomSFCPaginationArrow: React.SFC = (props) => { + return ( +
+ { (props.direction === 'next') ? '<' : '>' } +
+ ); +}; + +class CustomComponentClassPaginationArrow extends React.Component { + render() { + return ( +
+ { (this.props.direction === 'next') ? '<' : '>' } +
+ ); + } +} + class App extends React.Component { handleSelect(value: AppProps, states: any): void { this.setState({ value, states }); @@ -151,6 +169,18 @@ export class Main extends React.Component { minimumDate={new Date()} /> +
+

With custom SFC paginationArrowComponent

+ +
+
+

With custom ComponentClass paginationArrowComponent

+ +
); diff --git a/types/react-global-configuration/index.d.ts b/types/react-global-configuration/index.d.ts new file mode 100644 index 0000000000..d2a4157720 --- /dev/null +++ b/types/react-global-configuration/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for react-global-configuration 1.3 +// Project: https://github.com/morenofa/react-global-configuration#readme +// Definitions by: Ryo Kikuchi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export interface Options { + freeze: boolean; + assign: boolean; +} + +export function set(newConfiguration: any, newOptions?: Options): void; +export function get(key?: string): any; +export function get(key: string, fallbackValue: Value): Value; +export function serialize(): string; diff --git a/types/react-global-configuration/react-global-configuration-tests.ts b/types/react-global-configuration/react-global-configuration-tests.ts new file mode 100644 index 0000000000..05cd15f95d --- /dev/null +++ b/types/react-global-configuration/react-global-configuration-tests.ts @@ -0,0 +1,25 @@ +import config from "react-global-configuration"; + +interface UserConfig { + a: number; + b: string; + c: { + ca: 123; + cb: 'ABC'; + }; +} + +config.set({ + a: 456, + b: "DEF", + c: { + ca: 123, + cb: 'ABC', + } +}); + +config.serialize(); + +const all = config.get(); // all: any +const a = config.get('a', 789); // a: number +const d = config.get('d'); // d: any diff --git a/types/react-global-configuration/tsconfig.json b/types/react-global-configuration/tsconfig.json new file mode 100644 index 0000000000..c75d7c7cce --- /dev/null +++ b/types/react-global-configuration/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, + "allowSyntheticDefaultImports": true + }, + "files": [ + "index.d.ts", + "react-global-configuration-tests.ts" + ] +} diff --git a/types/react-global-configuration/tslint.json b/types/react-global-configuration/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-global-configuration/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-hammerjs/index.d.ts b/types/react-hammerjs/index.d.ts index e3bb4a826c..03f3f36f98 100644 --- a/types/react-hammerjs/index.d.ts +++ b/types/react-hammerjs/index.d.ts @@ -1,21 +1,30 @@ -// Type definitions for react-hammerjs 0.5 +// Type definitions for react-hammerjs 1.0 // Project: https://github.com/JedWatson/react-hammerjs#readme // Definitions by: Jason Unger +// Cecchi MacNaughton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as Hammer from 'hammerjs'; -import * as React from 'react'; +import * as Hammer from "hammerjs"; +import * as React from "react"; type Omit = Pick>; -type HammerOptionsWithRecognizers = Omit & { +type HammerOptionsWithRecognizers = Omit & { recognizers?: { [gesture: string]: RecognizerOptions }; }; declare namespace ReactHammer { interface ReactHammerProps { - direction?: number; + direction?: + | "DIRECTION_NONE" + | "DIRECTION_LEFT" + | "DIRECTION_RIGHT" + | "DIRECTION_UP" + | "DIRECTION_DOWN" + | "DIRECTION_HORIZONTAL" + | "DIRECTION_VERTICAL" + | "DIRECTION_ALL"; options?: HammerOptionsWithRecognizers; recognizeWith?: { [gesture: string]: Recognizer | string }; vertical?: boolean; diff --git a/types/react-hammerjs/v0/index.d.ts b/types/react-hammerjs/v0/index.d.ts new file mode 100644 index 0000000000..e3bb4a826c --- /dev/null +++ b/types/react-hammerjs/v0/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for react-hammerjs 0.5 +// Project: https://github.com/JedWatson/react-hammerjs#readme +// Definitions by: Jason Unger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as Hammer from 'hammerjs'; +import * as React from 'react'; + +type Omit = Pick>; + +type HammerOptionsWithRecognizers = Omit & { + recognizers?: { [gesture: string]: RecognizerOptions }; +}; + +declare namespace ReactHammer { + interface ReactHammerProps { + direction?: number; + options?: HammerOptionsWithRecognizers; + recognizeWith?: { [gesture: string]: Recognizer | string }; + vertical?: boolean; + action?: HammerListener; + onDoubleTap?: HammerListener; + onPan?: HammerListener; + onPanCancel?: HammerListener; + onPanEnd?: HammerListener; + onPanStart?: HammerListener; + onPinch?: HammerListener; + onPinchCancel?: HammerListener; + onPinchEnd?: HammerListener; + onPinchIn?: HammerListener; + onPinchStart?: HammerListener; + onPress?: HammerListener; + onPressUp?: HammerListener; + onRotate?: HammerListener; + onRotateCancel?: HammerListener; + onRotateEnd?: HammerListener; + onRotateMove?: HammerListener; + onRotateStart?: HammerListener; + onSwipe?: HammerListener; + onTap?: HammerListener; + } +} +declare const ReactHammer: React.ComponentClass; +export = ReactHammer; diff --git a/types/react-hammerjs/v0/react-hammerjs-tests.tsx b/types/react-hammerjs/v0/react-hammerjs-tests.tsx new file mode 100644 index 0000000000..7743cf3a4b --- /dev/null +++ b/types/react-hammerjs/v0/react-hammerjs-tests.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import Hammer from 'react-hammerjs'; + +class ReactHammer extends React.Component { + swipe: Hammer.ReactHammerProps['onSwipe'] = input => { + console.log(input.deltaX); + } + + render() { + const { children, ...props } = this.props; + return ( + + {children} + + ); + } +} diff --git a/types/react-hammerjs/v0/tsconfig.json b/types/react-hammerjs/v0/tsconfig.json new file mode 100644 index 0000000000..f8a95be3c6 --- /dev/null +++ b/types/react-hammerjs/v0/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": ["../../"], + "paths": { + "react-hammerjs": ["react-hammerjs/v0"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "esModuleInterop": true + }, + "files": ["index.d.ts", "react-hammerjs-tests.tsx"] +} diff --git a/types/react-hammerjs/v0/tslint.json b/types/react-hammerjs/v0/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-hammerjs/v0/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-i18next/v4/index.d.ts b/types/react-i18next/v4/index.d.ts index 14676aba7e..758a00edef 100644 --- a/types/react-i18next/v4/index.d.ts +++ b/types/react-i18next/v4/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for react-i18next 4.6 // Project: https://github.com/i18next/react-i18next // Definitions by: Giedrius Grabauskas +// Netanel Gilad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -31,7 +32,7 @@ export { * interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} */ export interface InjectedTranslateProps { - t?: TranslationFunction; + t: TranslationFunction; } export as namespace reactI18Next; diff --git a/types/react-i18next/v4/react-i18next-tests.tsx b/types/react-i18next/v4/react-i18next-tests.tsx index 6105ccf921..3e57dd091b 100644 --- a/types/react-i18next/v4/react-i18next-tests.tsx +++ b/types/react-i18next/v4/react-i18next-tests.tsx @@ -17,17 +17,16 @@ const AnotherComponent = translate('view', { wait: true, translateFuncName: '_' class InnerYetAnotherComponent extends React.Component { render() { - const t = this.props.t!; + const t = this.props.t; return

{t('usingDefaultNS', { /* options t options */ })}

; } } const YetAnotherComponent = translate()(InnerYetAnotherComponent); -@translate(['view', 'nav'], { wait: true }) class TranslatableView extends React.Component { render() { - const t = this.props.t!; + const t = this.props.t; const interpolateComponent = "a interpolated component"; return ( @@ -55,12 +54,14 @@ class TranslatableView extends React.Component { } } +const WrappedTranslatableView = translate(['view', 'nav'], { wait: true })(TranslatableView); + class App extends React.Component { render() { return (
- +
); @@ -81,12 +82,14 @@ loadNamespaces({ components: [App], i18n }).then(() => { }).catch(error => { }); type Key = "view" | "nav"; -@translate(['view', 'nav']) class GenericsTest extends React.Component { render() { return null; } } -@translate('view') +translate(['view', 'nav'])(GenericsTest); + class GenericsTest2 extends React.Component { render() { return null; } } + +translate('view')(GenericsTest2); diff --git a/types/react-i18next/v4/translate.d.ts b/types/react-i18next/v4/translate.d.ts index d41b4dc00a..9a4fb6ddc2 100644 --- a/types/react-i18next/v4/translate.d.ts +++ b/types/react-i18next/v4/translate.d.ts @@ -1,5 +1,6 @@ import * as React from "react"; import { i18n } from "i18next"; +import { InjectedTranslateProps } from "react-i18next"; export interface TranslateOptions { withRef?: boolean; @@ -11,5 +12,14 @@ export interface TranslateOptions { i18n?: i18n; } +// Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766 +export type Omit = Pick; + +// Injects props and removes them from the prop requirements. +// Adds the new properties t (or whatever the translation function is called) and i18n if needed. +export type InferableComponentEnhancerWithProps = +

(component: React.ComponentClass

| React.StatelessComponent

) => + React.ComponentClass>; + // tslint:disable-next-line:ban-types -export default function translate(namespaces?: TKey[] | TKey, options?: TranslateOptions): (WrappedComponent: C) => C; +export default function translate(namespaces?: TKey[] | TKey, options?: TranslateOptions): InferableComponentEnhancerWithProps<"t">; diff --git a/types/react-infinite-scroll-component/index.d.ts b/types/react-infinite-scroll-component/index.d.ts index 768ad1831b..f43fc50e24 100644 --- a/types/react-infinite-scroll-component/index.d.ts +++ b/types/react-infinite-scroll-component/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/ankeetmaini/react-infinite-scroll-component#readme // Definitions by: Stephanie Roy // Bartosz Dotryw +// David Kevork // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -34,7 +35,7 @@ declare namespace InfiniteScroll { /** * You can send a loader component to show while the component waits for the next load of data. e.g.

Loading...

or any fancy loader element */ - loader?: React.ReactNode; + loader: React.ReactNode; /** * This function will be called, it should return the fresh data that you want to show the user @@ -59,7 +60,7 @@ declare namespace InfiniteScroll { /** * Any JSX that you want to show the user, default={

Release to refresh

} */ - releaseToRefreshContent?: boolean; + releaseToRefreshContent?: React.ReactNode; /** * A threshold value defining when InfiniteScroll will call next. Default value is 0.8. It means the next will be called when user comes below 80% of the total height. @@ -84,6 +85,11 @@ declare namespace InfiniteScroll { */ hasChildren?: boolean; + /** + * Children component which will be rendered + */ + children?: React.ReactNode; + /** * Set a scroll y position for the component to render with. */ diff --git a/types/react-infinite-scroll-component/react-infinite-scroll-component-tests.tsx b/types/react-infinite-scroll-component/react-infinite-scroll-component-tests.tsx index 2b5a01d4cc..6eb67569a0 100644 --- a/types/react-infinite-scroll-component/react-infinite-scroll-component-tests.tsx +++ b/types/react-infinite-scroll-component/react-infinite-scroll-component-tests.tsx @@ -10,6 +10,7 @@ const props: InfiniteScroll.InfiniteScrollProps = { dataLength: 4, hasMore: true, endMessage: 'The end.', + loader:

Loading...

, next: () => null, }; diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index c1dff99d71..899859a69d 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -8,6 +8,7 @@ // Brian Houser , // Krister Kari // Martin Raedlinger +// Kanitkorn Sujautra // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -94,6 +95,7 @@ declare namespace ReactIntl { interface Props extends PropsBase { value: DateSource; + children?: (formattedDate: string) => React.ReactNode; } } @@ -104,6 +106,7 @@ declare namespace ReactIntl { interface Props extends PropsBase { value: DateSource; + children?: (formattedTime: string) => React.ReactNode; } } class FormattedTime extends React.Component { } @@ -125,6 +128,7 @@ declare namespace ReactIntl { interface Props extends PropsBase { value: DateSource; + children?: (formattedRelative: string) => React.ReactNode; } } @@ -154,6 +158,7 @@ declare namespace ReactIntl { interface Props extends PropsBase { value: number; + children?: (formattedNumber: string) => React.ReactNode; } } class FormattedNumber extends React.Component { } @@ -177,6 +182,7 @@ declare namespace ReactIntl { interface Props extends PropsBase { value: number; + children?: (formattedPlural: React.ReactNode) => React.ReactNode; } } class FormattedPlural extends React.Component { } diff --git a/types/react-intl/react-intl-tests.tsx b/types/react-intl/react-intl-tests.tsx index b69c59bd74..d3d30757a1 100644 --- a/types/react-intl/react-intl-tests.tsx +++ b/types/react-intl/react-intl-tests.tsx @@ -96,6 +96,17 @@ class SomeComponent extends React.Component + + {formattedRelative => formattedRelative.toUpperCase()} + + + + {formattedNum => ( + {formattedNum} + )} + + - - - - - - - - - - {(formattedNum: string) => ( - {formattedNum} + + {formattedPlural => ( + {formattedPlural} )} - + + + + + + + + {formattedDate => formattedDate.toUpperCase()} + + + + + + + + {formattedTime => formattedTime.toUpperCase()} + ; } } diff --git a/types/react-joyride/index.d.ts b/types/react-joyride/index.d.ts index 7cc118a2f0..d081aa87cf 100644 --- a/types/react-joyride/index.d.ts +++ b/types/react-joyride/index.d.ts @@ -1,11 +1,31 @@ -// Type definitions for react-joyride 1.11 +// Type definitions for react-joyride 2.0 // Project: https://github.com/gilbarbara/react-joyride -// Definitions by: Daniel Rosenwasser , Ben Dixon +// Definitions by: DongYoon Kang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; +export type Action = 'init' | 'start' | 'stop' | 'reset' | 'restart' | 'prev' | + 'next' | 'go' | 'index' | 'close' | 'skip' | 'update'; + +export type Lifecycle = 'init' | 'ready' | 'beacon' | 'tooltip' | 'complete' | 'error'; + +export type Status = 'idle' | 'ready' | 'waiting' | 'running' | + 'paused' | 'skipped' | 'finished' | 'error'; + +export type EventType = + 'tour:start' | + 'step:before' | + 'beacon' | + 'tooltip' | + 'step:after' | + 'tour:end' | + // these usually don't happen in a normal tour + 'tour:status' | + 'error:target_not_found' | + 'error'; + export default class Joyride extends React.Component { constructor(props: Props); @@ -41,156 +61,186 @@ export interface Locale { skip?: string; } -export interface Props { +export interface Props extends OverridableProps { /** * The tour's steps. Defaults to [] */ - steps?: Step[]; + steps: Step[]; /** - * The initial step index. Defaults to 0 + * Setting a number here will turn Joyride into controlled mode. + * You will receive the state events in the callback and you'll have to update this prop by yourself. */ stepIndex?: number; /** - * Run/stop the tour. Defaults to false + * Run/stop the tour. Defaults to true. */ run?: boolean; /** - * Open the tooltip automatically for the first step, without showing a beacon. Defaults to false - */ - autoStart?: boolean; - - /** - * Toggle keyboard navigation (esc, space bar, return). Defaults to true - */ - keyboardNavigation?: boolean; - - /** - * The strings used in the tooltip. Defaults to `{ back: 'Back', close: 'Close', last: 'Last', next: 'Next', skip: 'Skip' }` - */ - locale?: Locale; - - /** - * Delay the reposition of the current step while the window is being resized. Defaults to false - */ - resizeDebounce?: boolean; - - /** - * The amount of delay for the resizeDebounce callback. Defaults to 200 - */ - resizeDebounceDelay?: number; - - /** - * The gap around the target inside the hole. Defaults to 5 - */ - holePadding?: number; - - /** - * The scrollTop offset used in scrollToSteps. Defaults to 20 + * The scroll distance from the element scrollTop value. Defaults to 20. */ scrollOffset?: number; - /** - * Scroll the page to the next step if needed. Defaults to true - */ - scrollToSteps?: boolean; - /** * Scroll the page for the first step. Defaults to false */ scrollToFirstStep?: boolean; - /** - * Display a back button. Defaults to true - */ - showBackButton?: boolean; - - /** - * Display an overlay with holes above your steps (for tours only). Defaults to true - */ - showOverlay?: boolean; - - /** - * Allow mouse and touch events within overlay hole, and prevent hole:click callback from being sent. Defaults to false - */ - allowClicksThruHole?: boolean; - /** * Display a link to skip the tour. Defaults to false */ showSkipButton?: boolean; /** - * Display the tour progress in the next button e.g. 2/5 in continuous tours. Defaults to false + * Disable auto scrolling between steps. Defaults to false. */ - showStepsProgress?: boolean; + disableScrolling?: boolean; /** - * The tooltip offset from the target. Defaults to 30 - */ - tooltipOffset?: number; - - /** - * The type of your presentation. It can be continuous (played sequencially with the Next button) or single. Defaults to single - */ - type?: "continuous" | "single"; - - /** - * Don't close the tooltip on clicking the overlay. Defaults to false - */ - disableOverlay?: boolean; - - /** - * Console.log Joyride's inner actions. Defaults to false + * Log Joyride's actions to the console. Defaults to false. */ debug?: boolean; /** - * It will be called when the tour's state changes. + * It will be called when Joyride's state changes. It returns a single parameter with the state. */ - callback?(options: any): void; + callback?(options: (data: State) => any): void; + + /** + * The tour is played sequentially with the Next button. Defaults to false. + */ + continuous?: boolean; } -export interface Step { - title?: string; - text?: React.ReactNode; - target: string; - position?: "top" | "top-left" | "top-right" | "bottom" | "bottom-left" | "bottom-right" | "right" | "left"; - type?: "click" | "hover"; +export interface OverridableProps { + /** + * A React component or function to be used instead the default Beacon. + */ + beaconComponent?: React.ReactNode; + + /** + * Allow mouse and touch events thru the spotlight. You can click links in your app. Defaults to true. + */ + spotlightClicks?: boolean; + + /** + * The padding of the spotlight. Defaults to 10. + */ + spotlightPadding?: number; + + /** + * Display the tour progress in the next button _e.g. 2/5 _in continuous tours. Defaults to false. + */ + showProgress?: boolean; + + /** + * Disable closing the tooltip on ESC. Defaults to false. + */ + disableCloseOnEsc?: boolean; + + /** + * Don't show the overlay. Defaults to false + */ + disableOverlay?: boolean; + + /** + * Don't close the tooltip when clicking the overlay. Defaults to false. + */ + disableOverlayClose?: boolean; + + /** + * The strings used in the tooltip. Defaults to `{ back: 'Back', close: 'Close', last: 'Last', next: 'Next', skip: 'Skip' }` + */ + locale?: Locale; + + /** + * A React component or function to be used instead the default Tooltip excluding the arrow. + */ + tooltipComponent?: React.ReactNode; + + /** + * Options to be passed to react-floater. + */ + floaterProps?: object; + + /** + * Hide the "back" button. Defaults to false. + */ + hideBackButton?: boolean; + + styles?: StepStyles; +} + +export interface Step extends OverridableProps { + /** + * The target for the step. It can be a CSS selector or an HtmlElement directly (but using refs created in the same render would required an additional render afterwards). + */ + target: HTMLElement | string; + /** + * The tooltip's body. + */ + content: React.ReactNode | string; + + /** + * The tooltip's title. + */ + title?: React.ReactNode | string; + + /** + * Don't show the Beacon before the tooltip. Defaults to false. + */ + disableBeacon?: boolean; + + /** + * The event to trigger the beacon. It can be click or hover. Defaults to click. + */ + event?: 'click' | 'hover'; + + /** + * Force the step to be fixed. Defaults to false. + */ isFixed?: boolean; - allowClicksThruHole?: boolean; - style?: StepStyles; - [prop: string]: any; -} + /** + * The distance from the target to the tooltip. Defaults to 10. + */ + offset?: number; + /** + * The placement of the beacon and tooltip. It will re-position itself if there's no space available. + * Defaults to bottom. + */ + placement?: 'top' | 'top-start' | 'top-end' | + 'bottom' | 'bottom-start' | 'bottom-end' | + 'left' | 'left-start' | 'left-end' | + 'right' | 'right-start' | 'right-end' | + 'auto' | 'center'; + + /** + * The placement of the beacon. It will use the placement if nothing is passed and it can be: top, bottom, left, right. + */ + placementBeacon?: 'top' | 'bottom' | 'left' | 'right'; +} export interface StepStyles { - backgroundColor?: string; - borderRadius?: string; - color?: string; - mainColor?: string; - textAlign?: string; - width?: string; - beacon?: BeaconStyles; - [style: string]: any; -} - -export interface BeaconStyles { - offsetX?: number; - offsetY?: number; - inner?: string; - outer?: string; + /** + * See https://github.com/gilbarbara/react-joyride/blob/master/docs/styling.md + */ + options?: { + [s: string]: any; + }; } export interface State { - action: string; + action: Action; index: number; - play: boolean; - redraw: boolean; - shouldPlay: boolean; - showTooltip: boolean; - xPos: number; - yPos: number; - skipped: boolean; + controlled: boolean; + lifecycle: Lifecycle; + size: number; + status: Status; + /** + * The current step. + */ + step: Step; + type: EventType; } diff --git a/types/react-joyride/react-joyride-tests.tsx b/types/react-joyride/react-joyride-tests.tsx index 52fc24f3c9..82171e98e2 100644 --- a/types/react-joyride/react-joyride-tests.tsx +++ b/types/react-joyride/react-joyride-tests.tsx @@ -5,12 +5,13 @@ class NewComponent extends React.Component { j: Joyride; steps: Step[] = [{ - title: "Title", - text: "Hurray", - target: ".selectable", - position: "top-right", - type: "click", - style: { + title: "Title", + content: "Hurray", + target: ".selectable", + placement: "top-end", + event: "click", + styles: { + options: { backgroundColor: "#000", borderRadius: "0", color: "#000", @@ -32,17 +33,16 @@ class NewComponent extends React.Component { hole: { backgroundColor: "#000", } - }, - name: "my-name", - parent: "MyParent" + } }, - { - target: ".other-selectable", - text: (
Also works
) - }]; + }, + { + target: ".other-selectable", + content: (
Also works
) + }]; render() { - return ; + return ; } doStuff() { @@ -54,6 +54,6 @@ class NewComponent extends React.Component { this.j.addTooltip(this.steps[0]); - const { title, position } = this.j.getProgress().step; + const { title, placement } = this.j.getProgress().step; } } diff --git a/types/react-lifecycle-component/index.d.ts b/types/react-lifecycle-component/index.d.ts new file mode 100644 index 0000000000..315d04f7fb --- /dev/null +++ b/types/react-lifecycle-component/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for react-lifecycle-component 2.0 +// Project: https://github.com/JamieDixon/react-lifecycle-component +// Definitions by: Alexander Fisher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { ComponentLifecycle, Component, ComponentClass } from 'react'; +import { Connect } from 'react-redux'; + +export interface LifecycleStateProps

{ + component: ComponentClass; +} + +export interface LifecycleDispatchProps

extends ComponentLifecycle {} + +export interface Props

extends LifecycleStateProps, LifecycleDispatchProps {} + +export class LifecycleComponent extends Component, any> {} + +export function applyLifecycle

( + component: ComponentClass, +): ComponentClass

>; + +export const connectWithLifecycle: Connect; diff --git a/types/redux-little-router/package.json b/types/react-lifecycle-component/package.json similarity index 64% rename from types/redux-little-router/package.json rename to types/react-lifecycle-component/package.json index 6d68bf2f9b..bb0e2b57d2 100644 --- a/types/redux-little-router/package.json +++ b/types/react-lifecycle-component/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "redux": "^3.6.0" + "redux": "^4.0.0" } -} +} \ No newline at end of file diff --git a/types/react-lifecycle-component/react-lifecycle-component-tests.tsx b/types/react-lifecycle-component/react-lifecycle-component-tests.tsx new file mode 100644 index 0000000000..6c4a7407d4 --- /dev/null +++ b/types/react-lifecycle-component/react-lifecycle-component-tests.tsx @@ -0,0 +1,98 @@ +import * as React from 'react'; +import { Dispatch } from 'redux'; +import { connect } from 'react-redux'; +import { + connectWithLifecycle, + LifecycleDispatchProps, + applyLifecycle, + LifecycleStateProps, + LifecycleComponent, +} from 'react-lifecycle-component'; + +interface State { + stateFoo: number; +} + +interface Props extends StateProps, DispatchProps { +} + +interface StateProps { + propsFoo: number; +} + +interface DispatchProps { + bar(): void; +} + +class ComponentFoo extends React.Component { + constructor(props: Props) { + super(props); + this.state = { + stateFoo: 0, + }; + } + render() { + return ( +

+
Props Foo: {this.props.propsFoo}
+
State Foo: {this.state.stateFoo}
+ +
+ ); + } +} + +type MapStateProps = StateProps & LifecycleStateProps; + +function mapStateToProps(): MapStateProps { + return { + component: ComponentFoo, + propsFoo: 8675309, + }; +} + +type MapDispatchProps = DispatchProps & LifecycleDispatchProps; + +function mapDispatchToProps(dispatch: Dispatch): MapDispatchProps { + return { + bar() { + dispatch({ type: 'Bar'}); + }, + componentWillMount() { + dispatch({ type: 'ComponentWillMount'}); + }, + componentDidMount() { + dispatch({ type: 'ComponentDidMount'}); + }, + componentWillUpdate(nextProps, nextState, nextContext) { + const fooIsEqual: boolean = nextProps.propsFoo === nextState.stateFoo; + const hasNextContext: boolean = !!nextContext; + dispatch({ type: 'ComponentWillUpdate'}); + }, + componentDidUpdate(nextProps, nextState, nextContext) { + const fooIsEqual: boolean = nextProps.propsFoo === nextState.stateFoo; + const hasNextContext: boolean = !!nextContext; + dispatch({ type: 'ComponentDidUpdate'}); + }, + componentWillReceiveProps(nextProps, nextContext) { + const fooIsGreaterThanZero: boolean = nextProps.propsFoo > 0; + const hasNextContext: boolean = !!nextContext; + dispatch({ type: 'ComponentWillReceiveProps'}); + }, + componentWillUnmount() { + dispatch({ type: 'ComponentWillUnmount'}); + }, + shouldComponentUpdate(nextProps, nextState, nextContext) { + const fooIsEqual: boolean = nextProps.propsFoo === nextState.stateFoo; + const hasNextContext: boolean = !!nextContext; + return !fooIsEqual; + }, + }; +} + +const connectWithLifecylceContainer = + connectWithLifecycle(mapStateToProps, mapDispatchToProps)(ComponentFoo); +const applyLifecycleContainer = + connect(mapStateToProps, mapDispatchToProps)(applyLifecycle(ComponentFoo)); +const lifecycleContainer = + connect(mapStateToProps, mapDispatchToProps)(LifecycleComponent); diff --git a/types/react-lifecycle-component/tsconfig.json b/types/react-lifecycle-component/tsconfig.json new file mode 100644 index 0000000000..d9aad16e53 --- /dev/null +++ b/types/react-lifecycle-component/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-lifecycle-component-tests.tsx" + ] +} diff --git a/types/react-lifecycle-component/tslint.json b/types/react-lifecycle-component/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-lifecycle-component/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-datepicker/index.d.ts b/types/react-native-datepicker/index.d.ts index 365fb6ced6..dd69061311 100644 --- a/types/react-native-datepicker/index.d.ts +++ b/types/react-native-datepicker/index.d.ts @@ -36,6 +36,7 @@ export interface DatePickerProps { customStyles?: any; minuteInterval?: number; TouchableComponent?: React.Component; + locale?: string; } declare class DatePicker extends React.Component { diff --git a/types/react-native-material-ui/index.d.ts b/types/react-native-material-ui/index.d.ts index 91ae62a3fb..b215820f2b 100644 --- a/types/react-native-material-ui/index.d.ts +++ b/types/react-native-material-ui/index.d.ts @@ -1,11 +1,14 @@ -// Type definitions for react-native-material-ui 1.30 +// Type definitions for react-native-material-ui 1.31 // Project: https://github.com/xotahal/react-native-material-ui // Definitions by: Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { Component } from 'react'; -import { ViewStyle, TextStyle, Image } from 'react-native'; +import { StyleProp, ViewStyle as ViewStyleRaw, TextStyle as TextStyleRaw, Image } from 'react-native'; + +export type ViewStyle = StyleProp; +export type TextStyle = StyleProp; export interface ActionButtonProps { actions?: string[] | JSX.Element[] | Array<{ diff --git a/types/react-native-mauron85-background-geolocation/index.d.ts b/types/react-native-mauron85-background-geolocation/index.d.ts new file mode 100644 index 0000000000..19ce3c03c1 --- /dev/null +++ b/types/react-native-mauron85-background-geolocation/index.d.ts @@ -0,0 +1,543 @@ +// Type definitions for react-native-mauron85-background-geolocation 0.5 +// Project: https://github.com/mauron85/react-native-background-geolocation#readme +// Definitions by: Györög Norbert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export type Event = 'location' | 'stationary' | 'activity' | 'start' | 'stop' | 'error' | 'authorization' | 'foreground' | 'background' | 'abort_requested'; +export type iOSActivityType = 'AutomotiveNavigation' | 'OtherNavigation' | 'Fitness' | 'Other'; +export type Provider = 'gps' | 'network' | 'passive' | 'fused'; +export type ActivityType = 'IN_VEHICLE' | 'ON_BICYCLE' | 'ON_FOOT' | 'RUNNING' | 'STILL' | 'TILTING' | 'UNKNOWN' | 'WALKING'; +export type LogLevel = 'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'; +export type HeadlessTaskEventName = 'location' | 'stationary' | 'activity'; + +export interface ConfigureOptions { + /** + * Set location provider + * Platform: all + * @default DISTANCE_FILTER_PROVIDER + * @see {@link https://github.com/mauron85/react-native-background-geolocation/blob/master/PROVIDERS.md|PROVIDERS} + */ + locationProvider?: number; + + /** + * Desired accuracy in meters. Possible values [HIGH_ACCURACY, MEDIUM_ACCURACY, LOW_ACCURACY, PASSIVE_ACCURACY]. + * Accuracy has direct effect on power drain. Lower accuracy = lower power drain. + * Platform: all + * Provider: all + * @default MEDIUM_ACCURACY + */ + desiredAccuracy?: number; + + /** + * Stationary radius in meters. When stopped, the minimum distance the device must move beyond the stationary location for aggressive background-tracking to engage. + * Platform: all + * Provider: DISTANCE_FILTER + * @default 50 + */ + stationaryRadius?: number; + + /** + * When enabled, the plugin will emit sounds for life-cycle events of background-geolocation! See debugging sounds table. + * Platform: all + * Provider: all + * @default false + * @see {@link https://github.com/mauron85/react-native-background-geolocation#debugging-sounds|Debugging sounds} + */ + debug?: boolean; + + /** + * The minimum distance (measured in meters) a device must move horizontally before an update event is generated. + * Platform: all + * Provider: DISTANCE_FILTER, RAW + * @default 500 + * @see {@link https://apple.co/2oHo2CV|Apple docs} + */ + distanceFilter?: number; + + /** + * Enable this in order to force a stop() when the application terminated (e.g. on iOS, double-tap home button, swipe away the app). + * Platform: all + * Provider: all + * @default true + */ + stopOnTerminate?: boolean; + + /** + * Start background service on device boot. + * Platform: Android + * Provider: all + * @default false + */ + startOnBoot?: boolean; + + /** + * The minimum time interval between location updates in milliseconds. + * Platform: Android + * Provider: all + * @default 60000 + * @see {@link https://bit.ly/1x00RUu|Android docs} + */ + interval?: number; + + /** + * Fastest rate in milliseconds at which your app can handle location updates. + * Platform: Android + * Provider: ACTIVITY + * @default 120000 + * @see {@link https://bit.ly/1x00RUu|Android docs} + */ + fastestInterval?: number; + + /** + * Rate in milliseconds at which activity recognition occurs. Larger values will result in fewer activity detections while improving battery life. + * Platform: Android + * Provider: ACTIVITY + * @default 10000 + */ + activitiesInterval?: number; + + /** + * DEPRECATED! + * Stop location updates, when the STILL activity is detected. + * Platform: Android + * Provider: ACTIVITY + * @default true + */ + stopOnStillActivity?: boolean; + + /** + * Enable/disable local notifications when tracking and syncing locations. + * Platform: Android + * Provider: all + * @default true + */ + notificationsEnabled?: boolean; + + /** + * Allow location sync service to run in foreground state. Foreground state also requires a notification to be presented to the user. + * Platform: Android + * Provider: all + * @default false + */ + startForeground?: boolean; + + /** + * Custom notification title in the drawer. + * Platform: Android + * Provider: all + * @default "Background tracking" + */ + notificationTitle?: string; + + /** + * Custom notification text in the drawer. + * Platform: Android + * Provider: all + * @default "ENABLED" + */ + notificationText?: string; + + /** + * The accent color to use for notification. Eg. #4CAF50. + * Platform: Android + * Provider: all + */ + notificationIconColor?: string; + + /** + * The filename of a custom notification icon. + * Platform: Android + * Provider: all + */ + notificationIconLarge?: string; + + /** + * The filename of a custom notification icon. + * Platform: Android + * Provider: all + */ + notificationIconSmall?: string; + + /** + * Presumably, this affects iOS GPS algorithm. + * [AutomotiveNavigation, OtherNavigation, Fitness, Other] + * Platform: iOS + * Provider: all + * @default "OtherNavigation" + * @see {@link https://apple.co/2oHofpH|Apple docs} + */ + activityType?: iOSActivityType; + + /** + * Pauses location updates when app is paused. + * Platform: iOS + * Provider: all + * @default false + * @see {@link https://apple.co/2CbjEW2|Apple docs} + */ + pauseLocationUpdates?: boolean; + + /** + * Switch to less accurate significant changes and region monitory when in background. + * Platform: iOS + * Provider: all + * @default false + */ + saveBatteryOnBackground?: boolean; + + /** + * Server url where to send HTTP POST with recorded locations + * Platform: all + * Provider: all + * @see {@link https://github.com/mauron85/react-native-background-geolocation#http-locations-posting|HTTP locations posting} + */ + url?: string; + + /** + * Server url where to send fail to post locations + * Platform: all + * Provider: all + * @see {@link https://github.com/mauron85/react-native-background-geolocation#http-locations-posting|HTTP locations posting} + */ + syncUrl?: string; + + /** + * Specifies how many previously failed locations will be sent to server at once. + * Platform: all + * Provider: all + * @default 100 + */ + syncThreshold?: string; + + /** + * Optional HTTP headers sent along in HTTP request. + * Platform: all + * Provider: all + */ + httpHeaders?: any; + + /** + * Limit maximum number of locations stored into db. + * Platform: all + * Provider: all + * @default 10000 + */ + maxLocations?: number; + + /** + * Customization post template. + * Platform: all + * Provider: all + * @see {@link https://github.com/mauron85/react-native-background-geolocation#custom-post-template|Custom post template} + */ + postTemplate?: any; +} + +export interface LocationOptions { + /** + * Maximum time in milliseconds device will wait for location. + */ + timeout?: number; + + /** + * Maximum age in milliseconds of a possible cached location that is acceptable to return. + */ + maximumAge?: number; + + /** + * If true and if the device is able to provide a more accurate position, it will do so. + */ + enableHighAccuracy?: boolean; +} + +export interface LocationError { + /** Reason of an error occurring when using the geolocating device. */ + code: number; + + /** Message describing the details of the error */ + message: string; +} + +export interface Location { + /** ID of location as stored in DB (or null) */ + id: number; + provider: Provider; + locationProvider: number; + /** UTC time of this fix, in milliseconds since January 1, 1970. */ + time: number; + /** Latitude, in degrees. */ + latitude: number; + /** Longitude, in degrees. */ + longitude: number; + /** Estimated accuracy of this location, in meters. */ + accuracy: number; + /** Speed if it is available, in meters/second over ground. */ + speed: number; + /** Altitude if available, in meters above the WGS 84 reference ellipsoid. */ + altitude: number; + /** Bearing, in degrees. */ + bearing: number; + /** True if location was recorded by mock provider. (ANDROID ONLY) */ + isFromMockProvider?: boolean; + /** True if device has mock locations enabled. (ANDROID ONLY) */ + mockLocationsEnabled?: boolean; +} + +export interface Activity { + /** Percentage indicating the likelihood user is performing this activity. */ + confidence: number; + /** IN_VEHICLE, ON_BICYCLE, ON_FOOT, RUNNING, STILL, TILTING, UNKNOWN, WALKING */ + type: ActivityType; +} + +export interface LogEntry { + /** ID of log entry as stored in db. */ + id: number; + /** Timestamp in milliseconds since beginning of UNIX epoch. */ + timestamp: number; + level: string; + message: string; + /** Recorded stacktrace. (Android only, on iOS part of message) */ + stackTrace: string; +} + +export interface ServiceStatus { + isRunning: boolean; + locationServicesEnabled: boolean; + authorization: number; + hasPermissions: boolean; +} + +export interface EventSubscription { + remove(): void; +} + +export interface HeadlessTaskEvent { + /** Name of the event [ "location", "stationary", "activity" ] */ + name: HeadlessTaskEventName; + /** + * Event parameters. + * @see {@link https://github.com/mauron85/react-native-background-geolocation#events|Events} + */ + params: any; +} + +export interface BackgroundGeolocationStatic { + DISTANCE_FILTER_PROVIDER: 0; + ACTIVITY_PROVIDER: 1; + RAW_PROVIDER: 2; + + BACKGROUND_MODE: 0; + FOREGROUND_MODE: 1; + + NOT_AUTHORIZED: 0; + AUTHORIZED: 1; + AUTHORIZED_FOREGROUND: 2; + + HIGH_ACCURACY: 0; + MEDIUM_ACCURACY: 100; + LOW_ACCURACY: 1000; + PASSIVE_ACCURACY: 10000; + + LOG_ERROR: 'ERROR'; + LOG_WARN: 'WARN'; + LOG_INFO: 'INFO'; + LOG_DEBUG: 'DEBUG'; + LOG_TRACE: 'TRACE'; + + PERMISSION_DENIED: 1; + LOCATION_UNAVAILABLE: 2; + TIMEOUT: 3; + + events: Event[]; + + /** + * Platform: iOS, Android + * @param options + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#configureoptions-success-fail|Docs} + */ + configure(options: ConfigureOptions, success?: () => void, fail?: () => void): void; + + /** + * Start background geolocation. + * Platform: iOS, Android + * @see {@link https://github.com/mauron85/react-native-background-geolocation#start|Docs} + */ + start(): void; + + /** + * Stop background geolocation. + * Platform: iOS, Android + * @see {@link https://github.com/mauron85/react-native-background-geolocation#stop|Docs} + */ + stop(): void; + + /** + * One time location check to get current location of the device. + * Platform: iOS, Android + * @param success + * @param fail + * @param options + * @see {@link https://github.com/mauron85/react-native-background-geolocation#getcurrentlocationsuccess-fail-options|Docs} + */ + getCurrentLocation(success: (location: Location) => void, fail: (error: LocationError) => void, options: LocationOptions): void; + + /** + * One time check for status of location services. In case of error, fail callback will be executed. + * This method is deprecated and will be removed in next major version. Use checkStatus as replacement. + * Platform: iOS, Android + * @param success + * @param fail + * @deprecated + * @see {@link https://github.com/mauron85/react-native-background-geolocation#islocationenabledsuccess-fail|Docs} + */ + isLocationEnabled(success: (enabled: boolean) => void, fail?: () => void): void; + + /** + * Check status of the service. + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#checkstatussuccess-fail|Docs} + */ + checkStatus(success: (status: ServiceStatus) => void, fail?: () => void): void; + + /** + * Show app settings to allow change of app location permissions. + * Platform: Android >= 6, iOS >= 8.0 + * @see {@link https://github.com/mauron85/react-native-background-geolocation#showappsettings|Docs} + */ + showAppSettings(): void; + + /** + * Show system settings to allow configuration of current location sources. + * Platform: Android + * @see {@link https://github.com/mauron85/react-native-background-geolocation#showlocationsettings|Docs} + */ + showLocationSettings(): void; + + /** + * Method will return all stored locations. This method is useful for initial rendering of user location on a map just after application launch. + * Platform: iOS, Android + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#getlocationssuccess-fail|Docs} + */ + getLocations(success: (locations: Location[]) => void, fail?: () => void): void; + + /** + * Method will return locations which have not yet been posted to server. + * Platform: iOS, Android + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#getvalidlocationssuccess-fail|Docs} + */ + getValidLocations(success: (location: Location[]) => void, fail?: () => void): void; + + /** + * Delete location with locationId. + * Platform: iOS, Android + * @param locationId + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#deletelocationlocationid-success-fail|Docs} + */ + deleteLocation(locationId: number, success?: () => void, fail?: () => void): void; + + /** + * Delete all stored locations. + * Platform: iOS, Android + * You don't need to delete all locations. + * The plugin manages the number of stored locations automatically and the total count never exceeds the number as defined by option.maxLocations. + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#deletealllocationssuccess-fail|Docs} + */ + deleteAllLocations(success?: () => void, fail?: () => void): void; + + /** + * Normally the plugin will handle switching between BACKGROUND and FOREGROUND mode itself. + * Calling switchMode you can override plugin behavior and force it to switch into other mode. + * Platform: iOS + * @param modeId + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#switchmodemodeid-success-fail|Docs} + */ + switchMode(modeId: number, success?: () => void, fail?: () => void): void; + + /** + * Force sync of pending locations. + * Option syncThreshold will be ignored and all pending locations will be immediately posted to syncUrl in single batch. + * Platform: Android, iOS + * @param success + * @param fail + */ + forceSync(success?: () => void, fail?: () => void): void; + + /** + * Return all logged events. Useful for plugin debugging. + * Platform: Android, iOS + * @param limit + * @param fromId + * @param minLevel + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#getlogentrieslimit-fromid-minlevel-success-fail|Docs} + */ + getLogEntries(limit: number, fromId: number, minLevel: LogLevel, success: (entries: LogEntry[]) => void, fail?: () => void): void; + + /** + * Return all logged events. Useful for plugin debugging. + * Platform: Android, iOS + * @param limit + * @param fromId + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#getlogentrieslimit-fromid-minlevel-success-fail|Docs} + */ + getLogEntries(limit: number, fromId: number, success: (entries: LogEntry[]) => void, fail?: () => void): void; + + /** + * Return all logged events. Useful for plugin debugging. + * Platform: Android, iOS + * @param limit + * @param success + * @param fail + * @see {@link https://github.com/mauron85/react-native-background-geolocation#getlogentrieslimit-fromid-minlevel-success-fail|Docs} + */ + getLogEntries(limit: number, success: (entries: LogEntry[]) => void, fail?: () => void): void; + + /** + * Unregister all event listeners for given event. + * @param event + * @see {@link https://github.com/mauron85/react-native-background-geolocation#removealllistenersevent|Docs} + */ + removeAllListeners(event: Event): void; + + /** + * Register event listener. + * @param event + * @param callbackfn + * @see {@link https://github.com/mauron85/react-native-background-geolocation#events|Docs} + */ + on(event: Event, callbackfn: (...args: any[]) => void): EventSubscription; + + startTask(callbackfn: (taskKey: number) => void): void; + + endTask(taskKey: number): void; + + /** + * A special task that gets executed when the app is terminated, but the plugin was configured to continue running in the background (option stopOnTerminate: false). + * In this scenario the {@link https://bit.ly/2okJECK|Activity} was killed by the system and all registered event listeners will not be triggered until the app is relaunched. + * @param callbackfn + * @see {@link https://github.com/mauron85/react-native-background-geolocation#android-headless-task-experimental|Android Headless Task (Experimental)} + */ + headlessTask(callbackfn: (event: HeadlessTaskEvent) => void): void; +} + +declare const BackgroundGeolocation: BackgroundGeolocationStatic; + +export default BackgroundGeolocation; diff --git a/types/react-native-mauron85-background-geolocation/react-native-mauron85-background-geolocation-tests.ts b/types/react-native-mauron85-background-geolocation/react-native-mauron85-background-geolocation-tests.ts new file mode 100644 index 0000000000..3c5934e4ec --- /dev/null +++ b/types/react-native-mauron85-background-geolocation/react-native-mauron85-background-geolocation-tests.ts @@ -0,0 +1,108 @@ +// Test taken from Quick example at https://github.com/mauron85/react-native-background-geolocation#quick-example + +import { Component } from 'react'; +import { Alert } from 'react-native'; +import BackgroundGeolocation from 'react-native-mauron85-background-geolocation'; + +class BgTracking extends Component { + componentDidMount() { + BackgroundGeolocation.configure({ + desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY, + stationaryRadius: 50, + distanceFilter: 50, + notificationTitle: 'Background tracking', + notificationText: 'enabled', + debug: true, + startOnBoot: false, + stopOnTerminate: false, + locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER, + interval: 10000, + fastestInterval: 5000, + activitiesInterval: 10000, + stopOnStillActivity: false, + url: 'http://192.168.81.15:3000/location', + httpHeaders: { + 'X-FOO': 'bar' + }, + // customize post properties + postTemplate: { + lat: '@latitude', + lon: '@longitude', + foo: 'bar' // you can also add your own properties + } + }); + + BackgroundGeolocation.on('location', (location) => { + // handle your locations here + // to perform long running operation on iOS + // you need to create background task + BackgroundGeolocation.startTask(taskKey => { + // execute long running task + // eg. ajax post location + // IMPORTANT: task has to be ended by endTask + BackgroundGeolocation.endTask(taskKey); + }); + }); + + BackgroundGeolocation.on('stationary', (stationaryLocation) => { + // handle stationary locations here + }); + + BackgroundGeolocation.on('error', (error) => { + console.log('[ERROR] BackgroundGeolocation error:', error); + }); + + BackgroundGeolocation.on('start', () => { + console.log('[INFO] BackgroundGeolocation service has been started'); + }); + + BackgroundGeolocation.on('stop', () => { + console.log('[INFO] BackgroundGeolocation service has been stopped'); + }); + + BackgroundGeolocation.on('authorization', (status) => { + console.log('[INFO] BackgroundGeolocation authorization status: ' + status); + if (status !== BackgroundGeolocation.AUTHORIZED) { + // we need to set delay or otherwise alert may not be shown + setTimeout(() => + Alert.alert('App requires location tracking permission', 'Would you like to open app settings?', [ + {text: 'Yes', onPress: () => BackgroundGeolocation.showAppSettings()}, + {text: 'No', onPress: () => console.log('No Pressed'), style: 'cancel'} + ]), 1000); + } + }); + + BackgroundGeolocation.on('background', () => { + console.log('[INFO] App is in background'); + }); + + BackgroundGeolocation.on('foreground', () => { + console.log('[INFO] App is in foreground'); + }); + + BackgroundGeolocation.on('abort_requested', () => { + console.log('[INFO] Server responded with 285 Updates Not Required'); + }); + + BackgroundGeolocation.checkStatus(status => { + console.log('[INFO] BackgroundGeolocation service is running', status.isRunning); + console.log('[INFO] BackgroundGeolocation services enabled', status.locationServicesEnabled); + console.log('[INFO] BackgroundGeolocation auth status: ' + status.authorization); + + // you don't need to check status before start (this is just the example) + if (!status.isRunning) { + BackgroundGeolocation.start(); // triggers start on start event + } + }); + + // you can also just start without checking for status + // BackgroundGeolocation.start(); + } + + componentWillUnmount() { + // unregister all event listeners + BackgroundGeolocation.events.forEach(event => BackgroundGeolocation.removeAllListeners(event)); + } +} + +export default BgTracking; diff --git a/types/react-native-mauron85-background-geolocation/tsconfig.json b/types/react-native-mauron85-background-geolocation/tsconfig.json new file mode 100644 index 0000000000..e0cfccd5e6 --- /dev/null +++ b/types/react-native-mauron85-background-geolocation/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true, + "jsx": "react-native" + }, + "files": [ + "index.d.ts", + "react-native-mauron85-background-geolocation-tests.ts" + ] +} diff --git a/types/react-native-mauron85-background-geolocation/tslint.json b/types/react-native-mauron85-background-geolocation/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-mauron85-background-geolocation/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-snap-carousel/index.d.ts b/types/react-native-snap-carousel/index.d.ts index dca8f53e9f..0679b4ac82 100644 --- a/types/react-native-snap-carousel/index.d.ts +++ b/types/react-native-snap-carousel/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: jnbt // Jacob Froman // Nikolay Polukhin +// Guillaume Amat // Vitor Luiz Cavalcanti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -229,7 +230,7 @@ export interface CarouselProps extends React.Props { /** * Used to define custom interpolations */ - slideInterpolatedStyle?(animatedValue: number, carouselProps: CarouselProps): StyleProp; + slideInterpolatedStyle?(index: number, animatedValue: Animated.AnimatedValue, carouselProps: CarouselProps): StyleProp; /** * Optional style for each item's container (the one whose scale and opacity are animated) */ diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 6a54805118..98f6c92c3f 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -31,6 +31,7 @@ /// /// +import * as PropTypes from 'prop-types'; import * as React from 'react'; type Constructor = new(...args: any[]) => T; @@ -2179,7 +2180,7 @@ export interface WebViewIOSLoadRequestEvent { loading: boolean; title: string; canGoForward: boolean; - navigationType: "other" | "click"; + navigationType: "click" | "formsubmit" | "backforward" | "reload" | "formresubmit" | "other"; url: string; } @@ -2252,7 +2253,7 @@ export interface WebViewUriSource { * The HTTP Method to use. Defaults to GET if not specified. * NOTE: On Android, only GET and POST are supported. */ - method?: string; + method?: "GET" | "POST"; /* * Additional HTTP headers to send with the request. @@ -8465,8 +8466,8 @@ export namespace Animated { export function parallel(animations: Array, config?: ParallelConfig): CompositeAnimation; type Mapping = { [key: string]: Mapping } | AnimatedValue; - interface EventConfig { - listener?: ValueListenerCallback; + interface EventConfig { + listener?: (event?: NativeSyntheticEvent) => void; useNativeDriver?: boolean; } @@ -8486,7 +8487,7 @@ export namespace Animated { * ]), *``` */ - export function event(argMapping: Array, config?: EventConfig): (...args: any[]) => void; + export function event(argMapping: Array, config?: EventConfig): (...args: any[]) => void; /** * Make any React component Animatable. Used to create `Animated.View`, etc. @@ -8936,7 +8937,7 @@ export const PixelRatio: PixelRatioStatic; export interface ComponentInterface

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

; } /** @@ -8958,7 +8959,7 @@ export function requireNativeComponent

( viewName: string, componentInterface?: ComponentInterface

, extraConfig?: { nativeOnly?: any } -): React.ComponentClass

; +): React.ComponentClass>>; export function findNodeHandle( componentOrHandle: null | number | React.Component | React.ComponentClass @@ -9001,10 +9002,10 @@ export namespace addons { // // Prop Types // -export const ColorPropType: React.Requireable; -export const EdgeInsetsPropType: React.Requireable; -export const PointPropType: React.Requireable; -export const ViewPropTypes: React.Requireable; +export const ColorPropType: React.Validator; +export const EdgeInsetsPropType: React.Validator; +export const PointPropType: React.Validator; +export const ViewPropTypes: React.ValidationMap; declare global { function require(name: string): any; diff --git a/types/react-native/test/animated.tsx b/types/react-native/test/animated.tsx index c27af04bb9..40f8c37ee7 100644 --- a/types/react-native/test/animated.tsx +++ b/types/react-native/test/animated.tsx @@ -1,6 +1,6 @@ -import * as React from "react-native"; +import * as React from "react"; -import { Animated, View } from "react-native"; +import { Animated, View, NativeSyntheticEvent, NativeScrollEvent } from "react-native"; function TestAnimatedAPI() { // Value @@ -63,6 +63,17 @@ function TestAnimatedAPI() { Animated.stagger(100, [spring1, springXY]); + const listener = (e?: NativeSyntheticEvent) => { + if (e) { + console.warn(e.nativeEvent.contentOffset.y); + } + }; + + Animated.event( + [{ nativeEvent: { contentOffset: { y: v1 } } }], + { useNativeDriver: true, listener }, + ); + return ( (e: NativeSyntheticEvent): voi e.nativeEvent; } +type ElementProps = C extends React.Component ? P : never; + class CustomView extends React.Component { render() { return Custom View; } } -class Welcome extends React.Component { +class Welcome extends React.Component & { color: string }> { + static propTypes = { + ...ViewPropTypes, + color: ColorPropType, + }; + refs: { [key: string]: any; rootView: View; @@ -218,8 +227,9 @@ class Welcome extends React.Component { } render() { + const { color, ...props } = this.props; return ( - + Welcome to React Native To get started, edit index.ios.js @@ -628,6 +638,7 @@ class WebViewTest extends React.Component { originWhitelist={['https://origin.test']} saveFormDataDisabled={false} nativeConfig={{ component: 'test', props: {}, viewManager: {} }} + onShouldStartLoadWithRequest={(event) => event.navigationType !== 'formresubmit'} /> ); } diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index b52c4829f5..1e6211926e 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -23,6 +23,7 @@ // Jake // Gustavo Brunoro // Denis Frezzato +// Mickael Wegerich // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -457,10 +458,16 @@ export type NavigationTabAction = | NavigationNavigateAction | NavigationBackAction; +export type NavigationDrawerAction = + | NavigationOpenDrawerAction + | NavigationCloseDrawerAction + | NavigationToggleDrawerAction; + export type NavigationAction = | NavigationInitAction | NavigationStackAction - | NavigationTabAction; + | NavigationTabAction + | NavigationDrawerAction; export type NavigationRouteConfig = | NavigationComponent @@ -600,7 +607,7 @@ export interface NavigationEventsProps extends ViewProps { export const NavigationEvents: React.ComponentType; export interface NavigationScreenProp { - state: S; + state: S & { params?: P }; dispatch: NavigationDispatch; goBack: (routeKey?: string | null) => boolean; dismiss: () => boolean; diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index 6bf037eb4a..a9063577a6 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -336,6 +336,24 @@ function renderBasicDrawerNavigator(): JSX.Element { ); } +interface ParamsOnStateProps { + navigation: NavigationScreenProp<{}, { foobar: string }>; +} + +class ParamsOnState extends React.Component { + render() { + if (this.props.navigation.state.params) { + // $ExpectType string + this.props.navigation.state.params.foobar; + } else { + // $ExpectType undefined + this.props.navigation.state.params; + } + + return ; + } +} + interface CustomTransitionerProps { navigation: NavigationScreenProp; } diff --git a/types/react-numeric-input/index.d.ts b/types/react-numeric-input/index.d.ts index bc28d95825..8dc64f3ba3 100644 --- a/types/react-numeric-input/index.d.ts +++ b/types/react-numeric-input/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for react-numeric-input 2.2 // Project: https://github.com/vlad-ignatov/react-numeric-input#readme // Definitions by: Heather Booker +// Aarni Koskela // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -9,38 +10,52 @@ import * as React from 'react'; export = NumericInput; declare namespace NumericInput { - interface NumericInputProps extends React.Props { + type BoundsFunctionProp = number | ((component: NumericInput) => number | undefined); + type Omit = Pick>; // via TS 2.8 manual + interface NumericInputProps extends Omit< + React.InputHTMLAttributes, + 'min' | 'max' | 'step' | 'onChange' | 'defaultValue' | 'onInvalid' | 'style' + > { addLabelText?: string; - className?: string; + componentClass?: string; defaultValue?: number | string; - disabled?: boolean; - format?: ((s: string) => string); - max?: number | ((v: number) => number); - maxLength?: number; - min?: number | ((v: number) => number); - mobile?: boolean | 'auto' | ((this: NumericInput) => any); // TODO: fix `any` - noValidate?: boolean| string; + format?: ((value: number | null) => string); + max?: BoundsFunctionProp; + min?: BoundsFunctionProp; + mobile?: boolean | 'auto' | ((component: NumericInput) => boolean); + noStyle?: boolean; + noValidate?: boolean | string; onBlur?: React.FocusEventHandler; - onChange?: ((v: number, s: string, i: JSX.Element) => void); + onChange?: ((value: number | null, stringValue: string, input: HTMLInputElement) => void); onFocus?: React.FocusEventHandler; - onInput?: ((...args: any[]) => void); - onInvalid?: ((err: string, v: number, s: string) => void); + onInput?: React.FormEventHandler; + onInvalid?: ((error: string, value: number | null, stringValue: string) => void); onKeyDown?: React.KeyboardEventHandler; - onSelect?: ((...args: any[]) => void); - onValid?: ((v: number, s: string) => void); - parse?: ((s: string) => number | string); - pattern?: string; - precision?: number | ((this: NumericInput) => void); - readOnly?: boolean; - required?: boolean; - size?: number | string; + onSelect?: React.ReactEventHandler; + onValid?: ((value: number | null, stringValue: string) => void); + parse?: ((stringValue: string) => number | null); + precision?: number | ((component: NumericInput) => number | null | undefined); snap?: boolean; - step?: number | object; // TODO: should be `number | ` + step?: number | ((component: NumericInput, direction: string) => number | undefined); strict?: boolean; - style?: { [key: string]: { [key: string]: string } } | boolean; - type?: string; + style?: {[key: string]: React.CSSProperties} | boolean; value?: number | string; } + // Exposed here for the function prop handlers that get the NumericInput instance as a parameter. + // Lifted directly from react-numeric-input@79874ccbe:/src/NumericInput.jsx#L63-L73 + interface NumericInputState { + btnDownActive?: boolean; + btnDownHover?: boolean; + btnUpActive?: boolean; + btnUpHover?: boolean; + selectionEnd?: number | null; + selectionStart?: number | null; + stringValue?: string; + value?: number | null; + } } -declare class NumericInput extends React.Component {} +declare class NumericInput extends React.Component { + static DIRECTION_UP: string; + static DIRECTION_DOWN: string; +} diff --git a/types/react-numeric-input/react-numeric-input-tests.tsx b/types/react-numeric-input/react-numeric-input-tests.tsx index 811b77a4c7..fc55835330 100644 --- a/types/react-numeric-input/react-numeric-input-tests.tsx +++ b/types/react-numeric-input/react-numeric-input-tests.tsx @@ -3,6 +3,16 @@ import NumericInput = require('react-numeric-input'); export class NumericInputTest extends Component { render() { - return(); + return ( + (comp.state.value || 1) + 1} + format={(x) => `EUR ${x}`} + parse={(s) => parseFloat(s.replace(/EUR /, ''))} + step={(comp, dir) => (dir === NumericInput.DIRECTION_UP ? 9 : 1)} + style={{wrap: {color: 'orange'}}} + className="hello" + /> + ); } } diff --git a/types/react-onsenui/index.d.ts b/types/react-onsenui/index.d.ts index 1b90fb1c50..3124fa32f2 100644 --- a/types/react-onsenui/index.d.ts +++ b/types/react-onsenui/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for React Onsen UI (react-onsenui) 2.9 +// Type definitions for React Onsen UI (react-onsenui) 2.9.4 // Project: https://onsen.io/v2/docs/guide/react/ -// Definitions by: Ozytis , Salim , Jemmyw +// Definitions by: Ozytis , +// Salim , +// Jemmyw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -291,12 +293,15 @@ export class Fab extends Component<{ position?: string, disabled?: boolean, onClick?(e?: React.MouseEvent): void, + name?: string, + className?: string }, any> {} export class Button extends Component<{ modifier?: string, disabled?: boolean, ripple?: boolean, + name?: string, className?: string, onClick?(e?: React.MouseEvent): void }, any> {} @@ -304,8 +309,12 @@ export class Button extends Component<{ export class Input extends Component<{ modifier?: string, disabled?: boolean, + readOnly?: boolean, onChange?: (e: React.ChangeEvent) => void, + onBlur?: (e: React.FocusEvent) => void, + onFocus?: (e: React.FocusEvent) => void, value?: string, + defaultValue?: string, checked?: boolean, placeholder?: string, type?: string, @@ -321,7 +330,10 @@ export class Radio extends Component<{ onChange?(e: Event): void, value?: string, checked?: boolean, - inputId?: string + defaultChecked?: boolean, + inputId?: string, + name?: string, + className?: string }, any> {} export class Checkbox extends Component<{ @@ -330,7 +342,9 @@ export class Checkbox extends Component<{ onChange?(e: Event): void, value?: string, checked?: boolean, - inputId?: string + inputId?: string, + name?: string, + className?: string }, any> {} export class Range extends Component<{ @@ -349,14 +363,18 @@ export class Select extends Component<{ autofocus?: boolean, required?: boolean, form?: string, - size?: string + size?: string, + name?: string, + className?: string }, any> {} export class Switch extends Component<{ + modifier?: string, onChange?(e: SwitchChangeEvent): void, checked?: boolean, disabled?: boolean, inputId?: string, + name?: string, className?: string }, any> {} diff --git a/types/react-onsenui/react-onsenui-tests.tsx b/types/react-onsenui/react-onsenui-tests.tsx index a2c2534914..b4f4d540b3 100644 --- a/types/react-onsenui/react-onsenui-tests.tsx +++ b/types/react-onsenui/react-onsenui-tests.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; import { SplitterSide, Splitter, SplitterContent, - Page, Input, Button, + Page, Input, Button, Radio, Checkbox, Select, Switch, } from "react-onsenui"; class AppState { @@ -19,7 +19,12 @@ export class App extends React.Component { } onChange(event: React.ChangeEvent) {} + onBlur(event: React.FocusEvent) {} + onFocus(event: React.FocusEvent) {} onClick(event: React.MouseEvent) {} + onRadioChange(event: Event) {} + onCheckboxChange(event: Event) {} + onSelectChange(event: React.ChangeEvent) {} render() { return ( @@ -38,8 +43,16 @@ export class App extends React.Component { Test page - - + + + + Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt magni, voluptas debitis + similique porro a molestias consequuntur earum odio officiis natus, amet hic, iste sed + dignissimos esse fuga! Minus, alias. + + + + + ); +} diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index f0ad8596ab..a3f1a5625e 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -19,8 +19,8 @@ declare module 'recompose' { type predicate = mapper; type predicateDiff = (current: T, next: T) => boolean - // Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766 - type Omit = Pick; + // Diff / Omit taken from https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html + type Omit = Pick> interface Observer{ next(props: T): void; diff --git a/types/redux-form/lib/FieldArray.d.ts b/types/redux-form/lib/FieldArray.d.ts index d800452a3e..f321164b84 100644 --- a/types/redux-form/lib/FieldArray.d.ts +++ b/types/redux-form/lib/FieldArray.d.ts @@ -34,6 +34,7 @@ interface FieldsProps { forEach(callback: FieldIterate): void; get(index: number): FieldValue; getAll(): FieldValue[]; + removeAll(): void; insert(index: number, value: FieldValue): void; length: number; map(callback: FieldIterate): R[]; diff --git a/types/redux-little-router/index.d.ts b/types/redux-little-router/index.d.ts deleted file mode 100644 index 5ea39ce138..0000000000 --- a/types/redux-little-router/index.d.ts +++ /dev/null @@ -1,171 +0,0 @@ -// Type definitions for redux-little-router 14.0 -// Project: https://github.com/FormidableLabs/redux-little-router -// Definitions by: priecint -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import * as React from "react"; -import { Reducer, Middleware, StoreEnhancer } from "redux"; - -export interface Routes { - [index: string]: RouteDefinition; -} - -export interface RouteDefinition { - [index: string]: string | RouteDefinition; -} - -export interface LocationOptions { - persistQuery?: boolean; -} - -export interface Query { - [key: string]: string; -} - -export interface Params { - [key: string]: string; -} - -export interface Location { - pathname?: string; - options?: LocationOptions; - params?: Params; - previous?: Location; - query?: Query; - result?: TResult; - hash?: string; -} - -export interface BrowserRouterOptions { - routes: Routes; - basename?: string; -} - -export interface RouterState { - router: Location; -} - -export function routerForBrowser(options: BrowserRouterOptions): { - reducer: Reducer; - middleware: Middleware; - enhancer: StoreEnhancer; -}; - -export interface ServerRouterOptions { - routes: Routes; - request: { - path: string; - baseUrl: string; - url: string; - query: { - [key: string]: string; - } - }; -} - -export function routerForExpress(options: ServerRouterOptions): { - reducer: Reducer; - middleware: Middleware; - enhancer: StoreEnhancer; -}; - -export interface HapiRouterOptions { - routes: Routes; - request: { - path: string; - url: string; - query: { - [key: string]: string; - } - }; -} - -export function routerForHapi(options: HapiRouterOptions): { - reducer: Reducer; - middleware: Middleware; - enhancer: StoreEnhancer; -}; - -export function initializeCurrentLocation(location: Location): { - type: string; - payload: Location; -}; - -export interface PersistentQueryLinkProps { - className?: string; - href: Href; - persistQuery?: boolean; - target?: string; - onClick?: React.EventHandler>; -} - -export interface LinkProps extends PersistentQueryLinkProps { - replaceState?: boolean; -} - -export class Link extends React.Component { -} - -export class PersistentQueryLink extends React.Component { -} - -export interface FragmentPropsForRoute { - forRoute: string; -} - -export interface FragmentPropsWithConditions { - withConditions: (location: Location) => boolean; -} - -// https://stackoverflow.com/q/37688318 -export type FragmentProps = FragmentPropsForRoute | FragmentPropsWithConditions | (FragmentPropsForRoute & FragmentPropsWithConditions); - -export class Fragment extends React.Component { -} - -export type Href = string | Location; - -export function push(href: Href, options?: LocationOptions): { - type: string; - payload: Location & { - state: { - reduxLittleRouter: { - query: {}; - options: LocationOptions; - }; - }; - }; -}; - -export function replace(href: Href, options?: LocationOptions): { - type: string; - payload: Location & { - state: { - reduxLittleRouter: { - query: {}; - options: LocationOptions; - }; - }; - }; -}; - -export function go(index: number): { - type: string; - payload: number; -}; - -export function goBack(): { - type: string; -}; - -export function goForward(): { - type: string; -}; - -export const LOCATION_CHANGED: string; -export const PUSH: string; -export const REPLACE: string; -export const GO: string; -export const GO_BACK: string; -export const GO_FORWARD: string; diff --git a/types/redux-little-router/redux-little-router-tests.tsx b/types/redux-little-router/redux-little-router-tests.tsx deleted file mode 100644 index ad65cc399d..0000000000 --- a/types/redux-little-router/redux-little-router-tests.tsx +++ /dev/null @@ -1,93 +0,0 @@ -import * as React from "react"; -import { createStore, compose, combineReducers, applyMiddleware, Reducer, Dispatch } from "redux"; -import { connect } from "react-redux"; - -import { - Fragment, - go, - GO, - GO_BACK, - GO_FORWARD, - goBack, - goForward, - Href, - initializeCurrentLocation, - Link, - Location, - LOCATION_CHANGED, - LocationOptions, - Params, - push, - PUSH, - replace, - REPLACE, - routerForBrowser, - RouterState -} from "redux-little-router"; - -const goBackActionType: string = GO_BACK; -const goForwardActionType: string = GO_FORWARD; -const locationChangedActionType: string = LOCATION_CHANGED; -const pushActionType: string = PUSH; -const replaceActionType: string = REPLACE; - -const { - reducer, - middleware, - enhancer -} = routerForBrowser({ - routes: { - "/": { - title: "Home" - } - } -}); - -const store = createStore( - combineReducers({ router: reducer }), - { router: {} }, - compose(enhancer, applyMiddleware(middleware)) -); - -const initialLocation = store.getState().router; - -if (initialLocation) { - store.dispatch(initializeCurrentLocation(initialLocation)); -} - -interface TestProps { - currentPath?: string; -} - -interface DispatchProps { - go: (index: number) => void; - goBack: () => void; - goForward: () => void; - push: (path: string) => void; - replace: (path: string) => void; -} - -const TestComponent: React.SFC = ({ currentPath }) => ( -

- -
- Current Path: {currentPath} - -
-
-
-); - -const mapStateToProps = (state: RouterState): TestProps => ({ - currentPath: state.router.pathname -}); - -const mapDispatchToProps = (dispatch: Dispatch<{}>): DispatchProps => ({ - go: index => dispatch(go(index)), - goBack: () => dispatch(goBack()), - goForward: () => dispatch(goForward()), - push: path => dispatch(push(path)), - replace: path => dispatch(replace(path)) -}); - -const connectedTest = connect(mapStateToProps)(TestComponent); diff --git a/types/rrc/rrc-tests.tsx b/types/rrc/rrc-tests.tsx index 74f15045f4..5a7cd7e224 100644 --- a/types/rrc/rrc-tests.tsx +++ b/types/rrc/rrc-tests.tsx @@ -13,7 +13,7 @@ import { OnUpdateCall } from "rrc"; -class RouteOne extends React.Component> { +class RouteOne extends React.Component { render() { return
> { } } -class RouteTwo extends React.Component> { +class RouteTwo extends React.Component { private readonly onUpdate: OnUpdateCall = (location) => { console.log("update"); }; render() { @@ -64,7 +64,7 @@ interface Params { page: number; } -class RouteFour extends React.Component> { +class RouteFour extends React.Component { private readonly routes: RouteConfiguration[] = [ { path: "/four/something/:page", component: RouteTwo } ]; diff --git a/types/sanitize-html/index.d.ts b/types/sanitize-html/index.d.ts index 2e7527e3fc..f90ec12f65 100644 --- a/types/sanitize-html/index.d.ts +++ b/types/sanitize-html/index.d.ts @@ -4,8 +4,12 @@ // Afshin Darian // BehindTheMath // Rinze de Laat +// Will Gibson +// A penguin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import {Options} from "htmlparser2"; + export = sanitize; declare function sanitize(dirty: string, options?: sanitize.IOptions): string; @@ -51,6 +55,7 @@ declare namespace sanitize { nonTextTags?: string[]; selfClosing?: string[]; transformTags?: { [tagName: string]: string | Transformer }; + parser?: Options; } diff --git a/types/sanitize-html/sanitize-html-tests.ts b/types/sanitize-html/sanitize-html-tests.ts index b02a5a6653..0fbce8ed44 100644 --- a/types/sanitize-html/sanitize-html-tests.ts +++ b/types/sanitize-html/sanitize-html-tests.ts @@ -35,3 +35,9 @@ let options: sanitize.IOptions = { let unsafe = '
'; let safe = sanitize(unsafe, options); + +options.parser = { + decodeEntities: true +}; + +safe = sanitize(unsafe, options); diff --git a/types/screenfull/index.d.ts b/types/screenfull/index.d.ts index 26b9188bde..0ca3d642b9 100644 --- a/types/screenfull/index.d.ts +++ b/types/screenfull/index.d.ts @@ -1,11 +1,12 @@ -// Type definitions for screenfull.js 3.3.0 +// Type definitions for screenfull.js 3.3.3 // Project: https://github.com/sindresorhus/screenfull.js // Definitions by: Ilia Choly // lionelb // Joel Shepherd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.5 -declare var screenfull: IScreenfull; +declare var screenfull: IScreenfull | false; interface IScreenfullRaw { requestFullscreen?: string; diff --git a/types/screenfull/screenfull-tests.ts b/types/screenfull/screenfull-tests.ts index efb03da1ab..db6f2a1b25 100644 --- a/types/screenfull/screenfull-tests.ts +++ b/types/screenfull/screenfull-tests.ts @@ -1,40 +1,40 @@ import screenfull = require('screenfull'); function test_fullscreen_page() { - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.request(); } } function test_fullscreen_element() { var elem = document.getElementById('target'); - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.request(elem); } } function test_toggle() { var elem = document.getElementById('target'); - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.toggle(elem); } } function test_exit() { - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.request(); } document.getElementById('target').addEventListener('click', function () { - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.exit(); } }) } function test_raw_detect_change() { - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { document.addEventListener(screenfull.raw.fullscreenchange, function () { - if (screenfull.isFullscreen) { + if (screenfull && screenfull.isFullscreen) { console.log('fullscreen'); } else { console.log('not fullscreen'); @@ -44,7 +44,7 @@ function test_raw_detect_change() { } function test_raw_error() { - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { document.addEventListener(screenfull.raw.fullscreenerror, function (event) { console.error('Failed to enable fullscreen', event); }); @@ -52,9 +52,9 @@ function test_raw_error() { } function test_detect_change() { - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.onchange(function () { - if (screenfull.isFullscreen) { + if (screenfull && screenfull.isFullscreen) { console.log('fullscreen'); } else { console.log('not fullscreen'); @@ -64,7 +64,7 @@ function test_detect_change() { } function test_detect_error() { - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.onerror(function (event) { console.error('Failed to enable fullscreen', event); }); @@ -72,9 +72,9 @@ function test_detect_error() { } function test_listener_on() { - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.on('change', function () { - if (screenfull.isFullscreen) { + if (screenfull && screenfull.isFullscreen) { console.log('fullscreen'); } else { console.log('not fullscreen'); @@ -87,9 +87,9 @@ function test_listener_on() { } function test_listener_off() { - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.off('change', function () { - if (screenfull.isFullscreen) { + if (screenfull && screenfull.isFullscreen) { console.log('fullscreen'); } else { console.log('not fullscreen'); @@ -103,7 +103,7 @@ function test_listener_off() { function test_access_element() { var elem = document.getElementById('target'); - if (screenfull.enabled) { + if (screenfull && screenfull.enabled) { screenfull.request(elem); if (elem !== screenfull.element) { alert('incorrect element property'); diff --git a/types/scrypt-js/index.d.ts b/types/scrypt-js/index.d.ts new file mode 100644 index 0000000000..e3ee7fa68f --- /dev/null +++ b/types/scrypt-js/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for scrypt-js 2.0 +// Project: https://github.com/ricmoo/scrypt-js +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function scrypt( + password: Buffer, + salt: Buffer, + N: number, + r: number, + p: number, + dklen: number, + callback: ( + error: Error | undefined | null, + progress: number, + key?: string, + ) => void +): void; + +export = scrypt; diff --git a/types/scrypt-js/scrypt-js-tests.ts b/types/scrypt-js/scrypt-js-tests.ts new file mode 100644 index 0000000000..21c77fb16c --- /dev/null +++ b/types/scrypt-js/scrypt-js-tests.ts @@ -0,0 +1,7 @@ +import scrypt = require('scrypt-js'); + +const testBuffer = Buffer.from('test'); +const testCB = (err: Error | undefined | null, progress: number) => {}; + +// $ExpectType void +scrypt(testBuffer, testBuffer, 1, 1, 1, 1, testCB); diff --git a/types/scrypt-js/tsconfig.json b/types/scrypt-js/tsconfig.json new file mode 100644 index 0000000000..8c6c60e736 --- /dev/null +++ b/types/scrypt-js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "scrypt-js-tests.ts" + ] +} diff --git a/types/scrypt-js/tslint.json b/types/scrypt-js/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/scrypt-js/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sharedb/index.d.ts b/types/sharedb/index.d.ts index 7b34c85583..1620808f99 100644 --- a/types/sharedb/index.d.ts +++ b/types/sharedb/index.d.ts @@ -5,9 +5,7 @@ /// -import { Doc, Query, Error, Action, RawOp, Op } from './lib/sharedb'; - -type UseCallback = ((request: {action: Action, agent: any, req: any, collection: string, id: string, query: any, op: RawOp}, callback: () => void) => void); +import * as ShareDB from './lib/sharedb'; interface PubSubOptions { prefix?: string; @@ -24,13 +22,36 @@ declare class sharedb { addProjection(name: string, collection: string, fields: {}): any; listen(stream: any): void; close(callback?: (err: Error) => any): void; - use(action: Action, fn: UseCallback); - types: { - register: () => void + use(action: sharedb.UseAction, fn: sharedb.UseCallback); + static types: { + register: (type: { name?: string, uri?: string, [key: string]: any}) => void; }; } declare namespace sharedb { + type UseAction = 'connect' | 'op' | 'doc' | 'query' | 'submit' | 'apply' | 'commit' | 'after submit' | 'receive'; + type UseCallback = ((request: {action: UseAction, agent: any, req: any, collection: string, id: string, query: any, op: ShareDB.RawOp}, callback: () => void) => void); + + abstract class DB { + projectsSnapshots: boolean; + disableSubscribe: boolean; + close(callback?: () => void): void; + commit(collection: string, id: string, op: Op, snapshot, options, callback: (...args: any[]) => any): void; + getSnapshot(collection: string, id: string, fields, options, callback: (...args: any[]) => any): void; + getSnapshotBulk(collection: string, ids: string, fields, options, callback: (...args: any[]) => any): void; + getOps(collection: string, id: string, from: number, to: number, options, callback: (...args: any[]) => any): void; + getOpsToSnapshot(collection: string, id: string, from: number, snapshot: number, options, callback: (...args: any[]) => any): void; + getOpsBulk(collection: string, fromMap, toMap, options, callback: (...args: any[]) => any): void; + getCommittedOpVersion(collection: string, id: string, snapshot, op, options, callback: (...args: any[]) => any): void; + query(collection: string, query: Query, fields, options, callback: (...args: any[]) => any): void; + queryPoll(collection: string, query: Query, options, callback: (...args: any[]) => any): void; + queryPollDoc(collection: string, id: string, query: Query, options, callback: (...args: any[]) => any): void; + canPollDoc(): boolean; + skipPoll(): boolean; + } + + class MemoryDB extends DB { } + abstract class PubSub { private static shallowCopy(obj: any); protected prefix?: string; @@ -56,8 +77,26 @@ declare namespace sharedb { class Connection { constructor(ws: WebSocket); - get(collectionName: string, documentID: string): Doc; - createFetchQuery(collectionName: string, query: string, options: {results?: Query[]}, callback: (err: Error, results: any) => any): Query; - createSubscribeQuery(collectionName: string, query: string, options: {results?: Query[]}, callback: (err: Error, results: any) => any): Query; + get(collectionName: string, documentID: string): ShareDB.Doc; + createFetchQuery(collectionName: string, query: string, options: {results?: ShareDB.Query[]}, callback: (err: Error, results: any) => any): ShareDB.Query; + createSubscribeQuery(collectionName: string, query: string, options: {results?: ShareDB.Query[]}, callback: (err: Error, results: any) => any): ShareDB.Query; } + type Doc = ShareDB.Doc; + type Query = ShareDB.Query; + type Error = ShareDB.Error; + type Op = ShareDB.Op; + type AddNumOp = ShareDB.AddNumOp; + type ListMoveOp = ShareDB.ListMoveOp; + type ListInsertOp = ShareDB.ListInsertOp; + type ListDeleteOp = ShareDB.ListDeleteOp; + type ListReplaceOp = ShareDB.ListReplaceOp; + type StringInsertOp = ShareDB.StringInsertOp; + type StringDeleteOp = ShareDB.StringDeleteOp; + type ObjectInsertOp = ShareDB.ObjectInsertOp; + type ObjectDeleteOp = ShareDB.ObjectDeleteOp; + type ObjectReplaceOp = ShareDB.ObjectReplaceOp; + type SubtypeOp = ShareDB.SubtypeOp; + + type Path = ShareDB.Path; + type ShareDBSourceOptions = ShareDB.ShareDBSourceOptions; } diff --git a/types/sharedb/lib/client.d.ts b/types/sharedb/lib/client.d.ts index ad8328dc83..08999f2449 100644 --- a/types/sharedb/lib/client.d.ts +++ b/types/sharedb/lib/client.d.ts @@ -1,12 +1,28 @@ /// -import * as WebSocket from 'ws'; +import * as WS from 'ws'; import * as ShareDB from './sharedb'; export class Connection { - constructor(ws: WebSocket); + constructor(ws: WebSocket | WS); get(collectionName: string, documentID: string): Doc; createFetchQuery(collectionName: string, query: string, options: {results?: Query[]}, callback: (err: Error, results: any) => any): Query; createSubscribeQuery(collectionName: string, query: string, options: {results?: Query[]}, callback: (err: Error, results: any) => any): Query; } export type Doc = ShareDB.Doc; export type Query = ShareDB.Query; +export type Error = ShareDB.Error; +export type Op = ShareDB.Op; +export type AddNumOp = ShareDB.AddNumOp; +export type ListMoveOp = ShareDB.ListMoveOp; +export type ListInsertOp = ShareDB.ListInsertOp; +export type ListDeleteOp = ShareDB.ListDeleteOp; +export type ListReplaceOp = ShareDB.ListReplaceOp; +export type StringInsertOp = ShareDB.StringInsertOp; +export type StringDeleteOp = ShareDB.StringDeleteOp; +export type ObjectInsertOp = ShareDB.ObjectInsertOp; +export type ObjectDeleteOp = ShareDB.ObjectDeleteOp; +export type ObjectReplaceOp = ShareDB.ObjectReplaceOp; +export type SubtypeOp = ShareDB.SubtypeOp; + +export type Path = ShareDB.Path; +export type ShareDBSourceOptions = ShareDB.ShareDBSourceOptions; diff --git a/types/sharedb/lib/sharedb.d.ts b/types/sharedb/lib/sharedb.d.ts index 1b9b7ee5df..426eac5a0e 100644 --- a/types/sharedb/lib/sharedb.d.ts +++ b/types/sharedb/lib/sharedb.d.ts @@ -1,3 +1,5 @@ +import { EventEmitter } from 'events'; + export type Path = ReadonlyArray; export type Snapshot = number; @@ -29,7 +31,6 @@ export interface RawOp { d: string; } export type OTType = 'ot-text' | 'ot-json0' | 'ot-text-tp2' | 'rich-text'; -export type Action = 'connect'|'op'|'doc'|'query'|'submit'|'apply'|'commit'|'after submit'|'receive'; export interface Error { code: number; message: string; @@ -41,27 +42,44 @@ export interface ShareDBSourceOptions { source?: boolean; } export type Callback = (err: Error) => any; -export class Doc { +export type DocEvent = 'load' | 'create' | 'before op' | 'op' | 'del' | 'error' | 'no write pending' | 'nothing pending'; + +export class Doc extends EventEmitter { type: string; id: string; data: any; fetch: (callback: (err: Error) => void) => void; subscribe: (callback: (err: Error) => void) => void; - on: (event: 'load'|'create'|'before op'|'op'|'del'|'error', callback: (...args: any[]) => any) => void; - ingestSnapshot: (snapshot: Snapshot, callback: Callback) => void; - destroy: () => void; + + on(event: 'load' | 'no write pending' | 'nothing pending', callback: () => void): this; + on(event: 'create', callback: (source: boolean) => void): this; + on(event: 'op' | 'before op', callback: (ops: Op[], source: boolean) => void): this; + on(event: 'del', callback: (data: any, source: boolean) => void): this; + on(event: 'error', callback: (err: Error) => void): this; + + addListener(event: 'load' | 'no write pending' | 'nothing pending', callback: () => void): this; + addListener(event: 'create', callback: (source: boolean) => void): this; + addListener(event: 'op' | 'before op', callback: (ops: Op[], source: boolean) => void): this; + addListener(event: 'del', callback: (data: any, source: boolean) => void): this; + addListener(event: 'error', callback: (err: Error) => void): this; + + ingestSnapshot(snapshot: Snapshot, callback: Callback): void; + destroy(): void; create(data: any, callback?: Callback): void; create(data: any, type?: OTType, callback?: Callback): void; create(data: any, type?: OTType, options?: ShareDBSourceOptions, callback?: Callback): void; - submitOp: (data: ReadonlyArray, options?: ShareDBSourceOptions, callback?: Callback) => void; - del: (options: ShareDBSourceOptions, callback: (err: Error) => void) => void; - removeListener: (eventName: string, listener: () => any) => void; + submitOp(data: ReadonlyArray, options?: ShareDBSourceOptions, callback?: Callback): void; + del(options: ShareDBSourceOptions, callback: (err: Error) => void): void; + whenNothingPending(callback: (err: Error) => void): void; } -export class Query { +export type QueryEvent = 'ready' | 'error' | 'changed' | 'insert' | 'move' | 'remove' | 'extra'; +export class Query extends EventEmitter { ready: boolean; results: Doc[]; extra: any; - on: (event: 'ready'|'error'|'changed'|'insert'|'move'|'remove'|'extra', callback: (...args: any[]) => any) => any; - destroy: () => void; + on(event: QueryEvent, callback: (...args: any[]) => any): this; + addListener(event: QueryEvent, callback: (...args: any[]) => any): this; + removeListener(event: QueryEvent, listener: (...args: any[]) => any): this; + destroy(): void; } diff --git a/types/shopify-buy/index.d.ts b/types/shopify-buy/index.d.ts index 7140f85515..11f15d9dfd 100644 --- a/types/shopify-buy/index.d.ts +++ b/types/shopify-buy/index.d.ts @@ -310,10 +310,10 @@ declare namespace ShopifyBuy { lineItems: LineItem[]; /** - * Get current subtotal price for all line items. + * Get current subtotal price for all line items, before shipping, taxes, and discounts. * Example: two items have been added to the cart that cost $1.25 then the subtotal will be 2.50 */ - subtotal: string; + subtotalPrice: string; } export interface LineItem extends GraphModel { diff --git a/types/shopify-buy/shopify-buy-tests.ts b/types/shopify-buy/shopify-buy-tests.ts index 0e65990121..2813dc4d5d 100644 --- a/types/shopify-buy/shopify-buy-tests.ts +++ b/types/shopify-buy/shopify-buy-tests.ts @@ -371,7 +371,7 @@ function renderCartItems() { /* Update Total Cart Pricing ============================================================ */ function updateTotalCartPricing() { - $('.cart .pricing').text(formatAsMoney(cart.subtotal)); + $('.cart .pricing').text(formatAsMoney(cart.subtotalPrice)); } /* Format amount as currency diff --git a/types/slate-react/index.d.ts b/types/slate-react/index.d.ts index c79b945a5b..31e7b95cbf 100644 --- a/types/slate-react/index.d.ts +++ b/types/slate-react/index.d.ts @@ -1,108 +1,166 @@ -// Type definitions for slate-react 0.12 +// Type definitions for slate-react 0.18 // Project: https://github.com/ianstormtaylor/slate // Definitions by: Andy Kent // Jamie Talbot // Jan Löbel // Patrick Sachs // Brandon Shelton +// Irwan Fario Subastian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import { Mark, Node, Block, Change, Schema, Value, Stack } from 'slate'; -import * as Immutable from 'immutable'; -import * as React from 'react'; +import { Mark, Node, Change, Schema, Value, Stack, Document } from "slate"; +import * as Immutable from "immutable"; +import * as React from "react"; // Values prefixed with "data-..." (Used for spellchecking according to docs) export interface RenderAttributes { - [key: string]: any; + [key: string]: any; } export interface RenderMarkProps { - attributes: RenderAttributes; - children: React.ReactNode; - editor: Editor; - mark: Mark; - marks: Immutable.Set; - node: Node; - offset: number; - text: string; + attributes: RenderAttributes; + children: React.ReactNode; + editor: Editor; + mark: Mark; + marks: Immutable.Set; + node: Node; + offset: number; + text: string; } export interface RenderNodeProps { - attributes: RenderAttributes; - children: React.ReactNode; - editor: Editor; - isSelected: boolean; - key: string; - node: Node; - parent: Node; + attributes: RenderAttributes; + children: React.ReactNode; + editor: Editor; + isSelected: boolean; + key: string; + node: Node; + parent: Node; } export interface Plugin { - onBeforeInput?: (event: Event, change: Change, editor: Editor) => Change | void; - onBlur?: (event: Event, change: Change, editor: Editor) => Change | void; - onFocus?: (event: Event, change: Change, editor: Editor) => Change | void; - onClick?: (event: Event, change: Change, editor: Editor) => Change | void; - onCopy?: (event: Event, change: Change, editor: Editor) => Change | void; - onCut?: (event: Event, change: Change, editor: Editor) => Change | void; - onDrop?: (event: Event, change: Change, editor: Editor) => Change | void; - onKeyDown?: (event: Event, change: Change, editor: Editor) => Change | void; - onKeyUp?: (event: Event, change: Change, editor: Editor) => Change | void; - onPaste?: (event: Event, change: Change, editor: Editor) => Change | void; - onSelect?: (event: Event, change: Change, editor: Editor) => Change | void; - onChange?: (change: Change) => any; - renderEditor?: (props: RenderAttributes, editor: Editor) => object | void; - schema?: Schema; - decorateNode?: (node: Node) => Range[] | void; - renderMark?: (props: RenderMarkProps) => any; - renderNode?: (props: RenderNodeProps) => any; - renderPlaceholder?: (props: RenderAttributes) => any; - renderPortal?: (props: RenderAttributes) => any; - validateNode?: (node: Node) => any; + onBeforeInput?: ( + event: Event, + change: Change, + editor: Editor + ) => Change | void; + onBlur?: (event: Event, change: Change, editor?: Editor) => Change | void; + onFocus?: (event: Event, change: Change, editor?: Editor) => Change | void; + onClick?: (event: Event, change: Change, editor?: Editor) => Change | void; + onCopy?: (event: Event, change: Change, editor?: Editor) => Change | void; + onCut?: (event: Event, change: Change, editor?: Editor) => Change | void; + onDragEnd?: ( + event: Event, + change: Change, + editor?: Editor + ) => Change | void; + onDragEnter?: ( + event: Event, + change: Change, + editor?: Editor + ) => Change | void; + onDragExit?: ( + event: Event, + change: Change, + editor?: Editor + ) => Change | void; + onDragLeave?: ( + event: Event, + change: Change, + editor?: Editor + ) => Change | void; + onDragOver?: ( + event: Event, + change: Change, + editor?: Editor + ) => Change | void; + onDragStart?: ( + event: Event, + change: Change, + editor?: Editor + ) => Change | void; + onDrop?: (event: Event, change: Change, editor?: Editor) => Change | void; + onInput?: (event: Event, change: Change, editor?: Editor) => Change | void; + onKeyDown?: ( + event: Event, + change: Change, + editor?: Editor + ) => Change | void; + onKeyUp?: (event: Event, change: Change, editor?: Editor) => Change | void; + onPaste?: (event: Event, change: Change, editor?: Editor) => Change | void; + onSelect?: (event: Event, change: Change, editor?: Editor) => Change | void; + onChange?: (change: Change, editor?: Editor) => any; + renderEditor?: (props: RenderAttributes, editor?: Editor) => object | void; + schema?: Schema; + decorateNode?: (node: Node) => Range[] | void; + renderMark?: (props: RenderMarkProps) => any; + renderNode?: (props: RenderNodeProps) => any; + renderPlaceholder?: (props: RenderAttributes) => any; + renderPortal?: (props: RenderAttributes) => any; + validateNode?: (node: Node) => any; } export interface BasicEditorProps { - value: Value; - autoCorrect?: boolean; - autoFocus?: boolean; - className?: string; - onChange?: (change: Change) => any; - placeholder?: any; - plugins?: Plugin[]; - readOnly?: boolean; - role?: string; - schema?: Schema; - spellCheck?: boolean; - style?: { [key: string]: string }; - tabIndex?: number; + value: Value; + autoCorrect?: boolean; + autoFocus?: boolean; + className?: string; + onChange?: (change: Change) => any; + placeholder?: any; + plugins?: Plugin[]; + readOnly?: boolean; + role?: string; + schema?: Schema; + spellCheck?: boolean; + style?: React.CSSProperties; + tabIndex?: number; } // tsling:disable interface-over-type-literal export type EditorProps = BasicEditorProps & Plugin; export interface EditorState { - schema: Schema; - value: Value; - stack: Stack; // [TODO] define stack + schema: Schema; + value: Value; + stack: Stack; // [TODO] define stack } export class Editor extends React.Component { - schema: Schema; - value: Value; - stack: Stack; + schema: Schema; + value: Value; + stack: Stack; - // Instance Methods - blur(): void; - change(fn: (change: Change) => any): void; - change(...args: any[]): void; - focus(): void; + readonly plugins: Plugin[]; + + // Instance Methods + blur(): void; + change(fn: (change: Change) => any): void; + change(...args: any[]): void; + focus(): void; } -export type SlateType = 'fragment' | 'html' | 'node' | 'rich' | 'text' | 'files'; +export type SlateType = + | "fragment" + | "html" + | "node" + | "rich" + | "text" + | "files"; -export function findDOMNode(node: Node): Element; -export function findDOMRange(range: Range): Range; +export function cloneFragment( + event: Event, + value: Value, + fragment?: Document, + callback?: () => void +): void; +export function findDOMNode(node: Node, win?: Window): Element; +export function findDOMRange(range: Range, win?: Window): Range; export function findNode(element: Element, value: Value): Node; export function findRange(selection: Selection, value: Value): Range; export function getEventRange(event: Event, value: Value): Range; export function getEventTransfer(event: Event): { type: SlateType; node: Node }; -export function setEventTransfer(event: Event, type: SlateType, data: any): void; +export function setEventTransfer( + event: Event, + type: SlateType, + data: any +): void; diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index 30c0b5a376..f1cd8ecc64 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for slate 0.33 +// Type definitions for slate 0.40 // Project: https://github.com/ianstormtaylor/slate // Definitions by: Andy Kent // Jamie Talbot @@ -6,758 +6,1525 @@ // Brandon Shelton // Kalley Powell // Francesco Agnoletto +// Irwan Fario Subastian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Immutable from 'immutable'; +import * as Immutable from "immutable"; -export class Data { - [key: string]: any; - static create(options: Data): Data; - static fromJSON(object: Record): Data; - static fromJS(object: Record): Data; +export class Data extends Immutable.Record({}) { + [key: string]: any; + + static create(properties: object): Data; + static fromJSON(object: object): Data; + static fromJS(object: object): Data; } export interface RulesByNodeType { - [key: string]: Rules; + [key: string]: Rules; } -export interface ObjectsAndTypes { - objects?: string[]; - types?: string[]; +export interface ObjectAndType { + object?: string; + types?: string; } -export type InvalidReason = - | 'child_object_invalid' - | 'child_required' - | 'child_type_invalid' - | 'child_unknown' - | 'first_child_object_invalid' - | 'first_child_type_invalid' - | 'last_child_object_invalid' - | 'last_child_type_invalid' - | 'node_data_invalid' - | 'node_is_void_invalid' - | 'node_mark_invalid' - | 'node_text_invalid' - | 'parent_object_invalid' - | 'parent_type_invalid'; - export interface Rules { - data?: { - [key: string]: (v: any) => boolean; - }; - first?: ObjectsAndTypes; - isVoid?: boolean; - last?: ObjectsAndTypes; - nodes?: Array<{ - objects?: string[]; - types?: string[]; - min?: number; - max?: number; - }>; - normalize?: ( - change: Change, - reason: InvalidReason, - context: Record - ) => void; - parent?: ObjectsAndTypes; - text?: RegExp; + data?: { + [key: string]: (v: any) => boolean; + }; + first?: ObjectAndType | ObjectAndType[]; + isVoid?: boolean; + last?: ObjectAndType | ObjectAndType[]; + nodes?: Array<{ + min?: number; + max?: number; + match?: ObjectAndType | ObjectAndType[]; + }>; + normalize?: (change: Change, error: SlateError) => void; + parent?: ObjectAndType | ObjectAndType[]; + text?: RegExp; } export interface SchemaProperties { - document?: Rules; - blocks?: RulesByNodeType; - inlines?: RulesByNodeType; + document?: Rules; + blocks?: RulesByNodeType; + inlines?: RulesByNodeType; } export class Schema extends Immutable.Record({}) { - document: Rules; - blocks: RulesByNodeType; - inlines: RulesByNodeType; + stack: Stack; + rules: Rules[]; - static create(properties: SchemaProperties | Schema): Schema; - static fromJSON(object: SchemaProperties): Schema; - static fromJS(object: SchemaProperties): Schema; - static isSchema(maybeSchema: any): maybeSchema is Schema; + static create(properties: SchemaProperties | Schema): Schema; + static fromJSON(object: SchemaProperties): Schema; + static fromJS(object: SchemaProperties): Schema; + static isSchema(maybeSchema: any): maybeSchema is Schema; - toJSON(): SchemaProperties; -} + validateNode(node: Node): Error | void; + testNode(node: Node): boolean; + assertNode(node: Node): boolean; + getNodeRules(node: Node): any[]; + isVoid(node: Node): boolean; + isAtomic(mark: Mark): boolean; + normalizeNode(node: Node): () => void; + testRules(object: any, rules: object | any[]): boolean; + validateRules( + object: any, + rule: object | any[], + rules: any[] | null, + options?: object + ): Error | void; -export interface HistoryJSON { - object?: 'history'; - redos?: Immutable.Stack; - undos?: Immutable.Stack; -} - -export class History extends Immutable.Record({ redos: Immutable.Stack(), undos: Immutable.Stack() }) { - object: 'history'; - - static create(properties: HistoryJSON | History): History; - static createOperationsList(operations: Operation[] | Immutable.List): Immutable.List; - static fromJSON(object: HistoryJSON): History; - static fromJS(object: HistoryJSON): History; - static isHistory(maybeHistory: any): maybeHistory is History; - - save(operation: Operation, options: { merge?: boolean, skip?: boolean }): History; - toJSON(): HistoryJSON; + toJSON(): SchemaProperties; + toJS(): SchemaProperties; } export interface ValueProperties { - document?: Document; - selection?: Range; - history?: History; - schema?: Schema; - data?: Record; - decorations?: Immutable.List | null; + document?: Document; + selection?: Selection; + history?: History; + schema?: Schema; + data?: Data; + decorations?: Immutable.List | null; } export interface ValueJSON { - document?: DocumentJSON; - selection?: Range; - history?: History; - schema?: Schema; - data?: Record; - decorations?: Immutable.List | null; - object?: 'value'; + document?: DocumentJSON; + selection?: Selection; + history?: History; + schema?: Schema; + data?: Data; + decorations?: Immutable.List | null; + object?: "value"; } +export type Path = Immutable.List | string; + export class Value extends Immutable.Record({}) { - document: Document; - selection: Range; - history: History; - schema: Schema; - data: Record; - object: 'value'; - decorations: Immutable.List | null; + document: Document; + selection: Selection; + history: History; + schema: Schema; + data: Data; + object: "value"; + decorations: Immutable.List; - readonly anchorText: Text; - readonly focusText: Text; - readonly startText: Text; - readonly endText: Text; + readonly anchorText: Text; + readonly focusText: Text; + readonly startText: Text; + readonly endText: Text; + readonly nextText: Text; + readonly previousText: Text; - readonly anchorBlock: Block; - readonly focusBlock: Block; - readonly startBlock: Block; - readonly endBlock: Block; + readonly anchorBlock: Block; + readonly focusBlock: Block; + readonly startBlock: Block; + readonly endBlock: Block; + readonly nextBlock: Block; + readonly previousBlock: Block; - readonly anchorInline: Inline; - readonly focusInline: Inline; - readonly startInline: Inline; - readonly endInline: Inline; + readonly anchorInline: Inline; + readonly focusInline: Inline; + readonly startInline: Inline; + readonly endInline: Inline; + readonly nextInline: Inline; + readonly previousInline: Inline; - readonly marks: Immutable.Set; - readonly activeMarks: Immutable.Set; - readonly blocks: Immutable.List; - readonly fragment: Document; - readonly inlines: Immutable.List; - readonly text: Immutable.List; - readonly characters: Immutable.List; - readonly hasUndos: boolean; - readonly hasRedos: boolean; + readonly marks: Immutable.Set; + readonly activeMarks: Immutable.Set; + readonly blocks: Immutable.List; + readonly fragment: Document; + readonly inlines: Immutable.List; + readonly texts: Immutable.List; - readonly anchorKey: string; - readonly focusKey: string; - readonly startKey: string; - readonly endKey: string; - readonly anchorOffset: number; - readonly focusOffset: number; - readonly startOffset: number; - readonly endOffset: number; - readonly isBackward: boolean; - readonly isBlurred: boolean; - readonly isCollapsed: boolean; - readonly isExpanded: boolean; - readonly isFocused: boolean; - readonly isForward: boolean; + static create(properties?: ValueProperties | Value): Value; + static createProperties(attrs: ValueProperties | Value): ValueProperties; + static fromJSON(properties: ValueJSON): Value; + static fromJS(properties: ValueJSON): Value; + static isValue(maybeValue: any): maybeValue is Value; - static create(properties?: ValueProperties | Value): Value; - static fromJSON(properties: ValueJSON): Value; - static fromJS(properties: ValueJSON): Value; - static isValue(maybeValue: any): maybeValue is Value; - - change(): Change; - toJSON(): ValueJSON; + change(): Change; + toJSON(): ValueJSON; + addMark(path: Path, offset: number, length: number, mark: Mark): Value; + insertNode(path: Path, node: Node): Value; + insertText( + path: Path, + offset: number, + text: string, + marks: Immutable.Set + ): Value; + isValue(value: Value): boolean; + mergeNode(path: Path): Value; + moveNode(path: Path, newPath: Path, newIndex?: number): Value; + removeMark(path: Path, offset: number, length: number, mark: Mark): Value; + removeNode(path: Path): Value; + removeText(path: Path, offset: number, text: Text): Value; + setNode(path: Path, properties: any): Value; + setMark( + path: Path, + offset: number, + length: number, + mark: Mark, + properties: MarkProperties + ): Value; + setProperties(properties: ValueProperties): Value; + setSelection(properties: RangeProperties): Value; + splitNode(path: Path, position: number, properties: any): Value; + mapRanges(iterator: () => void): Value; + clearAtomicRanges(key: string, from: number, to?: number): Value; } export interface DocumentProperties { - nodes?: Immutable.List | Node[]; - key?: string; - data?: Immutable.Map | Record; + nodes?: Immutable.List | Node[]; + key?: string; + data?: Immutable.Map | { [key: string]: any }; } export interface DocumentJSON { - nodes?: NodeJSON[]; - key?: string; - data?: Record; - object?: 'document'; + nodes?: NodeJSON[]; + key?: string; + data?: { [key: string]: any }; + object?: "document"; } -export class Document> extends BaseNode< - DataMap +export class Document extends BaseNode< + DataMap > { - object: 'document'; - nodes: Immutable.List; + object: "document"; + nodes: Immutable.List; - static create( - properties: DocumentProperties | Document | Immutable.List | Node[] - ): Document; + static create( + properties: + | DocumentProperties + | Document + | Immutable.List + | Node[] + ): Document; + static fromJSON(properties: DocumentJSON | Document): Document; + static fromJS(properties: DocumentJSON | Document): Document; + static isDocument(maybeDocument: any): maybeDocument is Document; - static fromJSON(properties: DocumentJSON | Document): Document; - static fromJS(properties: DocumentJSON | Document): Document; - static isDocument(maybeDocument: any): maybeDocument is Document; - - toJSON(): DocumentJSON; + toJSON(): DocumentJSON; } export interface BlockProperties { - type: string; - key?: string; - nodes?: Immutable.List; - isVoid?: boolean; - data?: Immutable.Map | Record; + type: string; + key?: string; + nodes?: Immutable.List; + data?: Immutable.Map | { [key: string]: any }; } export interface BlockJSON { - type: string; - key?: string; - nodes?: NodeJSON[]; - isVoid?: boolean; - data?: Record; - object: 'block'; + type: string; + key?: string; + nodes?: Array; + data?: { [key: string]: any }; + object: "block"; } export class Block extends BaseNode { - isVoid: boolean; - object: 'block'; - nodes: Immutable.List; + object: "block"; + nodes: Immutable.List; - static create(properties: BlockProperties | Block | string): Block; - static createList( - array: (BlockProperties[] | Block[] | string[]) - ): Immutable.List; - static fromJSON(properties: BlockJSON | Block): Block; - static fromJS(properties: BlockJSON | Block): Block; - static isBlock(maybeBlock: any): maybeBlock is Block; + static create(properties: BlockProperties | Block | string): Block; + static createList( + array?: BlockProperties[] | Block[] | string[] + ): Immutable.List; + static fromJSON(properties: BlockJSON | Block): Block; + static fromJS(properties: BlockJSON | Block): Block; + static isBlock(maybeBlock: any): maybeBlock is Block; + static isBlockList( + maybeBlockList: any + ): maybeBlockList is Immutable.List; - toJSON(): BlockJSON; + toJSON(): BlockJSON; } export interface InlineProperties { - type: string; - key?: string; - nodes?: Immutable.List; - isVoid?: boolean; - data?: Immutable.Map | Record; + type: string; + key?: string; + nodes?: Immutable.List; + data?: Immutable.Map | { [key: string]: any }; } export interface InlineJSON { - type: string; - key?: string; - nodes?: NodeJSON[]; - isVoid?: boolean; - data?: Record; - object: 'inline'; + type: string; + key?: string; + nodes?: NodeJSON[]; + data?: { [key: string]: any }; + object: "inline"; } export class Inline extends BaseNode { - isVoid: boolean; - object: 'inline'; - nodes: Immutable.List; + object: "inline"; + nodes: Immutable.List; - static create(properties: InlineProperties | Inline | string): Inline; - static createList( - array: (InlineProperties[] | Inline[] | string[]) - ): Immutable.List; - static fromJSON(properties: InlineJSON | Inline): Inline; - static fromJS(properties: InlineJSON | Inline): Inline; - static isInline(maybeInline: any): maybeInline is Inline; + static create(properties: InlineProperties | Inline | string): Inline; + static createList( + array?: InlineProperties[] | Inline[] | string[] + ): Immutable.List; + static fromJSON(properties: InlineJSON | Inline): Inline; + static fromJS(properties: InlineJSON | Inline): Inline; + static isInline(maybeInline: any): maybeInline is Inline; + static isInlineList( + maybeInlineList: any + ): maybeInlineList is Immutable.List; - toJSON(): InlineJSON; -} - -export interface Leaf { - object: 'leaf'; - marks?: Mark[]; - text: string; + toJSON(): InlineJSON; } export interface TextProperties { - key?: string; - characters: Immutable.List; + key?: string; + text?: string; + marks?: Mark[]; } export interface TextJSON { - key?: string; - characters?: Character[]; - leaves: Leaf[]; - object: 'text'; + key?: string; + leaves: LeafJSON[]; + object: "text"; +} + +export interface LeafAndOffset { + startOffset: number; + endOffset: number; + index: number; + leaf: Leaf; } export class Text extends Immutable.Record({}) { - object: 'text'; - characters: Immutable.List; - key: string; - text: string; + object: "text"; + key: string; - static create(properties: TextProperties | Text | string): Text; - static fromJSON(properties: TextJSON | Text): Text; - static fromJS(properties: TextJSON | Text): Text; - static isText(maybeText: any): maybeText is Text; + readonly text: string; - toJSON(): TextJSON; + static create(properties: TextProperties | Text | string): Text; + static createList( + elements?: + | Text[] + | TextProperties[] + | Immutable.List + | Immutable.List + ): Immutable.List; + static fromJSON(properties: TextJSON | Text): Text; + static fromJS(properties: TextJSON | Text): Text; + static isText(maybeText: any): maybeText is Text; + + toJSON(): TextJSON; + + getKeysToPathsTable(): object; + getString(): string; + searchLeafAtOffset(offset: number): LeafAndOffset; + addMark(index: number, length: number, mark: Mark): Text; + addMarks(index: number, lenght: number, marks: Immutable.Set): Text; + getLeaves(decorations?: Range[]): Immutable.List; + getActiveMarksBetweenOffset( + startOffset: number, + endOffset: number + ): Immutable.Set; + getActiveMarks(): Immutable.Set; + getFirstText(): Text; + getLastText(): Text; + getText(): string; + getMarksBetweenOffset( + startOffset: number, + endOffset: number + ): Immutable.Set; + getMarks(): Immutable.OrderedSet; + getMarksAsArray(): Mark[]; + getMarksAtIndex(index: number): Mark; + getNode(key: string): Node | null; + getPath(key: string | Path): Path; + hasNode(key: string): boolean; + insertText(offset: number, text: string, marks?: Immutable.Set): Text; + regenerateKey(): Text; + removeMark(index: number, length: Mark, mark: Mark): Text; + removeText(start: number, length: number): Text; + resolvePath(path: Path, index: number): Immutable.List; + updateMark( + index: number, + length: number, + mark: Mark, + properties: MarkProperties + ): Text; + splitText(offset: number): Text[]; + mergeText(text: Text): Text; + normalize(schema: Schema): () => void | null; + validate(schema: Schema): Error | null; + getFirstInvalidNode(schema: Schema): Text | null; + setLeaves(leaves: Immutable.List): Text; +} + +export interface LeafProperties { + marks?: Immutable.Set; + text?: string; +} + +export interface LeafJSON { + marks?: Mark[]; + text?: string; +} + +export class Leaf extends Immutable.Record({}) { + object: "leaf"; + marks: Immutable.Set | null; + text: string; + + static create(properties: LeafProperties): Leaf; + static createLeaves(leaves: Immutable.List): Immutable.List; + static splitLeaves( + leaves: Immutable.List, + offset: number + ): Array>; + static createList( + attrs?: + | Leaf[] + | LeafProperties[] + | Immutable.List + | Immutable.List + ): Immutable.List; + static fromJSON(properties: LeafJSON): Leaf; + static fromJS(properties: LeafJSON): Leaf; + static isLeaf(maybeLeaf: any): maybeLeaf is Leaf; + static isLeafList( + maybeLeafList: any + ): maybeLeafList is Immutable.List; + + updateMark(mark: Mark, newMark: Mark): Leaf; + addMarks(marks: Immutable.Set): Leaf; + addMark(mark: Mark): Leaf; + removeMark(mark: Mark): Leaf; + toJSON(): LeafProperties; } export type Node = Document | Block | Inline | Text; export type NodeJSON = DocumentJSON | BlockJSON | InlineJSON | TextJSON; +export type NodeProperties = + | DocumentProperties + | BlockProperties + | InlineProperties + | TextProperties; // tslint:disable-next-line strict-export-declare-modifiers -declare class BaseNode> extends Immutable.Record( - {} -) { - data: Immutable.Map; - type: string; - key: string; - object: 'document' | 'block' | 'inline' | 'text'; - nodes: Immutable.List; - readonly text: string; +declare class BaseNode< + DataMap = { [key: string]: any } +> extends Immutable.Record({}) { + data: Immutable.Map; + type: string; + key: string; + object: "document" | "block" | "inline" | "text"; + nodes: Immutable.List; - filterDescendants(iterator: (node: Node) => boolean): Immutable.List; - findDescendants(iterator: (node: Node) => boolean): Node | null; - getBlocksAtRange(range: Range): Immutable.List; - getBlocks(): Immutable.List; - getCharactersAtRange(range: Range): Immutable.List; - getChild(key: string | Node): Node | null; - getClosestBlock(key: string | Node): Block | null; - getClosestInline(key: string | Node): Inline | null; - getClosest(key: string | Node, match: (node: Node) => boolean): Node | null; - getDepth(key: string | Node): number; - getDescendant(key: string | Node): Node | null; - getFirstText(): Text | null; - getFragmentAtRange(range: Range): Document; - getFurthest(key: string, iterator: (node: Node) => boolean): Node | null; - getFurthestAncestor(key: string): Node | null; - getFurthestBlock(key: string): Block | null; - getFurthestInline(key: string): Inline | null; - getFurthestOnlyChildAncestor(key: string): Node | null; - getInlinesAtRange(range: Range): Immutable.List; - getLastText(): Text | null; - getMarksAtRange(range: Range): Immutable.Set; - getNextBlock(key: string | Node): Block | null; - getNextSibling(key: string | Node): Node | null; - getNextText(key: string | Node): Text | null; - getParent(key: string | Node): Node | null; - getPreviousBlock(key: string | Node): Block | null; - getPreviousSibling(key: string | Node): Node | null; - getPreviousText(key: string | Node): Text | null; - getTexts(): Immutable.List; - getTextsAsArray(): Text[]; - getTextAtOffset(offset: number): Text | null; - getTextsAtRange(range: Range): Immutable.List; - getTextsAtRangeAsArray(range: Range): Text[]; - hasChild(key: string | Node): boolean; -} + readonly text: string; -export interface CharacterProperties { - marks?: Immutable.Set | Mark[]; - text: string; -} + static isNode(maybeNode: any): maybeNode is Node; + static isNodeList( + maybeNodeList: any + ): maybeNodeList is Immutable.List; + static createProperties( + attrs: NodeProperties | string | Node + ): NodeProperties; + static fromJSON(value: NodeJSON | Node): Node; + static fromJS(value: NodeJSON | Node): Node; -export class Character extends Immutable.Record({}) { - object: 'character'; - marks: Immutable.Set; - text: string; - - static create( - properties: CharacterProperties | Character | string - ): Character; - static createList( - array: (CharacterProperties[] | Character[] | string[]) - ): Immutable.List; - static fromJSON(properties: CharacterProperties | Character): Character; - static fromJS(properties: CharacterProperties | Character): Character; - static isCharacter(maybeCharacter: any): maybeCharacter is Character; - - toJSON(): CharacterProperties; + addMark(path: Path, offset: number, length: number, mark: Mark): Node; + createDecoration(properties: DecorationProperties | Decoration): Decoration; + createPoint(properties: PointProperties | Point): Point; + createRange(properties: RangeProperties | Range): Range; + createSelection(properties: SelectionProperties | Selection): Selection; + filterDescendants(iterator: (node: Node) => boolean): Immutable.List; + findDescendants(iterator: (node: Node) => boolean): Node | null; + getActiveMarksAtRange(range: Range): Immutable.Set; + getAncestors(path: Path): Immutable.List | null; + getBlocksAtRange(range: Range): Immutable.List; + getBlocksAtRangeAsArray(range: Range): Block[]; + getBlocks(): Immutable.List; + getBlocksAsArray(): Block[]; + getBlocksByType(type: string): Immutable.List; + getBlocksByTypeAsArray(type: string): Block[]; + getChild(path: Path): Node | null; + getClosestBlock(path: Path): Block | null; + getClosestInline(path: Path): Inline | null; + getClosestVoid(path: Path, schema: Schema): Node | null; + getClosest(path: Path, iterator: (node: Node) => boolean): Node | null; + getCommonAncestor(a: Path, b: Path): Node; + getDecorations(stack: Stack): Immutable.List; + getDepth(path: Path, startAt?: number): number; + getDescendant(path: Path): Node | null; + getFirstInvalidNode(schema: Schema): Node | null; + getFirstText(): Text | null; + getFragmentAtRange(range: Range): Document; + getFurthest(path: Path, iterator: (node: Node) => boolean): Node | null; + getFurthestAncestor(path: Path): Node | null; + getFurthestBlock(path: Path): Block | null; + getFurthestInline(path: Path): Inline | null; + getFurthestOnlyChildAncestor(path: Path): Node | null; + getInlines(): Immutable.List; + getInlinesAsArray(): Inline[]; + getInlinesAtRange(range: Range): Immutable.List; + getInlinesAtRangeAsArray(range: Range): Inline[]; + getInlinesByType(type: string): Immutable.List; + getInlinesByTypeAsArray(type: string): Inline[]; + getInsertMarksAtRange(range: Range): Immutable.Set; + getKeysToPathsTable(): object; + getLastText(): Text | null; + getMarks(): Immutable.Set; + getMarksAsArray(): Mark[]; + getMarksAtPosition(key: string, offset: number): Immutable.Set; + getMarksAtRange(range: Range): Immutable.Set; + getMarksByType(type: string): Immutable.Set; + getMarksByTypeAsArray(type: string): Mark[]; + getNextBlock(key: string | Node): Block | null; + getNextNode(path: Path): Node | null; + getNextSibling(path: Path): Node | null; + getNextText(path: Path): Text | null; + getNode(path: Path): Node | null; + getOffset(key: string): number; + getOffsetAtRange(range: Range): number; + getOrderedMarks(): Immutable.OrderedSet; + getOrderedMarksAtRange(range: Range): Immutable.OrderedSet; + getOrderedMarksBetweenPositions( + startKey: string, + startOffset: number, + endKey: string, + endOffset: number + ): Immutable.OrderedSet; + getOrderedMarksByType(type: string): Immutable.OrderedSet; + getParent(path: Path): Node | null; + getPath(key: string | Path): Path; + getPreviousBlock(key: string | Node): Block | null; + getPreviousNode(path: Path): Node | null; + getPreviousSibling(path: Path): Node | null; + getPreviousText(path: Path): Text | null; + getSelectionIndexes( + range: Range, + isSelected?: boolean + ): { start: number; end: number } | null; + getText(): string; + getTextAtOffset(offset: number): Text | null; + getTextDirection(): string | null; + getTexts(): Immutable.List; + getTextsAsArray(): Text[]; + getTextsAtRange(range: Range): Immutable.List; + getTextsAtRangeAsArray(range: Range): Text[]; + getTextsBetweenPositionsAsArray(startKey: string, endKey: string): Text[]; + hasBlockChildren(): boolean; + hasChild(path: Path): boolean; + hasInlineChildren(): boolean; + hasDescendant(path: Path): boolean; + hasNode(path: Path): boolean; + hasVoidParent(path: Path, schema: Schema): boolean; + insertNode(path: Path, node: Node): Node; + insertText( + path: Path, + offset: number, + text: string, + marks: Immutable.Set + ): Node; + isLeafBlock(): boolean; + isLeafInline(): boolean; + mapChildren(iterator: () => void): Node; + mapDescendants(iterator: () => void): Node; + mergeNode(path: Path): Node; + moveNode(path: Path, newPath: Path, newIndex?: number): Node; + normalize(schema: Schema): () => void | void; + refinedNOde(path: Path, key: string): Node | null; + refindPath(path: Path, key: string): Immutable.List | null; + regenerateKey(): Node; + removeMark(path: Path, offset: number, length: number, mark: Mark): Node; + removeNode(path: Path): Node; + removeText(path: Path, offset: number, text: string): Node; + replaceNode(path: Path, node: Node): Node; + resolvePath(path: Path, index: number): Immutable.List; + resolvePoint(point: Point): Point; + resolveRange(range: Range): Range; + setNode(path: Path, properties: NodeProperties): Node; + setMark( + path: Path, + offset: number, + length: number, + mark: Mark, + properties: MarkProperties + ): Node; + splitNode(path: Path, position: number, properties: NodeProperties): Node; + validate(schema: Schema): Error | void; } export interface MarkProperties { - type: string; - data?: Immutable.Map | Record; + type: string; + data?: Immutable.Map | { [key: string]: any }; } export interface MarkJSON { - type: string; - data?: Record; + type: string; + data?: { [key: string]: any }; } export class Mark extends Immutable.Record({}) { - object: 'mark'; - type: string; - data: Immutable.Map; + object: "mark"; + type: string; + data: Immutable.Map; - static create(properties: MarkProperties | Mark | string): Mark; - static createSet( - array: (MarkProperties[] | Mark[] | string[]) - ): Immutable.Set; - static fromJSON(properties: MarkJSON | Mark): Mark; - static fromJS(properties: MarkJSON | Mark): Mark; - static isMark(maybeMark: any): maybeMark is Mark; + static create(properties: MarkProperties | Mark | string): Mark; + static createSet( + array: MarkProperties[] | Mark[] | string[] + ): Immutable.Set; + static fromJSON(properties: MarkJSON | Mark): Mark; + static fromJS(properties: MarkJSON | Mark): Mark; + static isMark(maybeMark: any): maybeMark is Mark; - toJSON(): MarkProperties; + toJSON(): MarkProperties; +} + +export interface ChangeOption { + normalize?: boolean; } export class Change extends Immutable.Record({}) { - object: 'change'; - value: Value; - operations: Immutable.List; + object: "change"; + value: Value; + operations: Immutable.List; - call(customChange: (change: Change, ...args: any[]) => Change): Change; - withoutNormalization(customChange: (change: Change) => void): Change; + call(customChange: (change: Change, ...args: any[]) => Change): Change; - applyOperations(operations: Operation[]): Change; - applyOperation(operation: Operation): Change; + applyOperations(operations: Operation[]): Change; + applyOperation(operation: Operation): Change; - // Full Value Change - setValue(properties: Value | ValueProperties): Change; + withoutNormalization(fn: (change: Change) => void): Change; + setOperationFlag(key: string, value: any): Change; + getFlag(key: string, options?: object): any; + unsetOperationFlag(key: string): 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; - 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; + // Full Value Change + setValue(properties: Value | ValueProperties): Change; - // Selection Changes - blur(): Change; - collapseToAnchor(): Change; - collapseToFocus(): Change; - collapseToStart(): Change; - collapseToEnd(): Change; - collapseToStartOf(node: Node): Change; - collapseToEndOf(node: Node): Change; - collapseToStartOfNextBlock(): Change; - collapseToEndOfNextBlock(): Change; - collapseToStartOfPreviousBlock(): Change; - collapseToEndOfPreviousBlock(): Change; - collapseToStartOfNextText(): Change; - collapseToEndOfNextText(): Change; - collapseToStartOfPreviousText(): Change; - collapseToEndOfPreviousText(): Change; - extend(n: number): Change; - extendToStartOf(node: Node): Change; - extendToEndOf(node: Node): Change; - flip(): Change; - focus(): Change; - move(n: number): Change; - moveStart(n: number): Change; - moveEnd(n: number): Change; - moveOffsetsTo(anchorOffset: number, focusOffset: number): Change; - moveToRangeOf(node: Node): Change; - select(properties: Range | RangeProperties): Change; - selectAll(): Change; - deselect(): 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; - // Document Changes - deleteBackwardAtRange(range: Range, n: number): Change; - deleteForwardAtRange(range: Range, n: number): Change; - deleteAtRange(range: Range): Change; - insertBlockAtRange( - range: Range, - block: Block | BlockProperties | string - ): Change; - insertFragmentAtRange(range: Range, fragment: Document): Change; - insertInlineAtRange( - range: Range, - inline: Inline | InlineProperties - ): Change; - insertTextAtRange(range: Range, text: string): Change; - addMarkAtRange(range: Range, mark: Mark | MarkProperties | string): Change; - setBlocksAtRange(range: Range, properties: BlockProperties | string): Change; - setInlinesAtRange( - range: Range, - properties: InlineProperties | string - ): Change; - splitBlockAtRange(range: Range, depth: number): Change; - splitInlineAtRange(range: Range, depth: number): Change; - removeMarkAtRange( - range: Range, - mark: Mark | MarkProperties | string - ): Change; - toggleMarkAtRange( - range: Range, - mark: Mark | MarkProperties | string - ): Change; - unwrapBlockAtRange( - range: Range, - properties: BlockProperties | string - ): Change; - unwrapInlineAtRange( - range: Range, - properties: InlineProperties | string - ): Change; - wrapBlockAtRange( - range: Range, - properties: BlockProperties | string - ): Change; - wrapInlineAtRange( - range: Range, - properties: InlineProperties | string - ): Change; - wrapTextAtRange(range: Range, prefix: string, suffix?: string): Change; + // Selection Changes + blur(): 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; + flip(): Change; + focus(): Change; + move(n: number): Change; - // History Changes - redo(): Change; - undo(): 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; + isFocused?: boolean; + marks?: Immutable.Set | null; +} + +export interface SelectionJSON { + anchor?: PointJSON; + focus?: PointJSON; + isFocused?: boolean; + isBackward?: boolean | null; + marks?: MarkJSON[] | null; +} + +export class Selection extends BaseRange { + object: "selection"; + anchor: Point; + focus: Point; + isFocused: boolean; + marks: Immutable.Set | null; + + readonly isBlurred: boolean; + + static create( + properties: SelectionProperties | Selection | Range + ): Selection; + static createProperties( + attrs: SelectionProperties | string | Selection | Range + ): SelectionProperties; + static fromJSON(properties: SelectionJSON): Selection; + + toJSON(): SelectionJSON; + + isSelection(maybeSelection: any): maybeSelection is Selection; + setIsFocused(value: boolean): Selection; + setMarks(marks: Immutable.Set): Selection; + setProperties(properties: Selection | SelectionProperties): Selection; } export interface RangeProperties { - anchorKey?: string | null; - anchorOffset?: number; - focusKey?: string | null; - focusOffset?: number; - isFocused?: boolean; - isBackward?: boolean | null; - marks?: Immutable.Set | null; + anchor?: Point; + focus?: Point; } export interface RangeJSON { - anchorKey?: string | null; - anchorOffset?: number; - focusKey?: string | null; - focusOffset?: number; - isFocused?: boolean; - isBackward?: boolean | null; - marks?: MarkJSON[] | null; + anchor?: PointJSON; + focus?: PointJSON; } -export class Range extends Immutable.Record({}) { - object: 'range'; - anchorKey: string | null; - anchorOffset: number; - focusKey: string | null; - focusOffset: number; - isFocused: boolean; - isBackward: boolean | null; - marks: Immutable.Set | null; +export class Range extends BaseRange { + object: "range"; + anchor: Point; - readonly isBlurred: boolean; - readonly isCollapsed: boolean; - readonly isExpanded: boolean; - readonly isForward: boolean; - readonly startKey: string; - readonly startOffset: number; - readonly endKey: string; - readonly endOffset: number; + static create(properties: RangeProperties | Range): Range; + static createList( + elements?: + | Range[] + | RangeProperties[] + | Immutable.List + | Immutable.List + ): Immutable.List; + static createProperties( + attrs: RangeProperties | string | Range + ): RangeProperties; + static fromJSON(properties: RangeJSON): Range; + static fromJS(properties: RangeJSON): Range; + static isRange(maybeRange: any): maybeRange is Range; - static create(properties: RangeProperties | Range): Range; - static fromJSON(properties: RangeJSON): Range; - static fromJS(properties: RangeJSON): Range; - static isRange(maybeRange: any): maybeRange is Range; + toJSON(): RangeJSON; +} - toJSON(): RangeProperties; +export interface DecorationProperties { + anchor?: Point; + focus?: Point; + mark?: Mark | null; +} - hasAnchorAtStartOf(node: Node): boolean; - hasFocusAtStartOf(node: Node): boolean; - hasStartAtStartOf(node: Node): boolean; - hasEndAtStartOf(node: Node): boolean; - hasEdgeAtStartOf(node: Node): boolean; +export interface DecorationJSON { + anchor?: PointJSON; + focus?: PointJSON; + mark?: MarkJSON | null; +} - hasAnchorAtEndOf(node: Node): boolean; - hasFocusAtEndOf(node: Node): boolean; - hasStartAtEndOf(node: Node): boolean; - hasEndAtEndOf(node: Node): boolean; - hasEdgeAtEndOf(node: Node): boolean; +export class Decoration extends BaseRange { + object: "decoration"; + anchor: Point; + focus: Point; + mark: Mark | null; + static create(properties: DecorationProperties | Range): Decoration; + static createList( + elements?: + | Decoration[] + | DecorationProperties[] + | Immutable.List + | Immutable.List + ): Immutable.List; + static createProperties( + attrs: DecorationProperties | string | Decoration + ): DecorationProperties; + static fromJSON(properties: DecorationJSON): Decoration; + static fromJS(properties: DecorationJSON): Decoration; + static isDecoration(maybeDecoration: any): maybeDecoration is Decoration; - hasAnchorBetween(node: Node, start: number, end: number): boolean; - hasFocusBetween(node: Node, start: number, end: number): boolean; - hasStartBetween(node: Node, start: number, end: number): boolean; - hasEndBetween(node: Node, start: number, end: number): boolean; - hasEdgeBetween(node: Node, start: number, end: number): boolean; + toJSON(): DecorationJSON; - hasAnchorIn(node: Node): boolean; - hasFocusIn(node: Node): boolean; - hasStartIn(node: Node): boolean; - hasEndIn(node: Node): boolean; - hasEdgeIn(node: Node): boolean; + setProperties(properties: Decoration | DecorationProperties): Decoration; +} - isAtStartOf(node: Node): boolean; - isAtEndOf(node: Node): boolean; +export type RangeTypeProperties = + | RangeProperties + | SelectionProperties + | DecorationProperties; + +export type RangeTypeJSON = RangeJSON | SelectionJSON | DecorationJSON; +export type RangeType = Range | Selection | Decoration; + +// tslint:disable-next-line strict-export-declare-modifiers +declare class BaseRange extends Immutable.Record({}) { + readonly isCollapsed: boolean; + readonly isExpanded: boolean; + readonly isBackward: boolean; + readonly isForward: boolean; + readonly isUnset: boolean; + readonly isSet: boolean; + readonly start: Point; + readonly end: Point; + + flip(): RangeType; + moveForward(n?: number): RangeType; + moveBackward(n?: number): RangeType; + + moveAnchorBackward(n?: number): RangeType; + moveAnchorForward(n?: number): RangeType; + moveAnchorTo(path: Path, offset?: number): RangeType; + moveAnchorToStartOfNode(node: Node): RangeType; + moveAnchorToEndOfNode(node: Node): RangeType; + + moveEndBackward(n?: number): RangeType; + moveEndForward(n?: number): RangeType; + moveEndTo(path: Path, offset?: number): RangeType; + moveEndToStartOfNode(node: Node): RangeType; + moveEndToEndOfNode(node: Node): RangeType; + + moveFocusBackward(n?: number): RangeType; + moveFocusForward(n?: number): RangeType; + moveFocusTo(path: Path, offset?: number): RangeType; + moveFocusToStartOfNode(node: Node): RangeType; + moveFocusToEndOfNode(node: Node): RangeType; + + moveStartBackward(n?: number): RangeType; + moveStartForward(n?: number): RangeType; + moveStartTo(path: Path, offset?: number): RangeType; + moveStartToStartOfNode(node: Node): RangeType; + moveStartToEndOfNode(node: Node): RangeType; + + moveToAnchor(): RangeType; + moveToEnd(): RangeType; + moveToEndOfNode(node: Node): RangeType; + moveToFocus(): RangeType; + moveToRangeOfNode(start: Node, end?: Node): RangeType; + moveToStart(): RangeType; + moveToStartOfNode(node: Node): RangeType; + + normalize(node: Node): RangeType; + + setAnchor(anchor: Point): RangeType; + setEnd(point: Point): RangeType; + setFocus(focus: Point): RangeType; + setIsAtomic(value: boolean): RangeType; + setIsFocused(value: boolean): RangeType; + setMarks(marks: Immutable.Set): RangeType; + setPoints(values: Point[]): RangeType; + updatePoints(updator: () => Point): RangeType; + setStart(point: Point): RangeType; + setProperties( + properties: RangeTypeProperties | string | RangeType + ): RangeType; + + toJSON(): RangeTypeJSON; + toRange(): RangeType; + unset(): RangeType; +} + +export interface PointProperties { + key?: string | null; + offset?: number; + path?: Path | null; +} + +export interface PointJSON { + key?: string | null; + offset?: number; + path?: Path | null; + object: "point"; +} + +export class Point extends Immutable.Record({}) { + object: "point"; + key: string | null; + offset: number; + path: Path | null; + + static create(properties: PointProperties | Point): Point; + static createProperties(properties: PointProperties | Point): Point; + static fromJSON(properties: PointJSON): Point; + static fromJS(properties: PointJSON): Point; + static isPoint(maybePoint: any): maybePoint is Point; + + readonly isSet: boolean; + readonly isUnset: boolean; + + isAtEndOfNode(node: Node): boolean; + isAtStartOfNode(node: Node): boolean; + isInNode(node: Node): boolean; + moveBackward(n?: number): Point; + moveForward(n?: number): Point; + moveTo(path: Path, offset?: number): Point; + moveToStartOfNode(node: Node): Point; + moveToEndOfNode(node: Node): Point; + normalize(node: Node): Point; + setKey(key: string): Point; + setOffset(offset: number): Point; + setPath(path: Path): Point; + toJSON(options: any): object; + unset(): Point; } export type Operation = - | InsertTextOperation - | RemoveTextOperation - | AddMarkOperation - | RemoveMarkOperation - | SetMarkOperation - | InsertNodeOperation - | MergeNodeOperation - | MoveNodeOperation - | RemoveNodeOperation - | SetNodeOperation - | SplitNodeOperation - | SetSelectionOperation - | SetValueOperation; + | InsertTextOperation + | RemoveTextOperation + | AddMarkOperation + | RemoveMarkOperation + | SetMarkOperation + | InsertNodeOperation + | MergeNodeOperation + | MoveNodeOperation + | RemoveNodeOperation + | SetNodeOperation + | SplitNodeOperation + | SetSelectionOperation + | SetValueOperation; export interface InsertTextOperation { - type: 'insert_text'; - path: number[]; - offset: number; - text: string; - marks: Mark[]; + type: "insert_text"; + path: number[]; + offset: number; + text: string; + marks: Mark[]; } export interface RemoveTextOperation { - type: 'remove_text'; - path: number[]; - offset: number; - text: string; + type: "remove_text"; + path: number[]; + offset: number; + text: string; } export interface AddMarkOperation { - type: 'add_mark'; - path: number[]; - offset: number; - length: number; - mark: Mark; + type: "add_mark"; + path: number[]; + offset: number; + length: number; + mark: Mark; } export interface RemoveMarkOperation { - type: 'remove_mark'; - path: number[]; - offset: number; - length: number; - mark: Mark; + type: "remove_mark"; + path: number[]; + offset: number; + length: number; + mark: Mark; } export interface SetMarkOperation { - type: 'set_mark'; - path: number[]; - offset: number; - length: number; - mark: Mark; - properties: MarkProperties; + type: "set_mark"; + path: number[]; + offset: number; + length: number; + mark: Mark; + properties: MarkProperties; } export interface InsertNodeOperation { - type: 'insert_node'; - path: number[]; - node: Node; + type: "insert_node"; + path: number[]; + node: Node; } export interface MergeNodeOperation { - type: 'merge_node'; - path: number[]; - position: number; + type: "merge_node"; + path: number[]; + position: number; } export interface MoveNodeOperation { - type: 'move_node'; - path: number[]; - newPath: number[]; + type: "move_node"; + path: number[]; + newPath: number[]; } export interface RemoveNodeOperation { - type: 'remove_node'; - path: number[]; - node: Node; + type: "remove_node"; + path: number[]; + node: Node; } export interface SetNodeOperation { - type: 'set_node'; - path: number[]; - properties: BlockProperties | InlineProperties | TextProperties; + type: "set_node"; + path: number[]; + properties: BlockProperties | InlineProperties | TextProperties; } export interface SplitNodeOperation { - type: 'split_node'; - path: number[]; - position: number; - target: number; + type: "split_node"; + path: number[]; + position: number; + target: number; } export interface SetSelectionOperation { - type: 'set_selection'; - properties: RangeProperties; - selection: Range; + type: "set_selection"; + properties: RangeProperties; + selection: Range; } export interface SetValueOperation { - type: 'set_value'; - properties: ValueProperties; - value: Value; + type: "set_value"; + properties: ValueProperties; + value: Value; } -export const Operations: { - apply: (value: Value, operation: Operation) => Value; - invert: (operation: Operation) => Operation; -}; +export interface Operations { + apply: (value: Value, operation: Operation) => Value; + invert: (operation: Operation) => Operation; +} + +export interface StackProperties { + plugins?: any[]; +} + +export interface StackJSON { + object: "stack"; + plugins: any[]; +} export class Stack extends Immutable.Record({}) { - plugins: any[]; + object: "stack"; + plugins: any[]; + + static create(attrs: StackProperties): Stack; + static isStack(maybeStack: any): maybeStack is Stack; + + static fromJSON(properties: StackJSON): Stack; + static fromJS(properties: StackJSON): Stack; + toJSON(options: any): object; } -export function setKeyGenerator(func: () => string): null; -export function resetKeyGenerator(): null; +export interface HistoryProperties { + undos?: Operation[]; + redos?: Operation[]; +} + +export interface HistoryJSON { + object: "history"; + undos: any[]; + redos: any[]; +} + +export interface HistoryOptions { + merge?: boolean; + skip?: boolean; +} + +export class History extends Immutable.Record({}) { + redos: Stack; + undos: Stack; + object: "history"; + + static create(attrs: History | HistoryProperties): History; + static createOperationsList( + oeprations?: Immutable.List | Operation[] + ): Immutable.List; + static fromJSON(object: HistoryJSON): History; + static fromJS(object: HistoryJSON): History; + static isHistory(maybeHistory: any): maybeHistory is History; + + save(operation: Operation, options?: HistoryOptions): History; + toJSON(): HistoryJSON; + toJS(): HistoryJSON; +} + +export type ErrorCode = + | "child_object_invalid" + | "child_required" + | "child_type_invalid" + | "child_unknown" + | "first_child_object_invalid" + | "first_child_type_invalid" + | "last_child_object_invalid" + | "last_child_type_invalid" + | "next_sibling_object_invalid" + | "next_sibling_type_invalid" + | "node_data_invalid" + | "node_is_void_invalid" + | "node_mark_invalid" + | "node_object_invalid" + | "node_text_invalid" + | "node_type_invalid" + | "parent_object_invalid" + | "parent_type_invalid" + | "previous_sibling_object_invalid" + | "previous_sibling_type_invalid"; + +export class SlateError extends Error { + code: ErrorCode; + [key: string]: any; +} + +export interface KeyUtils { + create(key: string): string; + setGenerator(func: () => any): void; + resetGenerator(): void; +} + +export type useMemoization = () => void; +export type resetMemoization = () => void; + +export interface PathUtils { + compare( + path: Immutable.List, + target: Immutable.List + ): number | null; + create(attrs: Immutable.List | string): Immutable.List; + crop( + a: Immutable.List, + b: Immutable.List, + size?: number + ): Array>; + decrement( + path: Immutable.List, + n?: number, + index?: number + ): Immutable.List; + increment( + path: Immutable.List, + n?: number, + index?: number + ): Immutable.List; + isAbove( + path: Immutable.List, + target: Immutable.List + ): boolean; + isAfter( + path: Immutable.List, + target: Immutable.List + ): boolean; + isBefore( + path: Immutable.List, + target: Immutable.List + ): boolean; + lift(path: Immutable.List): Immutable.List; + max(a: Immutable.List, b: Immutable.List): number; + min(a: Immutable.List, b: Immutable.List): number; + relate( + a: Immutable.List, + b: Immutable.List + ): Immutable.List; +} export {}; diff --git a/types/slate/slate-tests.ts b/types/slate/slate-tests.ts index 25f222b4e1..91ef2dadcb 100644 --- a/types/slate/slate-tests.ts +++ b/types/slate/slate-tests.ts @@ -1,39 +1,39 @@ -import { Value, Data, NodeJSON, Document } from "slate"; +import { Value, Data, BlockJSON, Document } from "slate"; -const data = Data.create({ foo: "bar "}); +const data = Data.create({ foo: "bar " }); const value = Value.create({ data }); -const change = value.change() -.focus() -.selectAll() -.delete() -.insertText('A bit of rich text, followed by...') -.moveOffsetsTo(10, 14) -.addMark('bold') -.collapseToEndOfNextBlock() -.insertBlock({ - type: 'image', - isVoid: true, - data: { - src: 'http://placekitten.com/200/300', - alt: 'Kittens', - className: 'img-responsive', - }, -}) -.insertBlock('paragraph'); +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: NodeJSON = { +const node: BlockJSON = { object: "block", type: "paragraph", - isVoid: false, - data: {}, nodes: [ { object: "text", leaves: [ { - object: 'leaf', text: "example", - marks: [], + marks: [] } ] } @@ -43,7 +43,5 @@ const node: NodeJSON = { const doc = Document.fromJSON({ object: "document", data: {}, - nodes: [ - node - ], + nodes: [node] }); diff --git a/types/smtp-server/index.d.ts b/types/smtp-server/index.d.ts index d7e25dd342..3b5f320613 100644 --- a/types/smtp-server/index.d.ts +++ b/types/smtp-server/index.d.ts @@ -153,8 +153,8 @@ export interface SMTPServerOptions extends tls.TlsOptions { */ banner?: string; /** - * optional maximum allowed message size in bytes, - * see details:https://github.com/andris9/smtp-server#using-size-extension + * optional maximum allowed message size in bytes + * ([see details](https://github.com/andris9/smtp-server#using-size-extension)) */ size?: number; /** @@ -176,7 +176,7 @@ export interface SMTPServerOptions extends tls.TlsOptions { * use ['AUTH'] as this value. * If you want to allow authentication in clear text, set it to ['STARTTLS']. */ - disabledCommands?: string[]; // TODO ('AUTH' | 'STARTTLS' | 'XCLIENT' | 'XFORWARD')[]; + disabledCommands?: string[]; // TODO: ('AUTH' | 'STARTTLS' | 'XCLIENT' | 'XFORWARD')[]; /** * optional boolean, if set to true then allow using STARTTLS * but do not advertise or require it. It only makes sense @@ -224,17 +224,17 @@ export interface SMTPServerOptions extends tls.TlsOptions { maxClients?: number; /** * boolean, if set to true expects to be behind a proxy that emits a - * PROXY header{http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt} (version 1 only) + * [PROXY](http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt) header (version 1 only) */ useProxy?: boolean; /** * boolean, if set to true, enables usage of - * XCLIENT{http://www.postfix.org/XCLIENT_README.html} extension to override connection properties. + * [XCLIENT](http://www.postfix.org/XCLIENT_README.html) extension to override connection properties. * See session.xClient (Map object) for the details provided by the client */ useXClient?: boolean; /** - * boolean, if set to true, enables usage of XFORWARD{http://www.postfix.org/XFORWARD_README.html} extension. + * boolean, if set to true, enables usage of [XFORWARD](http://www.postfix.org/XFORWARD_README.html) extension. * See session.xForward (Map object) for the details provided by the client */ useXForward?: boolean; @@ -248,27 +248,27 @@ export interface SMTPServerOptions extends tls.TlsOptions { socketTimeout?: ms; /** * How many millisceonds to wait before disconnecting pending - * connections once server.close() has been called (defaults to 30 seconds) + * connections once `server.close()` has been called (defaults to 30 seconds) */ closeTimeout?: ms; /** - * The callback to handle authentications (see details https://github.com/andris9/smtp-server#handling-authentication) + * The callback to handle authentications ([see details](https://github.com/andris9/smtp-server#handling-authentication)) */ - onAuth?(auth: SMTPServerAuthentication, session: SMTPServerSession, callback: (err: Error | null | undefined, response: SMTPServerAuthenticationResponse) => void): void; + onAuth?(auth: SMTPServerAuthentication, session: SMTPServerSession, callback: (err: Error | null | undefined, response?: SMTPServerAuthenticationResponse) => void): void; /** - * The callback to handle the client connection. (see details https://github.com/andris9/smtp-server#validating-client-connection) + * The callback to handle the client connection. ([see details](https://github.com/andris9/smtp-server#validating-client-connection)) */ onConnect?(session: SMTPServerSession, callback: (err?: Error | null) => void): void; /** - * the callback to validate MAIL FROM commands (see details https://github.com/andris9/smtp-server#validating-sender-addresses) + * the callback to validate MAIL FROM commands ([see details](https://github.com/andris9/smtp-server#validating-sender-addresses)) */ onMailFrom?(address: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error | null) => void): void; /** - * The callback to validate RCPT TO commands (see details https://github.com/andris9/smtp-server#validating-recipient-addresses) + * The callback to validate RCPT TO commands ([see details](https://github.com/andris9/smtp-server#validating-recipient-addresses)) */ onRcptTo?(address: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error | null) => void): void; /** - * the callback to handle incoming messages (see details https://github.com/andris9/smtp-server#processing-incoming-message) + * the callback to handle incoming messages ([see details](https://github.com/andris9/smtp-server#processing-incoming-message)) */ onData?(stream: Readable, session: SMTPServerSession, callback: (err?: Error | null) => void): void; /** @@ -299,16 +299,21 @@ export class SMTPServer extends EventEmitter { listen(handle: any, listeningListener?: () => void): net.Server; // tslint:disable-line unified-signatures /** Closes the server */ - close(callback: (err?: Error | null) => void): void; + close(callback: () => void): void; updateSecureContext(options: tls.TlsOptions): void; /** Authentication handler. Override this */ - onAuth(auth: SMTPServerAuthentication, session: SMTPServerSession, callback: (err: Error | null | undefined, response: SMTPServerAuthenticationResponse) => void): void; + onAuth(auth: SMTPServerAuthentication, session: SMTPServerSession, callback: (err: Error | null | undefined, response?: SMTPServerAuthenticationResponse) => void): void; + /** Override this */ onClose(session: SMTPServerSession, callback: (err?: Error | null) => void): void; + /** Override this */ onConnect(session: SMTPServerSession, callback: (err?: Error | null) => void): void; + /** Override this */ onData(stream: Readable, session: SMTPServerSession, callback: (err?: Error | null) => void): void; + /** Override this */ onMailFrom(address: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error | null) => void): void; + /** Override this */ onRcptTo(address: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error | null) => void): void; addListener(event: 'close', listener: () => void): this; @@ -317,6 +322,14 @@ export class SMTPServer extends EventEmitter { emit(event: 'close'): boolean; emit(event: 'error', err: Error): boolean; + listenerCount(event: 'close' | 'error'): number; + + listeners(event: 'close'): Array<() => void>; + listeners(event: 'error'): Array<(err: Error) => void>; + + off(event: 'close', listener: () => void): this; + off(event: 'error', listener: (err: Error) => void): this; + on(event: 'close', listener: () => void): this; on(event: 'error', listener: (err: Error) => void): this; @@ -329,6 +342,11 @@ export class SMTPServer extends EventEmitter { prependOnceListener(event: 'close', listener: () => void): this; prependOnceListener(event: 'error', listener: (err: Error) => void): this; - listeners(event: 'close'): Array<() => void>; - listeners(event: 'error'): Array<(err: Error) => void>; + rawListeners(event: 'close'): Array<() => void>; + rawListeners(event: 'error'): Array<(err: Error) => void>; + + removeAllListener(event: 'close' | 'error'): this; + + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; } diff --git a/types/smtp-server/smtp-server-tests.ts b/types/smtp-server/smtp-server-tests.ts index 839d4ee3bc..52578ad4a8 100644 --- a/types/smtp-server/smtp-server-tests.ts +++ b/types/smtp-server/smtp-server-tests.ts @@ -2,76 +2,159 @@ import { AddressInfo } from 'net'; import { SMTPServer, SMTPServerAddress, SMTPServerAuthentication, SMTPServerAuthenticationResponse, SMTPServerOptions, SMTPServerSession } from 'smtp-server'; import { Readable } from 'stream'; -const options: SMTPServerOptions = { - hideSTARTTLS: true, - onConnect, - onMailFrom, - onRcptTo, - onData, - onClose, -}; +function test_with_handlers_as_options() { + const options: SMTPServerOptions = { + hideSTARTTLS: true, + onConnect, + onMailFrom, + onRcptTo, + onData, + onClose, + }; -const port = 2525; + const port = 2525; -function onConnect(session: SMTPServerSession, callback: (err?: Error) => void): void { - console.log(`[${session.id}] onConnect`); - callback(); -} - -function onAuth(auth: SMTPServerAuthentication, session: SMTPServerSession, callback: (err: Error | undefined, response?: SMTPServerAuthenticationResponse) => void): void { - if (auth.method === 'PLAIN' && auth.username === 'username' && auth.password === 'password') { - callback(undefined, { user: auth.username }); - } else { - callback(new Error('Invalid username or password')); - } -} - -function onMailFrom(from: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error) => void): void { - console.log(`[${session.id}] onMailFrom ${from.address}`); - if (from.address.split('@')[1] === 'spammer.com') { - // code 421 disconnects SMTP session immediately - callback(Object.assign(new Error('we do not like spam!'), { responseCode: 421 })); - } else { + function onConnect(session: SMTPServerSession, callback: (err?: Error) => void): void { + console.log(`[${session.id}] onConnect`); callback(); } -} -function onRcptTo(to: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error) => void): void { - console.log(`[${session.id}] onRcptTo ${to.address}`); - callback(); -} + function onAuth(auth: SMTPServerAuthentication, session: SMTPServerSession, callback: (err: Error | undefined, response?: SMTPServerAuthenticationResponse) => void): void { + if (auth.method === 'PLAIN' && auth.username === 'username' && auth.password === 'password') { + callback(undefined, { user: auth.username }); + } else { + callback(new Error('Invalid username or password')); + } + } -function onData(stream: Readable, session: SMTPServerSession, callback: (err?: Error) => void): void { - console.log(`[${session.id}] onData started`); + function onMailFrom(from: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error) => void): void { + console.log(`[${session.id}] onMailFrom ${from.address}`); + if (from.address.split('@')[1] === 'spammer.com') { + // code 421 disconnects SMTP session immediately + callback(Object.assign(new Error('we do not like spam!'), { responseCode: 421 })); + } else { + callback(); + } + } - let messageLength = 0; + function onRcptTo(to: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error) => void): void { + console.log(`[${session.id}] onRcptTo ${to.address}`); + callback(); + } - stream.on('data', (chunk: Buffer) => { - console.log(`[${session.id}] onData got data chunk ${chunk.length} bytes`); - messageLength += chunk.length; + function onData(stream: Readable, session: SMTPServerSession, callback: (err?: Error) => void): void { + console.log(`[${session.id}] onData started`); + + let messageLength = 0; + + stream.on('data', (chunk: Buffer) => { + console.log(`[${session.id}] onData got data chunk ${chunk.length} bytes`); + messageLength += chunk.length; + }); + + stream.once('end', () => { + console.log(`[${session.id}] onData finished after reading ${messageLength} bytes`); + callback(); + }); + } + + function onClose(session: SMTPServerSession) { + console.log(`[${session.id}] onClose`); + } + + const server = new SMTPServer(options); + + server.on('error', (err) => { + console.log(`Server got error:`, err); }); - stream.once('end', () => { - console.log(`[${session.id}] onData finished after reading ${messageLength} bytes`); - callback(); + server.on('close', () => { + console.log('Server closed'); + }); + + server.listen(port, () => { + const address = server.server.address() as AddressInfo; + console.log(`Listening on [${address.address}]:${address.port}`); + }); + + server.close(() => { + console.log('Server closed'); }); } -function onClose(session: SMTPServerSession) { - console.log(`[${session.id}] onClose`); +function test_with_handlers_in_subclass() { + class MySMTPServer extends SMTPServer { + onConnect(session: SMTPServerSession, callback: (err?: Error) => void): void { + console.log(`[${session.id}] onConnect`); + callback(); + } + + onAuth(auth: SMTPServerAuthentication, session: SMTPServerSession, callback: (err: Error | null | undefined, response?: SMTPServerAuthenticationResponse) => void): void { + if (auth.method === 'PLAIN' && auth.username === 'username' && auth.password === 'password') { + callback(undefined, { user: auth.username }); + } else { + callback(new Error('Invalid username or password')); + } + } + + onMailFrom(from: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error) => void): void { + console.log(`[${session.id}] onMailFrom ${from.address}`); + if (from.address.split('@')[1] === 'spammer.com') { + // code 421 disconnects SMTP session immediately + callback(Object.assign(new Error('we do not like spam!'), { responseCode: 421 })); + } else { + callback(); + } + } + + onRcptTo(to: SMTPServerAddress, session: SMTPServerSession, callback: (err?: Error) => void): void { + console.log(`[${session.id}] onRcptTo ${to.address}`); + callback(); + } + + onData(stream: Readable, session: SMTPServerSession, callback: (err?: Error) => void): void { + console.log(`[${session.id}] onData started`); + + let messageLength = 0; + + stream.on('data', (chunk: Buffer) => { + console.log(`[${session.id}] onData got data chunk ${chunk.length} bytes`); + messageLength += chunk.length; + }); + + stream.once('end', () => { + console.log(`[${session.id}] onData finished after reading ${messageLength} bytes`); + callback(); + }); + } + + onClose(session: SMTPServerSession) { + console.log(`[${session.id}] onClose`); + } + } + + const options: SMTPServerOptions = { + hideSTARTTLS: true + }; + + const port = 2525; + + const server = new MySMTPServer(options); + + server.on('error', (err) => { + console.log(`Server got error:`, err); + }); + + server.on('close', () => { + console.log('Server closed'); + }); + + server.listen(port, () => { + const address = server.server.address() as AddressInfo; + console.log(`Listening on [${address.address}]:${address.port}`); + }); + + server.close(() => { + console.log('Server closed'); + }); } - -const server = new SMTPServer(options); - -server.on('error', (err) => { - console.log(`Server got error:`, err); -}); - -server.on('close', () => { - console.log('Server closed'); -}); - -server.listen(port, () => { - const address = server.server.address() as AddressInfo; - console.log(`Listening on [${address.address}]:${address.port}`); -}); diff --git a/types/socket.io-p2p/index.d.ts b/types/socket.io-p2p/index.d.ts new file mode 100644 index 0000000000..3667726700 --- /dev/null +++ b/types/socket.io-p2p/index.d.ts @@ -0,0 +1,135 @@ +// Type definitions for socket.io-p2p 2.2 +// Project: https://github.com/socketio/socket.io-p2p +// Definitions by: Sascha Englert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export as namespace Socketiop2p; + +export = SocketioP2PStatic; + +/** + * Creates the P2P object + * @param socket Socket.io socket + * @param opts Object of viable options + * @param cb Optional callback + */ +declare class SocketioP2PStatic { + useSockets: boolean; + usePeerConnection: boolean; + decoder: any; + socket: any; + cb: () => void; + defaultOps: SocketioP2PStatic.DefaultOps; + opts: SocketioP2PStatic.P2POptions; + peerOpts: SocketioP2PStatic.PeerOpts; + numConnectedClients: number; + + constructor( + socket: any, + opts?: SocketioP2PStatic.P2POptions, + cb?: () => void + ); + + on(event: string, callback: (data: any) => void): void; + emit(eventName: any, data: any): void; + + /** + * Upgrade the connection to p2p + */ + upgrade(): void; + disconnect(): void; + binarySlice(arr: any[], interval: number, cb: () => void): void; + setupPeerEvents(peer: any): void; +} + +declare namespace SocketioP2PStatic { + interface DefaultOps { + autoUpgrade: boolean; + numClients: number; + } + interface PeerOpts { + /** + * Set to true if this is the initiating peer + * @default false + */ + initiator?: boolean; + /** + * Custom WebRTC channel configuration (used by createDataChannel) + * @default {} + */ + channelConfig?: object; + /** + * Custom WebRTC data channel name + * @default + */ + channelName?: string; + /** + * Custom WebRTC configuration (used by RTCPeerConnection constructor) + * @default {iceServers:[{urls:'stun:stun.l.google.com:19302'},{urls:'stun:global.stun.twilio.com:3478?transport=udp'}]} + */ + config?: object; + /** + * Custom WebRTC video/voice constrainst (used by RTCPeerConnection constructor) + * @default {} + */ + constraints?: object; + /** + * Custom offer contstraints (used by createOffer methode) + * @default {} + */ + offerConstraints?: object; + /** + * Custom answer constraints (used by createAnswer method) + */ + answerConstraints?: object; + /** + * Function to transform generated SDP signaling data (for advanced users) + * @default (sdp)=>sdp + */ + sdpTransfrom?: (sdp: any) => any; + /** + * If video/voice is desired, pass stream from getUserMedia + * @default false + */ + stream?: boolean; + /** + * An array of MediaStreams returned from getUserMedia + * @default [] + */ + streams?: MediaStream[]; + /** + * Set to false to disable trickle ICE and get single 'signal' event (slower) + * @default true + */ + trickle?: boolean; + /** + * Custom WebRTC implementation, mainly useful in node to specify the wrtc package + * @default {} + */ + wrtc?: RTCPeerConnection | RTCSessionDescription | RTCIceCandidate; + /** + * Set to true to create the stream in Object Mode. In this mode, incoming string data is not automatically converted to Buffer objects + * @default false + */ + objectMode?: boolean; + } + + interface P2POptions { + /** + * Max number of peers each client can connect to + * @default 5 + */ + numClients?: number; + /** + * Upgrade to p2p connection (from s.io one) when peers are ready + * @default true + */ + autoUpgrade?: boolean; + /** + * Object of options passed to underlying peers + * @default {} + */ + peerOpts?: PeerOpts; + } +} diff --git a/types/socket.io-p2p/socket.io-p2p-tests.ts b/types/socket.io-p2p/socket.io-p2p-tests.ts new file mode 100644 index 0000000000..f6e3548685 --- /dev/null +++ b/types/socket.io-p2p/socket.io-p2p-tests.ts @@ -0,0 +1,14 @@ +import P2P = require("socket.io-p2p"); +import io = require("socket.io-client"); + +const socket = io(); +const p2p = new P2P(socket); + +p2p.on("ready", () => { + p2p.usePeerConnection = true; + p2p.emit("peer-obj", { peerId: 1 }); +}); + +p2p.on("peer-msg", data => { + console.log(data); +}); diff --git a/types/socket.io-p2p/tsconfig.json b/types/socket.io-p2p/tsconfig.json new file mode 100644 index 0000000000..75c4112267 --- /dev/null +++ b/types/socket.io-p2p/tsconfig.json @@ -0,0 +1,16 @@ +{ + "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", "socket.io-p2p-tests.ts"] +} diff --git a/types/socket.io-p2p/tslint.json b/types/socket.io-p2p/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/socket.io-p2p/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sqlanywhere/index.d.ts b/types/sqlanywhere/index.d.ts new file mode 100644 index 0000000000..d56bfb7993 --- /dev/null +++ b/types/sqlanywhere/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for sqlanywhere 1.0 +// Project: https://github.com/sqlanywhere/node-sqlanywhere +// Definitions by: Peter Keuter +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export function createConnection(): SybaseConnection; + +export interface SybaseConnection { + connect( + params: ConnectionParameters, + cb: (err: Error | undefined) => void + ): void; + close(cb: (err?: Error) => void): void; + disconnect(cb: (err?: Error) => void): void; + connected(): boolean; + exec(query: string, cb: (err: Error | undefined, result: any) => void); + exec( + query: string, + placeholders: any[], + cb: (err: Error | undefined, result: any) => void + ); + prepare( + query: string, + cb: (err: Error | undefined, stmt: Statement) => void + ); + prepare(query: string): Statement; + commit(cb: (err: Error | undefined) => void): void; + rollback(cb: (err: Error | undefined) => void): void; +} + +export interface ConnectionParameters { + Server: string; + UserId: string; + DatabaseFile?: string; + AutoStart?: string; + Password: string; + Host?: string; +} + +export interface Statement { + exec(args: any[], cb: (err: Error | undefined, rows: any[]) => void); + exec(args: any[]): any[]; + getMoreResults(): any[]; + drop(cb: (err: Error | undefined) => void): void; +} +declare const _default: { + createConnection: typeof createConnection; +}; +export default _default; diff --git a/types/sqlanywhere/sqlanywhere-tests.ts b/types/sqlanywhere/sqlanywhere-tests.ts new file mode 100644 index 0000000000..b6151e77aa --- /dev/null +++ b/types/sqlanywhere/sqlanywhere-tests.ts @@ -0,0 +1,13 @@ +import sqlanywhere = require("sqlanywhere"); + +const connection: sqlanywhere.SybaseConnection = sqlanywhere.createConnection(); +connection.connect( + { + Host: "test", + UserId: "Test", + Password: "Test", + Server: "Test" + }, + err => err +); +connection.exec("SELECT * FROM TEST", (err, res) => res); diff --git a/types/sqlanywhere/tsconfig.json b/types/sqlanywhere/tsconfig.json new file mode 100644 index 0000000000..4270f0546c --- /dev/null +++ b/types/sqlanywhere/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitThis": true, + "noImplicitAny": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sqlanywhere-tests.ts" + ] +} diff --git a/types/sqlanywhere/tslint.json b/types/sqlanywhere/tslint.json new file mode 100644 index 0000000000..10d875b8db --- /dev/null +++ b/types/sqlanywhere/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/stream-throttle/index.d.ts b/types/stream-throttle/index.d.ts new file mode 100644 index 0000000000..30ba038907 --- /dev/null +++ b/types/stream-throttle/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for stream-throttle 0.1 +// Project: https://github.com/tjgq/node-stream-throttle +// Definitions by: Daniel Byrne +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +export interface ThrottleOptions { + readonly rate: number; + readonly chunksize?: number; +} + +export class Throttle extends Transform { + constructor(options: ThrottleOptions); +} + +export class ThrottleGroup { + constructor(options: ThrottleOptions); + throttle(options: ThrottleOptions): Throttle; +} diff --git a/types/stream-throttle/stream-throttle-tests.ts b/types/stream-throttle/stream-throttle-tests.ts new file mode 100644 index 0000000000..bbd8f8ce86 --- /dev/null +++ b/types/stream-throttle/stream-throttle-tests.ts @@ -0,0 +1,7 @@ +import { Throttle, ThrottleGroup } from 'stream-throttle'; + +const throttle = new Throttle({rate: 1}); +const throttleGroup = new ThrottleGroup({rate: 1}); + +// $ExpectType Throttle +throttleGroup.throttle({rate: 1}); diff --git a/types/stream-throttle/tsconfig.json b/types/stream-throttle/tsconfig.json new file mode 100644 index 0000000000..b9e4185c58 --- /dev/null +++ b/types/stream-throttle/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stream-throttle-tests.ts" + ] +} diff --git a/types/stream-throttle/tslint.json b/types/stream-throttle/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/stream-throttle/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 06b7fbbb70..fcb008c07b 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -716,6 +716,16 @@ declare namespace Stripe { * or "transfer_failure" */ type?: string; + + /** + * For automatic Stripe payouts only, only returns transactions that were payed out on the specified payout ID. + */ + payout?: string; + + /** + * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10. + */ + limit?: number; } } @@ -1340,7 +1350,7 @@ declare namespace Stripe { livemode: boolean; - metadata?: IMetadata; + metadata: IMetadata; /** * Shipping information associated with the customer. diff --git a/types/stripejs/customer.d.ts b/types/stripejs/customer.d.ts new file mode 100644 index 0000000000..fcde40a32a --- /dev/null +++ b/types/stripejs/customer.d.ts @@ -0,0 +1,299 @@ +export interface Customer { + /** + * The Address of the customer + */ + address: Address; + + /** + * The email address of the customer + */ + email: string; + + /** + * The full name of the owner + */ + name: string; + + /** + * The phone number of the customer + * NOTE: This includes the extension + */ + phone: string; + + /** + * Verified customer’s address + */ + readonly verified_address: Address; + + /** + * Verified customer’s email address + */ + readonly verified_email: string; + + /** + * Verified customer’s full name + */ + readonly verified_name: string; + + /** + * Verified customer’s phone number + */ + readonly verified_phone: string; +} + +// --- CUSTOMER ADDRESS --- // +export interface Address { + /** + * City/District/Suburb/Town/Village. + */ + city: string; + + /** + * Two-letter country code, capitalized + * NOTE: The codes are specified by the ISO3166 alpha-2 + */ + country: string; + + /** + * Address line 1 (Street address/PO Box/Company name). + */ + line1: string; + + /** + * Address line 2 (Apartment/Suite/Unit/Building). + */ + line2: string; + + /** + * ZIP or postal code + */ + postal_code: string; + + /** + * State/County/Province/Region. + */ + state: string; +} + +// --- CARD PAYMENT OPTION --- // +/** + * @see https://stripe.com/docs/api#card_object + */ +export interface Card { + /** + * The unique identifier of the bank account + */ + id: string; + + /** + * The account this card belongs to. + * NOTE: This attribute will not be in the card object if the card belongs to a customer or recipient instead. + */ + object: 'card'; + + account?: string; + + /** + * City/District/Suburb/Town/Village + */ + address_city: string; + + /** + * The country in which the address is located + */ + address_country: string; + + /** + * Address line 1 (Street address/PO Box/Company name) + */ + address_line1: string; + + /** + * The results of address_line1 if it was provided + */ + address_line1_check: checkStatus; + + /** + * Address line 2 (Apartment/Suite/Unit/Building) + */ + address_line2: string; + + /** + * State/County/Province/Region. + */ + address_state: string; + + /** + * ZIP or postal code + */ + address_zip: string; + + /** + * The results of address_zip if it was provided + */ + address_zip_check: checkStatus; + + /** + * A set of available payout methods for this card + * NOTE: Only values from this set should be passed as the method when creating a transfer + */ + available_payout_methods: ['standard'] | ['standard', 'instant']; + + /** + * The brand of the card + */ + brand: 'American Express' | 'Diners Club' | 'Discover' | 'JCB' | 'MasterCard' | 'UnionPay' | 'Visa' | 'Unknown'; + + /** + * Two-letter ISO code representing the country of the card + * You could use this attribute to get a sense of the international breakdown of cards you’ve collected + */ + country: string; + + /** + * Three-letter ISO code for currency + * Only applicable on accounts (not customers or recipients). + * The card can be used as a transfer destination for funds in this currency + */ + currency?: string; + + /** + * The customer that this card belongs to + * NOTE: This attribute will not be in the card object if the card belongs to an account or recipient instead + */ + customer?: any; + + /** + * If a CVC was provided, results of the check + */ + cvc_check: checkStatus; + + /** + * Only applicable on accounts (not customers or recipients) + * This indicates whether this card is the default external account for its currency + */ + default_for_currency?: boolean; + + /** + * The last four digits of the device account number. + * NOTE: For tokenized numbers only + */ + dynamic_last4: string; + + /** + * Two-digit number representing the card’s expiration month + */ + exp_month: number; + + /** + * Four-digit number representing the card’s expiration year + */ + exp_year: number; + + /** + * Uniquely identifies this particular card number + */ + fingerprint: string; + + /** + * Card funding type + */ + funding: 'credit' | 'debit' | 'prepaid' | 'unknown'; + + /** + * The last four digits of the card + */ + last4: string; + + /** + * The name of the cardholder + */ + name: string; + + /** + * The recipient that this card belongs to. + * NOTE: This attribute will not be in the card object if the card belongs to a customer or account instead + */ + recipient?: string; + + /** + * If the card number is tokenized, this is the method that was used + */ + tokenization_method: 'apple_pay' | 'android_pay'; + + /** + * Your own saved information with this card + */ + metadata: { [key: string]: string }; +} + +export type checkStatus = 'pass' | 'fail' | 'unavailable' | 'unchecked'; + +// --- BANK ACCOUNT PAYMENT OPTION --- // +/** + * @see https://stripe.com/docs/api#customer_bank_account_object + */ +export interface BankAccount { + /** + * The unique identifier of the bank account + */ + id: string; + + object: 'bank_account'; + + /** + * The name of the person or business that owns the bank account. + */ + account_holder_name: string; + + /** + * The type of entity that holds the account. + */ + account_holder_type: 'individual' | 'company'; + + /** + * Name of the bank associated with the routing number + * @example 'STRIPE TEST BANK' + */ + bank_name: string; + + /** + * The routing transit number for the bank account + */ + routing_number: string; + + /** + * Two-letter ISO code representing the country the bank account is located in + * @example 'US' + */ + country: string; + /** + * Three-letter ISO code for the currency paid out to the bank account + * @example 'usd' + */ + currency: string; + + customer: string; + + /** + * Uniquely identifies this particular bank account. + * NOTE: You can use this attribute to check whether two bank accounts are the same + */ + fingerprint: string; + + /** + * The last 4 digits of the bank number + */ + last4: string; + + /** + * Your own saved information with this bank account + */ + metadata: { [key: string]: string }; + + /** + * The status of the bank account + * @see https://stripe.com/docs/api#customer_bank_account_object-status + */ + status: 'new' | 'validated' | 'verified' | 'verification_failed' | 'errored'; +} diff --git a/types/stripejs/element.d.ts b/types/stripejs/element.d.ts new file mode 100644 index 0000000000..9a1b8b17e2 --- /dev/null +++ b/types/stripejs/element.d.ts @@ -0,0 +1,414 @@ +import { StripeError } from "./index"; + +export interface ElementFactory { + /** + * Creates a new StripeJS element + * @see https://stripe.com/docs/stripe-js/reference#elements-create + * @param type - The type of element that should be created + * @param options - Any options that should be used to con + * + * @example ``` + * const style = { + * base: { + * color: '#303238', + * fontSize: '16px', + * color: "#32325d", + * fontSmoothing: 'antialiased', + * '::placeholder': { + * color: '#ccc', + * }, + * }, + * invalid: { + * color: '#e5424d', + * ':focus': { + * color: '#303238', + * }, + * }, + * }; + * const cardElement = elementCreator.create('card', {style: style}) + * ``` + * + * @return The created element + */ + create( + type: ElementType, + options: CardElementOptions | IBANElementOptions | IdealBankOptions | PaymentButtonOptions + ): StripeElement; +} + +export interface ElementCreatorOptions { + /** + * Fonts that should be used for styling the element + * @see https://stripe.com/docs/stripe-js/reference#stripe-elements + */ + fonts?: FontCSSElement[] | FontConfigElement[]; + + /** + * The translation that should be used for the element text + * `auto` defaults to the browser language + * + * NOTE: Only use the `string` option in combination with + * @see isLanguageTag + * + * @default 'auto' + */ + locale?: 'auto' | 'da' | 'de' | 'en' | 'es' | 'fi' | 'fr' | 'it' | 'ja' | 'no' | 'nl' | 'sv' | 'zh' | string; + + /** + * Whether or not the locale is written in a language code + * This can be used in combination with localization libraries so that language names won't have to be formatted + * @example `en-US` + * + * @since 0.1.0 + */ + isIETFLocaleTag?: boolean; +} + +export interface FontCSSElement { + /** + * A relative or absolute URL pointing to a CSS file with `@font-face` definitions + * @example 'https://fonts.googleapis.com/css?family=Open+Sans' + */ + cssSrc: string; +} + +export interface FontConfigElement { + /** + * The name of the font family + * @example 'Times New Roman' + */ + family?: string; + + /** + * A src value pointing to your custom font file. + * @example + * 'url(https://somewebsite.com/path/to/font.woff)' + * 'url(path/to/font.woff)' + */ + src?: string; + + /** + * The style of the text + * @default 'normal' + */ + style?: 'normal' | 'italic' | 'oblique'; + + /** + * A unicode range for the font that should be used + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range + */ + unicodeRange?: string; + + /** + * The weight of the font + * NOTE: This cannot be a number! + */ + weight?: 'initial' | 'inherit' | 'bold' | 'bolder' | 'lighter' | 'normal' | 'revert' | 'unset'; +} + +// --- ELEMENT --- // +export interface StripeElement { + /** + * Mount the element to the DOM + * @see https://stripe.com/docs/stripe-js/reference#element-mount + * + * @param element - A HTML DOM element or a CSS selector + * + * @example ``` + * + *
+ * + * cardElement.mount('#card-element'); + * ``` + */ + mount(element: HTMLElement | string): void; + + /** + * Watch for changes on the element + * @see https://stripe.com/docs/stripe-js/reference#element-on + * + * @param event - What event to listen to + * @param handler - The handler function that is called when the event fires + */ + on(event: 'blur' | 'focus' | 'ready', handler: () => void): void; + on(event: 'click', handler: (event: { preventDefault: () => void }) => void): void; + on(event: 'change', handler: (event: OnChange) => void): void; + + /** + * Blur the element + * @see https://stripe.com/docs/stripe-js/reference#other-methods + */ + blur(): void; + + /** + * Clear the value of the element + */ + clear(): void; + + /** + * Removes the Element from the DOM and destroys it + * NOTE: a destroyed element can not be re-activated or re-mounted to the DOM + */ + destroy(): void; + + /** + * Give focus to the element + */ + focus(): void; + + /** + * Unmounts the Element from the DOM + * Call `element.mount()` to re-attach it to the DOM + * @see mount + */ + unmount(): void; + + /** + * Updates the options the Element was initialized with + * NOTE: Updates are merged into the existing configuration + * @param options - The options that should be used to update the element + */ + update(options: CardElementOptions | IBANElementOptions | IdealBankOptions | PaymentButtonOptions): void; +} + +/** + * The type of element that can be created by the ElementCreator + * @see ElementCreator + */ +export type ElementType = 'card' | 'cardNumber' | 'cardExpiry' | 'cardCvc' | 'postalCode'; + +// --- ELEMENT EVENTS --- // +export interface OnChange { + /** + * true if the value is empty + */ + empty: boolean; + + /** + * true if the value is well-formed and potentially complete + */ + complete: boolean; + + /** + * The current validation error if any + */ + error: StripeError; + + /** + * The value of the element + * @see CardElementOptions.value for more information + * NOTE: This is only filled is the element is of a Card type + * + * ----- + * + * The selected bank. Can be one of the banks listed in the + * @see https://stripe.com/docs/sources/ideal#optional-specifying-the-customers-bank + * NOTE: This is also filled when the element is of IdealBank type + */ + value?: any; + + /** + * The type of card that was used + * @example 'visa' + * NOTE: This is only available when the element is of Card or Cardnumber type + */ + brand?: string; + + /** + * The country code of the entered IBAN + * NOTE: This is only available when the element is of IBAN type + */ + country?: string; + + /** + * The financial institution that services the account whose IBAN was entered into the Element. + * NOTE: This is only available when the element is of IBAN type + */ + bankName: string; +} + +// --- CARD ELEMENT --- // +export interface CardElementOptions extends BaseOptions { + /** + * A pre-filled value + * NOTE: Sensitive card information (card number, CVC, and expiration date) cannot be pre-filled + * @see placeholder + * + * @example {postalCode: '94110'} + */ + value?: any; + + /** + * Whether or not to hide the postal code + * NOTE: If you are already collecting a full billing address or postal code elsewhere, set this to `true` + * @default false + */ + hidePostalCode?: boolean; + + /** + * Appearance of the icon in the Element + */ + iconStyle?: 'solid' | 'default'; + + /** + * A placeholder text + * NOTE: This is only available for `cardNumber`, `cardExpiry` & `cardCvc` elements + */ + placeholder?: string; +} + +// --- IBAN ELEMENT --- // +export interface IBANElementOptions extends BaseOptions { + /** + * Specify the list of countries or country-groups whose IBANs you want to allow + */ + supportedCountries?: string[]; + + /** + * Customize the country and format of the placeholder IBAN + * @default 'DE" + */ + placeholderCountry?: string; + + /** + * Appearance of the icon in the Element + */ + iconStyle?: 'solid' | 'default'; +} + +// --- IDEAL ELEMENT --- // +export interface IdealBankOptions extends BaseOptions { + /** + * A pre-filled value for the Element. Can be one of the banks listed in the + * @see https://stripe.com/docs/sources/ideal#optional-specifying-the-customers-bank + * + * @example 'abn_amro' + */ + value?: string; +} + +// --- PAYMENT BUTTON ELEMENT --- // +export interface PaymentButtonOptions { + paymentRequest: any; + + /** + * Set custom class names on the container DOM element when the Stripe Element is in a + * particular state. + */ + classes?: { + base?: string; /** @default StripeElement */ + complete?: string; /** @default StripeElement--complete */ + focus: string; /** @default StripeElement--focus */ + invalid: string; /** @default StripeElement--invalid */ + }; + + style?: { + base?: PaymentRequestButtonStyle; + complete?: PaymentRequestButtonStyle; + empty?: PaymentRequestButtonStyle; + invalid?: PaymentRequestButtonStyle; + }; +} + +export interface PaymentRequestButtonStyle { + /** + * The type of button that should be shown + * @default 'default' + */ + type?: 'default' | 'donate' | 'buy'; + + /** + * The theme of the button that should be used + * @default 'dark' + */ + theme?: 'dark' | 'light' | 'light-outline'; + + /** + * The height of the button + * @example '25px' + */ + height?: string; +} + +// --- BASE OPTIONS FOR ELEMENTS --- // +/** + * @deprecated Do not use this interface. This is only here to minimize code duplication + */ +export interface BaseOptions { + /** + * Set custom class names on the container DOM element when the Stripe Element is in a + * particular state. + */ + classes?: { + base?: string; /** @default StripeElement */ + complete?: string; /** @default StripeElement--complete */ + empty?: string; /** @default StripeElement--empty */ + focus?: string; /** @default StripeElement--focus */ + invalid?: string; /** @default StripeElement--invalid */ + webkitAutofill?: string; /** @default StripeElement--webkit-autofill */ + }; + + /** + * Customize appearance using CSS properties + */ + style?: { + base?: StyleAttributes; + complete?: StyleAttributes; + empty?: StyleAttributes; + invalid?: StyleAttributes; + }; + + /** + * Whether or not the icon should be hidden + * @default false + */ + hideIcon?: boolean; + + /** + * Whether or not the input is disabled + * @default false + */ + disabled?: boolean; +} + +/** + * Styling settings for a Stripe Element + */ +export interface StyleAttributes { + color?: string; + fontFamily?: string; + fontSize?: string; + fontSmoothing?: string; + fontStyle?: string; + fontVariant?: any; + iconColor?: string; + lineHeight?: string; + letterSpacing?: string; + + /** + * Align text inside the element + * NOTE: Only available for the `cardNumber`, `cardExpiry`, and `cardCvc` Elements + */ + textAlign?: string; + '::-ms-clear'?: MSClearAttributes; + + /** + * Add padding to the element + * NOTE: Only available for the `idealBank` Element + */ + padding?: string; + + textDecoration?: string; + textShadow?: string; + textTransform?: string; + ':hover'?: StyleAttributes; + ':focus'?: StyleAttributes; + '::placeholder'?: StyleAttributes; + '::selection'?: StyleAttributes; + ':-webkit-autofill'?: StyleAttributes; + ':disabled'?: StyleAttributes; +} + +export interface MSClearAttributes extends StyleAttributes { + display?: string; +} diff --git a/types/stripejs/index.d.ts b/types/stripejs/index.d.ts new file mode 100644 index 0000000000..f2a7ab21aa --- /dev/null +++ b/types/stripejs/index.d.ts @@ -0,0 +1,147 @@ +// Type definitions for stripe.js 3.0 +// Project: https://stripe.com/ +// Definitions by: Robin van Tienhoven +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { StripeElement, ElementCreatorOptions, ElementFactory } from './element'; +import { StripePaymentOptions, StripePaymentRequest } from './payment'; +import { BankTokenData, PiiTokenData, TokenData, IBANTokenData, TokenResult } from './token'; +import { SourceData, SourceResult } from './source'; + +export interface StripeJS { + /** + * The currently used key + */ + _apiKey: string; + + /** + * The mode in which the requests are currently done + * @example 'test' + */ + _keyMode: string; + + /** + * Initialization function for StripeJS + * @see https://stripe.com/docs/stripe-js/reference#including-stripejs + * + * @param key - The public key of the user + * @param [options] - Any options to configure StripeJS + * + * @return StripeJS instance + */ + (key: string, options?: StripeConfigOptions): StripeJS; + + /** + * Create an instance of elements which can be used to manage a group of StripeJS elements + * @see https://stripe.com/docs/stripe-js/reference#stripe-elements + * + * @param [options] - Configuration options for the elements object + * + * @return an instance of `Elements` to manage a group of elements + */ + elements(options?: ElementCreatorOptions): ElementFactory; + + /** + * Creates a new payment request based on the given options + * @see https://stripe.com/docs/stripe-js/reference#stripe-payment-request + * + * @param options - Options that should be used to configure the payment request + */ + paymentRequest(options: StripePaymentOptions): StripePaymentRequest; + + /** + * to convert information collected by Elements into a single-use token that you safely pass to your server + * to use in an API call + * @see https://stripe.com/docs/stripe-js/reference#stripe-create-token + * + * @param element - The element from which the data should be extracted + * @param [data] - an object containing additional payment information you might have collected + * + * @return an object containing the generated token or an error + */ + createToken(element: StripeElement, data?: TokenData | IBANTokenData): Promise; + createToken(type: 'bank_account', data: BankTokenData): Promise; + createToken(type: 'pii', data: PiiTokenData): Promise; + + /** + * convert payment information collected by Elements into a Source object that you safely pass + * to your server to use in an API call + * @see https://stripe.com/docs/stripe-js/reference#stripe-create-source + * + * @param element - The element from which information should be extracted + * @param data - An object containing the type of Source you want to create and any additional payment source information + * NOTE: You cannot pass raw card information without an `Element`! + * + * @return an object containing the generated Source or an error + */ + createSource(element: StripeElement, data: SourceData): Promise; + createSource(data: SourceData): Promise; + + /** + * Retrieve a Source using its unique ID and client secret + * NOTE: The parameters are always available in any source object fetched with StripeJS + * + * @param id - Unique identifier of the source + * @param client_secret - A secret available to the web client that created the Source + * + * @return an object containing the generated Source or an error + */ + retrieveSource({id, client_secret}: { id: string, client_secret: string }): Promise; +} + +export interface StripeConfigOptions { + stripeAccount: string; +} + +/** + * @see https://stripe.com/docs/api#errors + */ +export interface StripeError { + /** + * The type of error that has occurred + */ + type: errorType; + + /** + * For card errors, the ID of the failed charge + */ + charge?: string; + + /** + * For some errors that could be handled programmatically, + * a short string indicating the error code reported + */ + code?: string; + + /** + * For card errors resulting from a card issuer decline, + * a short string indicating the card issuer’s reason for the decline if they provide one + */ + decline_code?: string; + + /** + * A URL to more information about the error code reported + */ + doc_url?: string; + + /** + * A human-readable message providing more details about the error. + * NOTE: For card errors, these messages can be shown to your users + */ + message?: string; + + /** + * If the error is parameter-specific, the parameter related to the error + */ + param?: string; +} + +export type errorType = + 'api_connection_error' | + 'api_error' | + 'authentication_error' | + 'card_error' | + 'idempotency_error' | + 'invalid_request_error' | + 'rate_limit_error'; diff --git a/types/stripejs/payment.d.ts b/types/stripejs/payment.d.ts new file mode 100644 index 0000000000..bad5419ec1 --- /dev/null +++ b/types/stripejs/payment.d.ts @@ -0,0 +1,235 @@ +import { ShippingAddress, ShippingOption } from "./shipping"; + +/** + * The Payment request object that can be used to make payments + * @see https://stripe.com/docs/stripe-js/reference#the-payment-request-object + */ +export interface StripePaymentRequest { + /** + * Whether or not a payment can be made + * NOTE: When no API is available it resolves with `null` + * + * @see https://stripe.com/docs/stripe-js/reference#payment-request-can-make-payment + */ + canMakePayment(): Promise; + + /** + * Shows the browser’s payment UI + * NOTE: When using the paymentRequestButton Element, this is called for you under the hood + * NOTE: This method must be called as the result of a user interaction (for example, in a click handler) + * + * @see https://stripe.com/docs/stripe-js/reference#payment-request-show + */ + show(): void; + + /** + * Updates the payment information + * NOTE: can only be called when the browser payment UI is not showing + * + * @param options - Payment information that should be used by Stripe + * + * @see https://stripe.com/docs/stripe-js/reference#payment-request-update + */ + update(options: UpdateOptions): void; + + /** + * Register your event listener + * @see https://stripe.com/docs/stripe-js/reference#payment-request-on + */ + on(event: 'cancel', handler: () => void): void; + + on(event: 'token' | 'source', handler: (event: StripePaymentResponse) => void): void; + + on(event: 'shippingaddresschange', handler: (event: NewShippingAddress) => void): void; + + on(event: 'shippingoptionchange', handler: (event: NewShippingOptions) => void): void; +} + +export interface CanMakePaymentResult { + /** + * true if the browser payment API supports Apple Pay. + * NOTE: using the paymentRequestButton Element is automatically cross-browser. + * If you use this PaymentRequest object to create a paymentRequestButton Element, you don‘t need to check applePay yourself + */ + readonly applePay: boolean; +} + +/** + * @see https://stripe.com/docs/stripe-js/reference#payment-request-on + */ +export interface NewShippingAddress { + /** + * Calling this function with an UpdateDetails object merges your updates into the + * current PaymentRequest object. + */ + updateWith: (dataToUpdate: UpdateOptions) => void; + + /** + * The customer's selected ShippingAddress. + */ + shippingAddress: ShippingAddress; +} + +export interface NewShippingOptions { + /** + * Calling this function with an UpdateDetails object merges your updates into the + * current PaymentRequest object. + */ + updateWith: (dataToUpdate: UpdateOptions) => void; + + /** + * The selected shipping option + */ + shippingOption: ShippingOption; +} + +/** + * Payment options that can be set when updating the payment request + * @see https://stripe.com/docs/stripe-js/reference#payment-request-update + */ +export interface UpdateOptions { + /** + * The currency in which the customer should be charged + * @example 'usd' + */ + currency: string; + + /** + * The total amount the customer has to pay + * NOTE: This object is shown to the customer in the browser‘s payment UI + */ + total: PaymentItem; + + /** + * An array of payment item objects + * NOTE: The sum of the line item amounts does not need to add up to the total amount above + * @see total + * + * @default [] + */ + displayItems?: PaymentItem[]; + + /** + * An array of possible shipping options + * NOTE: This first one in the array will be listed as the default option + * + * @default [] + */ + shippingOptions?: ShippingOption[]; +} + +/** + * Configuration options for creating a payment request + * @see https://stripe.com/docs/stripe-js/reference#stripe-payment-request + */ +export interface StripePaymentOptions extends UpdateOptions { + /** + * The two letter code representing your country + * @example 'US' + */ + country: string; + + /** + * Whether or not the form should ask for the payer's name + * @default false + */ + requestPayerName?: boolean; + + /** + * Whether or not the form should ask for the payer's email address + * @default false + */ + requestPayerEmail?: boolean; + + /** + * Whether or not the form should ask for the payer's phone number + * @default false + */ + requestPayerPhone?: boolean; + + /** + * Whether or not a shipping address should be requested + * NOTE: Setting this to true requires `shippingOptions` to be set with at least one option! + * @see shippingOptions + */ + requestShipping?: boolean; +} + +export interface PaymentItem { + /** + * The amount the user has to pay in the given currency + * @see StripePaymentOptions.currency + */ + amount: number; + + /** + * A text that should be shown to the user + */ + label: string; + + /** + * Whether or not the payment should be executed immediately + * If you might change this amount later (for example, after you have calculated shipping costs), set this to `true` + */ + pending?: boolean; +} + +// --- PAYMENT RESPONSE FROM STRIPE --- // +/** + * @see https://stripe.com/docs/stripe-js/reference#payment-response-object + */ +export interface StripePaymentResponse { + /** + * NOTE: Only available when the event type 'token' was used + */ + readonly token?: any; + + /** + * NOTE: Only available when the event type 'source' was used + */ + readonly source?: any; + + /** + * A function to complete the payment and give feedback to the user + * Call this when you have processed the token data provided by the API + * + * @param status - The status that should be shown to the user + */ + complete: (status: completeStatus) => void; + + /** + * Information about the payer + * NOTE: This is only set if the corresponding field was set to `true` in the `PaymentOptions` + * + * @see PaymentOptions.requestPayerName + * @see PaymentOptions.requestPayerEmail + * @see PaymentOptions.requestPayerPhone + */ + readonly payerName?: string; + readonly payerEmail?: string; + readonly payerPhone?: string; + + /** + * The shipping address the payer selected + */ + readonly shippingAddress: ShippingAddress; + + /** + * The shipping option the payer selected + */ + readonly shippingOption: ShippingOption; + + /** + * The unique name of the payment handler the customer chose to authorize payment + * @example 'basic-card' + */ + readonly methodName: string; +} + +export type completeStatus = + 'success' | + 'fail' | + 'invalid_payer_name' | + 'invalid_payer_phone' | + 'invalid_payer_email' | + 'invalid_shipping_address'; diff --git a/types/stripejs/shipping.d.ts b/types/stripejs/shipping.d.ts new file mode 100644 index 0000000000..91d46963f8 --- /dev/null +++ b/types/stripejs/shipping.d.ts @@ -0,0 +1,90 @@ +/** + * @see https://stripe.com/docs/stripe-js/reference#shipping-address-object + */ +export interface ShippingAddress { + /** + * Two-letter country code, capitalized + * NOTE: The codes are specified by the ISO3166 alpha-2 + */ + country: string; + + /** + * An array of address line items + * @example ['185 Berry St.', 'Suite 500', 'P.O. Box 12345'] + */ + addressLine: string[]; + + /** + * The most coarse subdivision of a country + * NOTE: Depending on the country, this might correspond to a state, a province, an oblast, a prefecture, + * or something else along these lines. + */ + region: string; + + /** + * The name of a city, town, village, etc + */ + city: string; + + /** + * The postal code or ZIP code + * NOTE: This is known as the PIN code in India + */ + postalCode: string; + + /** + * The name of the recipient. + * NOTE: This might be a person, a business name, or contain “care of” (c/o) instructions + */ + recipient: string; + + /** + * The phone number of the recipient + * NOTE: This is only filled if `requestPayerPhone` was set to `true` + * + * @see PaymentOptions.requestPayerPhone + */ + phone: string; + + /** + * The sorting code as used in, for example, France + * NOTE: Not present on Apple platforms + */ + sortingCode: string; + + /** + * A logical subdivision of a city + * NOTE: Not present on Apple platforms + */ + dependentLocality: string; +} + +// --- SHIPPING OPTION --- // +/** + * Settings for a shipping location + * @see https://stripe.com/docs/stripe-js/reference#shipping-option-object + */ +export interface ShippingOption { + /** + * A unique ID you create to keep track of this shipping option. + * NOTE: You‘ll be told the ID of the selected option on changes and on completion. + */ + id: string; + + /** + * A short “title” for this shipping option. + */ + label: string; + + /** + * A longer description of this shipping option. + */ + detail: string; + + /** + * The shipping costs for this option + * NOTE: If the cost of this shipping option depends on the shipping address the customer enters, + * listen for the `shippingaddresschange` event. + */ + amount: number; +} diff --git a/types/stripejs/source.d.ts b/types/stripejs/source.d.ts new file mode 100644 index 0000000000..2a24eb7d5b --- /dev/null +++ b/types/stripejs/source.d.ts @@ -0,0 +1,316 @@ +import { StripeError } from "./index"; +import { Customer } from "./customer"; +import { Token } from "./token"; + +/** + * @see https://stripe.com/docs/api#sources + */ +export interface Source { + /** + * Unique identifier for the object + */ + id: string; + + object: 'source'; + + /** + * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, + * or 1 for ¥1, Japanese Yen being a zero-decimal currency) representing the total + * amount associated with the source + */ + amount: number; + + /** + * The client secret of the source. + * Used for client-side retrieval using a publishable key. + */ + client_secret: string; + + /** + * Information related to the code verification flow + * Present if the source is authenticated by a verification code + */ + code_verification?: CodeVerification; + + /** + * Time at which the object was created. + * Measured in seconds since the Unix epoch. + * (Timestamp) + */ + created: number; + + /** + * Three-letter ISO code for the currency associated with the source + */ + currency: string; + + /** + * The authentication flow of the source + */ + flow: 'redirect' | 'receiver' | 'code_verification' | 'none'; + + /** + * LIVE MODE = true + * TEST MODE = false + */ + livemode: boolean; + + /** + * Your own saved information with this bank account + */ + metadata: { [key: string]: string }; + + /** + * Information about the owner of the payment instrument that may be used or + * required by particular source types. + */ + owner: Customer; + + /** + * Information related to the receiver flow. + * Present if the source is a receiver + */ + receiver?: Receiver; + + /** + * Information related to the redirect flow. + * Present if the source is authenticated by a redirect + */ + redirect?: Redirect; + + /** + * Extra information about a source + * NOTE: This will appear on your customer’s statement every time you charge the source + */ + statement_descriptor: string; + + /** + * The status of the source + * NOTE: Only `chargeable` sources can be used to create a charge + */ + status: 'pending' | 'canceled' | 'failed' | 'consumed' | 'chargeable'; + + /** + * The type of the source. + * NOTE: The type is a payment method + */ + type: paymentOptions; + + /** + * A matching name to the type with extra information about the payment method + * @see type + */ + [key: string]: any; + + /** + * Whether this source should be reusable or not + */ + usage: 'reusable' | 'reusable'; +} + +export type paymentOptions = + 'ach_credit_transfer' | + 'ach_debit' | + 'alipay' | + 'bancontact' | + 'card' | + 'card_present' | + 'eps' | + 'giropay' | + 'ideal' | + 'multibanco' | + 'p24' | + 'paper_check' | + 'sepa_credit_transfer' | + 'sepa_debit' | + 'sofort' | + 'three_d_secure'; + +// --- CODE VERIFICATION --- // +export interface CodeVerification { + /** + * The number of attempts remaining to authenticate the + * source object with a verification code + */ + attempts_remaining: number; + + /** + * The status of the code verification + */ + status: 'pending' | 'attempts_remaining' | 'succeeded' | 'failed' | 'attempts_remaining'; +} + +// --- REDIRECT INFORMATION --- // +export interface Redirect { + /** + * The failure reason for the redirect + * Present only if the redirect status is `'failed'` + */ + failure_reason?: 'user_abort' | 'declined' | 'processing_error'; + + /** + * The URL you provide to redirect the customer to after they authenticated their payment + */ + return_url: string; + + /** + * The status of the redirect + * - Pending: ready to be used by your customer to authenticate the transaction + * - succeeded: succesful authentication, cannot be reused + * - not_required: redirect should not be used + * - failed: failed authentication, cannot be reused + */ + status: 'pending' | 'succeeded' | 'not_required' | 'failed'; + + /** + * The URL provided to you to redirect a customer to as part of a redirect + * authentication flow + */ + url: string; +} + +// --- RECEIVER INFORMATION --- // +export interface Receiver { + /** + * The address of the receiver source + * NOTE: This is the value that should be communicated to the customer to send their funds to + */ + address: string; + + /** + * The total amount that was charged by you + * NOTE: The amount charged is expressed in the source’s currency + */ + amount_charged: number; + + /** + * The total amount received by the receiver source + */ + amount_received: number; + + /** + * The total amount that was returned to the customer + * NOTE: The amount charged is expressed in the source’s currency + */ + amount_returned: number; +} + +// --- DATA TO CREATE A SOURCE --- // +/** + * @see https://stripe.com/docs/api#create_source + */ +export interface SourceData { + /** + * The type of the source to create + */ + type: paymentOptions; + + /** + * This is the amount for which the source will be chargeable once ready + */ + amount: number; + + /** + * Three-letter ISO code for the currency associated with the source + */ + currency: string; + + /** + * The authentication flow of the source + */ + flow: 'redirect' | 'receiver' | 'code_verification' | 'none'; + + /** + * Whether this source should be reusable or not + */ + usage: 'reusable' | 'single_use'; + + /** + * Information about a mandate possiblity attached to a source object + * (generally for bank debits) as well as its acceptance status + */ + mandate?: Mandate; + + /** + * Extra data you want to add to the source object + */ + metadata?: { [key: string]: string }; + + /** + * Information about the owner of the payment instrument that may be used or + * required by particular source types. + */ + owner?: Customer; + + /** + * Can be set only if the source is a receiver + */ + receiver?: Receiver; + + /** + * Required if the source is authenticated by a redirect + */ + redirect?: Redirect; + + /** + * An arbitrary string to be displayed on your customer’s statement + * @example if your website is RunClub and the item you’re charging for is a race ticket, + * you may want to specify a statement_descriptor of RunClub 5K race ticket. + */ + statement_descriptor?: string; + + three_d_secure_2_eap?: any; + + /** + * When passed, token properties will override source parameters + */ + token?: Token; +} + +export interface Mandate { + acceptance?: Acceptance; + + /** + * The method Stripe should use to notify the customer + * - email: an email is sent directly to the customer + * - manual: a source.mandate_notification event is sent to your webhooks endpoint and you should handle the notification + * - none: the underlying debit network does not require any notification + */ + notification_method?: 'email' | 'manual' | 'none'; +} + +export interface Acceptance { + /** + * The unix timestamp the mandate was accepted or refused at by the customer. + */ + date: number; + + /** + * The unix timestamp the mandate was accepted or refused at by the customer. + */ + ip: string; + + /** + * The status of the mandate acceptance + */ + status: 'accepted' | 'refused'; + + /** + * The user agent of the browser from which the mandate was accepted or refused by the customer + * NOTE: This can be unset by updating the value to `null` and then saving + */ + user_agent: string; +} + +// --- RESPONSE FROM STRIPE WHEN CREATING OR FETCHING A SOURCE --- // +export interface SourceResult { + /** + * The identifier of the source to be retrieved + */ + source: Source; + + /** + * There was an error. This includes client-side validation errors. + */ + error?: StripeError; +} diff --git a/types/stripejs/stripejs-tests.ts b/types/stripejs/stripejs-tests.ts new file mode 100644 index 0000000000..06799c2df5 --- /dev/null +++ b/types/stripejs/stripejs-tests.ts @@ -0,0 +1,102 @@ +import { StripeJS } from "stripejs"; +import { StripeElement } from "stripejs/element"; +import { CanMakePaymentResult, StripePaymentResponse } from "stripejs/payment"; +import { BankTokenData, IBANTokenData, TokenData, TokenResult } from "stripejs/token"; +import { SourceData, SourceResult } from "stripejs/source"; + +declare function describe(desc: string, fn: () => void): void; + +declare function it(desc: string, fn: () => void): void; + +describe('StripeJS', () => { + const stripe: StripeJS = {} as any; + + it('Should be able to initialize', () => { + stripe('test'); + stripe('test', {stripeAccount: 'test123'}); + }); + + it('Should be possible to get information from stripe', () => { + stripe._apiKey; + stripe._keyMode; + }); + + it('Should be possible to create and modify elements', () => { + const creator = stripe.elements(); + stripe.elements({fonts: [], locale: 'nl'}); + stripe.elements({fonts: [], locale: 'nl', isIETFLocaleTag: true}); + + const element = creator.create("cardCvc", {value: {postalCode: '94110'}}); + element.blur(); + element.focus(); + element.clear(); + element.on('focus', () => null); + element.on('click', (event: { preventDefault: () => void }) => event.preventDefault()); + element.mount('#card-element'); + element.mount(new HTMLElement()); + element.unmount(); + element.update({value: {postalCode: '123'}}); + element.destroy(); + }); + + it('Should be possible to create a payment request', () => { + const data = {country: 'NL', currency: 'eur', total: {amount: 100, label: 'hello world'}}; + const request = stripe.paymentRequest(data); + request.canMakePayment().then((result: CanMakePaymentResult | null) => null); + request.on('token', ((event: StripePaymentResponse) => { + const token: any = event.token ? event.token : null; + event.complete("fail"); + const name: string = event.payerName ? event.payerName : ''; + })); + request.show(); + request.update(data); + }); + + it('Should be possible to create a token', () => { + const element: StripeElement = {} as any; + const data: TokenData = { + name: '', + currency: 'eur', + address_city: '', + address_country: 'NL', + address_line1: '', + address_line2: '', + address_state: '', + address_zip: '', + }; + stripe.createToken(element, data).then((result: TokenResult) => result.token); + + const iban: IBANTokenData = { + currency: 'eur', + account_holder_name: '', + account_holder_type: 'company', + }; + stripe.createToken(element, iban).then((result: TokenResult) => result.token); + + const bankData = { + country: 'NL', + account_number: '12345' + }; + const bank: BankTokenData = {...iban, ...bankData}; + stripe.createToken('bank_account', bank).then((result: TokenResult) => result.token); + + stripe.createToken('pii', {personal_id_number: ''}).then((result: TokenResult) => result.error); + }); + + it('Should be possible to create a source object', () => { + const element: StripeElement = {} as any; + const data: SourceData = { + type: 'alipay', + flow: 'none', + amount: 1000, + currency: 'eur', + usage: 'single_use' + }; + stripe.createSource(element, data).then((result: SourceResult) => result.source); + stripe.createSource(data).then((result: SourceResult) => result.error); + }); + + it('Should be possible to fetch a source object', () => { + stripe.retrieveSource({id: '', client_secret: ''}).then((result: SourceResult) => result.source); + }); +}); diff --git a/types/stripejs/token.d.ts b/types/stripejs/token.d.ts new file mode 100644 index 0000000000..e3a3a51590 --- /dev/null +++ b/types/stripejs/token.d.ts @@ -0,0 +1,138 @@ +import { StripeError } from "./index"; +import { BankAccount, Card } from "./customer"; + +/** + * @see https://stripe.com/docs/api#token_object + */ +export interface Token { + /** + * The unique identifier for the token + */ + id: string; + + object: 'token'; + + /** + * Hash describing the bank account + */ + bank_account?: BankAccount; + + /** + * Hash describing the card used to make the charge + */ + card?: Card; + + /** + * IP address of the client that generated the token + */ + client_ip: string; + + /** + * Time at which the object was created. Measured in seconds since the Unix epoch + */ + created: string; + + /** + * LIVE MODE = `true` + * TEST MODE = `false` + */ + livemode: boolean; + + /** + * Type of the token + */ + type: 'account' | 'bank_account' | 'card' | 'pii'; + + /** + * Whether this token has already been used (tokens can be used only once) + */ + used: boolean; +} + +// --- DATA TO CREATE A TOKEN --- // +export interface TokenData { + /** + * The Cardholder name + */ + name: string; + + /** + * Fields for billing address information. + */ + address_line1: string; + address_line2: string; + address_city: string; + address_state: string; + address_zip: string; + + /** + * A two character country code identifying the country + * @example 'US' + */ + address_country: string; + + /** + * Used to add a card to an account + * NOTE: Currently, the only supported currency for debit card payouts is 'usd' + */ + currency?: string; +} + +// --- RESPONSE FROM STRIPE WHEN CREATING OR FETCHING A TOKEN --- // +export interface TokenResult { + /** + * The generated string that can be used for communication with the backend + */ + token?: Token; + + /** + * There was an error. This includes client-side validation errors. + */ + error?: StripeError; +} + +// --- DATA TO CREATE A PERSONAL TOKEN --- // +export interface PiiTokenData { + /** + * The personal ID number + */ + personal_id_number: string; +} + +// --- DATA TO CREATE A TOKEN BASED ON BANK INFORMATION --- // +export interface IBANTokenData { + /** + * Three-letter ISO code for the currency paid out to the bank account + * @example 'usd' + */ + currency: string; + + /** + * The name of the person or business that owns the bank account. + */ + account_holder_name: string; + + /** + * The type of entity that holds the account. + */ + account_holder_type: 'individual' | 'company'; +} + +export interface BankTokenData extends IBANTokenData { + /** + * The 2-digit country ISO code + * @example 'US' + */ + country: string; + + /** + * The bank account number + */ + account_number: string; + + /** + * The routing transit number for the bank account + * NOTE: This is optional if the {@link BankTokenData.currency} is 'eur' + */ + routing_number?: string; +} diff --git a/types/stripejs/tsconfig.json b/types/stripejs/tsconfig.json new file mode 100644 index 0000000000..8e844fa910 --- /dev/null +++ b/types/stripejs/tsconfig.json @@ -0,0 +1,31 @@ +{ + "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", + "customer.d.ts", + "element.d.ts", + "payment.d.ts", + "shipping.d.ts", + "source.d.ts", + "token.d.ts", + "stripejs-tests.ts" + ] +} + diff --git a/types/stripejs/tslint.json b/types/stripejs/tslint.json new file mode 100644 index 0000000000..1c2b5f91d1 --- /dev/null +++ b/types/stripejs/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // IBAN is written with an 'I' for example + "interface-name": false + } +} diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 9654334af2..426d86f1a9 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for styled-components 3.0 // Project: https://github.com/styled-components/styled-components // Definitions by: Igor Oleinikov +// Ihor Chulinda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -104,19 +105,20 @@ export interface ThemedBaseStyledInterface component: React.ComponentType

, ): ThemedStyledFunction>; } -export type BaseStyledInterface = ThemedBaseStyledInterface; -export type ThemedStyledInterface = ThemedBaseStyledInterface; -export type StyledInterface = ThemedStyledInterface; +export type ThemedStyledInterface = ThemedBaseStyledInterface extends never ? any : T>; +export type StyledInterface = ThemedStyledInterface; +// tslint:disable-next-line:no-empty-interface +export interface DefaultTheme {} export interface ThemeProviderProps { theme?: T | ((theme: T) => T); } -export type ThemeProviderComponent = React.ComponentClass< +export type BaseThemeProviderComponent = React.ComponentClass< ThemeProviderProps ->; - -export interface ThemedCssFunction { + >; +export type ThemeProviderComponent = BaseThemeProviderComponent extends never ? any : T>; +export interface BaseThemedCssFunction { ( strings: TemplateStringsArray, ...interpolations: SimpleInterpolation[] @@ -126,6 +128,7 @@ export interface ThemedCssFunction { ...interpolations: Array>> ): Array>>; } +export type ThemedCssFunction = BaseThemedCssFunction extends never ? any : T>; // Helper type operators type KeyofBase = keyof any; @@ -150,20 +153,20 @@ export interface ThemedStyledComponentsModule { strings: TemplateStringsArray, ...interpolations: SimpleInterpolation[] ): void; - withTheme

( - component: React.ComponentType

, - ): React.ComponentClass>; + withTheme: WithThemeFnInterface; ThemeProvider: ThemeProviderComponent; } declare const styled: StyledInterface; -export const css: ThemedCssFunction; +export const css: ThemedCssFunction; -export function withTheme

( - component: React.ComponentType

, -): React.ComponentClass>; +export type BaseWithThemeFnInterface =

( + component: React.ComponentType

, + ) => React.ComponentClass>; +export type WithThemeFnInterface = BaseWithThemeFnInterface extends never ? any : T>; +export const withTheme: WithThemeFnInterface; export function keyframes( strings: TemplateStringsArray, diff --git a/types/styled-system/dist/styles.d.ts b/types/styled-system/dist/styles.d.ts index 7c666f9a9d..b2a2a7cc27 100644 --- a/types/styled-system/dist/styles.d.ts +++ b/types/styled-system/dist/styles.d.ts @@ -98,6 +98,13 @@ export interface FontWeightProps { export function fontWeight(...args: any[]): any; +export type FontStyleValue = string; +export type ResponsiveFontStyleValue = ResponsiveValue; +export interface FontStyleProps { + fontStyle?: ResponsiveFontStyleValue; +} +export function fontStyle(...args: any[]): any; + export type LetterSpacingValue = number | string; export type ResponsiveLetterSpacingValue = ResponsiveValue; export interface LetterSpacingProps { @@ -258,6 +265,14 @@ export interface AlignContentProps { export function alignContent(...args: any[]): any; +export type JustifyItemsValue = string; +export type ResponsiveJustifyItemsValue = ResponsiveValue; + +export interface JustifyItemsProps { + justifyItems?: ResponsiveJustifyItemsValue; +} +export function alignContent(...args: any[]): any; + export type JustifyContentValue = | "center" | "start" @@ -477,6 +492,18 @@ export interface GridTemplatesRowsProps { export function gridTemplateRows(...args: any[]): any; +export interface GridTemplatesAreasProps { + gridTemplateAreas?: ResponsiveGridTemplateValue; +} + +export function gridTemplateAreas(...args: any[]): any; + +export interface GridAreaProps { + gridArea?: ResponsiveGridTemplateValue; +} + +export function gridArea(...args: any[]): any; + /** * Borders */ @@ -554,6 +581,14 @@ export interface OpacityProps { export function opacity(...arg: any[]): any; +export type OverflowValue = string | number; +export type ResponsiveOverflowValue = ResponsiveValue; + +export interface OverflowProps { + overflow?: ResponsiveOverflowValue; +} + +export function overflow(...arg: any[]): any; /** * Background */ diff --git a/types/supertest/index.d.ts b/types/supertest/index.d.ts index 092ab89bb4..77418352f9 100644 --- a/types/supertest/index.d.ts +++ b/types/supertest/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for SuperTest v2.0.1 // Project: https://github.com/visionmedia/supertest // Definitions by: Alex Varju +// Petteri Parkkila // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -23,12 +24,12 @@ declare namespace supertest { serverAddress(app: any, path: string): string; expect(status: number, callback?: CallbackHandler): this; expect(status: number, body: any, callback?: CallbackHandler): this; + expect(checker: (res: Response) => any): this; expect(body: string, callback?: CallbackHandler): this; expect(body: RegExp, callback?: CallbackHandler): this; expect(body: Object, callback?: CallbackHandler): this; expect(field: string, val: string, callback?: CallbackHandler): this; expect(field: string, val: RegExp, callback?: CallbackHandler): this; - expect(checker: (res: Response) => any): this; end(callback?: CallbackHandler): this; } diff --git a/types/supertest/supertest-tests.ts b/types/supertest/supertest-tests.ts index 24bbd4bd56..641b2bbabf 100644 --- a/types/supertest/supertest-tests.ts +++ b/types/supertest/supertest-tests.ts @@ -59,6 +59,17 @@ function hasPreviousAndNextKeys(res: supertest.Response) { if (!('prev' in res.body)) throw new Error("missing prev key"); } +// functional expect without response type +(request + .get('/') as supertest.Test) + .expect(res => { + if (!('next' in res.body)) return "missing next key"; + if (!('prev' in res.body)) throw new Error("missing prev key"); + }) + .end((err: any, res: supertest.Response) => { + if (err) throw err; + }); + // object expect (request .get('/') as supertest.Test) diff --git a/types/swiper/index.d.ts b/types/swiper/index.d.ts index 19c381fe28..42cf9eda51 100644 --- a/types/swiper/index.d.ts +++ b/types/swiper/index.d.ts @@ -1,461 +1,1621 @@ // Type definitions for Swiper 4.2 // Project: https://github.com/nolimits4web/Swiper -// Definitions by: Sebastián Galiano , Luca Trazzi , Eugene Matseruk +// Definitions by: Sebastián Galiano , Luca Trazzi , Eugene Matseruk , Luiz M. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.7 - -type CommonEvent = - | 'init' - | 'beforeDestroy' - | 'slideChange' - | 'slideChangeTransitionStart' - | 'slideChangeTransitionEnd' - | 'slideNextTransitionStart' - | 'slideNextTransitionEnd' - | 'slidePrevTransitionStart' - | 'slidePrevTransitionEnd' - | 'transitionStart' - | 'transitionEnd' - | 'touchStart' - | 'touchMove' - | 'touchMoveOpposite' - | 'sliderMove' - | 'touchEnd' - | 'click' - | 'tap' - | 'doubleTap' - | 'imagesReady' - | 'progress' - | 'reachBeginning' - | 'reachEnd' - | 'fromEdge' - | 'setTranslate' - | 'setTransition' - | 'resize'; - -type PaginationEvent = 'paginationRender' | 'paginationUpdate'; -type AutoplayEvent = 'autoplayStart' | 'autoplayStop' | 'autoplay'; -type LazyLoadingEvent = 'lazyImageLoad' | 'lazyImageReady'; - -type SwiperEvent = CommonEvent | PaginationEvent | AutoplayEvent | LazyLoadingEvent; - -interface NavigationOptions { - nextEl?: string | HTMLElement; - prevEl?: string | HTMLElement; - hideOnClick?: boolean; - disabledClass?: string; - hiddenClass?: string; -} - -interface PaginationOptions { - el?: string; - type?: 'bullets' | 'fraction' | 'progressbar' | 'custom'; - bulletElement?: string; - dynamicBullets?: boolean; - dynamicMainBullets?: number; - hideOnClick?: boolean; - clickable?: boolean; - progressbarOpposite?: boolean; - - bulletClass?: string; - bulletActiveClass?: string; - modifierClass?: string; - currentClass?: string; - totalClass?: string; - hiddenClass?: string; - progressbarFillClass?: string; - clickableClass?: string; - - renderBullet?: (index: number, className: string) => void; - renderFraction?: (currentClass: string, totalClass: string) => void; - renderProgressbar?: (progressbarFillClass: string) => void; - renderCustom?: (swiper: Swiper, current: number, total: number) => void; -} - -interface ScrollbarOptions { - el?: string | HTMLElement; - hide?: boolean; - draggable?: boolean; - snapOnRelease?: boolean; - dragSize?: 'auto' | number; - lockClass?: 'string'; - dragClass?: 'string'; -} - -interface AutoplayOptions { - delay?: number; - stopOnLastSlide?: boolean; - disableOnInteraction?: boolean; - reverseDirection?: boolean; - waitForTransition?: boolean; -} - -interface LazyLoadingOptions { - loadPrevNext?: string; - loadPrevNextAmount?: number; - loadOnTransitionStart?: boolean; - elementClass?: string; - loadingClass?: string; - loadedClass?: string; - preloaderClass?: string; -} - -interface FadeEffectOptions { - crossFade: boolean; -} - -interface CoverflowEffectOptions { - slideShadows?: boolean; - rotate?: number; - stretch?: number; - depth?: number; - modifier?: number; -} - -interface FlipEffectOptions { - slideShadows?: boolean; - limitRotation?: boolean; -} - -interface CubeEffectOptions { - slideShadows?: boolean; - shadow?: boolean; - shadowOffset: number; - shadowScale: number; -} - -interface ZoomOptions { - maxRatio?: number; - minRatio?: number; - toggle?: boolean; - containerClass?: string; - zoomedSlideClass?: string; -} - -interface KeyboardControlOptions { - enabled?: boolean; - onlyInViewport?: boolean; -} - -interface MouseWheelControlOptions { - forceToAxis?: boolean; - releaseOnEdges?: boolean; - invert?: boolean; - sensitivity?: number; - eventsTarged?: string | HTMLElement; -} - -interface VirtualSlidesRenderExternalData { - offset: number; - from: number; - to: number; - slides: any[]; -} - -interface VirtualSlidesOptions { - slides?: any[]; - cache?: boolean; - renderSlide?: (slide: any, index: number) => void; - renderExternal?: (data: VirtualSlidesRenderExternalData) => void; -} - -interface HashNavigationOptions { - watchState?: boolean; - replaceState?: boolean; -} - -interface HistoryNavigationOptions { - replaceState?: boolean; - key?: string; -} - -interface ControllerOptions { - control: Swiper; - inverse: boolean; - by: 'slide' | 'container'; -} - -interface AccessibilityOptions { - enabled?: boolean; - prevSlideMessage?: string; - nextSlideMessage?: string; - firstSlideMessage?: string; - lastSlideMessage?: string; - paginationBulletMessage?: string; - notificationClass?: string; -} - -interface SwiperOptions { - // General parameters - init?: boolean; - initialSlide?: number; - direction?: 'horizontal' | 'vertical'; - speed?: number; - setWrapperSize?: boolean; - virtualTranslate?: boolean; - width?: number; - height?: number; - autoHeight?: boolean; - roundLengths?: boolean; - nested?: boolean; - uniqueNavElements?: boolean; - effect?: 'slide' | 'fade' | 'cube' | 'coverflow' | 'flip'; - runCallbacksOnInit?: boolean; - watchOverflow?: boolean; - on?: {[key in SwiperEvent]?: () => void }; - - // Slides grid - spaceBetween?: number; - slidesPerView?: 'auto' | number; - slidesPerColumn?: number; - slidesPerColumnFill?: 'row' | 'column'; - slidesPerGroup?: number; - centeredSlides?: boolean; - slidesOffsetBefore?: number; - slidesOffsetAfter?: number; - normalizeSlideIndex?: boolean; - - // Grab cursor - grabCursor?: boolean; - - // Touches - touchEventsTarget?: 'container' | 'wrapper'; - touchRatio?: number; - touchAngle?: number; - simulateTouch?: boolean; - shortSwipes?: boolean; - longSwipes?: boolean; - longSwipesRatio?: number; - longSwipesMs?: number; - followFinger?: boolean; - allowTouchMove?: boolean; - threshold?: number; - touchMoveStopPropagation?: boolean; - iOSEdgeSwipeDetection?: boolean; - iOSEdgeSwipeThreshold?: number; - touchReleaseOnEdges?: boolean; - passiveListeners?: boolean; - - // Touch Resistance - resistance?: boolean; - resistanceRatio?: number; - - // Swiping / No swiping - preventIntercationOnTransition?: boolean; - allowSlidePrev?: boolean; - allowSlideNext?: boolean; - noSwiping?: boolean; - noSwipingClass?: string; - noSwipingSelector?: string; - swipeHandler?: string | HTMLElement; - - // Clicks - preventClicks?: boolean; - preventClicksPropagation?: boolean; - slideToClickedSlide?: boolean; - - // Freemode - freeMode?: boolean; - freeModeMomentum?: boolean; - freeModeMomentumRatio?: number; - freeModeMomentumVelocityRatio?: number; - freeModeMomentumBounce?: boolean; - freeModeMomentumBounceRatio?: number; - freeModeMinimumVelocity?: number; - freeModeSticky?: boolean; - - // Progress - watchSlidesProgress?: boolean; - watchSlidesVisibility?: boolean; - - // Images - preloadImages?: boolean; - updateOnImagesReady?: boolean; - // Loop - loop?: boolean; - loopAdditionalSlides?: number; - loopedSlides?: number; - loopFillGroupWithBlank?: boolean; - - // Breakpoints - breakpoints?: { - // TODO: extract possible parameters for breakpoints to separate interface - [index: number]: any; - }; - - // Observer - observer?: boolean; - observeParents?: boolean; - - // Namespace - containerModifierClass?: string; - slideClass?: string; - slideActiveClass?: string; - slideDuplicatedActiveClass?: string; - slideVisibleClass?: string; - slideDuplicateClass?: string; - slideNextClass?: string; - slideDuplicatedNextClass?: string; - slidePrevClass?: string; - slideDuplicatedPrevClass?: string; - wrapperClass?: string; - - // Components - navigation?: NavigationOptions; - pagination?: PaginationOptions; - scrollbar?: ScrollbarOptions; - autoplay?: AutoplayOptions; - parallax?: boolean; - lazy?: LazyLoadingOptions | boolean; - fadeEffect?: FadeEffectOptions; - coverflowEffect?: CoverflowEffectOptions; - flipEffect?: FlipEffectOptions; - cubeEffect?: CubeEffectOptions; - zoom?: ZoomOptions | boolean; - keyboard?: KeyboardControlOptions | boolean; - mousewheel?: MouseWheelControlOptions | boolean; - virtual?: VirtualSlidesOptions; - hashNavigation?: HashNavigationOptions; - history?: HistoryNavigationOptions; - controller?: ControllerOptions; - a11y?: AccessibilityOptions; -} - -interface Navigation { - nextEl: HTMLElement; - prevEl: HTMLElement; - update: () => void; -} -interface Pagination { - el: HTMLElement; - // TODO: dom7 like array - bullets: any[]; - - render: () => void; - update: () => void; -} - -interface Scrollbar { - eL: HTMLElement; - dragEl: HTMLElement; - - updateSize: () => void; -} - -interface Autoplay { - running: boolean; - - start: () => void; - stop: () => void; -} - -interface LazyLoading { - load: () => void; - loadInSlide: (index: number) => void; -} - -interface Zoom { - enabled: boolean; - scale: number; - - enable: () => void; - disable: () => void; - in: () => void; - out: () => void; - toggle: () => void; -} - -// Keyboard and Mousewheel control -interface Control { - enabled: boolean; - - enable: () => void; - disable: () => void; -} - -interface VirtualSlides { - cache: any; - from: number; - to: number; - slides: any[]; - - appendSlide: (slide: any) => void; - prependSlide: (slide: any) => void; - update: () => void; -} - -interface Controller { - control: Swiper; -} - -declare class Swiper { - constructor(container: string | Element, parameters?: SwiperOptions); - - // Properties - params: SwiperOptions; - // TODO: dom7 element - $el: any; - // TODO: dom7 element - $wrapperEl: any; - slides: HTMLElement[]; - width: number; - height: number; - translate: number; - progress: number; - activeIndex: number; - realIndex: number; - previousIndex: number; - isBeginning: boolean; - isEnd: boolean; - animating: boolean; - touches: { - startX: number; - startY: number; - currentX: number; - currentY: number; - diff: number; - }; - clickedIndex: number; - clickedSlide: HTMLElement; - allowSlideNext: boolean; - allowSlidePrev: boolean; - allowTouchMove: boolean; - - slideNext: (speed?: number, runCallbacks?: boolean) => void; - slidePrev: (speed?: number, runCallbacks?: boolean) => void; - slideTo: (index: number, speed?: number, runCallbacks?: boolean) => void; - slideToLoop: (index: number, speed?: number, runCallbacks?: boolean) => void; - slideReset: (speed?: number, runCallbacks?: boolean) => void; - slideToClosest: (speed?: number, runCallbacks?: boolean) => void; - updateAutoHeight: (speed?: number) => void; - update: () => void; - detachEvents: () => void; - attachEvents: () => void; - destroy: (deleteInstance?: boolean, cleanStyles?: boolean) => void; - appendSlide: (slides: Array<(HTMLElement | string)> | string | HTMLElement) => void; - prependSlide: (slides: Array<(HTMLElement | string)> | string | HTMLElement) => void; - removeSlide: (index: number) => void; - removeAllSlides: () => void; - setTranslate: (translate: number) => void; - getTranslate: () => void; - on: (event: SwiperEvent, handler: () => void) => void; - once: (event: SwiperEvent, handler: () => void) => void; - off: (event: SwiperEvent, handler?: () => void) => void; - unsetGrabCursor: () => void; - setGrabCursor: () => void; - - // components - navigation: Navigation; - pagination: Pagination; - scrollbar: Scrollbar; - autoplay: Autoplay; - zoom: Zoom; - keyboard: Control; - mousewheel: Control; - virtual: VirtualSlides; - controller: Controller; -} +// TypeScript Version: 2.9 declare module 'swiper' { - export = Swiper; + /** + * Common Swiper events. + */ + type CommonEvent = + | 'init' + | 'beforeDestroy' + | 'slideChange' + | 'slideChangeTransitionStart' + | 'slideChangeTransitionEnd' + | 'slideNextTransitionStart' + | 'slideNextTransitionEnd' + | 'slidePrevTransitionStart' + | 'slidePrevTransitionEnd' + | 'transitionStart' + | 'transitionEnd' + | 'touchStart' + | 'touchMove' + | 'touchMoveOpposite' + | 'sliderMove' + | 'touchEnd' + | 'click' + | 'tap' + | 'doubleTap' + | 'imagesReady' + | 'progress' + | 'reachBeginning' + | 'reachEnd' + | 'fromEdge' + | 'setTranslate' + | 'setTransition' + | 'resize'; + + /** + * Swiper pagination event names. + */ + type PaginationEvent = 'paginationRender' | 'paginationUpdate'; + + /** + * Swiper autoplay event names. + */ + type AutoplayEvent = 'autoplayStart' | 'autoplayStop' | 'autoplay'; + + /** + * Swiper lazy-loading event names. + */ + type LazyLoadingEvent = 'lazyImageLoad' | 'lazyImageReady'; + + /** + * Swiper event names. + */ + type SwiperEvent = CommonEvent | PaginationEvent | AutoplayEvent | LazyLoadingEvent; + + /** + * Swiper module types. + */ + type SwiperModule = + | Navigation + | Pagination + | Scrollbar + | Autoplay + | Parallax + | Lazy + | FadeEffect + | CoverflowEffect + | FlipEffect + | CubeEffect + | Zoom + | Keyboard + | Mousewheel + | Virtual + | HashNavigation + | History + | Controller + | A11y; + + type DOM7Element = any; + type SelectableElement = string | HTMLElement; + + /* + * Swiper options and events. + */ + + /** + * Main constructor options. + */ + interface SwiperOptions { + /** + * Whether Swiper should be initialised automatically when you create an instance. + * If disabled, then you need to init it manually by calling mySwiper.init() + * + * @default true + */ + init?: boolean; + + /** + * Index number of initial slide. + * + * @default 0 + */ + initialSlide?: number; + + /** + * Could be 'horizontal' or 'vertical' (for vertical slider). + * + * @default 'horizontal' + */ + direction?: 'horizontal' | 'vertical'; + + /** + * Duration of transition between slides (in ms) + * + * @default 300 + */ + speed?: number; + + /** + * Enabled this option and plugin will set width/height on swiper wrapper equal to total size of all slides. + * Mostly should be used as compatibility fallback option for browser that don't support flexbox layout well + */ + setWrapperSize?: boolean; + + /** + * Enabled this option and swiper will be operated as usual except it will not move, real translate values on wrapper will not be set. + * Useful when you may need to create custom slide transition + */ + virtualTranslate?: boolean; + + /** + * Swiper width (in px). Parameter allows to force Swiper width. + * Useful only if you initialize Swiper when it is hidden. + * + * @note Setting this parameter will make Swiper not responsive + */ + width?: number; + + /** + * Swiper height (in px). Parameter allows to force Swiper height. + * Useful only if you initialize Swiper when it is hidden. + * + * @note Setting this parameter will make Swiper not responsive + */ + height?: number; + + /** + * Set to true and slider wrapper will adopt its height to the height of the currently active slide + * + * @default false + */ + autoHeight?: boolean; + + /** + * Set to true to round values of slides width and height to prevent blurry texts on usual + * resolution screens (if you have such) + * + * @default false + */ + roundLengths?: boolean; + + /** + * Set to true on Swiper for correct touch events interception. Use only on + * swipers that use same direction as the parent one + * + * @default false + */ + nested?: boolean; + + /** + * If enabled (by default) and navigation elements' parameters passed as a string (like ".pagination") + * then Swiper will look for such elements through child elements first. + * Applies for pagination, prev/next buttons and scrollbar elements + * + * @default true + */ + uniqueNavElements?: boolean; + + /** + * Tranisition effect. Could be "slide", "fade", "cube", "coverflow" or "flip" + * + * @default 'slide' + */ + effect?: 'slide' | 'fade' | 'cube' | 'coverflow' | 'flip'; + + /** + * Fire [Transition/SlideChange][Start/End] events on swiper initialization. + * Such events will be fired on initialization in case of your initialSlide is not 0, or you use loop mode + * + * @default true + */ + runCallbacksOnInit?: boolean; + + /** + * When enabled Swiper will be disabled and hide navigation buttons on + * case there are not enough slides for sliding. + * + * @default false + */ + watchOverflow?: boolean; + + /** + * Register event handlers. + */ + on?: { [key in SwiperEvent]?: () => void }; + + // Slides grid + spaceBetween?: number; + slidesPerView?: number | 'auto'; + slidesPerColumn?: number; + slidesPerColumnFill?: 'row' | 'column'; + slidesPerGroup?: number; + centeredSlides?: boolean; + slidesOffsetBefore?: number; + slidesOffsetAfter?: number; + normalizeSlideIndex?: boolean; + + // Grab Cursor + grabCursor?: boolean; + + // Touches + // @TODO: verify next property + touchEventsTarget?: 'container' | 'wrapper'; + touchRatio?: number; + touchAngle?: number; + simulateTouch?: boolean; + shortSwipes?: boolean; + longSwipes?: boolean; + longSwipesRatio?: number; + longSwipesMs?: number; + followFinger?: boolean; + allowTouchMove?: boolean; + threshold?: number; + touchMoveStopPropagation?: boolean; + iOSEdgeSwipeDetection?: boolean; + iOSEdgeSwipeThreshold?: number; + touchReleaseOnEdges?: boolean; + passiveListeners?: boolean; + + // Touch Resistance + resistance?: boolean; + resistanceRatio?: number; + + // Swiping / No swiping + allowSlidePrev?: boolean; + allowSlideNext?: boolean; + noSwiping?: boolean; + noSwipingClass?: string; + // noSwipingSelector?: string; + swipeHandler?: SelectableElement; + + // Clicks + preventClicks?: boolean; + preventClicksPropagation?: boolean; + slideToClickedSlide?: boolean; + + // Freemode + freeMode?: boolean; + freeModeMomentum?: boolean; + freeModeMomentumRatio?: number; + freeModeMomentumVelocityRatio?: number; + freeModeMomentumBounce?: boolean; + freeModeMomentumBounceRatio?: number; + freeModeMinimumVelocity?: number; + freeModeSticky?: boolean; + + // Progress + watchSlidesProgress?: boolean; + watchSlidesVisibility?: boolean; + + // Images + preloadImages?: boolean; + updateOnImagesReady?: boolean; + + // Loop + loop?: boolean; + loopAdditionalSlides?: number; + loopedSlides?: number; + loopFillGroupWithBlank?: boolean; + + // Breakpoints + breakpoints?: { + [index: number]: SwiperOptions; + }; + + // Observer + observer?: boolean; + observeParents?: boolean; + + // Namespace + containerModifierClass?: string; + slideClass?: string; + slideActiveClass?: string; + slideDuplicatedActiveClass?: string; + slideVisibleClass?: string; + slideDuplicateClass?: string; + slideNextClass?: string; + slideDuplicatedNextClass?: string; + slidePrevClass?: string; + slideDuplicatedPrevClass?: string; + wrapperClass?: string; + + // Components + navigation?: NavigationOptions; + pagination?: PaginationOptions; + scrollbar?: ScrollbarOptions; + autoplay?: AutoplayOptions | boolean; + parallax?: boolean; + lazy?: LazyOptions | boolean; + fadeEffect?: FadeEffectOptions; + coverflowEffect?: CoverflowEffectOptions; + flipEffect?: FlipEffectOptions; + cubeEffect?: CubeEffectOptions; + zoom?: ZoomOptions | boolean; + keyboard?: KeyboardOptions | boolean; + mousewheel?: MousewheelOptions | boolean; + virtual?: VirtualOptions | boolean; + hashNavigation?: HashNavigationOptions | boolean; + history?: HistoryNavigationOptions | boolean; + a11y?: A11yOptions | boolean; + } + + interface EventsOptions { + /** + * Fired right after Swiper initialization. + * Note that with swiper.on('init') syntax it will + * work only in case you set init: false parameter. + * + * @example + * var swiper = new Swiper('.swiper-container', { + * init: false, + * // other parameters + * }); + * + * @example + * swiper.on('init', function() { + * // do something + * }); + * + * @example + * // init Swiper + * swiper.init(); + * + * @example + * // Otherwise use it as the parameter: + * var swiper = new Swiper('.swiper-container', { + * // other parameters + * on: { + * init: function () { + * // do something + * }, + * } + * }); + */ + init?: () => any; + + /** + * Triggered right beforey Swiper destoryed + */ + beforeDestroy?: () => any; + + /** + * Triggered when currently active slide is changed + */ + slideChange?: () => any; + + /** + * Triggered in the beginning of animation to other slide (next or previous). + */ + slideChangeTransitionStart?: () => any; + + /** + * Triggered after animation to other slide (next or previous). + */ + slideChangeTransitionEnd?: () => any; + + /** + * Same as "slideChangeTransitionStart" but for "forward" direction only + */ + slideNextTransitionStart?: () => any; + + /** + * Same as "slideChangeTransitionEnd" but for "forward" direction only + */ + slideNextTransitionEnd?: () => any; + + /** + * Same as "slideChangeTransitionStart" but for "backward" direction only + */ + slidePrevTransitionStart?: () => any; + + /** + * Same as "slideChangeTransitionEnd" but for "backward" direction only + */ + slidePrevTransitionEnd?: () => any; + + /** + * Triggered in the beginning of transition. + */ + transitionStart?: () => any; + + /** + * Triggered after transition. + */ + transitionEnd?: () => any; + + /** + * Triggered when user touch Swiper. Receives 'touchstart' event as an arguments. + */ + touchStart?: (event: any) => any; + + /** + * Triggered when user touch and move finger over Swiper. Receives 'touchmove' event as an arguments. + */ + touchMove?: (event: any) => any; + + /** + * Fired when user touch and move finger over + * Swiper in direction opposite to direction parameter. + * Receives 'touchmove' event as an arguments. + */ + touchMoveOpposite?: (event: any) => any; + + /** + * Triggered when user touch and move finger over Swiper and move it. + * Receives 'touchmove' event as an arguments. + */ + sliderMove?: (event: any) => any; + + /** + * Triggered when user release Swiper. Receives 'touchend' event as an arguments. + */ + touchEnd?: (event: any) => any; + + /** + * Triggered when user click/tap on Swiper after 300ms delay. Receives 'touchend' event as an arguments. + */ + click?: (event: any) => any; + + /** + * Triggered when user click/tap on Swiper. Receives 'touchend' event as an arguments. + */ + tap?: (event: any) => any; + + /** + * Triggered when user double tap on Swiper's container. Receives 'touchend' event as an arguments + */ + doubleTap?: (event: any) => any; + + /** + * Triggered right after all inner images are loaded. updateOnImagesReady should be also enabled + */ + imagesReady?: () => any; + + /** + * Triggered when Swiper progress is changed, as an arguments it receives + * progress that is always from 0 to 1 + */ + progress?: (progress: any) => any; + + /** + * Triggered when Swiper reach its beginning (initial position) + */ + reachBeginning?: () => any; + + /** + * Triggered when Swiper reach last slide + */ + reachEnd?: () => any; + + /** + * Triggered when Swiper goes from beginning or end position + */ + fromEdge?: () => any; + + /** + * Triggered when swiper's wrapper change its position. Receives current translate value as an arguments + */ + setTranslate?: (translate: any) => any; + + /** + * Triggered everytime when swiper starts animation. + * Receives current transition duration (in ms) as an arguments, + */ + setTransition?: (transition: any) => any; + + /** + * Triggered on window resize right before swiper's onresize manipulation + */ + resize?: () => any; + } + + interface NavigationOptions { + /** + * String with CSS selector or HTML element of the element that will work + * like "next" button after click on it + * + * @default null + */ + nextEl?: SelectableElement; + + /** + * String with CSS selector or HTML element of the element that will work + * like "prev" button after click on it + * + * @default null + */ + prevEl?: SelectableElement; + + /** + * buttons visibility after click on Slider's container + * + * @default false Toggle navigation + */ + hideOnClick?: boolean; + + /** + * CSS class name added to navigation button when it becomes disabled + * + * @default 'swiper-button-disabled' + */ + disabledClass?: string; + + /** + * CSS class name added to navigation button when it becomes hidden + * + * @default 'swiper-button-hidden' + */ + hiddenClass?: string; + } + + interface PaginationOptions { + el: SelectableElement; + + type?: 'bullets' | 'fraction' | 'progressbar' | 'custom'; + + bulletElement?: string; + + dynamicBullets?: boolean; + + hideOnClick?: boolean; + + clickable?: boolean; + + /** + * format fraction pagination current number. Function receives current number, + * and you need to return formatted value + */ + formatFractionCurrent?: (number: number) => number; + + /** + * format fraction pagination total number. Function receives total number, and you + * need to return formatted value + */ + formatFractionTotal?: (number: number) => number; + + renderBullet?: (index: number, className: string) => void; + + renderFraction?: (currentClass: string, totalClass: string) => void; + + renderProgressbar?: (progressbarFillClass: string) => void; + + /** + * This parameter is required for custom pagination type where you have to specify + * how it should be rendered. + * + * @example + * var swiper = new Swiper('.swiper-container', { + * //... + * renderCustom: function (swiper, current, total) { + * return current + ' of ' + total; + * } + * }); + */ + renderCustom?: (swiper: Swiper, current: number, total: number) => void; + + bulletClass?: string; + bulletActiveClass?: string; + modifierClass?: string; + currentClass?: string; + totalClass?: string; + hiddenClass?: string; + progressbarFillClass?: string; + clickableClass?: string; + } + + /** + * Object with scrollbar parameters. + * + * @example + * var mySwiper = new Swiper('.swiper-container', { + * scrollbar: { + * el: '.swiper-scrollbar', + * draggable: true, + * }, + * }); + */ + interface ScrollbarOptions { + /** + * String with CSS selector or HTML element of the container with scrollbar. + */ + el: SelectableElement; + + /** + * Hide scrollbar automatically after user interaction + * + * @default true + */ + hide?: boolean; + + /** + * Set to true to enable make scrollbar draggable that allows you to control slider position + * + * @default true + */ + draggable?: boolean; + + /** + * Set to true to snap slider position to slides when you release scrollbar + * + * @default false + */ + snapOnRelease?: boolean; + + /** + * Size of scrollbar draggable element in px + * + * @default 'auto' + */ + dragSize?: 'auto' | number; + + /** + * Scrollbar element additional CSS class when it is disabled + * + * @default 'swiper-scrollbar-lock' + */ + lockClass?: string; + + /** + * Scrollbar draggable element CSS class + * + * @default 'swiper-scrollbar-drag' + */ + dragClass?: string; + } + + /** + * Object with autoplay parameters or boolean true to enable with default settings. + * + * @example + * var mySwiper = new Swiper('.swiper-container', { + * autoplay: { + * delay: 5000, + * }, + * }); + */ + interface AutoplayOptions { + /** + * Delay between transitions (in ms). If this parameter is not specified, auto play will be disabled + * + * If you need to specify different delay for specifi slides you can do it by using + * data-swiper-autoplay (in ms) attribute on slide. + * + * @example + * + *

+ * + * @default 3000 + */ + delay?: number; + + /** + * Enable this parameter and autoplay will be stopped when it reaches last slide (has no effect in loop mode) + * + * @default false + */ + stopOnLastSlide?: boolean; + + /** + * Set to false and autoplay will not be disabled after + * user interactions (swipes), it will be restarted + * every time after interaction + * + * @default true + */ + disableOnInteraction?: boolean; + + /** + * Enables autoplay in reverse direction + * + * @default false + */ + reverseDirection?: boolean; + + /** + * When enabled autoplay will wait for wrapper transition to continue. + * Can be disabled in case of using Virtual Translate when your + * slider may not have transition + * + * @default true + */ + waitForTransition?: boolean; + } + + interface LazyOptions { + loadPrevNext?: boolean; + loadPrevNextAmount?: number; + loadOnTransitionStart?: boolean; + elementClass?: string; + loadingClass?: string; + loadedClass?: string; + preloaderClass?: string; + } + + /* + * Options - Effect + */ + + interface FadeEffectOptions { + crossfade?: boolean; + } + + interface CoverflowEffectOptions { + slideShadows?: boolean; + rotate?: number; + stretch?: number; + depth?: number; + modifier?: number; + } + + interface FlipEffectOptions { + slideShadows?: boolean; + limitRotation?: boolean; + } + + interface CubeEffectOptions { + slideShadows?: boolean; + shadow?: boolean; + shadowOffset?: number; + shadowScale?: number; + } + + interface ZoomOptions { + maxRatio?: number; + minRatio?: number; + toggle?: boolean; + containerClass?: string; + zoomedSlideClass?: string; + } + + interface KeyboardOptions { + enabled?: boolean; + onlyInViewport?: boolean; + } + + interface MousewheelOptions { + forceToAxis?: boolean; + releaseOnEdges?: boolean; + invert?: boolean; + sensitivity?: number; + eventsTarged?: SelectableElement; + } + + interface VirtualOptions { + slides?: any[]; + cache?: boolean; + renderSlide?: (slide: any, index: any) => any; + renderExternal?: (data: any) => any; + } + + interface HashNavigationOptions { + /** + * Set to true to enable also navigation through slides (when hashnav + * is enabled) by browser history or by setting directly hash on document location + * + * @default false + */ + watchState?: boolean; + + /** + * Works in addition to hashnav to replace current url state with the + * new one instead of adding it to history + * + * @default false + */ + replaceState?: boolean; + } + + interface HistoryNavigationOptions { + /** + * Works in addition to hashnav or history to replace current url state with the + * new one instead of adding it to history + * + * @default false + */ + replaceState?: boolean; + + /** + * Url key for slides + * + * @default 'slides' + */ + key?: string; + } + + /** + * Object with controller parameters or boolean true to enable with default settings. For example: + * + * @example + * var mySwiper = new Swiper('.swiper-container', { + * controller: { + * inverse: true, + * }, + * }); + */ + interface ControllerOptions { + /** + * Pass here another Swiper instance or array with Swiper instances that should be controlled + * by this Swiper + */ + control?: Swiper; + + /** + * Set to true and controlling will be in inverse direction + * + * @default false + */ + inverse?: boolean; + + /** + * Can be 'slide' or 'container'. Defines a way how to control another slider: slide by slide + * (with respect to other slider's grid) or depending on all slides/container + * (depending on total slider percentage). + * + * @default 'slide' + */ + by?: 'slide' | 'container'; + } + + interface A11yOptions { + /** + * Enables A11y + * + * @default true + */ + enabled?: boolean; + + /** + * Message for screen readers for previous button + * + * @default 'Previous slide' + */ + prevSlideMessage?: string; + + /** + * Message for screen readers for next button + * + * @default 'Next slide' + */ + nextSlideMessage?: string; + + /** + * Message for screen readers for previous button when swiper is on first slide + * + * @default 'This is the first slide' + */ + firstSlideMessage?: string; + + /** + * Message for screen readers for previous button when swiper is on last slide + * + * @default 'This is the last slide' + */ + lastSlideMessage?: string; + + /** + * Message for screen readers for single pagination bullet + * + * @default 'Go to slide {{index}}' + */ + paginationBulletMessage?: string; + + /** + * CSS class name of a11 notification + * + * @default 'swiper-notification' + */ + notificationClass?: string; + } + + /* + * Swiper exports the following as ES5 module (in swiper.esm.js). + */ + + /** + * Virtual Slides module. + */ + class Virtual { + /** + * Object with cached slides HTML elements + */ + cache: object; + + /** + * Index of first rendered slide + */ + from: number; + + /** + * Index of last rendered slide + */ + to: number; + + /** + * Array with slide items passed by virtual.slides parameter + */ + slides: any[]; + + /* + * Methods + */ + + /** + * Add new slides to the end. slides could be HTMLElement or HTML string with new slide or array + * with such slides, for example: + * + * @example + * mySwiper.appendSlide('
Slide 10"
') + * mySwiper.appendSlide([ + * '
Slide 10"
', + * '
Slide 11"
' + * ]); + */ + appendSlide(slide: HTMLElement | string): void; + + /** + * Add new slides to the beginning. slides could be HTMLElement or HTML string with new slide or + * array with such slides, for example: + * + * @example + * mySwiper.prependSlide('
Slide 0"
') + * mySwiper.prependSlide([ + * '
Slide 1"
', + * '
Slide 2"
' + * ]); + */ + prependSlide(slide: HTMLElement | string): void; + + /** + * Update virutal slides state + */ + update(): void; + } + + /** + * Keyboard Control module. + */ + class Keyboard { + /** + * Whether the keyboard control is enabled + */ + enabled: boolean; + + // Methods + /** + * Enable keyboard control + */ + enable(): void; + + /** + * Disable keyboard control + */ + disable(): void; + } + + /** + * Mousewheel Control module. + */ + class Mousewheel { + /** + * Whether the mousewheel control is enabled + */ + enabled: boolean; + + // Methods + /** + * Enable mousewheel control + */ + enable(): void; + + /** + * Disable mousewheel control + */ + disable(): void; + } + + /** + * Navigation module. + */ + class Navigation { + /** + * HTMLElement of "next" navigation button + */ + nextEl: HTMLElement; + + /** + * HTMLElement of "previous" navigation button + */ + prevEl: HTMLElement; + + /** + * Update navigation buttons state (enabled/disabled) + */ + update(): void; + } + + /** + * Pagination module. + */ + class Pagination { + /** + * HTMLElement of pagination container element + */ + el: HTMLElement; + + /** + * Dom7 array-like collection of pagination bullets + * HTML elements. To get specific slide HTMLElement + * use `mySwiper.pagination.bullets[1]`. + */ + bullets: DOM7Element[]; + + /** + * Render pagination layout + */ + render(): void; + + /** + * Update pagination state (enabled/disabled/active) + */ + update(): void; + } + + /** + * Scrollbar module. + */ + class Scrollbar { + // Properties + /** + * HTMLElement of Scrollbar container element + */ + el: HTMLElement; + + /** + * HTMLElement of Scrollbar draggable handler element + */ + dragEl: HTMLElement; + + // Methods + /** + * Updates scrollbar track and handler sizes + */ + updateSize(): void; + } + + /** + * Parallax module. + */ + class Parallax { } + + /** + * Zoom module. + */ + class Zoom { + /** + * Whether the zoom module is enabled + */ + enabled: boolean; + + /** + * Current image scale ratio + */ + scale: number; + + /** + * Enable zoom module + */ + enable(): void; + + /** + * Disable zoom module + */ + disable(): void; + + /** + * Zoom in image of the currently active slide + */ + in(): void; + + /** + * Zoom out image of the currently active slide + */ + out(): void; + + /** + * Toggle image zoom of the currently active slide + */ + toggle(): void; + } + + /** + * Lazy module. + */ + class Lazy { + /** + * Load/update lazy images based on current slider state (position) + */ + load(): void; + + /** + * Force to load lazy images in slide by specified index + * @param number index number of slide to load lazy images in + */ + loadInSlide(index: number): void; + } + + /** + * Controller module. + */ + class Controller { + /** + * Pass here another Swiper instance or array with Swiper instances that should be controlled + * by this Swiper + */ + control?: Swiper; + } + + /** + * Accessibility module (a11y$) + */ + class A11y { } + + /** + * History Navigation module. + */ + class History { } + + /** + * Hash Navigation module. + */ + class HashNavigation { + } + + /** + * Autoplay module. + */ + class Autoplay { + // Properties + /** + * Whether autoplay enabled and running + */ + running: boolean; + + // Methods + /** + * Start autoplay + */ + start(): boolean; + + /** + * Stop autoplay + */ + stop(): boolean; + } + + /** + * Fade Effect module. + */ + class FadeEffect { } + + /** + * Cube Effect module. + */ + class CubeEffect { } + + /** + * Flip Effect module. + */ + class FlipEffect { } + + /** + * Coverflow Effect module. + */ + class CoverflowEffect { } + + /** + * Core module + */ + class Swiper { + /** + * Constructs a new Swiper instance. + * + * @param container Where Swiper applies to. + * @param options Instance options. + */ + constructor(container: SelectableElement, options?: SwiperOptions); + + /** + * Object with passed initialization parameters + */ + params: SwiperOptions; + + /** + * Element with slider container. + */ + el: HTMLElement; + + /** + * Dom7 element with slider container HTML element. To get vanilla HTMLElement use el + */ + $el: DOM7Element; + + /** + * Slider wrapper HTML element. + */ + wrapperEl: HTMLElement; + + /** + * Dom7 element with slider wrapper HTML element. To get vanilla HTMLElement use wrapperEl + */ + $wrapperEl: DOM7Element; + + /** + * Dom7 array-like collection of slides HTML elements. To get specific slide HTMLElement use slides[1] + */ + slides: DOM7Element[]; + + /** + * Width of container + */ + width: number; + + /** + * Height of container + */ + height: number; + + /** + * Current value of wrapper translate + */ + translate: number; + + /** + * Current progress of wrapper translate (from 0 to 1) + */ + progress: number; + + /** + * Index number of currently active slide. + * + * @note Note, that in loop mode active index value will be always shifted + * on a number of looped/duplicated slides. + */ + activeIndex: number; + + /** + * Index number of currently active slide considering duplicated slides in loop mode + */ + realIndex: number; + + /** + * Index number of previously active slide + */ + previousIndex: number; + + /** + * true if slider on most "left"/"top" position + */ + isBeginning: true; + + /** + * true if slider on most "right"/"bottom" position + */ + isEnd: boolean; + + /** + * true if swiper is in transition + */ + animating: boolean; + + /** + * Object with the following touch event properties: + */ + touches: { + startX: number; + startY: number; + currentX: number; + currentY: number; + diff: number; + }; + + /** + * Index number of last clicked slide + */ + clickedIdex: number; + + /** + * Link to last clicked slide (HTMLElement) + */ + clickedSlide: HTMLElement; + + /** + * Disable/enable ability to slide to the next slides by assigning false/true to this property + * + * @default true + */ + allowSlideNext: boolean; + + /** + * Disable/enable ability to slide to the previous slides by assigning false/true to this property + * + * @default true + */ + allowSlidePrev: boolean; + + /** + * Disable/enable ability move slider by grabbing it with + * mouse or by touching it with finger (on touch screens) + * by assigning false/true to this property + * + * @default true + */ + allowTouchMove: boolean; + + // Methods + /** + * Run transition to next slide. + * + * @param speed Transition duration (in ms). + * @param runCallbacks Set it to false (by default it is true) and transition will + * not produce transition events. + */ + slideNext(speed: number, runCallbacks: boolean): void; + + /** + * Run transition to previous slide. + * + * @param speed Transition duration (in ms). + * @param runCallbacks Set it to false (by default it is true) and transition will + * not produce transition events. + */ + slidePrev(speed?: number, runCallbacks?: boolean): void; + + /** + * Run transition to the slide with index number equal to 'index' parameter for the + * duration equal to 'speed' parameter. + * + * @param index Index number of slide. + * @param speed Transition duration (in ms). + * @param runCallbacks Set it to false (by default it is true) and transition will + * not produce transition events. + */ + slideTo(index: number, speed?: number, runCallbacks?: boolean): void; + + /** + * You should call it after you add/remove slides + * manually, or after you hide/show it, or do any + * custom DOM modifications with Swiper + * This method also includes subcall of the following + * methods which you can use separately: + */ + update(): void; + + /** + * recalculate size of swiper container + */ + updateSize(): void; + + /** + * recalculate number of slides and their offsets. Useful after you add/remove slides with JavaScript + */ + updateSlides(): void; + + /** + * recalculate swiper progress + */ + updateProgress(): void; + + /** + * update active/prev/next classes on slides and bullets + */ + updateSlidesClasses(): void; + + /** + * tach all events listeners + */ + detachEvents(): void; + + /** + * Atach all events listeners again + */ + attachEvents(): void; + + /** + * Destroy slider instance and detach all events listeners, where + */ + destroy(deleteInstance: boolean, cleanupStyles: boolean): void; + + /** + * Set it to false (by default it is true) to not to delete Swiper instance + */ + deleteInstance: boolean; + + /** + * Set it to true (by default it is true) and all + * custom styles will be removed from slides, + * wrapper and container. Useful if you need to + * destroy Swiper and to init again with new + * options or in different direction + */ + cleanStyles: boolean; + + /** + * Installs modules on Swiper in runtime. + */ + static use(modules: SwiperModule[]): void; + + /** + * Add new slides to the end. slides could be + * HTMLElement or HTML string with new slide or + * array with such slides, for example: + * + * @example appendSlide('
Slide 10"
') + * @example + * appendSlide([ + * '
Slide 10"
', + * '
Slide 11"
' + * ]); + */ + appendSlide(slides: HTMLElement | string | string[]): void; + + /** + * Add new slides to the beginning. slides could be + * HTMLElement or HTML string with new slide or array with such slides, for example: + * + * @example prependSlide('
Slide 0"
') + * @example prependSlide([ + * '
Slide 1"
', + * '
Slide 2"
' + * ]); + */ + prependSlide(slides: HTMLElement | string | string[]): void; + + /** + * Remove selected slides. slideIndex could be a number with slide index to remove or array with indexes. + * + * @example removeSlide(0); // remove first slide + * @example removeSlide([0, 1]); // remove first and second slides + * @example removeAllSlides(); // Remove all slides + */ + removeSlide(slideIndex: number | number[]): void; + + /** + * Set custom css3 transform's translate value for swiper wrapper + */ + setTranslate(translate: any): void; + + /** + * Get current value of swiper wrapper css3 transform translate + */ + getTranslate(): any; + + /** + * Add event listener + */ + on(event: SwiperEvent, handler: () => void): void; + + /** + * Add event listener that will be executed only once + */ + once(event: SwiperEvent, handler: () => void): void; + + /** + * Remove event listener for specified event + * If no handler specified, removes all listeners for specified event + */ + off(event: SwiperEvent, handler?: () => void): void; + + /** + * Disable mousewheel control + */ + disableMousewheelControl(): void; + + /** + * Enable mousewheel control + */ + enableMousewheelControl(): void; + + /** + * Disable keyboard control + */ + disableKeyboardControl(): void; + + /** + * Enable keyboard control + */ + enableKeyboardControl(): void; + + /** + * Unset grab cursor + */ + unsetGrabCursor(): void; + + /** + * Set grab cursor + */ + setGrabCursor(): void; + + // Components + + /** + * Swiper Navigation module. + */ + navigation?: Navigation; + + /** + * Swiper Pagination module. + */ + pagination?: Pagination; + + /** + * Swiper Scrollbar module. + */ + scrollbar?: Scrollbar; + + /** + * Swiper Autoplay module. + */ + autoplay?: Autoplay; + + /** + * Swiper Parallax module. + */ + parallax?: Parallax; + + /** + * Swiper Lazy module. + */ + lazy?: Lazy; + + /** + * Swiper FadeEffect module. + */ + fadeEffect?: FadeEffect; + + /** + * Swiper CoverflowEffect module. + */ + coverflowEffect?: CoverflowEffect; + + /** + * Swiper FlipEffect module. + */ + flipEffect?: FlipEffect; + + /** + * Swiper CubeEffect module. + */ + cubeEffect?: CubeEffect; + + /** + * Swiper Zoom module. + */ + zoom?: Zoom; + + /** + * Swiper Keyboard module. + */ + keyboard?: Keyboard; + + /** + * Swiper Mousewheel module. + */ + mousewheel?: Mousewheel; + + /** + * Swiper Virtual module. + */ + virtual?: Virtual; + + /** + * Swiper HashNavigation module. + */ + hashNavigation?: HashNavigation; + + /** + * Swiper History module. + */ + history?: History; + + /** + * Swiper Controller module. + */ + controller?: Controller; + + /** + * Swiper A11y module. + */ + a11y?: A11y; + } +} + +// Use thru this when in TypeScript +declare module 'swiper/dist/js/swiper.esm' { + import alias = require('swiper'); + export = alias; } diff --git a/types/swiper/swiper-tests.ts b/types/swiper/swiper-tests.ts index dfb7df8eb2..a41b093001 100644 --- a/types/swiper/swiper-tests.ts +++ b/types/swiper/swiper-tests.ts @@ -3,53 +3,62 @@ * for more details, please see http://idangero.us/swiper/demos/ * @author Eugene Matseruk */ +import { Swiper, Navigation, History } from 'swiper'; + +const containerSelector = '.swiper-container'; /** * 010-default */ function defaultDemo() { - const swiper = new Swiper('.swiper-container'); + const swiper = new Swiper(containerSelector); } /** * 020-navigation */ function navigation() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }); + + swiper.navigation.update(); } /** * 030-pagination */ function pagination() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { pagination: { el: '.swiper-pagination', }, }); + + swiper.pagination.update(); } /** * 040-pagination-dynamic */ function paginationDynamic() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { pagination: { el: '.swiper-pagination', dynamicBullets: true, }, }); + + swiper.pagination.update(); } /** * 050-progress-pagination */ function paginationProgress() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { pagination: { el: '.swiper-pagination', type: 'progressbar', @@ -59,13 +68,16 @@ function paginationProgress() { prevEl: '.swiper-button-prev', }, }); + + swiper.pagination.update(); + swiper.navigation.update(); } /** * 060-pagination-fraction */ function paginationFraction() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { pagination: { el: '.swiper-pagination', type: 'fraction', @@ -75,13 +87,16 @@ function paginationFraction() { prevEl: '.swiper-button-prev', }, }); + + swiper.pagination.update(); + swiper.navigation.update(); } /** * 070-pagination-custom */ function paginationCustom() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { pagination: { el: '.swiper-pagination', clickable: true, @@ -90,25 +105,29 @@ function paginationCustom() { }, }, }); + + swiper.pagination.render(); } /** * 080-scrollbar */ function scrollbar() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { scrollbar: { el: '.swiper-scrollbar', hide: true, }, }); + + swiper.scrollbar.updateSize(); } /** * Vertical Slider */ function verticalSlider() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { direction: 'vertical', pagination: { el: '.swiper-pagination', @@ -121,7 +140,7 @@ function verticalSlider() { * Space Between Slides */ function spaceBetween() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { spaceBetween: 30, pagination: { el: '.swiper-pagination', @@ -134,7 +153,7 @@ function spaceBetween() { * Multiple Slides Per View */ function multipleSlidesPerView() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 3, spaceBetween: 30, pagination: { @@ -148,7 +167,7 @@ function multipleSlidesPerView() { * Auto Slides Per View / Carousel Mode */ function autoSlidesPerViewAndCarouserMode() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 'auto', spaceBetween: 30, pagination: { @@ -162,7 +181,7 @@ function autoSlidesPerViewAndCarouserMode() { * Centered Slides */ function centeredSlides() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 4, spaceBetween: 30, centeredSlides: true, @@ -177,7 +196,7 @@ function centeredSlides() { * Centered Slides + Auto Slides Per View */ function centeredSlidesAndAutoSlidesPerView() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 'auto', centeredSlides: true, spaceBetween: 30, @@ -192,7 +211,7 @@ function centeredSlidesAndAutoSlidesPerView() { * Free Mode / No Fixed Positions */ function freeModeAndNoFixedPositions() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 3, spaceBetween: 30, freeMode: true, @@ -207,7 +226,7 @@ function freeModeAndNoFixedPositions() { * Scroll Container */ function scrollContainer() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { direction: 'vertical', slidesPerView: 'auto', freeMode: true, @@ -222,7 +241,7 @@ function scrollContainer() { * Multi Row Slides Layout */ function multiRowSlides() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 3, slidesPerColumn: 2, spaceBetween: 30, @@ -257,7 +276,7 @@ function nestedSwipers() { * Grab Cursor */ function grabCursor() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 4, centeredSlides: true, spaceBetween: 30, @@ -273,7 +292,7 @@ function grabCursor() { * Loop Mode / Infinite Loop */ function loopMode() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 1, spaceBetween: 30, loop: true, @@ -292,7 +311,7 @@ function loopMode() { * Loop Mode with Multiple Slides Per Group */ function loopModeWithMultipleSlides() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 3, spaceBetween: 30, slidesPerGroup: 3, @@ -313,7 +332,7 @@ function loopModeWithMultipleSlides() { * Fade Effect */ function fadeEffect() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { spaceBetween: 30, effect: 'fade', pagination: { @@ -331,7 +350,7 @@ function fadeEffect() { * 3D Cube Effect */ function cube3dEffect() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { effect: 'cube', grabCursor: true, cubeEffect: { @@ -350,7 +369,7 @@ function cube3dEffect() { * 3D Coverflow Effect */ function coverflow3dEffect() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { effect: 'coverflow', grabCursor: true, centeredSlides: true, @@ -372,7 +391,7 @@ function coverflow3dEffect() { * 3D Flip Effect */ function flip3dEffect() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { effect: 'flip', grabCursor: true, pagination: { @@ -389,7 +408,7 @@ function flip3dEffect() { * Keyboard Control (Open in new window) */ function keyboardControl() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 1, spaceBetween: 30, keyboard: { @@ -410,7 +429,7 @@ function keyboardControl() { * Mousewheel Control */ function mouseWheelControl() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { direction: 'vertical', slidesPerView: 1, spaceBetween: 30, @@ -426,7 +445,7 @@ function mouseWheelControl() { * Autoplay */ function autoplay() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { spaceBetween: 30, centeredSlides: true, autoplay: { @@ -450,7 +469,7 @@ function autoplay() { function dynamicSlides() { let appendNumber = 4; let prependNumber = 1; - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 3, centeredSlides: true, spaceBetween: 30, @@ -463,22 +482,22 @@ function dynamicSlides() { prevEl: '.swiper-button-prev', }, }); - document.querySelector('.prepend-2-slides').addEventListener('click', (e) => { + document.querySelector('.prepend-2-slides').addEventListener('click', e => { e.preventDefault(); swiper.prependSlide([ `
Slide ${--prependNumber}
`, `
Slide ${--prependNumber}
`, ]); }); - document.querySelector('.prepend-slide').addEventListener('click', (e) => { + document.querySelector('.prepend-slide').addEventListener('click', e => { e.preventDefault(); swiper.prependSlide(`
Slide ${--prependNumber}
`); }); - document.querySelector('.append-slide').addEventListener('click', (e) => { + document.querySelector('.append-slide').addEventListener('click', e => { e.preventDefault(); swiper.appendSlide(`
Slide ${--appendNumber}
`); }); - document.querySelector('.append-2-slides').addEventListener('click', (e) => { + document.querySelector('.append-2-slides').addEventListener('click', e => { e.preventDefault(); swiper.appendSlide([ `
Slide ${--appendNumber}
`, @@ -513,7 +532,7 @@ function thumbsGalleryWithTwoWayControl() { * Hash Navigation (Open in new window) */ function hashNavigation() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { spaceBetween: 30, hashNavigation: { watchState: true, @@ -533,7 +552,7 @@ function hashNavigation() { * History API (Open in new window) */ function historyApi() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { spaceBetween: 50, slidesPerView: 1, navigation: { @@ -553,7 +572,7 @@ function historyApi() { * RTL Layout */ function rtlLayout() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { pagination: { el: '.swiper-pagination', clickable: true, @@ -569,7 +588,7 @@ function rtlLayout() { * Parallax */ function parallax() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { speed: 600, parallax: true, pagination: { @@ -587,7 +606,7 @@ function parallax() { * Lazy Loading Images */ function lazyLoadingImages() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { // Enable lazy loading lazy: true, pagination: { @@ -605,7 +624,7 @@ function lazyLoadingImages() { * Responsive Breakpoints */ function responsiveBreakpoints() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 5, spaceBetween: 50, // init: false, @@ -638,7 +657,7 @@ function responsiveBreakpoints() { * Auto Height */ function autoHeight() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { autoHeight: true, // enable auto height spaceBetween: 20, pagination: { @@ -656,7 +675,7 @@ function autoHeight() { * Zoom */ function zoom() { - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { zoom: true, pagination: { el: '.swiper-pagination', @@ -666,6 +685,14 @@ function zoom() { prevEl: '.swiper-button-prev', }, }); + + swiper.zoom.out(); + swiper.zoom.disable(); + + if (swiper.zoom.enabled) throw new Error('Zoom should be disabled!'); + + swiper.zoom.enable(); + swiper.zoom.in(); } /** @@ -677,7 +704,7 @@ function virtualSlides() { slides.push('Slide ' + (i + 1)); } - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 3, centeredSlides: true, spaceBetween: 30, @@ -693,15 +720,15 @@ function virtualSlides() { slides }, }); - document.querySelector('.slide-1').addEventListener('click', (e) => { + document.querySelector('.slide-1').addEventListener('click', e => { e.preventDefault(); swiper.slideTo(0, 0); }); - document.querySelector('.slide-250').addEventListener('click', (e) => { + document.querySelector('.slide-250').addEventListener('click', e => { e.preventDefault(); swiper.slideTo(249, 0); }); - document.querySelector('.slide-500').addEventListener('click', (e) => { + document.querySelector('.slide-500').addEventListener('click', e => { e.preventDefault(); swiper.slideTo(499, 0); }); @@ -712,7 +739,7 @@ function virtualSlides() { */ function slideableNavigation() { const menuButton = document.querySelector('.menu-button'); - const swiper = new Swiper('.swiper-container', { + const swiper = new Swiper(containerSelector, { slidesPerView: 'auto', initialSlide: 1, resistanceRatio: 0, @@ -739,3 +766,12 @@ function slideableNavigation() { } }); } + +/** + * Swiper module instalation. + */ +function staticUseModules() { + Swiper.use([Navigation, History]); + + const swiper = new Swiper(containerSelector); +} diff --git a/types/swiper/tslint.json b/types/swiper/tslint.json index b236115191..63d6d869ef 100644 --- a/types/swiper/tslint.json +++ b/types/swiper/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { + "no-self-import": false, // TODOs "no-declare-current-package": false, "no-single-declare-module": false diff --git a/types/three/index.d.ts b/types/three/index.d.ts index 5b4a156e4b..a392532e95 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -20,6 +20,7 @@ // Seth Kingsley , // Ethan Kay , // Methuselah96 +// Dilip Ramirez // Definitions: https://github.com//DefinitelyTyped export * from "./three-core"; diff --git a/types/three/test/examples/exporters/gltf-exporter.ts b/types/three/test/examples/exporters/gltf-exporter.ts new file mode 100644 index 0000000000..2a6e6f508e --- /dev/null +++ b/types/three/test/examples/exporters/gltf-exporter.ts @@ -0,0 +1,511 @@ +() => { + var container: HTMLElement; + var camera: THREE.PerspectiveCamera, + material: THREE.MeshStandardMaterial, + object: THREE.Object3D, + scene1: THREE.Scene, + renderer: THREE.WebGLRenderer; + var gridHelper: THREE.GridHelper, + sphere: THREE.Object3D, + waltHead: THREE.Object3D; + + var gltfExporter = new THREE.GLTFExporter(); + + var options = { + trs: true, + onlyVisible: true, + truncateDrawRange: true, + binary: true, + forceIndices: true, + forcePowerOfTwoTextures: true + }; + // gltfExporter.parse( + // scene1, + // function(result) { + // if (result instanceof ArrayBuffer) { + // saveArrayBuffer(result, "scene.glb"); + // } else { + // var output = JSON.stringify(result, null, 2); + // console.log(output); + // saveString(output, "scene.gltf"); + // } + // }, + // options + // ); + + var link = document.createElement("a"); + link.style.display = "none"; + document.body.appendChild(link); // Firefox workaround, see #6594 + + // function save(blob, filename) { + // link.href = URL.createObjectURL(blob); + // link.download = filename; + // link.click(); + + // // URL.revokeObjectURL( url ); breaks Firefox... + // } + + // function saveString(text, filename) { + // save(new Blob([text], { type: "text/plain" }), filename); + // } + + // function saveArrayBuffer(buffer, filename) { + // save( + // new Blob([buffer], { type: "application/octet-stream" }), + // filename + // ); + // } + + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + init(); + animate(); + + function init() { + container = document.createElement("div"); + document.body.appendChild(container); + + scene1 = new THREE.Scene(); + scene1.name = "Scene1"; + + // --------------------------------------------------------------------- + // Perspective Camera + // --------------------------------------------------------------------- + camera = new THREE.PerspectiveCamera( + 45, + window.innerWidth / window.innerHeight, + 1, + 2000 + ); + camera.position.set(600, 400, 0); + + camera.name = "PerspectiveCamera"; + scene1.add(camera); + + // --------------------------------------------------------------------- + // Ambient light + // --------------------------------------------------------------------- + var light = new THREE.AmbientLight(0xffffff, 0.2); + light.name = "AmbientLight"; + scene1.add(light); + + // --------------------------------------------------------------------- + // DirectLight + // --------------------------------------------------------------------- + light = new THREE.DirectionalLight(0xffffff, 1); + light.position.set(1, 1, 0); + light.name = "DirectionalLight"; + scene1.add(light); + + // --------------------------------------------------------------------- + // Grid + // --------------------------------------------------------------------- + gridHelper = new THREE.GridHelper(2000, 20); + gridHelper.position.y = -50; + gridHelper.name = "Grid"; + scene1.add(gridHelper); + + // --------------------------------------------------------------------- + // Axes + // --------------------------------------------------------------------- + var axes = new THREE.AxesHelper(500); + axes.name = "AxesHelper"; + scene1.add(axes); + + // --------------------------------------------------------------------- + // Simple geometry with basic material + // --------------------------------------------------------------------- + // Icosahedron + var mapGrid = new THREE.TextureLoader().load("textures/UV_Grid_Sm.jpg"); + mapGrid.wrapS = mapGrid.wrapT = THREE.RepeatWrapping; + var material = new THREE.MeshBasicMaterial({ + color: 0xffffff, + map: mapGrid + }); + + object = new THREE.Mesh(new THREE.IcosahedronGeometry(75, 0), material); + object.position.set(-200, 0, 200); + object.name = "Icosahedron"; + scene1.add(object); + + // Octahedron + material = new THREE.MeshBasicMaterial({ + color: 0x0000ff, + wireframe: true + }); + object = new THREE.Mesh(new THREE.OctahedronGeometry(75, 1), material); + object.position.set(0, 0, 200); + object.name = "Octahedron"; + scene1.add(object); + + // Tetrahedron + material = new THREE.MeshBasicMaterial({ + color: 0xff0000, + transparent: true, + opacity: 0.5 + }); + + object = new THREE.Mesh(new THREE.TetrahedronGeometry(75, 0), material); + object.position.set(200, 0, 200); + object.name = "Tetrahedron"; + scene1.add(object); + + // --------------------------------------------------------------------- + // Buffered geometry primitives + // --------------------------------------------------------------------- + // Sphere + sphere = new THREE.Mesh( + new THREE.SphereBufferGeometry(70, 10, 10), + new THREE.MeshStandardMaterial({ + color: 0xffff00, + metalness: 0.5, + roughness: 1.0, + flatShading: true + }) + ); + sphere.position.set(0, 0, 0); + sphere.name = "Sphere"; + scene1.add(sphere); + + // Cylinder + object = new THREE.Mesh( + new THREE.CylinderBufferGeometry(10, 80, 100), + new THREE.MeshStandardMaterial({ + color: 0xff00ff, + flatShading: true + }) + ); + object.position.set(200, 0, 0); + object.name = "Cylinder"; + scene1.add(object); + + // TorusKnot + object = new THREE.Mesh( + new THREE.TorusKnotGeometry(50, 15, 40, 10), + new THREE.MeshStandardMaterial({ + color: 0xff0000, + roughness: 1 + }) + ); + object.position.set(-200, 0, 0); + object.name = "Cylinder"; + scene1.add(object); + + // --------------------------------------------------------------------- + // Hierarchy + // --------------------------------------------------------------------- + var mapWood = new THREE.TextureLoader().load( + "textures/hardwood2_diffuse.jpg" + ); + + object = new THREE.Mesh( + new THREE.BoxBufferGeometry(40, 100, 100), + new THREE.MeshStandardMaterial({ + map: mapWood, + side: THREE.DoubleSide + }) + ); + object.position.set(-200, 0, 400); + object.name = "Cube"; + scene1.add(object); + + var object2 = new THREE.Mesh( + new THREE.BoxBufferGeometry(40, 40, 40, 2, 2, 2), + material + ); + object2.position.set(0, 0, 50); + object2.rotation.set(0, 45, 0); + object2.name = "SubCube"; + object.add(object2); + + // --------------------------------------------------------------------- + // Groups + // --------------------------------------------------------------------- + var group1 = new THREE.Group(); + group1.name = "Group"; + scene1.add(group1); + + var group2 = new THREE.Group(); + group2.name = "subGroup"; + group2.position.set(0, 50, 0); + group1.add(group2); + + object2 = new THREE.Mesh( + new THREE.BoxBufferGeometry(30, 30, 30), + material + ); + object2.name = "Cube in group"; + object2.position.set(0, 0, 400); + group2.add(object2); + + // --------------------------------------------------------------------- + // Triangle Strip + // --------------------------------------------------------------------- + var geometry = new THREE.BufferGeometry(); + var positions = new Float32Array([ + 0, + 0, + 0, + 0, + 80, + 0, + 80, + 0, + 0, + 80, + 80, + 0, + 80, + 0, + 80, + 80, + 80, + 80 + ]); + + var colors = new Float32Array([ + 1, + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 1 + ]); + + geometry.addAttribute( + "position", + new THREE.BufferAttribute(positions, 3) + ); + geometry.addAttribute("color", new THREE.BufferAttribute(colors, 3)); + object = new THREE.Mesh( + geometry, + new THREE.MeshBasicMaterial({ + side: THREE.DoubleSide, + vertexColors: THREE.VertexColors + }) + ); + object.position.set(140, -40, -250); + // object.setDrawMode(THREE.TriangleStripDrawMode); + object.name = "Custom buffered"; + object.userData = { data: "customdata", list: [1, 2, 3, 4] }; + + scene1.add(object); + + // --------------------------------------------------------------------- + // Line Strip + // --------------------------------------------------------------------- + var geometry = new THREE.BufferGeometry(); + var numPoints = 100; + var positions = new Float32Array(numPoints * 3); + + for (var i = 0; i < numPoints; i++) { + positions[i * 3] = i; + positions[i * 3 + 1] = Math.sin(i / 2) * 20; + positions[i * 3 + 2] = 0; + } + + geometry.addAttribute( + "position", + new THREE.BufferAttribute(positions, 3) + ); + object = new THREE.Line( + geometry, + new THREE.LineBasicMaterial({ color: 0xffff00 }) + ); + object.position.set(-50, 0, -200); + scene1.add(object); + + // --------------------------------------------------------------------- + // Buffer geometry truncated (DrawRange) + // --------------------------------------------------------------------- + var geometry = new THREE.BufferGeometry(); + var numElements = 6; + var outOfRange = 3; + + var positions = new Float32Array((numElements + outOfRange) * 3); + var colors = new Float32Array((numElements + outOfRange) * 3); + + positions.set([ + 0, + 0, + 0, + 0, + 80, + 0, + 80, + 0, + 0, + 80, + 0, + 0, + 0, + 80, + 0, + 80, + 80, + 0 + ]); + + colors.set([1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1]); + + geometry.addAttribute( + "position", + new THREE.BufferAttribute(positions, 3) + ); + geometry.addAttribute("color", new THREE.BufferAttribute(colors, 3)); + geometry.setDrawRange(0, numElements); + + object = new THREE.Mesh( + geometry, + new THREE.MeshBasicMaterial({ + side: THREE.DoubleSide, + vertexColors: THREE.VertexColors + }) + ); + object.name = "Custom buffered truncated"; + object.position.set(340, -40, -200); + + scene1.add(object); + + // --------------------------------------------------------------------- + // Points + // --------------------------------------------------------------------- + var numPoints = 100; + var pointsArray = new Float32Array(numPoints * 3); + for (var i = 0; i < numPoints; i++) { + pointsArray[3 * i] = -50 + Math.random() * 100; + pointsArray[3 * i + 1] = Math.random() * 100; + pointsArray[3 * i + 2] = -50 + Math.random() * 100; + } + + var pointsGeo = new THREE.BufferGeometry(); + pointsGeo.addAttribute( + "position", + new THREE.BufferAttribute(pointsArray, 3) + ); + + var pointsMaterial = new THREE.PointsMaterial({ + color: 0xffff00, + size: 5 + }); + var points = new THREE.Points(pointsGeo, pointsMaterial); + points.name = "Points"; + points.position.set(-200, 0, -200); + scene1.add(points); + + // --------------------------------------------------------------------- + // Ortho camera + // --------------------------------------------------------------------- + var cameraOrtho = new THREE.OrthographicCamera( + window.innerWidth / -2, + window.innerWidth / 2, + window.innerHeight / 2, + window.innerHeight / -2, + 0.1, + 10 + ); + scene1.add(cameraOrtho); + cameraOrtho.name = "OrthographicCamera"; + + material = new THREE.MeshLambertMaterial({ + color: 0xffff00, + side: THREE.DoubleSide + }); + + object = new THREE.Mesh( + new THREE.CircleGeometry(50, 20, 0, Math.PI * 2), + material + ); + object.position.set(200, 0, -400); + scene1.add(object); + + object = new THREE.Mesh( + new THREE.RingGeometry(10, 50, 20, 5, 0, Math.PI * 2), + material + ); + object.position.set(0, 0, -400); + scene1.add(object); + + object = new THREE.Mesh( + new THREE.CylinderGeometry(25, 75, 100, 40, 5), + material + ); + object.position.set(-200, 0, -400); + scene1.add(object); + + // --------------------------------------------------------------------- + // Big red box hidden just for testing `onlyVisible` option + // --------------------------------------------------------------------- + material = new THREE.MeshBasicMaterial({ + color: 0xff0000 + }); + object = new THREE.Mesh( + new THREE.BoxBufferGeometry(200, 200, 200), + material + ); + object.position.set(0, 0, 0); + object.name = "CubeHidden"; + object.visible = false; + scene1.add(object); + + // --------------------------------------------------------------------- + // + // + var loader = new THREE.OBJLoader(); + loader.load("models/obj/walt/WaltHead.obj", function(obj) { + waltHead = obj; + waltHead.scale.multiplyScalar(1.5); + waltHead.position.set(400, 0, 0); + scene1.add(waltHead); + }); + + // + + renderer = new THREE.WebGLRenderer({ antialias: true }); + renderer.setPixelRatio(window.devicePixelRatio); + renderer.setSize(window.innerWidth, window.innerHeight); + + container.appendChild(renderer.domElement); + + // + + window.addEventListener("resize", onWindowResize, false); + } + + function onWindowResize() { + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + } + + // + + function animate() { + requestAnimationFrame(animate); + + render(); + } + + function render() { + var timer = Date.now() * 0.0001; + + camera.position.x = Math.cos(timer) * 800; + camera.position.z = Math.sin(timer) * 800; + + camera.lookAt(scene1.position); + renderer.render(scene1, camera); + } +}; diff --git a/types/three/test/math/test_unit_math.ts b/types/three/test/math/test_unit_math.ts index b6c536085f..30e8691843 100644 --- a/types/three/test/math/test_unit_math.ts +++ b/types/three/test/math/test_unit_math.ts @@ -755,7 +755,7 @@ declare function equal(a: T, b: T, desc?: string): void; test( "getHSL", function () { var c = new THREE.Color( 0x80ffff ); - var hsl = c.getHSL(); + var hsl = c.getHSL( { h: 0, s: 0, l: 0 } ); ok( hsl.h == 0.5, "hue: " + hsl.h ); ok( hsl.s == 1.0, "saturation: " + hsl.s ); @@ -765,7 +765,7 @@ declare function equal(a: T, b: T, desc?: string): void; test( "setHSL", function () { var c = new THREE.Color(); c.setHSL(0.75, 1.0, 0.25); - var hsl = c.getHSL(); + var hsl = c.getHSL( { h: 0, s: 0, l: 0 } ); ok( hsl.h == 0.75, "hue: " + hsl.h ); ok( hsl.s == 1.00, "saturation: " + hsl.s ); diff --git a/types/three/test/webgl/webgl_geometries_with_context.ts b/types/three/test/webgl/webgl_geometries_with_context.ts new file mode 100644 index 0000000000..20e18f715a --- /dev/null +++ b/types/three/test/webgl/webgl_geometries_with_context.ts @@ -0,0 +1,185 @@ +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometries.html + +() => { + if (!Detector.webgl) Detector.addGetWebGLMessage(); + + var container: HTMLDivElement, stats: Stats; + + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer; + + init(); + animate(); + + function init() { + + container = document.createElement('div'); + document.body.appendChild(container); + + camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000); + camera.position.y = 400; + + scene = new THREE.Scene(); + + var light: THREE.DirectionalLight, object: THREE.Mesh | THREE.AxesHelper | THREE.ArrowHelper; + + scene.add(new THREE.AmbientLight(0x404040)); + + light = new THREE.DirectionalLight(0xffffff); + light.position.set(0, 1, 0); + scene.add(light); + + var map = THREE.ImageUtils.loadTexture('textures/UV_Grid_Sm.jpg'); + map.wrapS = map.wrapT = THREE.RepeatWrapping; + map.anisotropy = 16; + + var material = new THREE.MeshLambertMaterial({ map: map, side: THREE.DoubleSide }); + + // + + object = new THREE.Mesh(new THREE.SphereGeometry(75, 20, 10), material); + object.position.set(-400, 0, 200); + scene.add(object); + + object = new THREE.Mesh(new THREE.IcosahedronGeometry(75, 1), material); + object.position.set(-200, 0, 200); + scene.add(object); + + object = new THREE.Mesh(new THREE.OctahedronGeometry(75, 2), material); + object.position.set(0, 0, 200); + scene.add(object); + + object = new THREE.Mesh(new THREE.TetrahedronGeometry(75, 0), material); + object.position.set(200, 0, 200); + scene.add(object); + + // + + object = new THREE.Mesh(new THREE.PlaneGeometry(100, 100, 4, 4), material); + object.position.set(-400, 0, 0); + scene.add(object); + + object = new THREE.Mesh(new THREE.BoxGeometry(100, 100, 100, 4, 4, 4), material); + object.position.set(-200, 0, 0); + scene.add(object); + + object = new THREE.Mesh(new THREE.CircleGeometry(50, 20, 0, Math.PI * 2), material); + object.position.set(0, 0, 0); + scene.add(object); + + object = new THREE.Mesh(new THREE.RingGeometry(10, 50, 20, 5, 0, Math.PI * 2), material); + object.position.set(200, 0, 0); + scene.add(object); + + object = new THREE.Mesh(new THREE.CylinderGeometry(25, 75, 100, 40, 5), material); + object.position.set(400, 0, 0); + scene.add(object); + + // + + var points: THREE.Vector2[] = []; + + for (var i = 0; i < 50; i++) { + + points.push(new THREE.Vector2(Math.sin(i * 0.2) * Math.sin(i * 0.1) * 15 + 50, 0)); + + } + + object = new THREE.Mesh(new THREE.LatheGeometry(points, 20), material); + object.position.set(-400, 0, -200); + scene.add(object); + + object = new THREE.Mesh(new THREE.TorusGeometry(50, 20, 20, 20), material); + object.position.set(-200, 0, -200); + scene.add(object); + + object = new THREE.Mesh(new THREE.TorusKnotGeometry(50, 10, 50, 20), material); + object.position.set(0, 0, -200); + scene.add(object); + + + object = new THREE.Mesh( + new THREE.ParametricGeometry( + (u:number, v:number, dest:THREE.Vector3):void => { + dest.set(u, v, 0); + }, + 25, + 25 + ) + ); + + object = new THREE.AxesHelper(50); + object.position.set(200, 0, -200); + scene.add(object); + + object = new THREE.ArrowHelper(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 0), 50); + object.position.set(400, 0, -200); + scene.add(object); + + // + /* + * Inserting a new Canvas' WebGL rendering context + * (https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext) + */ + const canvas = document.createElement('canvas'); + const gl = canvas.getContext('webgl'); + + renderer = new THREE.WebGLRenderer({ antialias: true, context: gl }); + renderer.setPixelRatio(window.devicePixelRatio); + renderer.setSize(window.innerWidth, window.innerHeight); + + container.appendChild(renderer.domElement); + + stats = new Stats(); + stats.dom.style.position = 'absolute'; + stats.dom.style.top = '0px'; + container.appendChild(stats.dom); + + // + + window.addEventListener('resize', onWindowResize, false); + + } + + function onWindowResize() { + + camera.aspect = window.innerWidth / window.innerHeight; + camera.updateProjectionMatrix(); + + renderer.setSize(window.innerWidth, window.innerHeight); + + } + + // + + function animate() { + + requestAnimationFrame(animate); + + render(); + stats.update(); + + } + + function render() { + + var timer = Date.now() * 0.0001; + + camera.position.x = Math.cos(timer) * 800; + camera.position.z = Math.sin(timer) * 800; + + camera.lookAt(scene.position); + + for (var i = 0, l = scene.children.length; i < l; i++) { + + var object = scene.children[i]; + + object.rotation.x = timer * 5; + object.rotation.y = timer * 2.5; + + } + + renderer.render(scene, camera); + + } + +} diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index e62638c151..24bf1364f7 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -3369,7 +3369,7 @@ export class Color { */ getHexString(): string; - getHSL(): HSL; + getHSL(target: HSL): HSL; /** * Returns the value of this color in CSS context style. @@ -5425,6 +5425,14 @@ export interface WebGLRendererParameters { */ canvas?: HTMLCanvasElement; + + /** + * A WebGL Rendering Context. + * (https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext) + * Default is null + */ + context?: WebGLRenderingContext + /** * shader precision. Can be "highp", "mediump" or "lowp". */ diff --git a/types/three/three-gltfexporter.d.ts b/types/three/three-gltfexporter.d.ts index 2bdba480a7..454f491b20 100644 --- a/types/three/three-gltfexporter.d.ts +++ b/types/three/three-gltfexporter.d.ts @@ -1,9 +1,7 @@ -import { Object3D } from "three"; +import { Object3D } from "./three-core"; export class GLTFExporter { constructor(); parse(input: Object3D, onCompleted: (gltf: object) => void, options: object): null; - } - diff --git a/types/three/tsconfig.json b/types/three/tsconfig.json index ff443f85f7..a7a79e68f5 100644 --- a/types/three/tsconfig.json +++ b/types/three/tsconfig.json @@ -29,6 +29,7 @@ "test/webgl/webgl_camera.ts", "test/webgl/webgl_custom_attributes.ts", "test/webgl/webgl_geometries.ts", + "test/webgl/webgl_geometries_with_context.ts", "test/webgl/webgl_helpers.ts", "test/webgl/webgl_interactive_cubes.ts", "test/webgl/webgl_interactive_raycasting_points.ts", @@ -56,6 +57,7 @@ "test/examples/ctm/ctmloader.ts", "test/examples/octree.ts", "test/examples/loaders/webgl_loader_obj_mtl.ts", + "test/examples/exporters/gltf-exporter.ts", "test/webvr/webvr.ts" ] } diff --git a/types/through2-concurrent/index.d.ts b/types/through2-concurrent/index.d.ts new file mode 100644 index 0000000000..c4c0928b38 --- /dev/null +++ b/types/through2-concurrent/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for through2-concurrent 2.0 +// Project: https://github.com/almost/through2-concurrent +// Definitions by: Alorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { TransformFunction, FlushCallback } from 'through2'; +import { DuplexOptions, Transform as TransformStream } from 'stream'; + +declare function through2Concurrent(transform?: TransformFunction, flush?: FlushCallback): TransformStream; +declare function through2Concurrent(opts?: through2Concurrent.Through2ConcurrentOptions, transform?: TransformFunction, flush?: FlushCallback): TransformStream; + +declare namespace through2Concurrent { + interface Through2ConcurrentOptions extends DuplexOptions { + maxConcurrency?: number; + } + + function obj(transform?: TransformFunction, flush?: FlushCallback): TransformStream; + function obj(opts?: Through2ConcurrentOptions, transform?: TransformFunction, flush?: FlushCallback): TransformStream; +} + +export = through2Concurrent; diff --git a/types/through2-concurrent/through2-concurrent-tests.ts b/types/through2-concurrent/through2-concurrent-tests.ts new file mode 100644 index 0000000000..f76c2b4d6d --- /dev/null +++ b/types/through2-concurrent/through2-concurrent-tests.ts @@ -0,0 +1,27 @@ +import * as through2 from 'through2-concurrent'; +import { Transform } from 'stream'; + +let str: Transform; + +const transformFn = (err: any, data: any) => {}; +function flushCb(this: Transform, cb: () => void) { + cb(); +} +const opts = { + allowHalfOpen: false, + maxConcurrency: 5 +}; + +str = through2(); +str = through2(opts); +str = through2(transformFn); +str = through2(opts, transformFn); +str = through2(transformFn, flushCb); +str = through2(opts, transformFn, flushCb); + +str = through2.obj(); +str = through2.obj(opts); +str = through2.obj(transformFn); +str = through2.obj(opts, transformFn); +str = through2.obj(transformFn, flushCb); +str = through2.obj(opts, transformFn, flushCb); diff --git a/types/through2-concurrent/tsconfig.json b/types/through2-concurrent/tsconfig.json new file mode 100644 index 0000000000..ecd3066d61 --- /dev/null +++ b/types/through2-concurrent/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", + "through2-concurrent-tests.ts" + ] +} diff --git a/types/through2-concurrent/tslint.json b/types/through2-concurrent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/through2-concurrent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/through2/index.d.ts b/types/through2/index.d.ts index 3ff12ff86d..e24c15a3e3 100644 --- a/types/through2/index.d.ts +++ b/types/through2/index.d.ts @@ -1,19 +1,19 @@ // Type definitions for through2 v 2.0 // Project: https://github.com/rvagg/through2 -// Definitions by: Bart van der Schoor , jedmao , Georgios Valotasios -// Ben Chauvette < https://github.com/bdchauvette>, TeamworkGuy2 +// Definitions by: Bart van der Schoor , +// jedmao , +// Georgios Valotasios , +// Ben Chauvette < https://github.com/bdchauvette>, +// TeamworkGuy2 , +// Alorel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// import stream = require('stream'); -type TransformCallback = (err?: any, data?: any) => void; -type TransformFunction = (this: stream.Transform, chunk: any, enc: string, callback: TransformCallback) => void; -type FlushCallback = (this: stream.Transform, flushCallback: () => void) => void; - -declare function through2(transform?: TransformFunction, flush?: FlushCallback): stream.Transform; -declare function through2(opts?: stream.DuplexOptions, transform?: TransformFunction, flush?: FlushCallback): stream.Transform; +declare function through2(transform?: through2.TransformFunction, flush?: through2.FlushCallback): stream.Transform; +declare function through2(opts?: stream.DuplexOptions, transform?: through2.TransformFunction, flush?: through2.FlushCallback): stream.Transform; declare namespace through2 { interface Through2Constructor extends stream.Transform { @@ -21,6 +21,10 @@ declare namespace through2 { (opts?: stream.DuplexOptions): stream.Transform; } + type TransformCallback = (err?: any, data?: any) => void; + type TransformFunction = (this: stream.Transform, chunk: any, enc: string, callback: TransformCallback) => void; + type FlushCallback = (this: stream.Transform, flushCallback: () => void) => void; + /** * Convenvience method for creating object streams */ diff --git a/types/tiny-secp256k1/index.d.ts b/types/tiny-secp256k1/index.d.ts new file mode 100644 index 0000000000..7c71cab5cc --- /dev/null +++ b/types/tiny-secp256k1/index.d.ts @@ -0,0 +1,94 @@ +// Type definitions for tiny-secp256k1 1.0 +// Project: https://github.com/bitcoinjs/tiny-secp256k1 +// Definitions by: Eduardo Henke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +/** + * Checks if A is a point in the curve + * @param A should be: + * encoded with a sequence tag of 0x02, 0x03 or 0x04 + * A.x is within [1...p - 1] + * A.y is within [1...p - 1] + */ +export function isPoint(A: Buffer): boolean; + +/** + * Returns false if the point is not compressed. + */ +export function isPointCompressed(A: Buffer): boolean; + +/** + * Checks if point is private key + * @param d should be: + * 256-bit + * within [1...order - 1] + */ +export function isPrivate(d: Buffer): boolean; + +/** + * Returns null if result is at infinity. + * @param A isPoint(A) should be true + * @param B isPoint(B) should be true + * @param compressed optional, if true compresses the resulting point + */ +export function pointAdd(A: Buffer, B: Buffer, compressed?: boolean): Buffer | null; + +/** + * Returns null if result is at infinity. + * @param A isPoint(A) should be true + * @param tweak should be within [1...order - 1] + * @param compressed optional, if true compresses the resulting point + */ +export function pointAddScalar(A: Buffer, tweak: Buffer, compressed?: boolean): Buffer | null; + +/** + * Compresses point A. + * @param A isPoint(A) should be true + * @param compressed if true compresses A + */ +export function pointCompress(A: Buffer, compressed: boolean): Buffer; + +/** + * Returns null if result is at infinity. + * @param d isPrivate(d) should be true + * @param compressed optional, if true compresses the resulting point + */ +export function pointFromScalar(d: Buffer, compressed?: boolean): Buffer | null; + +/** + * Returns null if result is at infinity. + * @param A isPoint(A) should be true + * @param tweak should be within [1...order - 1] + * @param compressed optional, if true compresses the resulting point + */ +export function pointMultiply(A: Buffer, tweak: Buffer, compressed?: boolean): Buffer | null; + +/** + * Returns null if result is equal to 0. + * @param d isPrivate(d) should be true + * @param tweak should be within [1...order - 1] + */ +export function privateAdd(d: Buffer, tweak: Buffer): Buffer | null; + +/** + * Returns null if result is equal to 0. + * @param d isPrivate(d) should be true + * @param tweak should be within [1...order - 1] + */ +export function privateSub(d: Buffer, tweak: Buffer): Buffer | null; + +/** + * Returns normalized signatures, each of (r, s) values are guaranteed to less than order / 2. Uses RFC6979. + * @param message should be 256-bit + * @param privateKey isPrivate(privateKey) should be true + */ +export function sign(message: Buffer, privateKey: Buffer): Buffer; + +/** + * Returns false if any of (r, s) values are equal to 0, or if the signature is rejected. + * @param message should be 256-bit + * @param publicKey isPoint(publicKey) should be true + * @param signature signature should have all (r, s) values within range [0...order - 1] + */ +export function verify(message: Buffer, publicKey: Buffer, signature: Buffer): boolean; diff --git a/types/tiny-secp256k1/tiny-secp256k1-tests.ts b/types/tiny-secp256k1/tiny-secp256k1-tests.ts new file mode 100644 index 0000000000..1203f3fed1 --- /dev/null +++ b/types/tiny-secp256k1/tiny-secp256k1-tests.ts @@ -0,0 +1,11 @@ +import { pointFromScalar, sign, verify } from 'tiny-secp256k1'; + +const d = Buffer.from('5272e811987e04833abf88c2cdbb43eddfefd7b4afa50e87bfcd3a2b297f0a93'); +const Q = pointFromScalar(d); + +const message = new Buffer(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x77, 0x6f, 0x72, 0x6c, 0x64])); +const signature = sign(message, d); + +if (Q !== null) { + verify(message, Q, signature); +} diff --git a/types/tiny-secp256k1/tsconfig.json b/types/tiny-secp256k1/tsconfig.json new file mode 100644 index 0000000000..377e6d639c --- /dev/null +++ b/types/tiny-secp256k1/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "tiny-secp256k1-tests.ts" + ] +} diff --git a/types/tiny-secp256k1/tslint.json b/types/tiny-secp256k1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/tiny-secp256k1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/tough-cookie-filestore/index.d.ts b/types/tough-cookie-filestore/index.d.ts new file mode 100644 index 0000000000..d8b1cca501 --- /dev/null +++ b/types/tough-cookie-filestore/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for tough-cookie-filestore 0.0 +// Project: https://github.com/mitsuru/tough-cookie-filestore +// Definitions by: Christian Friedow +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = FileCookieStore; + +declare namespace FileCookieStore { + interface Cookie { + domain: string; + path: string; + key: string; + } +} + +declare class FileCookieStore { + idx: { + [domain: string]: { + [path: string]: { + [key: string]: FileCookieStore.Cookie, + }, + }, + }; + filePath: string; + synchronous: boolean; + + constructor(filePath: string); + + inspect(): string; + + findCookie(domain: string, path: string, key: string, cb: (whatever: null, cookie: FileCookieStore.Cookie | null | undefined) => void): void; + + findCookies(domain: string, path: string, cb: (whatever: null, cookies: FileCookieStore.Cookie[]) => void): void; + + putCookie(cookie: FileCookieStore.Cookie, path: string, key: string, cb: (whatever: null) => void): void; + + updateCookie(oldCookie: FileCookieStore.Cookie, newCookie: FileCookieStore.Cookie, cb: (whatever: null) => void): void; + + removeCookie(domain: string, path: string, key: string, cb: (whatever: null) => void): void; + + removeCookies(domain: string, path: string, cb: (whatever: null) => void): void; + + saveToFile(filePath: string, data: any, cb: () => void): void; + + loadFromFile(filePath: string, cb: (data: any) => void): void; +} diff --git a/types/tough-cookie-filestore/tough-cookie-filestore-tests.ts b/types/tough-cookie-filestore/tough-cookie-filestore-tests.ts new file mode 100644 index 0000000000..7ad52fa67c --- /dev/null +++ b/types/tough-cookie-filestore/tough-cookie-filestore-tests.ts @@ -0,0 +1,3 @@ +import FileCookieStore = require('tough-cookie-filestore'); + +const cookiestore = new FileCookieStore('cookies.json'); diff --git a/types/tough-cookie-filestore/tsconfig.json b/types/tough-cookie-filestore/tsconfig.json new file mode 100644 index 0000000000..e7ca3f1718 --- /dev/null +++ b/types/tough-cookie-filestore/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", + "tough-cookie-filestore-tests.ts" + ] +} diff --git a/types/tough-cookie-filestore/tslint.json b/types/tough-cookie-filestore/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/tough-cookie-filestore/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/twilio-video/index.d.ts b/types/twilio-video/index.d.ts new file mode 100644 index 0000000000..cc65da2c2c --- /dev/null +++ b/types/twilio-video/index.d.ts @@ -0,0 +1,522 @@ +// Type definitions for twilio-video 2.0 +// Project: https://twilio.com/video +// Definitions by: MindDoc , Darío Blanco +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { EventEmitter } from 'events'; + +/** + * Classes + */ +export class AccessTokenExpiredError extends TwilioError { + code: 20104; + message: 'Access Token expired or expiration date invalid'; +} +export class AccessTokenGrantsInvalidError extends TwilioError { + code: 20106; + message: 'Invalid Access Token grants'; +} +export class AccessTokenHeaderInvalidError extends TwilioError { + code: 20102; + message: 'Invalid Access Token header'; +} +export class AccessTokenIssuerInvalidError extends TwilioError { + code: 20103; + message: 'Invalid Access Token issuer/subject'; +} +export class AccessTokenNotYetValidError extends TwilioError { + code: 20105; + message: 'Access Token not yet valid'; +} +export class AccessTokenSignatureInvalidError extends TwilioError { + code: 20107; + message: 'Invalid Access Token signature'; +} +export class AudioTrack extends Track { + isStarted: boolean; + isEnabled: boolean; + kind: 'audio'; + mediaStreamTrack: MediaStreamTrack; + + attach(element?: HTMLMediaElement | string): HTMLMediaElement; + detach(element?: HTMLMediaElement | string): HTMLMediaElement[]; +} +export class ConfigurationAcquireFailedError extends TwilioError { + code: 53500; + message: 'Unable to acquire configuration'; +} +export class ConfigurationAcquireTurnFailedError extends TwilioError { + code: 53501; + message: 'Unable to acquire TURN credentials'; +} +export class LocalAudioTrack extends AudioTrack { + constructor(mediaStreamTrack: MediaStreamTrack, options?: LocalTrackOptions); + + id: Track.ID; + isStopped: boolean; + + disable(): LocalAudioTrack; + enable(enabled?: boolean): LocalAudioTrack; + stop(): LocalAudioTrack; +} +export class LocalAudioTrackPublication extends LocalTrackPublication { + kind: 'audio'; + track: LocalAudioTrack; + + unpublish(): LocalAudioTrackPublication; +} +export class LocalAudioTrackStats extends LocalTrackStats { + audioLevel: AudioLevel | null; + jitter: number | null; +} +export class LocalDataTrack extends Track { + constructor(options?: LocalDataTrackOptions); + + id: Track.ID; + kind: 'data'; + maxPacketLifeTime: number | null; + maxRetransmits: number | null; + ordered: boolean; + reliable: boolean; + + send(data: string | Blob | ArrayBuffer | ArrayBufferView): void; +} +export class LocalDataTrackPublication extends LocalTrackPublication { + kind: 'data'; + track: LocalDataTrack; + + unpublish(): LocalDataTrackPublication; +} +export class LocalParticipant extends Participant { + audioTracks: Map; + dataTracks: Map; + tracks: Map; + videoTracks: Map; + + publishTrack(localTrack: LocalTrack): Promise; + publishTrack( + mediaStreamTrack: MediaStreamTrack, options?: LocalTrackOptions, + ): Promise; + publishTracks( + tracks: LocalTrack[] | MediaStreamTrack[], + ): Promise; + setParameters(encodingParameters?: EncodingParameters | null): LocalParticipant; +} +export class LocalTrackPublication extends TrackPublication { + isTrackEnabled: boolean; + kind: Track.Kind; + track: LocalTrack; + + unpublish(): LocalTrackPublication; +} +export class LocalTrackStats extends TrackStats { + bytesSent: number | null; + packetsSent: number | null; + roundTripTime: number | null; +} +export class LocalVideoTrack extends VideoTrack { + constructor(mediaStreamTrack: MediaStreamTrack, options?: LocalTrackOptions); + + id: Track.ID; + isStopped: boolean; + + disable(): LocalVideoTrack; + enable(enabled?: boolean): LocalVideoTrack; + stop(): LocalVideoTrack; +} +export class LocalVideoTrackPublication extends LocalTrackPublication { + kind: 'video'; + track: LocalVideoTrack; + + unpublish(): LocalVideoTrackPublication; +} +export class LocalVideoTrackStats extends LocalTrackStats { + captureDimensions: VideoTrack.Dimensions | null; + dimensions: VideoTrack.Dimensions | null; + captureFrameRate: number | null; + frameRate: number | null; +} +export class MediaClientLocalDescFailedError extends TwilioError { + code: 53400; + message: 'Client is unable to create or apply a local media description'; +} +export class MediaClientRemoteDescFailedError extends TwilioError { + code: 53402; + message: 'Client is unable to apply a remote media description'; +} +export class MediaConnectionError extends TwilioError { + code: 53405; + message: 'Media connection failed'; +} +export class MediaNoSupportedCodecError extends TwilioError { + code: 53404; + message: 'No supported codec'; +} +export class MediaServerLocalDescFailedError extends TwilioError { + code: 53401; + message: 'Server is unable to create or apply a local media description'; +} +export class MediaServerRemoteDescFailedError extends TwilioError { + code: 53403; + message: 'Server is unable to apply a remote media description'; +} +export namespace Participant { + type Identity = string; + type SID = string; +} +export class Participant extends EventEmitter { + audioTracks: Map; + dataTracks: Map; + identity: Participant.Identity; + networkQualityLEvel: NetworkQualityLevel | null; + sid: Participant.SID; + state: string; + tracks: Map; + videoTracks: Map; +} +export class ParticipantDuplicateIdentityError extends TwilioError { + code: 53205; + message: 'Participant disconnected because of duplicate identity'; +} +export class ParticipantIdentityCharsInvalidError extends TwilioError { + code: 53202; + message: 'Participant identity contains invalid characters'; +} +export class ParticipantIdentityInvalidError extends TwilioError { + code: 53200; + message: 'Participant identity is invalid'; +} +export class ParticipantIdentityTooLongError extends TwilioError { + code: 53201; + message: 'Participant identity is too long'; +} +export class ParticipantMaxTracksExceededError extends TwilioError { + code: 53203; + message: 'Participant has too many Tracks'; +} +export class ParticipantNotFoundError extends TwilioError { + code: 53204; + message: 'Participant not found'; +} +export class RemoteAudioTrack extends AudioTrack { + sid: Track.SID; +} +export class RemoteAudioTrackPublication extends RemoteTrackPublication { + kind: 'audio'; + track: RemoteAudioTrack | null; +} +export class RemoteAudioTrackStats extends RemoteTrackStats { + audioLevel: AudioLevel | null; + jitter: number | null; +} +export class RemoteDataTrack extends Track { + isEnabled: boolean; + isSubscribed: boolean; + kind: 'data'; + maxPacketLifeTime: number | null; + maxRetransmits: number | null; + ordered: boolean; + reliable: boolean; + sid: Track.SID; +} +export class RemoteDataTrackPublication extends RemoteTrackPublication { + kind: 'data'; + track: RemoteDataTrack | null; +} +export class RemoteParticipant extends Participant { + audioTracks: Map; + dataTracks: Map; + tracks: Map; + videoTracks: Map; +} +export class RemoteTrackPublication extends TrackPublication { + isSubscribed: boolean; + isTrackEnabled: boolean; + kind: Track.Kind; + track: RemoteTrack | null; +} +export class RemoteTrackStats { + bytesReceived: number | null; + packetsReceived: number | null; +} +export class RemoteVideoTrack extends VideoTrack { + sid: Track.SID; +} +export class RemoteVideoTrackPublication extends RemoteTrackPublication { + kind: 'video'; + track: RemoteVideoTrack | null; +} +export class RemoteVideoTrackStats extends RemoteTrackStats { + dimensions: VideoTrack.Dimensions | null; + frameRate: number | null; +} +export namespace Room { + type SID = string; +} +export class Room extends EventEmitter { + dominantSpeaker: RemoteParticipant | null; + isRecording: boolean; + localParticipant: LocalParticipant; + name: string; + participants: Map; + sid: Room.SID; + state: string; + + disconnect(): Room; + getStats(): Promise; +} +export class RoomCompletedError extends TwilioError { + code: 53118; + message: 'Room completed'; +} +export class RoomConnectFailedError extends TwilioError { + code: 53104; + message: 'Unable to connect to Room'; +} +export class RoomCreateFailedError extends TwilioError { + code: 53103; + message: 'Unable to create Room'; +} +export class RoomInvalidParametersError extends TwilioError { + code: 53114; + message: 'Room creation parameter(s) incompatible with the Room type'; +} +export class RoomMaxParticipantsExceededError extends TwilioError { + code: 53105; + message: 'Room contains too many Participants'; +} +export class RoomMaxParticipantsOutOfRangeError extends TwilioError { + code: 53107; + message: 'MaxParticipants is out of range'; +} +export class RoomMediaRegionInvalidError extends TwilioError { + code: 53115; + message: 'MediaRegion is invalid'; +} +export class RoomMediaRegionUnavailableError extends TwilioError { + code: 53116; + message: 'There are no media servers available in the MediaRegion'; +} +export class RoomNameCharsInvalidError extends TwilioError { + code: 53102; + message: 'Room name contains invalid characters'; +} +export class RoomNameInvalidError extends TwilioError { + code: 53100; + message: 'Room name is invalid'; +} +export class RoomNameTooLongError extends TwilioError { + code: 53101; + message: 'Room name is too long'; +} +export class RoomNotFoundError extends TwilioError { + code: 53106; + message: 'Room not found'; +} +export class RoomRoomExistsError extends TwilioError { + code: 53113; + message: 'Room exists'; +} +export class RoomStatusCallbackInvalidError extends TwilioError { + code: 53111; + message: 'StatusCallback is invalid'; +} +export class RoomStatusCallbackMethodInvalidError extends TwilioError { + code: 53110; + message: 'StatusCallbackMethod is invalid'; +} +export class RoomStatusInvalidError extends TwilioError { + code: 53112; + message: 'Status is invalid'; +} +export class RoomSubscriptionOperationNotSupportedError extends TwilioError { + code: 53117; + message: 'The subscription operation requested is not supported for the Room type'; +} +export class RoomTimeoutOutOfRangeError extends TwilioError { + code: 53109; + message: 'Timeout is out of range'; +} +export class RoomTypeInvalidError extends TwilioError { + code: 53108; + message: 'RoomType is not valid'; +} +export class SignalingConnectionDisconnectedError extends TwilioError { + code: 53001; + message: 'Signaling connection disconnected'; +} +export class SignalingConnectionError extends TwilioError { + code: 53000; + message: 'Signaling connection error'; +} +export class SignalingConnectionTimeoutError extends TwilioError { + code: 53002; + message: 'Signaling connection timed out'; +} +export class SignalingIncomingMessageInvalidError extends TwilioError { + code: 53003; + message: 'Client received an invalid signaling message'; +} +export class SignalingOutgoingMessageInvalidError extends TwilioError { + code: 53004; + message: 'Client sent an invalid signaling message'; +} +export class StatsReport { + peerConnectionId: string; + localAudioTrackStats: LocalAudioTrackStats[]; + localVideoTrackStats: LocalVideoTrackStats[]; + remoteAudioTrackStats: RemoteAudioTrackStats[]; + remoteVideoTrackStats: RemoteVideoTrackStats[]; +} +export namespace Track { + type Kind = 'audio' | 'video' | 'data'; + type ID = string; + type SID = string; +} +export class Track extends EventEmitter { + kind: Track.Kind; + name: string; +} +export class TrackInvalidError extends TwilioError { + code: 53300; + message: 'Track is invalid'; +} +export class TrackNameCharsInvalidError extends TwilioError { + code: 53303; + message: 'Track name contains invalid characters'; +} +export class TrackNameInvalidError extends TwilioError { + code: 53301; + message: 'Track name is invalid'; +} +export class TrackNameIsDuplicatedError extends TwilioError { + code: 53304; + message: 'Track name is duplicated'; +} +export class TrackNameTooLongError extends TwilioError { + code: 53302; + message: 'Track name is too long'; +} +export class TrackPublication { + trackName: string; + trackSid: Track.SID; +} +export class TrackServerTrackCapacityReachedError extends TwilioError { + code: 53305; + message: 'The server has reached capacity and cannot fulfill this request.'; +} +export class TrackStats { + trackId: Track.ID; + trackSid: Track.SID; + timestamp: number; + ssrc: string; + packetsLost: number | null; + codec: string | null; +} +export class TwilioError extends Error { + code: number; + toString(): string; +} +export namespace VideoTrack { + interface Dimensions { + width: number | null; + height: number | null; + } +} +export class VideoTrack extends Track { + isStarted: boolean; + isEnabled: boolean; + dimensions: VideoTrack.Dimensions; + kind: 'video'; + mediaStreamTrack: MediaStreamTrack; + + attach(element?: HTMLMediaElement | string): HTMLVideoElement; + detach(element?: HTMLMediaElement | string): HTMLMediaElement[]; +} + +/** + * Global (https://media.twiliocdn.com/sdk/js/video/releases/2.0.0-beta1/docs/global.html) + */ +export const version: string; + +/** Members */ +export type AudioCodec = 'isac' | 'opus' | 'PCMA' | 'PCMU'; +export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off'; +export type VideoCodec = 'H264' | 'VP8' | 'VP9'; + +/** Methods */ +export function connect(token: string, options?: ConnectOptions): Promise; +export function createLocalAudioTrack(options?: CreateLocalTrackOptions): Promise; +export function createLocalTracks(options?: CreateLocalTracksOptions): Promise; +export function createLocalVideoTrack(options?: CreateLocalTrackOptions): Promise; +export function isSupported(): boolean; +export function rewriteLocalTrackIds(room: Room, trackStats: LocalTrackStats[]): LocalTrackStats[]; + +/** Type Definitions */ +export type AudioLevel = number; +export type AudioTrackPublication = LocalAudioTrackPublication | RemoteAudioTrackPublication; +export interface ConnectOptions { + abortOnIceServersTimeout?: boolean; + audio?: boolean | CreateLocalTrackOptions; + iceServers?: RTCIceServer[]; + iceServersTimeout?: number; + iceTransportPolicy?: RTCIceTransportPolicy; + insights?: boolean; + maxAudioBitRate?: number | null; + maxVideoBitRate?: number | null; + name?: string | null; + preferredAudioCodecs?: AudioCodec[]; + preferredVideoCodecs?: VideoCodec[] | VideoCodecSettings[]; + logLevel?: LogLevel | LogLevels; + tracks?: LocalTrack[] | MediaStreamTrack[]; + video?: boolean | CreateLocalTrackOptions; +} +export interface CreateLocalTrackOptions { + logLevel: LogLevel | LogLevels; + name?: string; + workaroundWebKitBug180748?: boolean; // Lol +} +export interface CreateLocalTracksOptions { + audio?: boolean | CreateLocalTrackOptions; + logLevel?: LogLevel | LogLevels; + video?: boolean | CreateLocalTrackOptions; +} +export type DataTrack = LocalDataTrack | RemoteDataTrack; +export type DataTrackPublication = LocalDataTrackPublication | RemoteDataTrackPublication; +export interface EncodingParameters { + maxAudioBitrate?: number | null; + maxVideoBitrate?: number | null; +} +export interface LocalDataTrackOptions { + maxPacketLifeTime?: number | null; + maxRetransmits?: number | null; + ordered?: boolean; +} +export type LocalTrack = LocalAudioTrack | LocalVideoTrack | LocalDataTrack; +export interface LocalTrackOptions { + logLevel: LogLevel | LogLevels; + name?: string; +} +export interface LogLevels { + default: LogLevel; + media: LogLevel; + signaling: LogLevel; + webrtc: LogLevel; +} +export type NetworkQualityLevel = number; +export type RemoteTrack = RemoteAudioTrack | RemoteVideoTrack | RemoteDataTrack; +export interface RemoteTrackPublicationOptions { + logLevel: LogLevel | LogLevels; +} +export interface TrackPublicationOptions { + logLevel: LogLevel | LogLevels; +} +export interface VideoCodecSettings { + codec: VideoCodec; +} +export type VideoTrackPublication = LocalVideoTrackPublication | RemoteVideoTrackPublication; +export interface VP8CodecSettings { + name: VideoCodec; + simulcast?: boolean; +} diff --git a/types/twilio-video/tsconfig.json b/types/twilio-video/tsconfig.json new file mode 100644 index 0000000000..763a8aad1b --- /dev/null +++ b/types/twilio-video/tsconfig.json @@ -0,0 +1,23 @@ +{ + "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", + "twilio-video-tests.ts" + ] +} diff --git a/types/twilio-video/tslint.json b/types/twilio-video/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/twilio-video/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/twilio-video/twilio-video-tests.ts b/types/twilio-video/twilio-video-tests.ts new file mode 100644 index 0000000000..b5cfe43e01 --- /dev/null +++ b/types/twilio-video/twilio-video-tests.ts @@ -0,0 +1,45 @@ +import * as Video from 'twilio-video'; + +// Examples taken from https://twilio.github.io/twilio-video/ (v2.x) + +Video.connect('$TOKEN', { name: 'room-name' }).then(room => { + room.participants.forEach(participantConnected); + room.on('participantConnected', participantConnected); + room.on('participantDisconnected', participantDisconnected); + room.once('disconnected', error => room.participants.forEach(participantDisconnected)); +}); + +function participantConnected(participant: Video.Participant) { + participant.on('trackSubscribed', trackSubscribed); + participant.on('trackUnsubscribed', trackUnsubscribed); + + participant.tracks.forEach(publication => { + const remotePublication = publication as Video.RemoteTrackPublication; + if (remotePublication.isSubscribed) { + trackSubscribed(remotePublication.track as Video.VideoTrack | Video.AudioTrack); + } + }); +} + +function participantDisconnected(participant: Video.Participant) { + participant.tracks.forEach((publication) => { + const remotePublication = publication as Video.RemoteTrackPublication; + if (remotePublication.isSubscribed) { + const { track } = remotePublication; + if (track) trackUnsubscribed(track as Video.AudioTrack | Video.VideoTrack); + } + }); +} + +function trackSubscribed(track: Video.VideoTrack | Video.AudioTrack) { + const media = track.attach(); + insertDomElement(media); +} + +function trackUnsubscribed(track: Video.VideoTrack | Video.AudioTrack) { + track.detach().forEach(element => element.remove()); +} + +function insertDomElement(element: any) { + // Do something with the dom element +} diff --git a/types/twitch-ext/index.d.ts b/types/twitch-ext/index.d.ts index 279d17cd14..81bc3d3643 100644 --- a/types/twitch-ext/index.d.ts +++ b/types/twitch-ext/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for twitch-ext 1.14 +// Type definitions for twitch-ext 1.15 // Project: https://dev.twitch.tv/docs/extensions/reference/#javascript-helper // Definitions by: Benedict Etzel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -29,6 +29,16 @@ interface TwitchExt { */ actions: TwitchExtActions; + /** + * @see https://dev.twitch.tv/docs/extensions/reference/#twitch-extension-feature-flags + */ + features: TwitchExtFeatures; + + /** + * @see https://dev.twitch.tv/docs/extensions/bits/#javascript-helper + */ + bits: TwitchExtBits; + /** * Helper methods for the Twitch Extension rig. * @see https://github.com/twitchdev/developer-rig @@ -137,6 +147,13 @@ interface TwitchExtActions { */ followChannel(channelName: string): void; + /** + * This function causes your video-component or video-overlay extension to be minimized. + * + * @see https://dev.twitch.tv/docs/extensions/reference/#minimize + */ + minimize(): void; + /** * This function registers a callback that is invoked whenever a user completes an interaction prompted by the followChannel action. * @@ -153,6 +170,164 @@ interface TwitchExtActions { requestIdShare(): void; } +interface TwitchExtFeatureFlags { + /** + * If this flag is true, you can send a chat message to the current channel using Send Extension Chat Message + * (subject to the authentication requirements documented for that endpoint). + */ + isChatEnabled: boolean; +} + +/** + * @see TwitchExt.features + */ +interface TwitchExtFeatures extends TwitchExtFeatureFlags { + /** + * This function enables you to receive real-time updates to changes of the features object. + * If this callback is invoked, you should re-check the Twitch.ext.features object for a change + * to any feature flag your extension cares about. + * + * @param callback The callback is called with an array of feature flags which were updated. + */ + onChanged( + callback: (changed: ReadonlyArray) => void + ): void; +} + +interface TwitchExtBitsProductCost { + /** + * Number of Bits required for the product. + */ + amount: string; + + /** + * Always the string "bits". Reserved for future use. + */ + type: "bits"; +} + +interface TwitchExtBitsProduct { + /** + * Cost object. + */ + cost: TwitchExtBitsProductCost; + + /** + * Registered display name for the SKU. + */ + displayName: string; + + /** + * This field is returned only for extension versions that are not in the Released state. + */ + inDevelopment?: boolean; + + /** + * Unique ID for the product. + */ + sku: string; +} + +interface TwitchExtBitsTransaction { + /** + * Display name of the user who executed the Bits in Extensions transaction. + */ + displayName: string; + + initiator: "CURRENT_USER" | "OTHER"; + + /** + * Full product object from getProducts call + */ + product: TwitchExtBitsProduct; + + /** + * ID of the transaction. + */ + transactionID: string; + + /** + * JWT containing the following transaction information in the payload. + * The JWT is a large, base64-encoded string. It can be verified using your developer secret. + */ + transactionReceipt: string; + + /** + * Twitch ID of the user who executed the transaction. + */ + userId: string; +} + +/** + * @see TwitchExt.bits + */ +interface TwitchExtBits { + /** + * This function returns a promise which resolves to an array of products available for Bits, + * for the extension, if the context supports Bits in Extensions actions. Otherwise, the + * promise rejects with an error; this can occur, for instance, if the extension is running in + * an older version of the developer rig or the mobile app, which does not support Bits in + * Extensions actions. + * + * @see https://dev.twitch.tv/docs/extensions/bits/#getproducts + */ + getProducts(): Promise>; + + /** + * This function takes a callback that is fired whenever a transaction is cancelled. + * @param callback The callback that is fired whenever a transaction is cancelled. + * + * @see https://dev.twitch.tv/docs/extensions/bits/#ontransactioncancelledcallback + */ + onTransactionCancelled(callback: () => void): void; + + /** + * This function registers a callback that is fired whenever a Bits in Extensions transaction + * is completed. + * @param callback The callback that is fired. + * + * @see https://dev.twitch.tv/docs/extensions/bits/#ontransactioncompletecallbacktransactionobject + */ + onTransactionComplete( + callback: (transaction: TwitchExtBitsTransaction) => void + ): void; + + /** + * This function sets the state of the extension helper, so it does not call live services for + * usage of Bits. Instead, it does a local loopback to the completion handler, after a fixed + * delay to simulate user approval and process latency. + * @param useLoopback Whether to use local looback. + * + * @see https://dev.twitch.tv/docs/extensions/bits/#setuseloopbackboolean + */ + setUseLoopback(useLoopback: boolean): void; + + /** + * Call this function when the viewer hovers over a product in your extension UI, to cause the + * Twitch UI to display a dialog showing the viewer’s Bits balance. + * The dialog displays for 1.5 seconds, unless your extension calls showBitsBalance again, in + * which case the 1.5-second timer resets. + * + * This is a “fire-and-forget” function: the extension developer does not need to tell Twitch + * when the viewer stops hovering over the product. + * + * On mobile, this function is ignored. + * + * @see https://dev.twitch.tv/docs/extensions/bits/#showbitsbalance + */ + showBitsBalance(): void; + + /** + * This function redeems a product with the specified SKU for the number of Bits specified in + * the catalog entry of that product. + * @param sku + * + * @see https://dev.twitch.tv/docs/extensions/bits/#usebitssku + * @see https://dev.twitch.tv/docs/extensions/bits/#exchanging-bits-for-a-product + */ + useBits(sku: string): void; +} + /** * The developer rig object as available under window.Twitch.ext.rig. * @@ -315,6 +490,11 @@ interface TwitchExtClientQueryParams { */ platform: "mobile" | "web"; + /** + * Indicates whether the extension is popped out. + */ + popout: "true" | "false"; + /** * The release state of the extension. */ diff --git a/types/twitch-ext/twitch-ext-tests.ts b/types/twitch-ext/twitch-ext-tests.ts index d981367fd5..f6a70f86cb 100644 --- a/types/twitch-ext/twitch-ext-tests.ts +++ b/types/twitch-ext/twitch-ext-tests.ts @@ -32,8 +32,59 @@ window.Twitch.ext.actions.onFollow((didFollow, channelName) => { console.log(`You followed ${channelName}`); } }); +window.Twitch.ext.actions.minimize(); window.Twitch.ext.actions.followChannel("hearthsim"); window.Twitch.ext.actions.requestIdShare(); +// Twitch Extension Feature flags +window.Twitch.ext.features.onChanged(changed => { + if (changed.indexOf("isChatEnabled") !== -1) { + if (window.Twitch.ext.features.isChatEnabled) { + console.log("Chat is now enabled"); + } + } +}); + +// Twitch Extension Bits +window.Twitch.ext.bits + .getProducts() + .then(products => { + console.log(`Got ${products.length} products`); + for (const product of products) { + console.log( + `Found product "${product.displayName}" with SKU ${product.sku}` + ); + console.log( + `Product costs ${product.cost.amount} ${product.cost.type}` + ); + if (typeof product.inDevelopment !== "undefined") { + if (product.inDevelopment) { + console.log("Product is in development"); + } else { + console.log("Product is not in development"); + } + } else { + console.log(""); + } + } + }) + .catch(error => { + console.error(`Got an error: ${error}`); + }); +window.Twitch.ext.bits.onTransactionCancelled(() => + console.log("Transaction cancelled") +); +window.Twitch.ext.bits.onTransactionComplete(transaction => { + console.log( + `${transaction.initiator} (${transaction.userId}) bought ${ + transaction.product.displayName + }` + ); + console.log(`Transaction id was ${transaction.transactionID}`); +}); +window.Twitch.ext.bits.setUseLoopback(true); +window.Twitch.ext.bits.showBitsBalance(); +window.Twitch.ext.bits.useBits("MY-PRODUCT"); + // Developer Rig window.Twitch.ext.rig.log("Hello, world!"); diff --git a/types/typography/index.d.ts b/types/typography/index.d.ts new file mode 100644 index 0000000000..2c5be43583 --- /dev/null +++ b/types/typography/index.d.ts @@ -0,0 +1,60 @@ +// Type definitions for typography 0.16 +// Project: https://github.com/KyleAMathews/typography.js +// Definitions by: Boye +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +interface BaseLine { + fontSize: string; + lineHeight: string; +} + +export interface VerticalRhythm { + rhythm: (value: number) => string; + scale: (value: number) => object; + adjustFontSizeTo: (value?: number | string) => object; + linesForFontSize: (fontSize: number) => number; + establishBaseline: () => BaseLine; +} + +export interface GoogleFont { + name: string; + styles: string[]; +} + +export interface TypographyOptions { + baseFontSize?: string; + baseLineHeight?: number; + scaleRatio?: number; + googleFonts?: GoogleFont[]; + headerFontFamily?: string[]; + bodyFontFamily?: string[]; + headerColor?: string; + bodyColor?: string; + headerWeight?: number | string; + bodyWeight?: number | string; + boldWeight?: number | string; + blockMarginBottom?: number; + includeNormalize?: boolean; + overrideStyles?: ( + VerticalRhythm: VerticalRhythm, + options: TypographyOptions, + styles: any + ) => object; + overrideThemeStyles?: ( + VerticalRhythm: VerticalRhythm, + options: TypographyOptions, + styles: any + ) => object; + plugins?: any[]; +} + +declare class Typography { + constructor(opts: TypographyOptions); + options: TypographyOptions; + createStyles(): string; + toJSON(): object; + injectStyles(): void; +} + +export default Typography; diff --git a/types/typography/tsconfig.json b/types/typography/tsconfig.json new file mode 100644 index 0000000000..cebfdd1e2b --- /dev/null +++ b/types/typography/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", + "typography-tests.ts" + ] +} diff --git a/types/typography/tslint.json b/types/typography/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/typography/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/typography/typography-tests.ts b/types/typography/typography-tests.ts new file mode 100644 index 0000000000..5b004d2eae --- /dev/null +++ b/types/typography/typography-tests.ts @@ -0,0 +1,12 @@ +import Typography from 'typography'; + +const typography = new Typography({ + baseFontSize: '18px', + baseLineHeight: 1.45, + headerFontFamily: ['Avenir Next', 'Helvetica Neue', 'Segoe UI', 'Helvetica', 'Arial', 'sans-serif'], + bodyFontFamily: ['Georgia', 'serif'] +}); + +typography.createStyles(); // $ExpectType string +typography.toJSON(); // $ExpectType object +typography.options; // $ExpectType TypographyOptions diff --git a/types/uploadcare/index.d.ts b/types/uploadcare/index.d.ts new file mode 100644 index 0000000000..3b3e4e1b09 --- /dev/null +++ b/types/uploadcare/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for uploadcare 0.4 +// Project: https://github.com/rexmorgan/uploadcare-node +// Definitions by: Jinesh Shah +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { ReadStream } from "fs"; + +declare namespace Uploadcare { + interface File { + original_file_url: string; + image_info: ImageInfo; + mime_type: string; + is_ready: boolean; + url: string; + uuid: string; + original_filename: string; + datetime_uploaded: string; + size: number; + is_image: boolean; + datetime_stored: string; + datetime_removed: string | null; + } + + interface ImageInfo { + orientation: null; + sequence: boolean; + format: string; + height: number; + width: number; + geo_location: null; + datetime_original: null; + dpi: number[]; + } + + interface Instance { + file: { + upload: ( + readStream: ReadStream, + options: { store?: boolean }, + callback: (err: Error, res: { file: string }) => void + ) => void; + fromUrl: ( + url: string, + options: { store?: boolean }, + callback: (err: Error, res: File) => void + ) => void; + }; + files: { + store: ( + uuid: string, + callback: (err: Error, res: File) => void + ) => void; + remove: ( + uuid: string, + callback: (err: Error, res: File) => void + ) => void; + }; + } +} + +declare function Uploadcare( + publicKey: string, + privateKey: string +): Uploadcare.Instance; + +export = Uploadcare; diff --git a/types/uploadcare/tsconfig.json b/types/uploadcare/tsconfig.json new file mode 100644 index 0000000000..44810d6b42 --- /dev/null +++ b/types/uploadcare/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "uploadcare-tests.ts"] +} diff --git a/types/uploadcare/tslint.json b/types/uploadcare/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/uploadcare/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/uploadcare/uploadcare-tests.ts b/types/uploadcare/uploadcare-tests.ts new file mode 100644 index 0000000000..295a470691 --- /dev/null +++ b/types/uploadcare/uploadcare-tests.ts @@ -0,0 +1,7 @@ +import * as Uploadcare from "uploadcare"; + +const uploadcare = Uploadcare("", ""); + +uploadcare.file.fromUrl("", {}, (err, res) => { + const file: Uploadcare.File = res; +}); diff --git a/types/validator/index.d.ts b/types/validator/index.d.ts index d51465d1a7..345a02858d 100644 --- a/types/validator/index.d.ts +++ b/types/validator/index.d.ts @@ -177,7 +177,7 @@ declare namespace ValidatorJS { isMultibyte(str: string): boolean; // check if the string contains only numbers. - isNumeric(str: string): boolean; + isNumeric(str: string, options?: IsNumericOptions): boolean; // check if the string is a valid port number. isPort(str: string): boolean; @@ -380,6 +380,13 @@ declare namespace ValidatorJS { icloud_lowercase?: boolean; icloud_remove_subaddress?: boolean; } + + /** + * Options for isNumeric + */ + interface IsNumericOptions { + no_symbols?: boolean; + } } /** diff --git a/types/validator/validator-tests.ts b/types/validator/validator-tests.ts index 784528d963..b939cfd0cb 100644 --- a/types/validator/validator-tests.ts +++ b/types/validator/validator-tests.ts @@ -565,6 +565,7 @@ let any: any; result = validator.isMultibyte('sample'); result = validator.isNumeric('sample'); + result = validator.isNumeric('+358', { no_symbols: true }); result = validator.isPort('sample'); diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index db3697b65a..09f9b28d0d 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -8,6 +8,7 @@ // Grzegorz Błaszczyk // Stéphane Roucheray // Adam Eisenreich +// Mei Qingguang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -32,7 +33,7 @@ * @return A player instance */ declare function videojs(id: any, options?: videojs.PlayerOptions, ready?: () => void): videojs.Player; -export = videojs; +export default videojs; export as namespace videojs; declare namespace videojs { @@ -4379,7 +4380,7 @@ declare namespace videojs { * * @fires Player#fullscreenchange */ - requestFullScreen(): Player; + requestFullscreen(): Player; /** * Report user activity @@ -4395,6 +4396,20 @@ declare namespace videojs { */ reset(): void; + /** + * Returns whether or not the player is in the "seeking" state. + * + * @return boolean True if the player is in the seeking state, false if not. + */ + seeking(): boolean; + + /** + * Returns the TimeRanges of the media that are currently available for seeking to. + * + * @return TimeRanges Returns the TimeRanges of the media that are currently available for seeking to. + */ + seekable(): TimeRanges; + /** * Select source based on tech-order or source-order * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise, diff --git a/types/video.js/video.js-tests.ts b/types/video.js/video.js-tests.ts index 814aec9edd..378a7150f3 100644 --- a/types/video.js/video.js-tests.ts +++ b/types/video.js/video.js-tests.ts @@ -1,4 +1,4 @@ -import * as videojs from 'video.js'; +import videojs from 'video.js'; videojs("example_video_1").ready(function() { // EXAMPLE: Start playing the video. @@ -57,7 +57,7 @@ videojs("example_video_1").ready(function() { this.height(480); - this.requestFullScreen(); + this.requestFullscreen(); testEvents(this); diff --git a/types/web3/eth/index.d.ts b/types/web3/eth/index.d.ts index d69b561a63..d31c334598 100644 --- a/types/web3/eth/index.d.ts +++ b/types/web3/eth/index.d.ts @@ -125,6 +125,7 @@ export default interface Eth { getProtocolVersion(cb?: Callback): Promise; getStorageAt( address: string, + position: number | BigNumber, defaultBlock?: BlockType, cb?: Callback ): Promise; diff --git a/types/web3/index.d.ts b/types/web3/index.d.ts index 9ddbc7a00b..9be7c33c48 100644 --- a/types/web3/index.d.ts +++ b/types/web3/index.d.ts @@ -43,7 +43,7 @@ declare class Web3 { bzz: Bzz; currentProvider: Provider; eth: Eth; - ssh: Shh; + shh: Shh; givenProvider: Provider; providers: Providers; setProvider(provider: Provider): void; diff --git a/types/web3/types.d.ts b/types/web3/types.d.ts index 4690b37e2b..c2b906c875 100644 --- a/types/web3/types.d.ts +++ b/types/web3/types.d.ts @@ -85,5 +85,12 @@ export interface Subscribe { on(type: "error", handler: (data: Error) => void): void; } -export class Shh {} // TODO: Type +export interface Shh { + generateSymKeyFromPassword(password: string): Promise; + generateSymKeyFromPassword( + password: string, + callback: Callback + ): void; + // TODO: type every method +} export class Bzz {} // TODO: Type diff --git a/types/web3/utils.d.ts b/types/web3/utils.d.ts index 659110faa6..a10ca39e01 100644 --- a/types/web3/utils.d.ts +++ b/types/web3/utils.d.ts @@ -29,6 +29,20 @@ type Unit = | "mether" | "gether" | "tether"; + +type Mixed = + | string + | number + | BigNumber + | { + type: string; + value: string; + } + | { + t: string; + v: string; + }; + export default interface Utils { BN: BigNumber; // TODO only static-definition isBN(any: any): boolean; @@ -62,7 +76,7 @@ export default interface Utils { val4?: string, val5?: string ): string; - soliditySha3(val: string): string; + soliditySha3(...val: Mixed[]): string; randomHex(bytes: number): string; stringToHex(val: string): string; toAscii(hex: string): string; diff --git a/types/web3/web3-tests.ts b/types/web3/web3-tests.ts index fc4be8534a..9498f8df69 100644 --- a/types/web3/web3-tests.ts +++ b/types/web3/web3-tests.ts @@ -5,9 +5,11 @@ const myProvider = new web3.providers.HttpProvider("http://localhost:5454"); web3.setProvider(myProvider); web3.eth.setProvider(myProvider); +const contractAddress = "0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe"; + const myContract = new web3.eth.Contract( [], - "0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe", + contractAddress, { from: "0x1234567890123456789012345678901234567891", gasPrice: "20000000000" @@ -21,3 +23,6 @@ myContract.options.gas = 5000000; const weiStr: string = web3.utils.toWei("100", "gwei"); const weiBn: BigNumber = web3.utils.toWei(web3.utils.toBN("1")); const rndHex: string = Web3.utils.randomHex(10); +const shhPromise: Promise = web3.shh.generateSymKeyFromPassword("xyz"); +const storage: Promise = web3.eth.getStorageAt(contractAddress, 0); +const sha3: string = web3.utils.soliditySha3(0, 1, "abc"); diff --git a/types/webpack-bundle-analyzer/index.d.ts b/types/webpack-bundle-analyzer/index.d.ts index 6b2db94b65..f1e3f2a3c6 100644 --- a/types/webpack-bundle-analyzer/index.d.ts +++ b/types/webpack-bundle-analyzer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for webpack-bundle-analyzer 2.9 +// Type definitions for webpack-bundle-analyzer 2.13 // Project: https://github.com/th0r/webpack-bundle-analyzer // Definitions by: Michael Strobel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,6 +7,9 @@ import * as webpack from 'webpack'; export namespace BundleAnalyzerPlugin { + type ExcludeAssetsPatternFn = (assetName: string) => boolean; + type ExcludeAssetsPattern = string | RegExp | ExcludeAssetsPatternFn; + interface Options { /** * Can be "server", "static" or "disabled". @@ -68,6 +71,16 @@ export namespace BundleAnalyzerPlugin { */ statsOptions?: null | webpack.Stats.ToJsonOptionsObject; + /** + * Default: `null`. + * Patterns that will be used to match against asset names to exclude them from the report. + * If pattern is a string it will be converted to RegExp via `new RegExp(str)`. + * If pattern is a function it should have the following signature `(assetName: string) => boolean` + * and should return true to exclude matching asset. + * If multiple patterns are provided asset should match at least one of them to be excluded. + */ + excludeAssets?: null | ExcludeAssetsPattern | ExcludeAssetsPattern[]; + /** * Log level. Can be "info", "warn", "error" or "silent". * Defaults to "info" diff --git a/types/webpack-bundle-analyzer/webpack-bundle-analyzer-tests.ts b/types/webpack-bundle-analyzer/webpack-bundle-analyzer-tests.ts index 0b5fcabcc7..7aa2b0aee7 100644 --- a/types/webpack-bundle-analyzer/webpack-bundle-analyzer-tests.ts +++ b/types/webpack-bundle-analyzer/webpack-bundle-analyzer-tests.ts @@ -19,6 +19,11 @@ const config: webpack.Configuration = { statsOptions: { source: false }, + excludeAssets: [ + 'foo', + /foo/, + assetName => assetName.indexOf('foo') !== -1 + ], logLevel: 'info' }) ] diff --git a/types/webvr-api/index.d.ts b/types/webvr-api/index.d.ts index 3d03a14d4b..a285d968b2 100644 --- a/types/webvr-api/index.d.ts +++ b/types/webvr-api/index.d.ts @@ -133,8 +133,8 @@ declare var VRDisplay: { }; interface VRLayer { - leftBounds?: number[] | null; - rightBounds?: number[] | null; + leftBounds?: number[] | Float32Array | null; + rightBounds?: number[] | Float32Array | null; source?: HTMLCanvasElement | null; } diff --git a/types/wegame-api/index.d.ts b/types/wegame-api/index.d.ts index fcddd82a32..18480ed2ea 100644 --- a/types/wegame-api/index.d.ts +++ b/types/wegame-api/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for wegame 1.1 +// Type definitions for wegame 2.2 // Project: https://developers.weixin.qq.com/minigame/dev/index.html // Definitions by: J.C // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -59,7 +59,7 @@ declare class Canvas { * @param contextType 上下文类型 * @param contextAttributes webgl 上下文属性,仅当 contextType 为 webgl 时有效 */ - getContext(contextType: "2d" | "webgl", contextAttributes: wx.types.RenderingContextConfig): WxRenderingContext | WxWebGLRenderingContext; + getContext(contextType: "2d" | "webgl", contextAttributes?: wx.types.RenderingContextConfig): WxRenderingContext | WxWebGLRenderingContext; /** * 把画布上的绘制内容以一个 data URI 的格式返回 */ @@ -404,7 +404,7 @@ declare class FeedbackButton extends CreatedButton { declare class OpenDataContext { /** - * 开放数据域和主域共享的 sharedCanvas + * 开放数据域和主域共享的 sharedCanvas,注意在开放数据域内时getContext只能使用2d模式 */ canvas: Canvas; /** @@ -1042,7 +1042,7 @@ declare namespace wx { complete?: () => void; } - type FileContentEncoding = "ascii" | "base64" | "binary" | "hex" | "ucs2/ucs-2/utf16le/utf-16le" | "utf-8/utf8" | "latin1"; + type FileContentEncoding = "ascii" | "base64" | "binary" | "hex" | "ucs2" | "ucs-2" | "utf16le" | "utf-16le" | "utf-8" | "utf8" | "latin1"; interface ReadfileParams { filePath: string; @@ -1079,7 +1079,7 @@ declare namespace wx { zipFilePath: string; targetPath: string; success?: () => void; - fail?: () => void; + fail?: (e?: any) => void; complete?: () => void; } @@ -1153,6 +1153,7 @@ declare namespace wx { width: number; height: number; onload: () => void; + onerror: (e?: any) => void; } // --启动参数 @@ -1317,11 +1318,11 @@ declare namespace wx { interface DownfileParams { url: string; + filePath: string; /** * HTTP 请求的 Header,Header 中不能设置 Referer */ - header: { [key: string]: string }; - filePath: string; + header?: { [key: string]: string }; success?: (res: { tempFilePath: string, statusCode: number }) => void; fail?: () => void; complete?: () => void; @@ -1355,7 +1356,7 @@ declare namespace wx { /** * res.data usually can be string or ArrayBuffer */ - success?: (res: { data: any, statusCode: number, header: { [key: string]: string } }) => void; + success?: (res: { data: any, statusCode: number, header?: { [key: string]: string } }) => void; fail?: () => void; complete?: () => void; } @@ -1389,7 +1390,7 @@ declare namespace wx { complete?: () => void; } - type SocketOpenCallback = (res: { header: { [key: string]: string } }) => void; + type SocketOpenCallback = (res: { header?: { [key: string]: string } }) => void; type SocketMessageCallback = (res: { data: string | ArrayBuffer }) => void; type SocketErrorCallback = (res: { errMsg: string }) => void; @@ -1566,7 +1567,7 @@ declare namespace wx { */ imageUrl?: string; /** - * 查询字符串,必须是 key1=val1&key2=val2 的格式。从这条转发消息进入后,可通过 wx.onLaunch() 或 wx.onShow 获取启动参数中的 query。 + * 查询字符串,必须是 key1=val1&key2=val2 的格式。从这条转发消息进入后,可通过 wx.getLaunchOptionsSync() 或 wx.onShow 获取启动参数中的 query。 */ query?: string; } @@ -1802,6 +1803,16 @@ declare namespace wx { // --文件系统 function getFileSystemManager(): FileSystemManager; + /** + * 系统环境变量 + */ + const env: { + /** + * 用户下载数据根目录 + */ + USER_DATA_PATH: string + }; + // --位置 /** * 获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用;当用户点击“显示在聊天顶部”时,此接口可继续调用。 @@ -2208,15 +2219,15 @@ declare namespace wx { /** * 监听用户点击右上角菜单的“转发”按钮时触发的事件 */ - function onShareAppMessage(cb: (data: types.ShareOption) => void): void; + function onShareAppMessage(cb: () => types.ShareOption): void; /** * 取消监听用户点击右上角菜单的“转发”按钮时触发的事件 */ - function offShareAppMessage(cb: (data: types.ShareOption) => void): void; + function offShareAppMessage(cb: () => types.ShareOption): void; /** * 显示当前页面的转发按钮 */ - function showShareMenu(param: { + function showShareMenu(param?: { /** * 是否使用带 shareTicket 的转发 */ diff --git a/types/wegame-api/wegame-api-tests.ts b/types/wegame-api/wegame-api-tests.ts index 88ad8fe1c3..a52f78ec9b 100644 --- a/types/wegame-api/wegame-api-tests.ts +++ b/types/wegame-api/wegame-api-tests.ts @@ -404,10 +404,12 @@ wx.getShareInfo({ } }); wx.hideShareMenu(); -wx.onShareAppMessage(res => { - res.imageUrl != null; - res.query != null; - res.title != null; +wx.onShareAppMessage((): wx.types.ShareOption => { + return { + imageUrl: "test.png", + title: "test title", + query: "__shareQueryStr" + }; }); wx.showShareMenu({ withShareTicket: true diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index ecdbd1e486..908ba026bd 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for wx-app 1.9 +// Type definitions for wx-app 2.2 // Project: https://mp.weixin.qq.com/debug/wxadoc/dev/api/ // Definitions by: taoqf // AlexStacker @@ -7,3556 +7,4117 @@ // TypeScript Version: 2.8 declare namespace wx { - // #region 基本参数 - interface DataResponse { - /** 回调函数返回的内容 */ - data: object | string | ArrayBuffer; - /** 开发者服务器返回的 HTTP 状态码 */ - statusCode: number; - /** 开发者服务器返回的 HTTP Response Header */ - header: object; - } - interface ErrMsgResponse { - /** 成功:ok,错误:详细信息 */ - errMsg: "ok" | string; - } - interface TempFileResponse { - /** 文件的临时路径 */ - tempFilePath: string; - } - interface BaseOptions { - /** 接口调用成功的回调函数 */ - success?(res: any): void; - /** 接口调用失败的回调函数 */ - fail?(res: any): void; - /** 接口调用结束的回调函数(调用成功、失败都会执行) */ - complete?(res: any): void; - } - // #endregion - // #region 网络API列表 - // 发起请求 - interface RequestHeader { - [key: string]: string; - } - interface RequestOptions extends BaseOptions { - /** 开发者服务器接口地址 */ - url: string; - /** 请求的参数 */ - data?: string | object | ArrayBuffer; - /** 设置请求的 header , header 中不能设置 Referer */ - header?: RequestHeader; - /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ - method?: - | "GET" - | "OPTIONS" - | "GET" - | "HEAD" - | "POST" - | "PUT" - | "DELETE" - | "TRACE" - | "CONNECT"; - /** 如果设为json,会尝试对返回的数据做一次 JSON.parse */ - dataType?: string; - /** - * 设置响应的数据类型。合法值:text、arraybuffer - * @version 1.7.0 - */ - responseType?: string; - /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ - success?(res: DataResponse): void; - } - /** - * wx.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 - */ - function request(options: RequestOptions): RequestTask; + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: object | string | ArrayBuffer; + /** 开发者服务器返回的 HTTP 状态码 */ + statusCode: number; + /** 开发者服务器返回的 HTTP Response Header */ + header: object; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + tempFilePath: string; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion + // #region 网络API列表 + // 发起请求 + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 开发者服务器接口地址 */ + url: string; + /** 请求的参数 */ + data?: string | object | ArrayBuffer; + /** 设置请求的 header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: + | "GET" + | "OPTIONS" + | "GET" + | "HEAD" + | "POST" + | "PUT" + | "DELETE" + | "TRACE" + | "CONNECT"; + /** 如果设为json,会尝试对返回的数据做一次 JSON.parse */ + dataType?: string; + /** + * 设置响应的数据类型。合法值:text、arraybuffer + * @version 1.7.0 + */ + responseType?: string; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + } + /** + * wx.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 + */ + function request(options: RequestOptions): RequestTask; - /** - * 返回一个 requestTask 对象,通过 requestTask,可中断请求任务。 - */ - interface RequestTask { - abort(): void; - } + /** + * 返回一个 requestTask 对象,通过 requestTask,可中断请求任务。 + */ + interface RequestTask { + abort(): void; + } - interface UploadTask { - /** - * 监听上传进度变化 - * @version 1.4.0 - */ - onProgressUpdate( - callback?: ( - res: { - /** 上传进度百分比 */ - progress: number; - /** 已经上传的数据长度,单位 Bytes */ - totalBytesSent: number; - /** 预期需要上传的数据总长度,单位 Bytes */ - totalBytesExpectedToSend: number; - } - ) => void - ): void; - /** - * 中断下载任务 - * @version 1.4.0 - */ - abort(): void; - } - // 上传下载 - interface UploadFileOptions extends BaseOptions { - /** 开发者服务器 url */ - url: string; - /** 要上传文件资源的路径 */ - filePath: string; - /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ - name: string; - /** HTTP 请求 Header , header 中不能设置 Referer */ - header?: RequestHeader; - /** HTTP 请求中其他额外的 form data */ - formData?: any; - } - /** - * 将本地资源上传到开发者服务器。 - * 如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后, - * 可通过此接口将本地资源上传到指定服务器。 - * 客户端发起一个 HTTPS POST 请求, - * 其中 Content-Type 为 multipart/form-data 。 - */ - function uploadFile(options: UploadFileOptions): UploadTask; - interface DownloadTask { - /** - * 监听下载进度变化 - * @version 1.4.0 - */ - onProgressUpdate( - callback?: ( - res: { - /** 下载进度百分比 */ - progress: number; - /** 已经下载的数据长度,单位 Bytes */ - totalBytesWritten: number; - /** 预期需要下载的数据总长度,单位 Bytes */ - totalBytesExpectedToWrite: number; - } - ) => void - ): void; - /** - * 中断下载任务 - * @version 1.4.0 - */ - abort(): void; - } - interface DownloadFileOptions extends BaseOptions { - /** 下载资源的 url */ - url: string; - /** 下载资源的类型,用于客户端识别处理,有效值:image/audio/video */ - type?: string; - /** HTTP 请求 Header */ - header?: RequestHeader; - /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ - success?(res: TempFileResponse): void; - } - /** - * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, - * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 - */ - function downloadFile(options: DownloadFileOptions): DownloadTask; - // WebSocket - interface ConnectSocketOptions extends BaseOptions { - /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ - url: string; - /** 请求的数据 */ - data?: any; - /** HTTP Header , header 中不能设置 Referer */ - header?: RequestHeader; - /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ - method?: string; - /** - * 子协议数组 - * @version 1.4.0 - */ - protocols?: string[]; - } - /** - * 创建一个 WebSocket 连接; - * 一个微信小程序同时只能有一个 WebSocket 连接, - * 如果当前已存在一个 WebSocket 连接, - * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 - */ - function connectSocket(options: ConnectSocketOptions): void; - /** 监听WebSocket连接打开事件。 */ - function onSocketOpen(callback: () => void): void; - /** 监听WebSocket错误。 */ - function onSocketError(callback: (error: any) => void): void; - interface SendSocketMessageOptions extends BaseOptions { - /** 需要发送的内容 */ - data: string; - } - /** - * 通过 WebSocket 连接发送数据,需要先 wx.connectSocket, - * 并在 wx.onSocketOpen 回调之后才能发送。 - */ - function sendSocketMessage(options: SendSocketMessageOptions): void; - /** - * 监听WebSocket接受到服务器的消息事件。 - */ - function onSocketMessage(callback: (res: DataResponse) => void): void; - /** - * 关闭WebSocket连接。 - */ - function closeSocket(): void; - /** 监听WebSocket关闭。 */ - function onSocketClose(callback: () => void): void; - // #endregion - // #region 媒体API列表 - // 媒体-----图片 - type ImageSizeType = "original" | "compressed"; - type ImageSourceType = "album" | "camera"; - type VideoSourceType = "album" | "camera"; - type CameraDevice = "front" | "back"; - interface TempFile { - /** 本地文件路径 */ - path: string; - /** 本地文件大小,单位:B */ - size: number; - } - interface TempFilesData { - /** 文件的临时路径 */ - tempFilePaths: string; - /** - * 图片的本地文件列表,每一项是一个 File 对象 - * @version 1.2.0 - */ - tempFiles: TempFile[]; - } - interface ChooseImageOptions extends BaseOptions { - /** 最多可以选择的图片张数,默认9 */ - count?: number; - /** original 原图,compressed 压缩图,默认二者都有 */ - sizeType?: ImageSizeType[]; - /** album 从相册选图,camera 使用相机,默认二者都有 */ - sourceType?: ImageSourceType[]; - /** 成功则返回图片的本地文件路径列表 tempFilePaths */ - success(res: TempFilesData): void; - } - /** - * 从本地相册选择图片或使用相机拍照。 - */ - function chooseImage(options: ChooseImageOptions): void; - interface PreviewImageOptions extends BaseOptions { - /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ - current?: string; - /** 需要预览的图片链接列表 */ - urls: string[]; - } - /** - * 预览图片。 - */ - function previewImage(options: PreviewImageOptions): void; - interface GetImageInfoOptions extends BaseOptions { - /** - * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 - */ - src: string; - } - /** - * 获取图片信息 - */ - function getImageInfo(options: GetImageInfoOptions): void; - interface SaveImageToPhotosAlbumOptions extends BaseOptions { - /** - * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 - */ - filePath: string; - success(res: { errMsg: string }): void; - } - /** - * 保存图片到系统相册。 - * 需要用户授权 scope.writePhotosAlbum - * @version 1.2.0 - */ - function saveImageToPhotosAlbum( - options: SaveImageToPhotosAlbumOptions - ): void; - // 媒体-----录音 - interface StartRecordOptions extends BaseOptions { - /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ - success?(res: TempFileResponse): void; - } - /** - * 开始录音。当主动调用wx.stopRecord, - * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 - * 注:文件的临时路径,在小程序本次启动期间可以正常使用, - * 如需持久保存,需在主动调用wx.saveFile,在小程序下次启动时才能访问得到。 - * @deprecated 1.6.0 - */ - function startRecord(options: StartRecordOptions): void; - interface StopRecordOptions extends BaseOptions { - success?(): void; - } - /** - * 主动调用停止录音。 - */ - function stopRecord(options?: StopRecordOptions): void; - type EncodeBitRate = - | 8000 - | 11025 - | 12000 - | 16000 - | 22050 - | 24000 - | 32000 - | 44100 - | 48000; - interface RecorderManagerStartOptions { - /** - * 指定录音的时长,单位 ms - * 如果传入了合法的 duration - * 在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟) - */ - duration?: number; - /** - * 采样率,有效值 8000/16000/44100 - */ - sampleRate?: number; - /** - * 否 录音通道数,有效值 1/2 - */ - numberOfChannels?: number; - /** - * 编码码率 - * 采样率和码率有一定要求,具体有效值如下: - * 采样率 编码码率 - * + 8000 16000 ~ 48000 - * + 11025 16000 ~ 48000 - * + 12000 24000 ~ 64000 - * + 16000 24000 ~ 96000 - * + 22050 32000 ~ 128000 - * + 24000 32000 ~ 128000 - * + 32000 48000 ~ 192000 - * + 44100 64000 ~ 320000 - * + 48000 64000 ~ 320000 - */ - encodeBitRate: number; - /** 音频格式,有效值 aac/mp3 */ - format: string; - /** - * 指定帧大小,单位 KB - * 传入 frameSize 后,每录制指定帧大小的内容后 - * 会回调录制的文件内容,不指定则不会回调。暂仅支持 mp3 格式。 - */ - frameSize: number; - } - interface OnRecorderManagerStopOptions { - tempFilePath: string; - } - interface OnFrameRecordedOptions { - /** 录音分片结果数据 */ - frameBuffer: ArrayBuffer; - /** 当前帧是否正常录音结束前的最后一帧 */ - isLastFrame: boolean; - } - interface RecorderManager { - /** 开始录音 */ - start(options?: RecorderManagerStartOptions): void; - /** 暂停录音 */ - pause(): void; - /** 继续录音 */ - resume(): void; - /** 停止录音 */ - stop(): void; - /** 录音开始事件 */ - onStart(callback?: () => void): void; - /** 录音暂停事件 */ - onPause(callback?: () => void): void; - /** 录音恢复事件 */ - onResume(callback?: () => void): void; - /** 录音停止事件,会回调文件地址 */ - onStop( - callback?: (options: OnRecorderManagerStopOptions) => void - ): void; - /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ - onFrameRecorded( - callback?: (options: OnFrameRecordedOptions) => void - ): void; - /** 录音错误事件, 会回调错误信息 */ - onError(callback?: (err: ErrMsgResponse) => void): void; - } - /** - * 获取全局唯一的录音管理器 recorderManager - * @version 1.6.0 - */ - function getRecorderManager(): RecorderManager; - // 媒体-----音频播放控制 - interface PlayVoiceOptions extends BaseOptions { - /** 需要播放的语音文件的文件路径 */ - filePath: string; - } - /** - * 开始播放语音,同时只允许一个语音文件正在播放, - * 如果前一个语音文件还没播放完,将中断前一个语音播放。 - * @deprecated 1.6.0 - */ - function playVoice(options: PlayVoiceOptions): void; - /** - * 暂停正在播放的语音。 - * 再次调用wx.playVoice播放同一个文件时,会从暂停处开始播放。 - * 如果想从头开始播放,需要先调用 wx.stopVoice。 - * @deprecated 1.6.0 - */ - function pauseVoice(): void; - /** - * 结束播放语音。 - * @deprecated 1.6.0 - */ - function stopVoice(): void; - // 媒体-----音乐播放控制 - interface BackgroundAudioPlayerState { - /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ - duration: number; - /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ - currentPosition: number; - /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ - status: number; - /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ - downloadPercent: number; - /** 歌曲数据链接,只有在当前有音乐播放时返回 */ - dataUrl: string; - } - interface GetBackgroundAudioPlayerStateOptions extends BaseOptions { - /** 接口调用成功的回调函数 */ - success?(state: BackgroundAudioPlayerState): void; - /** 接口调用失败的回调函数 */ - fail?(): void; - /** 接口调用结束的回调函数(调用成功、失败都会执行) */ - complete?(): void; - } - /** - * 获取音乐播放状态。 - * @deprecated 1.2.0 - */ - function getBackgroundAudioPlayerState( - options: GetBackgroundAudioPlayerStateOptions - ): void; - interface PlayBackgroundAudioOptions extends BaseOptions { - /** 音乐链接 */ - dataUrl: string; - /** 音乐标题 */ - title?: string; - /** 封面URL */ - coverImgUrl?: string; - } - /** - * 播放音乐,同时只能有一首音乐正在播放。 - * @deprecated 1.2.0 - */ - function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; - /** - * 暂停播放音乐。 - * @deprecated 1.2.0 - */ - function pauseBackgroundAudio(options?: PlayBackgroundAudioOptions): void; - interface SeekBackgroundAudioOptions extends BaseOptions { - /** 音乐位置,单位:秒 */ - position: number; - } - /** - * 控制音乐播放进度。 - * @deprecated 1.2.0 - */ - function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; - /** - * 停止播放音乐。 - * @deprecated 1.2.0 - */ - function stopBackgroundAudio(options?: PlayBackgroundAudioOptions): void; - /** - * 监听音乐播放。 - * @deprecated 1.2.0 - */ - function onBackgroundAudioPlay(callback: () => void): void; - /** - * 监听音乐暂停。 - * @deprecated 1.2.0 - */ - function onBackgroundAudioPause(callback: () => void): void; - /** - * 监听音乐停止。 - * @deprecated 1.2.0 - */ - function onBackgroundAudioStop(callback: () => void): void; - interface BackgroundAudioManager { - /** 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 */ - readonly duration: number; - /** 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 */ - readonly currentTime: number; - /** 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 */ - readonly paused: boolean; - /** 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav */ - src: string; - /** 音频开始播放的位置(单位:s) */ - startTime: number; - /** 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲。 是 */ - buffered: number; - /** 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ - title: string; - /** 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ - epname: string; - /** 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ - singer: string; - /** 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ - coverImgUrl: string; - /** 页面链接,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ - webUrl: string; - /** 播放 */ - play(): void; - /** 暂停 */ - pause(): void; - /** 停止 */ - stop(): void; - /** 跳转到指定位置,单位 s */ - seek(position: number): void; - /** 背景音频进入可以播放状态,但不保证后面可以流畅播放 */ - onCanplay(callback?: () => void): void; - /** 背景音频播放事件 */ - onPlay(callback?: () => void): void; - /** 背景音频暂停事件 */ - onPause(callback?: () => void): void; - /** 背景音频停止事件 */ - onStop(callback?: () => void): void; - /** 背景音频自然播放结束事件 */ - onEnded(callback?: () => void): void; - /** 背景音频播放进度更新事件 */ - onTimeUpdate(callback?: () => void): void; - /** 用户在系统音乐播放面板点击上一曲事件(iOS only) */ - onPrev(callback?: () => void): void; - /** 用户在系统音乐播放面板点击下一曲事件(iOS only) */ - onNext(callback?: () => void): void; - /** 背景音频播放错误事件 */ - onError(callback?: () => void): void; - /** 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ - onWaiting(callback?: () => void): void; - } - /** - * 获取全局唯一的背景音频管理器 backgroundAudioManager。 - * @version 1.2.0 - */ - function getBackgroundAudioManager(): BackgroundAudioManager; - // 媒体-----音频组件控制 - /** - * audioContext 通过 audioId 跟一个