diff --git a/.editorconfig b/.editorconfig index 404ff0701c..fc4ed3486f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,5 +5,5 @@ indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true -[{*.json,*.yml,*.ts}] +[{*.json,*.yml,*.ts,*.tsx,*.md}] indent_style = space diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 3fa1deaed3..6477b03f07 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -10,7 +10,7 @@ /types/abstract-leveldown/ @MeirionHughes @danwbyrne /types/acc-wizard/ @cyrilschumacher /types/accept/ @feinoujc -/types/accept-language-parser/ @kampfgnom +/types/accept-language-parser/ @kampfgnom @chatoo2412 /types/accepts/ @bomret @brikou /types/accounting/ @gerich-home @chrisleck /types/ace/ @Diullei @@ -19,7 +19,9 @@ /types/acorn/ @RReverser @e-cloud /types/actioncable/ @zhu1230 @szechyjs /types/actions-on-google/ @joelhegg +/types/active-win/ @BendingBender /types/activedirectory2/ @pasthelod +/types/activestorage/ @cbothner /types/activex-access/ @zspitz /types/activex-adodb/ @zspitz /types/activex-adox/ @zspitz @@ -46,13 +48,16 @@ /types/activex-word/ @zspitz /types/adal-angular/ @unindented @aciccarello /types/add-zero/ @Roaders +/types/adlib/ @Esri @MikeTschudi /types/adm-zip/ @jvilk @abner /types/adone/ @s0m3on3 @maxveres +/types/aes-js/ @federicobond /types/aframe/ @devpaul @bertoritger @twastvedt /types/agenda/ @meirgottlieb @princjef /types/agent-base/ @Shinigami92 /types/aggregate-error/ @BendingBender /types/agora-rtc-sdk/ @menthays +/types/airbnb-prop-types/ @milesj /types/ajv-errors/ @afshawnlotfi /types/ale-url-parser/ @msn0 /types/alertify/ @jjeffery @@ -62,9 +67,12 @@ /types/algoliasearch/ @cbaptiste @haroenv @aherve @samouss @keichinger /types/ali-app/ @taoqf /types/ali-oss/ @ptrdu +/types/all-keys/ @BendingBender +/types/all-property-names/ @BendingBender /types/allure-js-commons/ @zaqqaz /types/almost-equal/ @cmaddalozzo /types/alt/ @Shearerbeard +/types/amap-js-sdk/ @agasbzj /types/amazon-cognito-auth-js/ @scottescue /types/amazon-product-api/ @MattiLehtinen @alien35 /types/amcharts/ @ldrick @@ -155,10 +163,11 @@ /types/animejs/ @A-Babin /types/annyang/ @hisham @theluk /types/ansi/ @Gustavo6046 -/types/ansi-colors/ @rogierschouten +/types/ansi-colors/ @rogierschouten @BendingBender +/types/ansi-colors/v1/ @rogierschouten /types/ansi-escape-sequences/ @aomarks /types/ansi-escapes/ @jacobbubu -/types/ansi-regex/ @mvachhar +/types/ansi-regex/ @mvachhar @ffflorian /types/ansi-styles/ @brynbellomy @plylrnsdy /types/ansicolors/ @balupton /types/antlr4/ @mcchatman8009 @@ -187,8 +196,8 @@ /types/aqb/ @Athenkosi-Mase /types/arangodb/ @pluma /types/arbiter/ @arash16 -/types/arcgis-js-api/v3/ @Esri @bsvensson /types/arcgis-js-api/ @Esri @bsvensson +/types/arcgis-js-api/v3/ @Esri @bsvensson /types/arcgis-rest-api/ @JeffJacobson /types/arcgis-to-geojson-utils/ @JeffJacobson /types/archiver/ @dolanmiu @crevil @@ -198,9 +207,11 @@ /types/argparse/ @arcticwaters @tlaziuk @eps1lon /types/args/ @Slessi /types/argv/ @hookclaw +/types/arr-diff/ @BendingBender /types/arr-union/ @mrmlnc /types/array-find-index/ @samverschueren /types/array-foreach/ @skysteve +/types/array-move/ @BendingBender /types/array-sort/ @DanielMSchmidt /types/array-uniq/ @DanielRosenwasser /types/array-unique/ @CSLTech @@ -212,6 +223,7 @@ /types/ascii-art/ @lukaselmer /types/ascii2mathml/ @RagibHasin /types/asenv/ @remisery +/types/asn1/ @jgeurts /types/asn1js/ @microshine /types/aspnet-identity-pw/ @jt000 /types/assert/ @nicoabie @LinusU @@ -220,7 +232,8 @@ /types/assertsharp/ @brunolm /types/assets-webpack-plugin/ @kryops /types/astring/ @nkappler -/types/async/ @borisyankov @kern0 @Penryn @fenying @pascalmartin +/types/async/ @borisyankov @kern0 @Penryn @fenying @pascalmartin @Dmitri1337 +/types/async-busboy/ @hirochachacha /types/async-cache/ @BendingBender /types/async-lock/ @elisee @afharo @rhymmor /types/async-polling/ @Goldsmith42 @@ -243,16 +256,16 @@ /types/atpl/ @soywiz /types/audiosprite/ @Perlmint /types/auth-header/ @ForbesLindesay -/types/auth0/ @westy92 +/types/auth0/ @westy92 @ianhowe76 @dauledk /types/auth0-angular/ @homesar -/types/auth0-js/v7/ @advancedrei /types/auth0-js/ @adrianchia @mdurrant @peterblazejewicz +/types/auth0-js/v7/ @advancedrei /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 +/types/autobahn/ @darkl @a904guy @valepu @glenroy37 /types/autolinker/ @leonyu /types/autoprefixer/ @odnamrataizem @murt /types/autosize/ @kingdango @keika299 @NeekSandhu @@ -260,11 +273,12 @@ /types/await-timeout/ @szhu /types/awesomplete/ @webbiesdk @bmdixon @tbekolay @chrislopresto /types/aws-iot-device-sdk/ @niik @mlamp -/types/aws-lambda/ @skarum @tobyhede @buggy @y13i @wwwy3y3 @OrthoDex @MichaelMarner @daniel-cottone @kostya-misura @coderbyheart @palmithor @daniloraisi @simonbuchan @Haydabase @repl-chris @aneilbaboo @jeznag @louislarry @dpapukchiev @ohookins @trevor-leach @jagregory +/types/aws-lambda/ @skarum @tobyhede @buggy @y13i @wwwy3y3 @OrthoDex @MichaelMarner @daniel-cottone @kostya-misura @coderbyheart @palmithor @daniloraisi @simonbuchan @Haydabase @repl-chris @aneilbaboo @jeznag @louislarry @dpapukchiev @ohookins @trevor-leach @jagregory @dalen /types/aws-serverless-express/ @threesquared @jcaffey @mattmeye @albertovasquez /types/aws4/ @ajcrites /types/axe-webdriverjs/ @JoshuaKGoldberg /types/axel/ @ruslan-molodyko +/types/axios-case-converter/ @dkniffin /types/axios-token-interceptor/ @innovation-team /types/axon/ @jewbre /types/azure/ @AndrewGaspar @antiveeranna @SomaticIT @@ -303,15 +317,19 @@ /types/backo2/ @Retsam /types/backoff/ @BendingBender /types/baconjs/ @alexander-matsievsky @gekkio +/types/badgen/ @m5d215 /types/bagpipes/ @micmro /types/baidu-app/ @taoqf +/types/bandagedbd__bdapi/ @Acidic9 /types/barbellweights/ @evelijn /types/barcode/ @pvomhoff /types/bardjs/ @TepigMC /types/base-64/ @dolanmiu -/types/base-x/ @chrootsu +/types/base-x/ @chrootsu @BendingBender +/types/base-x/v1/ @chrootsu /types/base16/ @alechill /types/base64-arraybuffer/ @jbencook +/types/base64-async/ @BendingBender /types/base64-js/ @pe8ter /types/base64-url/ @urish /types/base64topdf/ @lucasriondel @@ -320,12 +338,14 @@ /types/basic-auth/ @moonpyk @vesse /types/basicauth-middleware/ @nchaulet /types/batch-stream/ @drudge +/types/battery-level/ @BendingBender /types/bazinga-translator/ @alexndlm /types/bcrypt/ @codeanimal @IOAyman @dstapleton92 /types/bcryptjs/ @RafaelKr @branoholy /types/bdfjs/ @jeremejevs /types/beats/ @urish /types/bech32/ @micksatana +/types/beeper/ @BendingBender /types/behavior3/ @carrrywu /types/bell/ @SimonSchick /types/bem-cn/ @selkinvitaly @@ -333,7 +353,7 @@ /types/better-curry/ @pocesar /types/better-queue/ @maozedong /types/better-scroll/ @stoneChen @cnjack -/types/better-sqlite3/ @Morfent @matrumz @sant123 +/types/better-sqlite3/ @Morfent @matrumz @sant123 @loghorn @andykais /types/bezier-easing/ @ptlis /types/bezier-js/ @danmarshall @Epskampie /types/bgiframe/ @sumegizoltan @@ -344,7 +364,9 @@ /types/bignum/ @Patman64 /types/bigscreen/ @dduugg /types/bin-pack/ @orentrutner +/types/bin-version/ @BendingBender /types/binary-parser/ @riggs @dolanmiu @yuhr +/types/binaryextensions/ @BendingBender /types/bind-ponyfill/ @skysteve /types/bindings/ @unindented /types/bintrees/ @CjS77 @@ -372,24 +394,25 @@ /types/bloom-filter/ @danwbyrne /types/bloomfilter/ @slawiko /types/blue-tape/ @sodatea -/types/bluebird/v1/ @Bartvds -/types/bluebird/v2/ @Bartvds @falsandtru /types/bluebird/ @lhecker +/types/bluebird/v2/ @Bartvds @falsandtru +/types/bluebird/v1/ @Bartvds /types/bluebird-global/ @d-ph /types/bluebird-retry/ @pvomhoff /types/blueimp-md5/ @rmartone @mkohlmyr -/types/bn.js/ @LogvinovLeon @HenryNguyen5 +/types/bn.js/ @LogvinovLeon @HenryNguyen5 @Gilthoniel /types/body-parser/ @santialbo @vilic @dreampulse @blendsdk @tlaziuk @jwalton /types/body-parser-xml/ @tbounsiar +/types/body-scroll-lock/ @kimcoder /types/bonjour/ @quentin-ol @octo-sniffle /types/bookshelf/ @arcticwaters @vesse -/types/boom/v3/ @rogatty -/types/boom/v4/ @rogatty @AJamesPhillips @jineshshah36 @danielmachado /types/boom/ @rogatty @AJamesPhillips @jineshshah36 @TimonVS @danielmachado +/types/boom/v4/ @rogatty @AJamesPhillips @jineshshah36 @danielmachado +/types/boom/v3/ @rogatty /types/bootbox/ @vbortone @konpikwastaken @kanup @icereed @trodi @stannynuytkens @renjfk /types/bootpag/ @rdeneau -/types/bootstrap/v3/ @borisyankov @denisname /types/bootstrap/ @denisname +/types/bootstrap/v3/ @borisyankov @denisname /types/bootstrap-3-typeahead/ @AndersonFriaca /types/bootstrap-datepicker/ @borisyankov /types/bootstrap-fileinput/ @CheCoxshall @@ -406,11 +429,12 @@ /types/bootstrap-validator/ @BradyLiles /types/bootstrap.paginator/ @derikwhittaker /types/bootstrap.timepicker/ @derikwhittaker @heatherbooker -/types/bootstrap.v3.datetimepicker/v3/ @bayitajesi /types/bootstrap.v3.datetimepicker/ @katonap +/types/bootstrap.v3.datetimepicker/v3/ @bayitajesi /types/bootstrap3-dialog/ @nakupanda @cnboland /types/bounce.js/ @cherrry /types/box2d/ @jbaldwin +/types/boxen/ @BendingBender /types/bpmn-moddle/ @haydos89 /types/brace-expansion/ @BendingBender /types/braces/ @vemoo @@ -430,11 +454,15 @@ /types/browser-sync/ @joeskeen @aznnomness /types/browserify/ @AndrewGaspar @jvilk @leonard-thieu @LinusU /types/browserslist/ @davecardwell -/types/bs58/ @chrootsu +/types/browserslist-useragent/ @nju33 +/types/bs58/ @chrootsu @BendingBender +/types/bs58/v3/ @chrootsu /types/bson/ @horiuchi @CaselIT -/types/btoa/ @johngeorgewright +/types/btoa/ @johngeorgewright @bricka +/types/buble/ @Kocal /types/bucks/ @zaneli /types/buffer-compare/ @chrootsu +/types/buffer-crc32/ @BendingBender /types/buffer-equal/ @Bartvds /types/buffer-from/ @burnnat /types/buffer-reader/ @nrlquaker @@ -442,8 +470,8 @@ /types/buffers/ @rhencke /types/bufferstream/ @Bartvds /types/builtin-modules/ @ajafff -/types/bull/v2/ @bgrieder @JProgrammer /types/bull/ @bgrieder @JProgrammer @marshall007 @weeco @blaugold @iamolegga @koblas @bondz @wuha-team @aleccool213 @danmana @kjellmorten @pc-jedi +/types/bull/v2/ @bgrieder @JProgrammer /types/bump-regex/ @silkentrance /types/bunnymq/ @cyrilschumacher /types/bunyan/ @amikhalev @@ -462,7 +490,9 @@ /types/bytewise/ @danwbyrne /types/c3/ @mcliment @gerinjacob @denyo @dmitryshindin @timn /types/cache-manager/ @GausSim +/types/cacheable-request/ @BendingBender /types/cached-path-relative/ @TeamworkGuy2 +/types/cadesplugin/ @Delagen @kmvi /types/cal-heatmap/ @RetroChrisB /types/caller/ @ignocide /types/callsite/ @newclear @@ -487,16 +517,17 @@ /types/cash/ @akvlko /types/casperjs/ @jedmao @urielch /types/cassandra-driver/ @Svjard @pc-jedi -/types/catbox/v7/ @jasonswearingen @AJamesPhillips /types/catbox/ @jasonswearingen @AJamesPhillips @saboya +/types/catbox/v7/ @jasonswearingen @AJamesPhillips /types/catbox-memory/ @SimonSchick /types/catbox-redis/ @SimonSchick /types/cbor/ @pushplay /types/ccap/ @taoqf /types/cesium/ @Zuzon @hnipps @szechyjs @golyalpha /types/cfn-response/ @ivoisbelongtous -/types/chai/v2/ @Bartvds @AGBrown /types/chai/ @jedmao @Bartvds @AGBrown @olivr70 @mwistrand @joshuakgoldberg @shaunluttin @Naktibalda @micksatana @ErikSchierboom +/types/chai/v2/ @Bartvds @AGBrown +/types/chai-almost/ @kclnn /types/chai-arrays/ @clementprevot /types/chai-as-promised/ @jt000 @Kuniwak @leonard-thieu @lazerwalker @mattbishop /types/chai-datetime/ @cliffburger @mattbishop @@ -516,6 +547,7 @@ /types/chai-uuid/ @harm-less /types/chai-webdriverio/ @sherlock1982 /types/chai-xml/ @jedigo +/types/chalk-animation/ @BendingBender /types/chance/ @cbowdon @brikou @cafesanu /types/change-emitter/ @iskandersierra /types/chardet/ @Gebatzens @@ -537,23 +569,27 @@ /types/chordsheetjs/ @adamsbloom /types/chosen-js/ @borisyankov @denisname /types/chownr/ @BendingBender -/types/chroma-js/v0/ @invliD /types/chroma-js/ @invliD @mpacholec -/types/chrome/ @matthewkimber @otiai10 @couven92 @rreverser @sreimer15 +/types/chroma-js/v0/ @invliD +/types/chrome/ @matthewkimber @otiai10 @couven92 @rreverser @sreimer15 @MatCarlson /types/chrome-apps/ @niikoo @AdamLay @pine613 @mzsm @RReverser @pyle @matthewkimber @otiai10 @couven92 @rreverser @sreimer15 /types/chromecast-caf-receiver/ @craigrbruce /types/chromecast-caf-sender/ @samuelmaddock /types/chromedriver/ @pe8ter /types/circuit-breaker-js/ @DeTeam /types/circular-json/ @jpevarnek -/types/ckeditor/v2/ @wittwert /types/ckeditor/ @wittwert @stuartlong @viktorpegy +/types/ckeditor/v2/ @wittwert +/types/ckeditor__ckeditor5-core/ @denisname +/types/ckeditor__ckeditor5-engine/ @denisname /types/ckeditor__ckeditor5-utils/ @denisname /types/clamp-js/ @Hikariii /types/clamp-js-main/ @sinziananicolae /types/classnames/ @adidahiya @JKillian @seansfkelley @mradamczyk @marvinhagemeister /types/cldrjs/ @RamanBut-Husaim @gcastre -/types/clean-css/ @tkrotoff +/types/clean-css/ @tkrotoff @GolaWaya +/types/clean-css/v3/ @tkrotoff +/types/clean-regexp/ @BendingBender /types/clean-stack/ @BendingBender /types/clean-webpack-plugin/ @j-f1 /types/clear-require/ @dan-j @@ -563,10 +599,13 @@ /types/cleave.js/ @clentfort @jasongi-at-sportsbet @sashashakun /types/cli/ @kayahr /types/cli-box/ @athasach +/types/cli-boxes/ @BendingBender /types/cli-color/ @ChaosinaCan +/types/cli-cursor/ @BendingBender /types/cli-interact/ @ffflorian /types/cli-progress/ @mhegazy /types/cli-spinner/ @janslow +/types/cli-spinners/ @BendingBender /types/cli-table/ @arylo /types/cli-table2/ @mgroenhoff /types/cli-truncate/ @danwbyrne @@ -584,6 +623,7 @@ /types/closure-compiler/ @mprobst /types/cloud-env/ @Morfent /types/cloudflare-apps/ @MartynasZilinskas +/types/clovelced-plugin-audiomanagement/ @marckassay /types/cls-hooked/ @aleung /types/clusterize.js/ @Pr1st0n /types/cmd-shim/ @cspotcode @@ -594,17 +634,20 @@ /types/codependency/ @morphatic /types/coffeeify/ @tkQubo /types/coinbase/ @rogierschouten +/types/coinlist/ @BendingBender /types/coinstring/ @mhegazy /types/collections/ @scarabedore -/types/color/v0/ @LKay -/types/color/v1/ @LKay -/types/color/v2/ @Airlun /types/color/ @Airlun @jameswlane +/types/color/v2/ @Airlun +/types/color/v1/ @LKay +/types/color/v0/ @LKay /types/color-convert/ @Airlun +/types/color-diff/ @katsanva /types/color-name/ @Ailrun /types/color-namer/ @in19farkt /types/color-string/ @BendingBender @danmarshall /types/colorbrewer/ @mtraynham +/types/colornames/ @manuth /types/colresizable/ @gilleswaeber /types/com.darktalker.cordova.screenshot/ @akarienta /types/com.wikitude.phonegap.wikitudeplugin/ @zbarbuto @@ -613,8 +656,8 @@ /types/combokeys/ @iclanton /types/cometd/ @derekcicerone @unindented @alxHenry /types/command-exists/ @BendingBender -/types/command-line-args/v4/ @CzBuCHi @75lb /types/command-line-args/ @75lb +/types/command-line-args/v4/ @CzBuCHi @75lb /types/command-line-commands/ @CzBuCHi /types/command-line-usage/ @matrumz @Dvorsky /types/commangular/ @hiraash @@ -633,13 +676,14 @@ /types/compose-function/ @denis-sokolov /types/compressible/ @BendingBender /types/compression/ @santialbo @rburgt -/types/compression-webpack-plugin/ @dublicator +/types/compression-webpack-plugin/ @dublicator @rhys-vdw /types/compute-quantile/ @mrmlnc /types/compute-stdev/ @mrmlnc /types/concat-stream/ @jmarianer /types/concaveman/ @DenisCarriere -/types/conf/v0/ @SamVerschueren /types/conf/ @SamVerschueren @BendingBender +/types/conf/v1/ @SamVerschueren @BendingBender +/types/conf/v0/ @SamVerschueren /types/confidence/ @jppellerin /types/config/ @RWander @forrestbice @jndonald3 @albertovasquez /types/config-yaml/ @me @@ -666,7 +710,9 @@ /types/console-ui/ @dfreeman /types/consolidate/ @soywiz @theosherry @nicolashenry /types/consul/ @chrootsu +/types/contains-path/ @BendingBender /types/content-disposition/ @bomret +/types/content-range/ @bricka /types/content-type/ @horiuchi @BendingBender /types/contentful-resolve-response/ @antonkarsten /types/contextjs/ @kernhanda @@ -682,14 +728,16 @@ /types/cookie_js/ @slawiko /types/cookiejar/ @paroxp /types/cookies/ @WangZishi @jkeylu @BendingBender +/types/copy/ @ffflorian /types/copy-paste/ @SrTobi /types/copy-text-to-clipboard/ @BendingBender /types/copy-webpack-plugin/ @flying-sheep +/types/copyfiles/ @ffflorian /types/cordova-ionic/ @hendrikmaus /types/cordova-plugin-app-version/ @Ritzlgrmft /types/cordova-plugin-background-mode/ @Lordnoname /types/cordova-plugin-badge/ @timbru31 -/types/cordova-plugin-ble-central/ @gjunge +/types/cordova-plugin-ble-central/ @gjunge @peitschie /types/cordova-plugin-bluetoothclassic-serial/ @tuvokki /types/cordova-plugin-canvascamera/ @lordazzi /types/cordova-plugin-device-name/ @larrybahr @@ -712,15 +760,16 @@ /types/core-object/ @dfreeman /types/correlation-id/ @natemara /types/cors/ @pluma -/types/cosmiconfig/v4/ @ozum /types/cosmiconfig/ @ozum @szeck87 @saadq @jinwoo +/types/cosmiconfig/v4/ @ozum /types/cote/ @makepost @roblabat /types/couchbase/ @maouida @fluggo /types/countdown/ @gjuchault /types/counterpart/ @santiagodoldan /types/countries-and-timezones/ @zero51 -/types/country-list/v1/ @iRoachie +/types/country-data/ @biltongza /types/country-list/ @iRoachie @Kimahriman +/types/country-list/v1/ @iRoachie /types/country-select-js/ @humrochagf /types/countup.js/ @shermendev /types/coverup/ @bevalorous @@ -733,6 +782,7 @@ /types/create-error/ @tkrotoff /types/create-hash/ @BendingBender /types/create-hmac/ @BendingBender +/types/create-html-element/ @BendingBender /types/create-react-class/ @jgoz /types/create-subscription/ @Asana @vsiao /types/createjs/ @evilangelist @gyohk @@ -749,6 +799,7 @@ /types/crpc/ @0xdeafcafe /types/crumb/ @lenovouser @SimonSchick /types/cryptiles/ @awendland +/types/crypto-hash/ @BendingBender /types/crypto-js/ @misak113 /types/crypto-random-string/ @MrManny /types/cryptojs/ @giabao @@ -771,20 +822,24 @@ /types/csv2json/ @dex4er /types/csvrow/ @codeanimal /types/csvtojson/ @EricByers @wcarson -/types/cucumber/v1/ @abraaoalves @jan-molak @isoung @BendingBender -/types/cucumber/v3/ @abraaoalves @jan-molak @isoung @BendingBender @ErikSchierboom /types/cucumber/ @abraaoalves @jan-molak @isoung @BendingBender @ErikSchierboom +/types/cucumber/v3/ @abraaoalves @jan-molak @isoung @BendingBender @ErikSchierboom +/types/cucumber/v1/ @abraaoalves @jan-molak @isoung @BendingBender /types/currency-formatter/ @mhegazy @davidmpaz /types/custom-error-generator/ @thmiceli -/types/custom-functions-runtime/ @OfficeDev @Zlatkovsky @mscharlock +/types/custom-functions-runtime/ @OfficeDev @akrantz @Zlatkovsky @mscharlock +/types/cwd/ @BendingBender /types/cwise/ @taoqf /types/cwise-compiler/ @taoqf /types/cwise-parser/ @taoqf /types/cybozulabs-md5/ @pine613 +/types/cycled/ @BendingBender +/types/cypress-axe/ @wKovacs64 /types/cytoscape/ @phreed @wy193777 @ypconstante @janniclas @cerberuser -/types/d3/v3/ @gustavderdrache @borisyankov @MatthiasJobst -/types/d3/v4/ @tomwanzek @gustavderdrache @borisyankov @denisname +/types/d/ @BendingBender /types/d3/ @tomwanzek @gustavderdrache @borisyankov @denisname +/types/d3/v4/ @tomwanzek @gustavderdrache @borisyankov @denisname +/types/d3/v3/ @gustavderdrache @borisyankov @MatthiasJobst /types/d3-array/ @gustavderdrache @borisyankov @tomwanzek @denisname /types/d3-axis/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-box/ @lk-chen @@ -799,7 +854,7 @@ /types/d3-drag/ @tomwanzek @gustavderdrache @borisyankov /types/d3-dsv/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-ease/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-fetch/ @ledragon +/types/d3-fetch/ @ledragon @denisname /types/d3-force/ @tomwanzek @gustavderdrache @borisyankov /types/d3-format/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-geo/ @ledragon @tomwanzek @gustavderdrache @borisyankov @@ -815,19 +870,19 @@ /types/d3-random/ @tomwanzek @gustavderdrache @borisyankov /types/d3-request/ @Ledragon @gustavderdrache @borisyankov @tomwanzek @denisname /types/d3-sankey/ @tomwanzek @gustavderdrache +/types/d3-scale/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-scale/v1/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-scale/ @tomwanzek @gustavderdrache @borisyankov /types/d3-scale-chromatic/ @Ledragon @gustavderdrache @borisyankov @henriquefm /types/d3-selection/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-selection-multi/ @gustavderdrache @borisyankov -/types/d3-shape/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-shape/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-time/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-time-format/ @tomwanzek @gustavderdrache @borisyankov /types/d3-timer/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-tip/ @brspnnggrt /types/d3-transition/ @tomwanzek @gustavderdrache @borisyankov /types/d3-voronoi/ @tomwanzek @gustavderdrache @borisyankov @denisname -/types/d3-zoom/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-zoom/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3.slider/ @lk-chen /types/d3kit/ @morphatic /types/d3pie/ @mc-petry @@ -851,7 +906,8 @@ /types/datatables.net-select/ @szechyjs /types/date-arithmetic/ @HeeL /types/date.format.js/ @balrob -/types/dateformat/ @aicest +/types/dateformat/ @aicest @BendingBender +/types/dateformat/v1/ @aicest /types/datejs/ @rupertavery /types/daterangepicker/ @SirMartin @smasala @nertzy /types/dav/ @ToastHawaii @@ -864,10 +920,13 @@ /types/deasync/ @Sicilica /types/debessmann/ @vkorehov /types/debounce/ @denis-sokolov @joshuakgoldberg @wcarson +/types/debounce-fn/ @BendingBender /types/debounce-promise/ @whtsky /types/debug/ @swook @galtalmor @zamb3zi @brasten /types/decamelize/ @samverschueren /types/decay/ @enaeseth +/types/decode-entities/ @waspothegreat +/types/decode-uri-component/ @BendingBender /types/decompress/ @plantain-00 @jbethke /types/decompress-response/ @DanielRosenwasser /types/decorum/ @dflor003 @@ -879,14 +938,16 @@ /types/deep-freeze/ @Bartvds @aluanhaddad /types/deep-freeze-es6/ @mattbishop /types/deep-freeze-strict/ @mhegazy +/types/default-gateway/ @BendingBender /types/defaults/ @IbtihelCHNAB +/types/defaults-deep/ @Kocal /types/defer-promise/ @niklasf /types/define-lazy-prop/ @BendingBender /types/defined/ @BendingBender /types/deglob/ @saadq /types/deku/ @pocka -/types/del/v2/ @AyaMorisawa /types/del/ @AyaMorisawa @BendingBender @bitjson +/types/del/v2/ @AyaMorisawa /types/delaunator/ @DenisCarriere @BTOdell /types/delete-empty/ @Alorel /types/deline/ @iarroyo5 @@ -905,8 +966,8 @@ /types/detect-browser/ @rogierschouten @carusology /types/detect-character-encoding/ @BendingBender /types/detect-hover/ @thomastilkema -/types/detect-indent/v0/ @Bartvds /types/detect-indent/ @Bartvds @BendingBender +/types/detect-indent/v0/ @Bartvds /types/detect-it/ @thomastilkema /types/detect-newline/ @BendingBender /types/detect-node/ @LogvinovLeon @@ -926,20 +987,25 @@ /types/diacritics/ @otociulis /types/dialogflow/ @dyladan /types/dicer/ @GoupilRobin @BendingBender -/types/diff/ @vvakame @szdc @moc-yuto +/types/diff/ @vvakame @szdc @moc-yuto @BendingBender +/types/diff/v3/ @vvakame @szdc @moc-yuto /types/diff2html/ @rtfpessoa /types/diffie-hellman/ @BendingBender /types/digibyte/ @lautarodragan @werewolfe /types/dinero.js/ @BendingBender +/types/dir-glob/ @BendingBender /types/dir-resolve/ @andy-ms +/types/dirname-regex/ @BendingBender /types/discontinuous-range/ @OiCMudkips /types/discord-rpc/ @jasonhaxstuff /types/discourse-sso/ @championswimmer /types/dispatchr/ @Ragg- /types/disposable-email-domains/ @geoffreak +/types/distributions/ @marcolanaro +/types/dlv/ @ryansonshine /types/dnssd/ @angelmerino @Maxr1998 /types/doccookies/ @jonegerton -/types/dockerode/ @seikho @nlaplante @isac322 @lazarusx @meisenzahl @thegecko @CameronDiver +/types/dockerode/ @seikho @nlaplante @isac322 @lazarusx @meisenzahl @thegecko @CameronDiver @p4sca1 /types/docopt/ @giggio /types/doctrine/ @rictic /types/document-promises/ @NotWoods @@ -947,8 +1013,10 @@ /types/documentdb/ @NoelAbrahams @brettferdosi @ctstone @yifanwu /types/documentdb-server/ @lith-light-g /types/documentdb-session/ @DanielRosenwasser +/types/doge-seed/ @BendingBender /types/dojo/ @vansimke /types/dom-clipboard-api/ @43081j +/types/dom-helpers/ @mctep /types/dom-inputevent/ @diagramatics /types/dom-loaded/ @ltetzlaff /types/dom-mediacapture-record/ @eliasmeire @@ -961,32 +1029,34 @@ /types/dookie/ @swanest /types/dot/ @ZombieHunter /types/dot-object/ @nkovacic -/types/dot-prop/v2/ @samverschueren /types/dot-prop/ @samverschueren @BendingBender +/types/dot-prop/v2/ @samverschueren /types/dotdir-regex/ @mrmlnc /types/dotdotdot/ @milanjaros -/types/dotenv/v2/ @jussikinnula @borekb @enaeseth /types/dotenv/ @jussikinnula @borekb @enaeseth @maxbeatty +/types/dotenv/v2/ @jussikinnula @borekb @enaeseth +/types/dotenv-flow/ @vincentlanglet /types/dotenv-safe/ @krenor -/types/dotenv-webpack/ @karol-majewski +/types/dotenv-webpack/ @karol-majewski @davecardwell /types/dotfile-regex/ @mrmlnc /types/dottie/ @domarmstrong /types/double-ended-queue/ @dsagal /types/doublearray/ @mzsm /types/doubleclick-gpt/ @johngeorgewright @steven-joyce /types/download/ @nicojs -/types/downloadjs/ @cwmoo740 +/types/downloadjs/ @cwmoo740 @josuedevmark /types/dplayer/ @Guanyunhan -/types/draft-js/ @dmitryrogozhny @eelco @ghotiphud @schwers @michael-yx-wu @willisplummer @smvilar @sulf @pablopunk +/types/draft-js/ @dmitryrogozhny @eelco @ghotiphud @schwers @michael-yx-wu @willisplummer @smvilar @sulf @pablopunk @claudiopro /types/drag-timetable/ @chinkan /types/draggabilly/ @jaydubu /types/dragster/ @zskovacs /types/dragula/ @pwelter34 @abruzzihraig +/types/drivelist/ @WholeMilk /types/dropbox-chooser/ @quas94 /types/dropboxjs/ @Steve-Fenton @xperiments /types/dropkickjs/ @VorobeY1326 -/types/dropzone/v4/ @nvivo @outring @renuo @Hikariii /types/dropzone/ @nvivo @outring @renuo @Hikariii @tedbcsgpro @dwaxweiler +/types/dropzone/v4/ @nvivo @outring @renuo @Hikariii /types/dts-generator/ @mtraynham /types/duplexer2/ @Goldsmith42 /types/duplexer3/ @BendingBender @@ -996,11 +1066,11 @@ /types/dustjs-linkedin/ @mdezem /types/dvtng-jss/ @Ptival /types/dw-bxslider-4/ @namerci -/types/dwt/v12/ @yushulx /types/dwt/ @yushulx @jbh @lincoln2018 @Tom-Dynamsoft /types/dygraphs/ @danvk /types/dymo-label-framework/ @thijskuipers /types/dynatable/ @francoismassart +/types/dynatrace/ @alvaro450 /types/dynogels/ @SpartanLabs @ramondeklein @stephentuso /types/each/ @misak113 /types/earcut/ @NaridaL @@ -1018,6 +1088,7 @@ /types/ecurve/ @mhegazy /types/ed25519/ @erikma /types/ed2curve/ @ffflorian +/types/ee-first/ @BendingBender /types/egg-mock/ @sheperdwind /types/egg.js/ @ToastHawaii /types/egjs__axes/ @naver @@ -1036,9 +1107,9 @@ /types/electron-load-devtool/ @prince0203 /types/electron-notifications/ @djpereira /types/electron-notify/ @djpereira -/types/electron-packager/ @SomaticIT @cortopy @jkleinsc @shiftkey -/types/electron-settings/v2/ @leonard-thieu +/types/electron-packager/ @SomaticIT @cortopy @jkleinsc @shiftkey @malept /types/electron-settings/ @icopp @nrlquaker +/types/electron-settings/v2/ @leonard-thieu /types/electron-spellchecker/ @unindented /types/electron-store/ @unindented @jsynowiec /types/electron-unhandled/ @jeremejevs @@ -1050,25 +1121,25 @@ /types/element-resize-detector/ @saranshkataria @franklixuefei /types/element-resize-event/ @rogierschouten @plgregoire /types/elementtree/ @dwieeb -/types/elliptic/ @danwbyrne +/types/elliptic/ @danwbyrne @Gilthoniel /types/elm/ @thSoft /types/email-templates/ @cyrilschumacher @gurisko @blankstar85 -/types/ember/v1/ @jedmao -/types/ember/v2/ @jedmao @bttf @dwickern @chriskrycho @theroncross @mfeckie @alexlafroscia @mike-north /types/ember/ @jedmao @bttf @dwickern @chriskrycho @theroncross @mfeckie @alexlafroscia @mike-north @BryanCrotaz -/types/ember-data/v2/ @dwickern @mike-north @chriskrycho +/types/ember/v2/ @jedmao @bttf @dwickern @chriskrycho @theroncross @mfeckie @alexlafroscia @mike-north +/types/ember/v1/ @jedmao /types/ember-data/ @dwickern @mike-north @chriskrycho -/types/ember-feature-flags/v3/ @tansongyang @mike-north +/types/ember-data/v2/ @dwickern @mike-north @chriskrycho /types/ember-feature-flags/ @tansongyang @mike-north +/types/ember-feature-flags/v3/ @tansongyang @mike-north /types/ember-mocha/ @dwickern @simonihmig @mike-north -/types/ember-modal-dialog/v2/ @tansongyang @mike-north /types/ember-modal-dialog/ @tansongyang @mike-north +/types/ember-modal-dialog/v2/ @tansongyang @mike-north +/types/ember-qunit/ @dwickern @mike-north @scalvert @dfreeman /types/ember-qunit/v2/ @dwickern @mike-north -/types/ember-qunit/ @dwickern @mike-north -/types/ember-resolver/v4/ @dfreeman @mike-north /types/ember-resolver/ @dfreeman @mike-north -/types/ember-test-helpers/v0/ @dwickern @mike-north +/types/ember-resolver/v4/ @dfreeman @mike-north /types/ember-test-helpers/ @dwickern @mike-north +/types/ember-test-helpers/v0/ @dwickern @mike-north /types/ember-testing-helpers/ @chriskrycho /types/ember__application/ @mike-north /types/ember__array/ @mike-north @@ -1087,12 +1158,14 @@ /types/ember__test-helpers/ @dfreeman @jamescdavis @mike-north /types/ember__utils/ @mike-north /types/emissary/ @vvakame -/types/emoji-mart/ @Kovensky @Nicell +/types/emoji-mart/ @Jessidhia @Nicell /types/emoji-regex/ @iKBAHT /types/emojione/ @dbrgn /types/empower/ @vvakame /types/empty-dir/ @BendingBender +/types/empty-trash/ @BendingBender /types/emscripten/ @zakki @periklis +/types/encodeurl/ @BendingBender /types/encoding-down/ @MeirionHughes @danwbyrne /types/end-of-stream/ @strax /types/engine.io/ @KentarouTakeda @@ -1100,8 +1173,12 @@ /types/enhanced-resolve/ @e-cloud @onigoetz @johnnyreilly /types/enigma.js/ @konne /types/enquire.js/ @screendriver +/types/ensure-error/ @BendingBender +/types/ensure-posix-path/ @BendingBender /types/ent/ @rogierschouten /types/entities/ @aliceklipper +/types/env-ci/ @BendingBender +/types/env-editor/ @BendingBender /types/env-paths/ @danwbyrne /types/env-to-object/ @MugeSo /types/envify/ @tkQubo @@ -1124,6 +1201,7 @@ /types/es6-promisify/ @harryshipton @bschlenk /types/es6-shim/ @rbuckton /types/es6-weak-map/ @pine +/types/escape-goat/ @BendingBender /types/escape-html/ @elisee /types/escape-latex/ @olsio /types/escape-regexp/ @jewbre @@ -1133,8 +1211,8 @@ /types/eslint-plugin-prettier/ @ikatyang /types/eslint-scope/ @mysticatea /types/eslint-visitor-keys/ @mysticatea -/types/esprima/v2/ @teppeis @RReverser /types/esprima/ @teppeis @RReverser @peter-scott +/types/esprima/v2/ @teppeis @RReverser /types/esprima-walk/ @tswaters /types/espruino/ @stasberkov @createdbyjurand /types/esri-leaflet/ @strajuser @@ -1145,10 +1223,10 @@ /types/eth-lightwallet/ @LogvinovLeon /types/ethereum-protocol/ @LogvinovLeon /types/ethereumjs-abi/ @LogvinovLeon -/types/ethereumjs-tx/ @LogvinovLeon +/types/ethereumjs-tx/ @LogvinovLeon @dmihal /types/ethereumjs-util/ @cortopy /types/ethjs-signer/ @doppio -/types/eureka-js-client/ @Schnillz +/types/eureka-js-client/ @Schnillz @karl-run @tombarton /types/evaporate/ @kookster @chrisrhoden @ailrun /types/event-emitter/ @LKay /types/event-emitter-es6/ @ahstro @@ -1157,14 +1235,16 @@ /types/event-loop-lag/ @rogierschouten /types/event-stream/ @flcdrg /types/event-to-promise/ @flying-sheep -/types/events/ @yasupeke -/types/eventsource/ @scottleedavis @afroozeh +/types/events/ @yasupeke @weareoutman +/types/eventsource/ @scottleedavis @afroozeh @snakedrak /types/evernote/ @corps /types/ex-react-native-i18n/ @maplerichie /types/excel-style-dataformatter/ @SanderDeWaal1992 /types/exceljs/ @rogierschouten @alitaheri /types/execa/ @douglasduteil @BendingBender @borekb @mickdekkers +/types/execall/ @BendingBender /types/exenv/ @christianchown +/types/exif/ @ffflorian /types/exit/ @Bartvds /types/exit-hook/ @BendingBender /types/exorcist/ @TeamworkGuy2 @@ -1175,16 +1255,16 @@ /types/expectations/ @vvakame /types/expired-storage/ @intolerance /types/expirymanager/ @DanielRose -/types/expo/v23/ @KonstantinKai -/types/expo/v24/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger -/types/expo/v25/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov -/types/expo/v26/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @tinaroh -/types/expo/v27/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo +/types/expo/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo @levansuper @ihmpavel @burtek @jkillian /types/expo/v30/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo -/types/expo/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo @levansuper @ihmpavel +/types/expo/v27/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo +/types/expo/v26/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @tinaroh +/types/expo/v25/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov +/types/expo/v24/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger +/types/expo/v23/ @KonstantinKai /types/expo-localization/ @burtek /types/expo__status-bar-height/ @dawnmist -/types/expo__vector-icons/ @incleaf +/types/expo__vector-icons/ @incleaf @robertying /types/express/ @borisyankov /types/express-brute/ @cyrilschumacher /types/express-brute-memcached/ @cyrilschumacher @@ -1205,6 +1285,7 @@ /types/express-formidable/ @tdolsen @evanshortiss /types/express-graphql/ @isman-usoh @nitintutlani @hubel @zya @mlamp @firede /types/express-handlebars/ @stpettersens @yhaskell +/types/express-http-proxy/ @ulrichb @Danscho /types/express-jsonschema/ @atd-schubert /types/express-jwt/ @wokim @kacepe @Sl1MBoy @milan-mimra /types/express-less/ @xieyubo @@ -1219,7 +1300,8 @@ /types/express-paginate/ @AmirTugi /types/express-partials/ @jt000 /types/express-promise-router/ @wanganjun -/types/express-rate-limit/ @cyrilschumacher @makepost +/types/express-rate-limit/ @cyrilschumacher @makepost @jdforsythe +/types/express-rate-limit/v2/ @cyrilschumacher @makepost /types/express-redis-cache/ @ajliv /types/express-route-fs/ @kripod /types/express-routemap/ @icopp @@ -1228,6 +1310,7 @@ /types/express-serve-static-core/ @borisyankov @19majkel94 @kacepe @micksatana @samijaber /types/express-session/ @horiuchi @jacobbogers @builtinnya @ry7n /types/express-sitemap-xml/ @ffflorian +/types/express-slow-down/ @jdforsythe /types/express-socket.io-session/ @AylaJK /types/express-to-koa/ @xiaohanzhang /types/express-unless/ @wokim @@ -1240,6 +1323,7 @@ /types/express-xml-bodyparser/ @noticeMaker @macedigital /types/extend/ @reppners /types/extjs/ @brian428 +/types/extra-watch-webpack-plugin/ @davecardwell /types/extract-files/ @Slessi /types/extract-stack/ @BendingBender /types/extract-text-webpack-plugin/ @flying-sheep @katyo @@ -1253,8 +1337,8 @@ /types/facebook-js-sdk/ @amritk @mahmoudzohdi @fluidsonic /types/facebook-pixel/ @noctishsu /types/factory-girl/ @stackbuilders @sestrella @elcuy -/types/faker/v3/ @Kuniwak /types/faker/ @bensw @basp @Kuniwak @mattbishop +/types/faker/v3/ @Kuniwak /types/falcor/ @Quramy /types/falcor-express/ @Quramy /types/falcor-http-datasource/ @Quramy @@ -1264,28 +1348,32 @@ /types/fancy-log/ @pine /types/fancybox/ @borisyankov /types/farbtastic/ @EnableSoftware +/types/fast-json-stable-stringify/ @BendingBender /types/fast-levenshtein/ @mizunashi-mana /types/fast-list/ @BendingBender /types/fast-stats/ @rogierschouten +/types/fast64/ @rarmatei /types/fastclick/ @shinnn /types/fastify-accepts/ @leomelzer /types/fastify-cors/ @jannikkeye +/types/fastify-favicon/ @tuelsch /types/fastify-jwt/ @jannikkeye /types/fastify-multipart/ @jannikkeye +/types/fastify-rate-limit/ @pc-jedi /types/fastify-static/ @leomelzer /types/favico.js/ @drowse314-dev-ymat -/types/favicons/ @mohsen1 +/types/favicons/ @mohsen1 @metsawyr /types/fb/ @JoshStrobl /types/fb-watchman/ @whtsky /types/fbemitter/ @kmxz /types/feather-icons/ @jineshshah36 /types/featherlight/ @xStrom -/types/feathersjs__authentication/ @AbraaoAlves @j2L4e +/types/feathersjs__authentication/ @AbraaoAlves @j2L4e @NickBolles /types/feathersjs__authentication-client/ @AbraaoAlves @j2L4e /types/feathersjs__authentication-jwt/ @j2L4e /types/feathersjs__authentication-local/ @j2L4e /types/feathersjs__authentication-oauth1/ @j2L4e -/types/feathersjs__authentication-oauth2/ @j2L4e +/types/feathersjs__authentication-oauth2/ @j2L4e @NickBolles /types/feathersjs__configuration/ @j2L4e /types/feathersjs__errors/ @j2L4e /types/feathersjs__express/ @j2L4e @DadUndead @@ -1299,7 +1387,8 @@ /types/feedme/ @codeanimal /types/feedparser/ @cortopy /types/fetch-jsonp/ @tkrotoff -/types/fetch-mock/ @asvetliakov @tamird @merrywhether @chrissinclair @matttennison @quentinbouygues @mtsmfm +/types/fetch-mock/ @asvetliakov @tamird @merrywhether @chrissinclair @matttennison @quentinbouygues @mtsmfm @captain-igloo @ChenNima +/types/fetch-mock/v6/ @asvetliakov @tamird @merrywhether @chrissinclair @matttennison @quentinbouygues @mtsmfm /types/fetch.io/ @newraina /types/ffi/ @loyd @waitingsong /types/ffi-napi/ @keerthi16 @KiranNiranjan @@ -1315,12 +1404,16 @@ /types/file-type/ @tcaesvk @BendingBender /types/file-url/ @coderslagoon /types/filenamify/ @rokt33r -/types/filesize/ @GiedriusGrabauskas @renchap +/types/filenamify-url/ @cprecioso +/types/filesize/ @GiedriusGrabauskas @renchap @Ky6uk /types/fill-pdf/ @westy92 +/types/filter-console/ @BendingBender /types/filter-invalid-dom-props/ @icopp /types/finalhandler/ @chrootsu /types/finch/ @DavidSichau /types/find/ @andypyrope +/types/find-cache-dir/ @BendingBender +/types/find-java-home/ @sjx233 /types/find-package-json/ @BendingBender /types/find-parent-dir/ @ikatyang /types/find-process/ @buaban @@ -1328,10 +1421,12 @@ /types/find-root/ @Alorel /types/find-up/ @BendingBender /types/find-versions/ @LogvinovLeon @carnesen -/types/findup-sync/ @Bartvds @ngbrown +/types/findup-sync/ @Bartvds @ngbrown @BendingBender +/types/findup-sync/v0/ @Bartvds @ngbrown /types/fined/ @BendingBender /types/fingerprintjs/ @zaneli -/types/fingerprintjs2/ @curtstate +/types/fingerprintjs2/ @curtstate @BendingBender +/types/fingerprintjs2/v1/ @curtstate /types/firebase-client/ @fpsscarecrow /types/firebase-token-generator/ @dotdotcommadot /types/firebird/ @karak @@ -1339,11 +1434,14 @@ /types/firefox-webext-browser/ @jsmnbom /types/firmata/ @troywweber7 /types/first-mate/ @GlenCFL +/types/first-run/ @BendingBender /types/fixed-data-table/ @pepaar @stephenjelfs /types/fixed-data-table-2/ @ilivit +/types/fkill/ @BendingBender /types/flagged-respawn/ @BendingBender /types/flat/ @chrootsu /types/fleximap/ @DanielRose +/types/flexmonster/ @flexmonster /types/flexslider/ @diullei /types/flickity/ @clmcgrath @wagich /types/flight/ @jonathanhedren @@ -1353,8 +1451,12 @@ /types/flot/ @burlandm @Anticom @admiralsmaster /types/flowdoc/ @animify /types/flowjs/ @ryan10132 +/types/fluent/ @huy-nguyen /types/fluent-ffmpeg/ @tcaesvk @DingWeizhe @mabidina +/types/fluent-langneg/ @huy-nguyen +/types/fluent-react/ @huy-nguyen /types/flush-write-stream/ @djcsdy +/types/flushable/ @pash90 /types/flux/ @stkb @GiedriusGrabauskas /types/fluxible/ @xbim /types/fluxible-addons-react/ @xbim @@ -1367,7 +1469,9 @@ /types/fontoxml/ @rolandzwaga /types/forever-agent/ @yavanosta /types/forever-monitor/ @shuntksh @wrboyce +/types/forge-apis/ @Autodesk-Forge /types/forge-di/ @adamcarr +/types/forge-viewer/ @Autodesk-Forge /types/form-data/ @soywiz @leonyu @BendingBender /types/form-serialize/ @tyler-johnson /types/form-serializer/ @flqw @@ -1389,16 +1493,16 @@ /types/fresh/ @BendingBender /types/freshy/ @qlonik /types/friendly-errors-webpack-plugin/ @bahlo -/types/frisby/v0/ @johnny4753 /types/frisby/ @cwoodland @johnny4753 +/types/frisby/v0/ @johnny4753 /types/from/ @Bartvds /types/from2/ @BendingBender /types/fromjs/ @glenndierckx /types/fromnow/ @marinewater /types/fs-cson/ @dex4er /types/fs-ext/ @OguzhanE -/types/fs-extra/v4/ @alan-agius4 @midknight41 @shiftkey @mees- /types/fs-extra/ @alan-agius4 @midknight41 @shiftkey @mees- @jrockwood +/types/fs-extra/v4/ @alan-agius4 @midknight41 @shiftkey @mees- /types/fs-extra-promise/ @midknight41 @jasonswearingen @HiromiShikata /types/fs-extra-promise-es6/ @midknight41 @jasonswearingen @geoffreak @HiromiShikata /types/fs-finder/ @misak113 @@ -1558,7 +1662,7 @@ /types/gapi.client.youtubereporting/ @Bolisov /types/gapi.drive/ @baxtersa /types/gapi.pagespeedonline/ @sgtfrankieboy -/types/gapi.people/ @tkrotoff +/types/gapi.people/ @tkrotoff @joshuaobrien /types/gapi.plus/ @tkrotoff /types/gapi.translate/ @sgtfrankieboy /types/gapi.urlshortener/ @sgtfrankieboy @@ -1566,6 +1670,7 @@ /types/gapi.youtubeanalytics/ @sgtfrankieboy /types/gaussian/ @scttcper /types/gc-stats/ @vfernandestoptal +/types/gdal/ @andreidigori /types/geetest/ @plantain-00 /types/gen-readlines/ @CodeAnimal /types/generate-changelog/ @ffflorian @@ -1574,37 +1679,54 @@ /types/generic-pool/ @jerray @wrboyce /types/gently/ @bonnici /types/geodesy/ @DenisCarriere @HandyG52 @excelulous -/types/geojson/ @cobster @atd-schubert @JeffJacobson @icholy +/types/geojson/ @cobster @atd-schubert @JeffJacobson @icholy @danvk /types/geojson2osm/ @DenisCarriere /types/geokdbush/ @DenisCarriere +/types/geolite2/ @ffflorian /types/geometry-dom/ @nakakura /types/geopattern/ @Gaelan /types/gestalt/ @serranoarevalo /types/get-caller-file/ @ajafff +/types/get-certain/ @BendingBender +/types/get-emails/ @BendingBender +/types/get-emoji/ @BendingBender /types/get-folder-size/ @mszczepanczyk +/types/get-func-name/ @BendingBender /types/get-node-dimensions/ @vincekovacs +/types/get-port/ @plantain-00 @BendingBender +/types/get-range/ @BendingBender /types/get-stdin/ @DanielRosenwasser /types/get-stream/ @douglasduteil @BendingBender +/types/get-urls/ @BendingBender /types/get-value/ @DanielRosenwasser /types/getenv/ @impankratov /types/getopts/ @azasypkin /types/getos/ @BendingBender /types/gettext.js/ @jucrouzet +/types/gfc/ @BendingBender /types/gh-pages/ @DanielRosenwasser /types/ghauth/ @Leko /types/gifffer/ @gatimus /types/gijgo/ @atatanasov /types/giraffe/ @darthapo /types/git/ @vvakame +/types/git-add-remote/ @BendingBender /types/git-branch/ @rynclark /types/git-config/ @stpettersens +/types/git-config-path/ @BendingBender /types/git-remote-origin-url/ @janslow +/types/git-repo-name/ @BendingBender /types/git-rev-sync/ @khoi-fish /types/git-root-dir/ @ffflorian /types/git-url-parse/ @ajafff +/types/git-user-email/ @BendingBender +/types/git-user-name/ @BendingBender +/types/git-username/ @BendingBender /types/gitconfiglocal/ @ffflorian /types/github-url-to-object/ @ajafff +/types/github-username/ @BendingBender /types/github-username-regex/ @BehindTheMath +/types/gl/ @sjx233 /types/gl-matrix/ @mattijskneppers @tatchx @nbabanov @auzmartist @surtr-isaz /types/gl-react/ @jussikinnula /types/gl-react-dom/ @jussikinnula @@ -1615,27 +1737,33 @@ /types/gl-texture2d/ @MathiasPaumgarten /types/gldatepicker/ @qcz /types/glidejs/ @milanjaros -/types/glob/v5/ @vvakame @voy /types/glob/ @vvakame @voy @ajafff +/types/glob/v5/ @vvakame @voy /types/glob-base/ @alan-agius4 /types/glob-expand/ @vvakame /types/glob-parent/ @mrmlnc /types/glob-stream/ @Bartvds @mrmlnc /types/glob-to-regexp/ @whatasoda +/types/global-dirs/ @BendingBender +/types/global-modules/ @BendingBender +/types/global-paths/ @BendingBender +/types/global-prefix/ @BendingBender /types/global-tunnel-ng/ @BendingBender /types/globalize/ @gcastre @afromogli @bryanforbes /types/globalize-compiler/ @iclanton /types/globby/ @douglasduteil @ikatyang /types/globule/ @durad -/types/glue/v4/ @gjednaszewski /types/glue/ @garfty +/types/glue/v4/ @gjednaszewski /types/gm/ @ChaosinaCan @maartenvanvliet @mlejva /types/go/ @NorthwoodsSoftware /types/google-adwords-scripts/ @jafaircl /types/google-apps-script/ @motemen @grant /types/google-apps-script-oauth2/ @dhayab /types/google-cloud__datastore/ @beaulac @ogawa0071 @ThomasdenH +/types/google-cloud__kms/ @ben-tbotlabs /types/google-cloud__pubsub/ @pheromonez @LunaPg @msiviero +/types/google-cloud__tasks/ @ifiokjr /types/google-earth/ @icholy /types/google-images/ @dolanmiu /types/google-libphonenumber/ @leonyu @winfinit @@ -1649,24 +1777,26 @@ /types/google.fonts/ @danmarshall /types/google.geolocation/ @vbortone /types/google.picker/ @grapswiz +/types/google.script.client-side/ @clomie /types/google.visualization/ @danludwig @gmoore-sjcorg @danmana @mlcheng @IvanBisultanov @glebm @shrujalshah28 /types/google__maps/ @indrimuska /types/googlemaps/ @cgwrench @nertzy @xaolas @mrmcnerd @martincostello @svenkreiss @bolatovumar @gauthierm /types/googlemaps.infobubble/ @Dashue /types/googlepay/ @Fluccioni @Radu-Raicea @fstanis -/types/got/v8/ @BendingBender @LinusU @ikokostya /types/got/ @BendingBender @LinusU @ikokostya @stijnvn -/types/graceful-fs/v2/ @Bartvds +/types/got/v8/ @BendingBender @LinusU @ikokostya /types/graceful-fs/ @Bartvds @BendingBender +/types/graceful-fs/v2/ @Bartvds /types/gradient-string/ @Ailrun /types/graham_scan/ @hberntsen /types/gramps__rest-helpers/ @claude /types/graphite-udp/ @EricByers /types/graphlib-dot/ @DomParfitt -/types/graphql/ @TonyPythoneer @calebmer @intellix @firede @kepennar @freiksenet @IvanGoncharov @DxCx @rportugal @tgriesser @dyst5422 @adnsio @divyenduz @bradzacher @clayne11 @JCMais +/types/graphql/ @TonyPythoneer @calebmer @intellix @firede @kepennar @freiksenet @IvanGoncharov @DxCx @rportugal @tgriesser @dyst5422 @adnsio @divyenduz @bradzacher @clayne11 @JCMais @langpavel /types/graphql-date/ @enaeseth /types/graphql-deduplicator/ @lfades /types/graphql-depth-limit/ @eritikass +/types/graphql-errors/ @MatiasOlivera /types/graphql-fields/ @feinoujc /types/graphql-iso-date/ @jwaldrip /types/graphql-list-fields/ @filipows @@ -1680,8 +1810,8 @@ /types/gravatar/ @denis-sokolov /types/gravatar-url/ @ivangabriele /types/greasemonkey/ @kotas -/types/grecaptcha/v0/ @brentj73 /types/grecaptcha/ @DethAriel @rafaeltavares +/types/grecaptcha/v0/ @brentj73 /types/gregorian-calendar/ @cwalv /types/gridfs-stream/ @liorm /types/gridstack/ @PascalSenn @ZoolWay @Sl1MBoy @@ -1689,6 +1819,7 @@ /types/grunt/ @jeffmay @basarat /types/gsap/ @codebelt @ProbablePrime @philipbulley @leomeloxp /types/gtin/ @RafaelKr +/types/guardian__prosemirror-invisibles/ @dddotsev /types/guid/ @maroy1986 /types/gulp/ @GiedriusGrabauskas /types/gulp-angular-templatecache/ @amanmahajan7 @@ -1768,29 +1899,35 @@ /types/gulp-watch/ @tkrotoff /types/gulp-zip/ @dudeofawesome /types/gzip-js/ @rhysd -/types/gzip-size/v3/ @plantain-00 /types/gzip-size/ @plantain-00 @jimivdw @andrewiggins -/types/h2o2/ @jasonswearingen @AJamesPhillips +/types/gzip-size/v3/ @plantain-00 +/types/h2o2/ @jasonswearingen @AJamesPhillips @garthk /types/halfred/ @dherges /types/halogen/ @steller /types/hammerjs/ @milkisevil @codler /types/handlebars/ @borisyankov @evil-shrike /types/handlebars-helpers/ @Toilal -/types/hapi/v8/ @jasonswearingen -/types/hapi/v12/ @jasonswearingen -/types/hapi/v15/ @jasonswearingen +/types/hapi/ @rafaelsouzaf @jhsimms @SimonSchick @saboya +/types/hapi/v17/ @rafaelsouzaf @jhsimms @SimonSchick @saboya /types/hapi/v16/ @jasonswearingen @AJamesPhillips -/types/hapi/ @rafaelsouzaf @jhsimms @SimonSchick +/types/hapi/v15/ @jasonswearingen +/types/hapi/v12/ @jasonswearingen +/types/hapi/v8/ @jasonswearingen /types/hapi-auth-basic/ @AJamesPhillips @saboya +/types/hapi-auth-bearer-token/ @saboya /types/hapi-auth-cookie/ @lenovouser @SimonSchick @Mutmatt -/types/hapi-auth-jwt2/v7/ @warrenseymour /types/hapi-auth-jwt2/ @warrenseymour @SimonSchick +/types/hapi-auth-jwt2/v7/ @warrenseymour /types/hapi-decorators/ @kenhowardpdx +/types/hapi-pino/ @saboya +/types/happypack/ @akashishu777 /types/har-format/ @micmro /types/hard-rejection/ @BendingBender /types/hard-source-webpack-plugin/ @woitechen /types/harmony-proxy/ @remojansen /types/has-ansi/ @BendingBender +/types/has-emoji/ @BendingBender +/types/has-yarn/ @BendgingBender /types/hash-file/ @HiromiShikata /types/hash-stream/ @BendingBender /types/hash-sum/ @DanielRosenwasser @@ -1798,6 +1935,7 @@ /types/hasher/ @flyfishMT /types/hashids/ @pocesar /types/hashmap/ @outring +/types/hashtag-regex/ @diogofcunha /types/hat/ @tup1tsa /types/haversine/ @screendriver /types/hbs/ @davidm77 @@ -1814,24 +1952,24 @@ /types/heredatalens/ @denyo /types/heremaps/ @Josh-ES @denyo @fx88 /types/heroku-logger/ @kylevogt +/types/hex-rgb/ @BendingBender /types/hex-rgba/ @r3nya /types/hexo-bunyan/ @segayuu /types/hexo-fs/ @segayuu /types/hexo-log/ @segayuu /types/hexo-util/ @segayuu -/types/hibp/ @lenovouser /types/highcharts/ @damianog @baltie @AlbertOzimek @hanssens /types/highcharts-ng/ @scatcher /types/highland/ @Bartvds @hgwood @iwllyu @alvis @notbobthebuilder /types/highlight.js/ @nikeee @sourrust @joshuakgoldberg /types/hiredis/ @titan -/types/history/v2/ @sergey-buturlakin @ngbrown -/types/history/v3/ @sergey-buturlakin @ngbrown @LKay /types/history/ @sergey-buturlakin @ngbrown @rokoroku +/types/history/v3/ @sergey-buturlakin @ngbrown @LKay +/types/history/v2/ @sergey-buturlakin @ngbrown /types/history.js/ @borisyankov @gjunge /types/historykana/ @h-shiratsuki /types/hjson/ @crunchie84 -/types/hls.js/ @jgainfort +/types/hls.js/ @jgainfort @brookback @adripanico /types/hoek/ @prashaantt /types/hoist-non-react-statics/ @JounQin /types/holderjs/ @renjfk @@ -1842,10 +1980,11 @@ /types/howler/ @xperiments @tdukart @alien35 @nicholashza /types/hpp/ @kryops /types/html-entities/ @xstoudi -/types/html-minifier/v1/ @tkrotoff /types/html-minifier/ @tkrotoff @rikuayanokozy +/types/html-minifier/v1/ @tkrotoff /types/html-pdf/ @westy92 /types/html-tag-names/ @sandersn +/types/html-tags/ @BendingBender /types/html-to-text/ @erykwarren /types/html-void-elements/ @rhysd /types/html-webpack-plugin/ @deevus @bumbleblym @tlaziuk @@ -1854,8 +1993,9 @@ /types/htmlbars-inline-precompile/ @chriskrycho /types/htmlparser2/ @staticfunction @LinusU /types/htmltojsx/ @basarat -/types/http-assert/ @jkeylu +/types/http-assert/ @jkeylu @stripedpajamas /types/http-aws-es/ @marcogrcr +/types/http-cache-semantics/ @BendingBender /types/http-codes/ @mhegazy /types/http-context/ @mtraynham /types/http-errors/ @tkrotoff @BendingBender @@ -1874,6 +2014,7 @@ /types/humane/ @jmvrbanac /types/humanize-plus/ @DenisCarriere /types/humanize-string/ @ragnarok56 +/types/humanize-url/ @BendingBender /types/humanparser/ @MichalPodeszwa /types/humps/ @nikeee /types/hyco-ws/ @mrcabellom @@ -1884,11 +2025,11 @@ /types/i18n/ @SomaticIT @FindQ /types/i18n-abide/ @smbell /types/i18n-js/ @ypresto -/types/i18next/v2/ @mxl @deerawan @GiedriusGrabauskas -/types/i18next/v8/ @mxl @deerawan @GiedriusGrabauskas /types/i18next/ @mxl @deerawan @GiedriusGrabauskas @lenovouser @qqilihq @butchyyyy -/types/i18next-browser-languagedetector/v0/ @cyrilschumacher @GiedriusGrabauskas +/types/i18next/v8/ @mxl @deerawan @GiedriusGrabauskas +/types/i18next/v2/ @mxl @deerawan @GiedriusGrabauskas /types/i18next-browser-languagedetector/ @cyrilschumacher @GiedriusGrabauskas +/types/i18next-browser-languagedetector/v0/ @cyrilschumacher @GiedriusGrabauskas /types/i18next-express-middleware/ @cyrilschumacher /types/i18next-ko/ @dwaxweiler /types/i18next-node-fs-backend/ @cyrilschumacher @lenovouser @@ -1901,6 +2042,7 @@ /types/ibm_db/ @agov /types/icepick/ @ngbrown @tobico /types/icheck/ @qcz +/types/icon-gen/ @ffflorian /types/iconv/ @delphinus35 /types/idyll/ @iocat /types/idyll-ast/ @iocat @@ -1926,25 +2068,28 @@ /types/imap/ @psnider /types/imap-simple/ @pushplay @iaarnio /types/imgur-rest-api/ @lukewestby +/types/immediate/ @BendingBender /types/imperium/ @gaetansenn /types/impress/ @borisyankov /types/in-app-purchase/ @l-jonas @IchordeDionysos /types/in-range/ @DanielRosenwasser /types/inboxsdk/ @rdoursenaud @amiram /types/incremental-dom/ @basarat @lanthaler @vvakame -/types/indent-string/ @mhegazy -/types/inert/v4/ @nycdotnet @AJamesPhillips +/types/indent-string/ @mhegazy @BendingBender /types/inert/ @nycdotnet @AJamesPhillips @lenovouser +/types/inert/v4/ @nycdotnet @AJamesPhillips /types/inflected/ @dsci /types/inflection/ @shiwano /types/inherits/ @chrootsu /types/ini/ @marcinporebski @carnesen /types/iniparser/ @chrootsu /types/init-package-json/ @kfarnung +/types/ink/ @cprecioso /types/inline-css/ @philipisapain /types/inline-style-prefixer/ @ahz @dpetrezselyova @franklixuefei /types/inquirer/ @tkQubo @ppathan @jouderianjr @bang88 @bitjson @synarque @jrockwood @kwkelly @Ailrun /types/inquirer-npm-name/ @manuth +/types/insert-css/ @hvoecking /types/insert-module-globals/ @leonard-thieu /types/insight/ @vvakame /types/instabug-reactnative/ @pengcao1 @@ -1953,46 +2098,61 @@ /types/intercom-web/ @fongandrew @salbahra @onatm /types/intercomjs/ @spencerwi /types/internal-ip/ @BendingBender +/types/internal-ip/v2/ @BendingBender /types/interpret/ @BendingBender /types/intl/ @RagibHasin /types/intl-locales-supported/ @Slessi /types/intl-messageformat/ @mhegazy /types/intl-relativeformat/ @mohsen1 -/types/intl-tel-input/v13/ @fdnhkj @leonard-thieu /types/intl-tel-input/ @fdnhkj @leonard-thieu @molnarm +/types/intl-tel-input/v13/ @fdnhkj @leonard-thieu /types/into-stream/ @BendingBender /types/intrinsic-scale/ @shalomdotnet /types/intro.js/ @anahkiasen /types/invariant/ @bennett000 /types/inversify-devtools/ @inversify /types/iobroker/ @AlCalzone -/types/ion-rangeslider/v1/ @dduugg @Karel-van-de-Plassche /types/ion-rangeslider/ @Karel-van-de-Plassche -/types/ioredis/v3/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot -/types/ioredis/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot @funthing @iamolegga @tingwai-to +/types/ion-rangeslider/v1/ @dduugg @Karel-van-de-Plassche +/types/iopipe__iopipe/ @javonharper +/types/ioredis/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot @funthing @iamolegga @tingwai-to @pettyalex +/types/ioredis/v3/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot @pettyalex /types/iota.lib.js/ @fogsh -/types/ip/ @codeanimal +/types/ip/ @codeanimal @BendingBender /types/ip-address/ @icopp @danwbyrne -/types/ip-regex/ @unindented +/types/ip-regex/ @renarsvilnis +/types/ip-regex/v2/ @unindented /types/ipcheck/ @bengry +/types/ipify/ @BendingBender /types/irc/ @phillips1012 /types/iri/ @BendingBender /types/iron/ @simonschick @rafaelsouzaf /types/is/ @cabralRodrigo @gricey432 +/types/is-absolute/ @BendingBender /types/is-absolute-url/ @mhegazy /types/is-alphanumerical/ @vutran /types/is-archive/ @mhegazy /types/is-array/ @pine +/types/is-array-sorted/ @BendingBender /types/is-binary-path/ @DanielRosenwasser +/types/is-buffer/ @rokt33r /types/is-callable/ @nieltg +/types/is-charging/ @BendingBender /types/is-ci/ @atd-schubert /types/is-color/ @VitorLuizC /types/is-compressed/ @mhegazy /types/is-docker/ @YashdalfTheGray +/types/is-dotdir/ @BendingBender +/types/is-dotfile/ @BendingBender +/types/is-elevated/ @BendingBender /types/is-empty/ @termosa /types/is-finite/ @mhegazy +/types/is-fullwidth-code-point/ @BendingBender +/types/is-function/ @evangeloszotos +/types/is-git-url/ @BendingBender /types/is-glob/ @mrmlnc /types/is-hotkey/ @petester42 @kalley +/types/is-installed-globally/ @BendingBender /types/is-ip/ @coderslagoon /types/is-mobile/ @LogvinovLeon /types/is-my-json-valid/ @kruncher @@ -2000,10 +2160,16 @@ /types/is-number/ @harryshipton /types/is-obj/ @forivall /types/is-object/ @wbhob +/types/is-online/ @BendingBender /types/is-path-cwd/ @DanielRosenwasser /types/is-path-in-cwd/ @mhegazy +/types/is-plain-obj/ @BendingBender +/types/is-png/ @jameswilddev +/types/is-progressive/ @BendingBender /types/is-promise/ @DanielRosenwasser +/types/is-reachable/ @BendingBender /types/is-regexp/ @forivall +/types/is-relative/ @BendingBender /types/is-relative-url/ @mhegazy /types/is-root/ @mhegazy /types/is-root-path/ @mhegazy @@ -2013,18 +2179,26 @@ /types/is-svg/ @BendingBender /types/is-text-path/ @mhegazy /types/is-touch-device/ @screendriver +/types/is-trademarked/ @BendingBender +/types/is-typedarray/ @BendingBender +/types/is-unc-path/ @BendingBender /types/is-url/ @RyotaMurohoshi /types/is-url-superb/ @kryops /types/is-uuid/ @tedre191 +/types/is-valid-glob/ @BendingBender +/types/is-valid-path/ @Goldsmith42 /types/is-windows/ @mizunashi-mana /types/isaac/ @mo /types/isbn-utils/ @elhaard /types/iscroll/ @csrakowski @devlato +/types/isexe/ @BendingBender /types/ismobilejs/ @Ty3uK /types/iso-3166-2/ @sicilica /types/iso8601-localizer/ @avielfedida /types/isomorphic-fetch/ @toddlucas /types/isotope-layout/ @avidenic @malinushj +/types/issue-parser/ @Leko +/types/issue-regex/ @BendingBender /types/istanbul/ @tkrotoff /types/istanbul-lib-coverage/ @jason0x43 /types/istanbul-lib-hook/ @jason0x43 @@ -2033,15 +2207,16 @@ /types/istanbul-lib-source-maps/ @jason0x43 /types/istanbul-middleware/ @hookclaw /types/istanbul-reports/ @jason0x43 +/types/istextorbinary/ @BendingBender /types/ityped/ @DanielRosenwasser /types/ix.js/ @Igorbek /types/jackrabbit/ @elvisvoer /types/jade/ @panuhorsmalahti /types/jalaali-js/ @alitaheri /types/japanese-holidays/ @syamatoo +/types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B @cyungmann @Roaders @devoto13 @fdim @pe8ter +/types/jasmine/v2/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B @cyungmann @devoto13 @fdim /types/jasmine/v1/ @borisyankov -/types/jasmine/v2/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B @cyungmann -/types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B @cyungmann @Roaders /types/jasmine-ajax/ @lgrignon /types/jasmine-data-provider/ @tlaziuk /types/jasmine-data_driven_tests/ @AnthonyMacKinnon @@ -2065,8 +2240,8 @@ /types/jcanvas/ @rogierschouten /types/jdataview/ @RReverser /types/jdenticon/ @mtr -/types/jest/v16/ @NoHomey @jwbay /types/jest/ @NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang @wsmd @JamieMason @douglasduteil @ahnpnl @joshuakgoldberg @UselessPickles @r3nya @hotell @sebald @andys8 +/types/jest/v16/ @NoHomey @jwbay /types/jest-axe/ @JoshuaKGoldberg /types/jest-cli/ @lifeiscontent /types/jest-diff/ @myabc @@ -2091,22 +2266,23 @@ /types/jjv/ @Nemo157 /types/jjve/ @Nemo157 /types/jmespath/ @pushplay -/types/johnny-five/ @nakakura @ujvzolee @workshop2 @xtrimsystems -/types/joi/v6/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW -/types/joi/v10/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @aconanlai -/types/joi/v13/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @dankraus @wanganjun @rafaelkallis @aconanlai @zaphoyd @thewillg @SimonSchick +/types/johnny-five/ @nakakura @ujvzolee @workshop2 @xtrimsystems @marcinobiedz /types/joi/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @dankraus @wanganjun @rafaelkallis @aconanlai @zaphoyd @thewillg @SimonSchick +/types/joi/v13/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @dankraus @wanganjun @rafaelkallis @aconanlai @zaphoyd @thewillg @SimonSchick +/types/joi/v10/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @aconanlai +/types/joi/v6/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW /types/joigoose/ @boothwhack /types/josa/ @vichyssoise /types/jotform-css.js/ @pandawood +/types/jpeg-autorotate/ @Slessi /types/jpeg-js/ @DanielRosenwasser /types/jpegtran-bin/ @hikoma /types/jpm/ @github-account-because-they-want-it /types/jqgrid/ @lokeshpeta /types/jqrangeslider/ @qcz -/types/jquery/v1/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu -/types/jquery/v2/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu /types/jquery/ @leonard-thieu @borisyankov @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @johnnyreilly @DickvdBrink @King2500 @terrymun +/types/jquery/v2/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu +/types/jquery/v1/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu /types/jquery-ajax-chain/ @humana-fragilitas /types/jquery-alertable/ @stever /types/jquery-animate-scroll/ @AndersonFriaca @@ -2231,6 +2407,7 @@ /types/js-data-angular/ @reppners /types/js-fixtures/ @kazimanzurrashid /types/js-git/ @Bartvds +/types/js-levenshtein/ @Kallu609 @naftis /types/js-md5/ @mwmccarthy /types/js-money/ @kanatkubash /types/js-nacl/ @ethanfrey @@ -2240,6 +2417,7 @@ /types/js-sha512/ @nicojs /types/js-string-escape/ @viralpickaxe /types/js-to-java/ @skyitachi +/types/js-types/ @BendingBender /types/js-url/ @pine /types/js-yaml/ @Bartvds @sclausen /types/js.spec/ @mattbishop @@ -2252,7 +2430,7 @@ /types/jsend/ @CaselIT /types/jsesc/ @Bartvds /types/jsfl/ @soywiz -/types/jsforce/ @dolanmiu @netes @amphro @tnoonan-salesforce @whiteabelincoln @borys-kupar +/types/jsforce/ @dolanmiu @netes @amphro @tnoonan-salesforce @whiteabelincoln @borys-kupar @catalandres /types/jsftp/ @xyleen /types/jsgraph/ @rosinbum /types/jshamcrest/ @dharkness @@ -2277,11 +2455,14 @@ /types/json3/ @NN--- /types/json5/ @Esemesek /types/json_ml/ @pluma +/types/jsonabc/ @ffflorian +/types/jsonapi-serializer/ @chiangf /types/jsonata/ @nick121212 /types/jsoneditor/ @alejo90 @errietta /types/jsoneditor-for-react/ @joshuakgoldberg /types/jsoneditoronline/ @vbortone -/types/jsonfile/ @dbowring +/types/jsonfile/ @dbowring @BendingBender +/types/jsonfile/v4/ @dbowring /types/jsonic/ @jacobbubu /types/jsonminify/ @no23reason /types/jsonnet/ @hookclaw @@ -2299,14 +2480,14 @@ /types/jsrender/ @zakki /types/jsreport-core/ @taoqf /types/jsreport-html-embedded-in-docx/ @taoqf -/types/jsreport-html-to-xlsx/v1/ @me /types/jsreport-html-to-xlsx/ @me +/types/jsreport-html-to-xlsx/v1/ @me /types/jsreport-jsrender/ @taoqf /types/jsreport-phantom-pdf/ @taoqf /types/jsreport-xlsx/ @taoqf /types/jsrp/ @harryshipton /types/jss/ @appsforartists @kof @pelotom @eps1lon -/types/jssha/ @randombk @SrTobi +/types/jssha/ @randombk @SrTobi @cakoose /types/jstimezonedetect/ @olamothe /types/jstorage/ @dflor003 /types/jstree/ @adaskothebeast @@ -2320,22 +2501,23 @@ /types/jui/ @easylogic /types/jui-core/ @easylogic /types/jui-grid/ @easylogic +/types/junk/ @BendingBender /types/just-debounce-it/ @azizhk /types/just-extend/ @pe8ter /types/just-pick/ @pe8ter /types/jweixin/ @taoqf @gomydodo -/types/jwplayer/ @martinduparc @kutomer @philippguertler @danielmcgraw @bpdsw +/types/jwplayer/ @martinduparc @kutomer @philippguertler @danielmcgraw @bpdsw @bebebebebe @djcsdy @drewwyatt /types/jws/ @JustinBeckwith /types/jwt-client/ @timoteoponce -/types/jwt-decode/v1/ @QuatroDevOfficial /types/jwt-decode/ @GiedriusGrabauskas @madsmadsen +/types/jwt-decode/v1/ @QuatroDevOfficial /types/jwt-express/ @nickp10 /types/jwt-simple/ @kenfdev @GaelMagnan /types/jwt-then/ @phenomax /types/k6/ @MajorBreakfast /types/kafka-node/ @dansitu @bkim54 @sfrooster @amiram -/types/karma/v1/ @tkrotoff @43081j /types/karma/ @tkrotoff @43081j @devoto13 +/types/karma/v1/ @tkrotoff @43081j /types/karma-chai/ @JayAndCatchFire /types/karma-chai-sinon/ @vasek17 /types/karma-coverage/ @tkrotoff @devoto13 @@ -2343,7 +2525,7 @@ /types/karma-jasmine/ @michelsalib /types/karma-viewport/ @karak /types/karma-webpack/ @mtraynham -/types/katex/ @mrand01 +/types/katex/ @mrand01 @knguyen0125 /types/kcors/ @Xstoudi @izayoiko /types/kdbush/ @DenisCarriere @chrfrasco /types/kdbxweb/ @Roang-zero1 @@ -2359,10 +2541,15 @@ /types/keypress.js/ @rcchen /types/keysym/ @harryshipton /types/keytar/ @miniak @shiftkey @juturu -/types/keyv/ @Arylo +/types/keyv/ @Arylo @BendingBender +/types/keyv__mongo/ @BendingBender +/types/keyv__mysql/ @BendingBender +/types/keyv__postgres/ @BendingBender +/types/keyv__redis/ @BendingBender +/types/keyv__sqlite/ @BendingBender /types/kik-browser/ @joelday -/types/klaw/v1/ @mceachen /types/klaw/ @mceachen +/types/klaw/v1/ @mceachen /types/klaw-sync/ @shiftkey /types/kms-json/ @sunnyone /types/knex/ @tkQubo @MeLlamoPablo @mastermatt @micksatana @shreyjain1994 @joelshepherd @@ -2384,6 +2571,7 @@ /types/knockout.validation/ @danludwig /types/knockout.viewmodel/ @oising /types/knockstrap/ @adaskothebeast +/types/known/ @BendingBender /types/knuddels-userapps-api/ @Knuddels /types/ko.plus/ @conficient /types/koa/ @DavidCai1993 @jkeylu @brikou @@ -2428,7 +2616,7 @@ /types/koa-route/ @migstopheles @jacogr /types/koa-router/ @hellopao @schfkt @JounQin @romain-faust @Guillaume-Mayer @falinor /types/koa-send/ @pe8ter @tlaziuk -/types/koa-session/ @kerol2r20 @tlaziuk +/types/koa-session/ @kerol2r20 @tlaziuk @hirochachacha /types/koa-session-minimal/ @longztian /types/koa-sslify/ @wingsbob /types/koa-static/ @hellopao @tlaziuk @@ -2457,6 +2645,8 @@ /types/lambda-tester/ @ivank @HajoAhoMantila /types/lasso/ @darkwebdev /types/later/ @jasond-s +/types/latest-semver/ @BendingBender +/types/latest-version/ @BendingBender /types/latinize/ @GiedriusGrabauskas /types/latlon-geohash/ @rimig /types/launchpad/ @rictic @@ -2467,8 +2657,8 @@ /types/ldap-filters/ @pluma /types/ldapjs/ @cvillemure @peterkooijmans /types/leadfoot/ @theintern -/types/leaflet/v0/ @rgripper /types/leaflet/ @alejo90 @atd-schubert @mcauer +/types/leaflet/v0/ @rgripper /types/leaflet-areaselect/ @awallat /types/leaflet-curve/ @onikiienko /types/leaflet-draw/ @matt-guest @reblace @YunS-Stacy @beschoenen @@ -2483,8 +2673,8 @@ /types/leaflet-providers/ @BendingBender /types/leaflet-rotatedmarker/ @robert-prib-polestar /types/leaflet-routing-machine/ @chanakadrathnayaka -/types/leaflet.awesome-markers/v0/ @Odrin @sebek64 /types/leaflet.awesome-markers/ @sebek64 +/types/leaflet.awesome-markers/v0/ @Odrin @sebek64 /types/leaflet.fullscreen/ @wcomartin /types/leaflet.gridlayer.googlemutant/ @ernest-rhinozeros /types/leaflet.heat/ @onderceylan @@ -2495,6 +2685,7 @@ /types/leaflet.pm/ @tkleinke /types/leaflet.polylinemeasure/ @RiON69 /types/leakage/ @atd-schubert +/types/leap-year/ @BendingBender /types/leapmotionts/ @logotype /types/ledgerhq__hw-transport/ @danwbyrne /types/ledgerhq__hw-transport-node-hid/ @danwbyrne @@ -2507,10 +2698,10 @@ /types/lestate/ @thelambdaparty /types/level-codec/ @danwbyrne /types/level-sublevel/ @basp -/types/leveldown/v1/ @tarruda @LinusU /types/leveldown/ @MeirionHughes @danwbyrne -/types/levelup/v1/ @blittle @tarruda +/types/leveldown/v1/ @tarruda @LinusU /types/levelup/ @MeirionHughes @danwbyrne +/types/levelup/v1/ @blittle @tarruda /types/leven/ @jmalonzo /types/levenshtein/ @geoffreak /types/libpq/ @Lodin @@ -2523,17 +2714,24 @@ /types/lil-uuid/ @Pr1st0n /types/lime-js/ @arthur-xavier /types/line-by-line/ @etomsen +/types/line-column-path/ @BendingBender /types/line-reader/ @stpettersens /types/linear-gradient/ @Jack-Works /types/lingui__core/ @huan086 /types/lingui__macro/ @huan086 /types/lingui__react/ @huan086 +/types/linkify-issues/ @BendingBender /types/linkify-it/ @praxxis -/types/linkifyjs/ @szhu +/types/linkify-urls/ @BendingBender +/types/linkifyjs/ @szhu @ovidiubute +/types/list-git-remotes/ @BendingBender /types/list-stream/ @IanStorm /types/listr/ @durad /types/lls/ @borislavjivkov +/types/load-google-maps-api/ @oBusk /types/load-json-file/ @SamVerschueren +/types/loadable__component/ @martynaskadisa +/types/loadable__server/ @martynaskadisa /types/loader-runner/ @e-cloud /types/loader-utils/ @Perlmint @TotooriaHyperion /types/loadjs/ @screendriver @@ -2544,13 +2742,14 @@ /types/localized-countries/ @coderslagoon /types/localizejs-library/ @salbahra /types/locate-path/ @me -/types/lockfile/v0/ @Bartvds +/types/lock-system/ @BendingBender /types/lockfile/ @Bartvds @BendingBender +/types/lockfile/v0/ @Bartvds /types/lockr/ @droritos /types/locks/ @flippynips /types/locutus/ @hookclaw -/types/lodash/v3/ @bczengel @chrootsu /types/lodash/ @bczengel @chrootsu @stepancar @aj-r @ailrun @e-cloud @thorn0 @jtmthf @DomiR +/types/lodash/v3/ @bczengel @chrootsu /types/lodash-es/ @stephenlautier @e-cloud /types/lodash-webpack-plugin/ @bumbleblym /types/lodash.add/ @bczengel @chrootsu @stepancar @@ -2851,6 +3050,7 @@ /types/looks-same/ @xcatliu /types/loopback/ @kattsushi @enko @sequoia @drmikecrowe @karimsa /types/loopback-boot/ @kattsushi +/types/loopbench/ @BendingBender /types/lorem-ipsum/ @durad /types/lory.js/ @kubosho @milkisevil /types/loud-rejection/ @BendingBender @@ -2862,13 +3062,14 @@ /types/lscache/ @Chris-Martinezz /types/ltx/ @PJakcson @BendingBender /types/luaparse/ @stpettersens +/types/lunr/ @seantanly @hokiegeek /types/lunr/v0/ @sebastian-lenz -/types/lunr/ @seantanly /types/lusca/ @crutchcorn -/types/luxon/ @colbydehart @FourwingsY @jsiebern @mastermatt +/types/luxon/ @colbydehart @FourwingsY @jsiebern @mastermatt @pietrovismara @dawnmist /types/lwip/ @AyaMorisawa /types/lz-string/ @M0ns1gn0r /types/lzma-native/ @leshow +/types/macrotask/ @BendingBender /types/magic-number/ @stpettersens /types/magicsuggest/ @leonardochaia /types/magnet-uri/ @tlaziuk @@ -2888,6 +3089,7 @@ /types/mali-compose/ @danwbyrne /types/mali-onerror/ @danwbyrne /types/mandrill-api/ @pocesar +/types/mangopay2-nodejs-sdk/ @ifiokjr /types/map-obj/ @BendingBender /types/mapbox/ @anahkiasen @Fluccioni /types/mapbox-gl/ @dobrud @patrickr @@ -2895,11 +3097,12 @@ /types/mapbox__geo-viewport/ @fnberta /types/mapbox__geojson-area/ @n0nick /types/mapbox__polyline/ @Kern0 @mklopets +/types/mapbox__s3urls/ @sebastianvera /types/mapbox__shelf-pack/ @Perlmint /types/mapnik/ @ipv4sec /types/mapsjs/ @davismj /types/mariasql/ @bennett000 -/types/mark.js/ @renjfk @RomanGotsiy +/types/mark.js/ @renjfk @RomanGotsiy @LucianBuzzo /types/markdown-it/ @rapropos /types/markdown-it-anchor/ @seryl /types/markdown-it-container/ @hronex @@ -2907,18 +3110,20 @@ /types/markdown-pdf/ @MonsieurMan /types/markdownlint/ @ark120202 /types/marked/ @worr @BendingBender @CrossR @mwickett +/types/marked-terminal/ @bkendall /types/marker-animate-unobtrusive/ @viskin /types/markerclustererplus/ @enanox @mxl /types/markitup/ @drillbits /types/marko/ @darkwebdev /types/maskedinput/ @lokeshpeta /types/masonry-layout/ @m-a-wilson @warriorrocker -/types/massive/v3/ @swissspidy @clarenceh -/types/massive/v4/ @swissspidy @clarenceh @AmazingTurtle /types/massive/ @swissspidy @clarenceh @AmazingTurtle @mike-engel +/types/massive/v4/ @swissspidy @clarenceh @AmazingTurtle +/types/massive/v3/ @swissspidy @clarenceh /types/match-media-mock/ @asvetliakov -/types/match-sorter/ @claasahl -/types/material-components-web/ @BrentDouglas @ckosti +/types/match-sorter/ @claasahl @chrisru +/types/matcher/ @BendingBender +/types/material-components-web/ @BrentDouglas @ckosti @agroupp /types/material-design-lite/ @bradzacher /types/material-ui/ @ngbrown @theigor @alitaheri @herrmanno @DaIgeb @allienna @schlesingermatthias @InsidersByte @artyomsv @dan-j @minodisk @samwalshnz @reggino /types/material-ui-datatables/ @coding2012 @@ -2928,13 +3133,15 @@ /types/material__checkbox/ @BrentDouglas @ckosti /types/material__chips/ @BrentDouglas @ckosti /types/material__dialog/ @BrentDouglas @ckosti -/types/material__drawer/ @BrentDouglas @ckosti +/types/material__dom/ @agroupp +/types/material__drawer/ @BrentDouglas @ckosti @agroupp /types/material__floating-label/ @BrentDouglas @ckosti /types/material__form-field/ @BrentDouglas @ckosti /types/material__grid-list/ @BrentDouglas @ckosti /types/material__icon-toggle/ @BrentDouglas @ckosti /types/material__line-ripple/ @BrentDouglas @ckosti /types/material__linear-progress/ @BrentDouglas @ckosti +/types/material__list/ @agroupp /types/material__menu/ @BrentDouglas @ckosti /types/material__notched-outline/ @BrentDouglas @ckosti /types/material__radio/ @BrentDouglas @ckosti @@ -2948,8 +3155,8 @@ /types/material__textfield/ @BrentDouglas @ckosti /types/material__toolbar/ @BrentDouglas @ckosti /types/material__top-app-bar/ @BrentDouglas @ckosti -/types/materialize-css/v0/ @eriklieben @leonyu @SinghSukhdeep @jfcere @scote @LiadIdan /types/materialize-css/ @huww98 @MaximBalaganskiy @MonizDave @broccoliarchy +/types/materialize-css/v0/ @eriklieben @leonyu @SinghSukhdeep @jfcere @scote @LiadIdan /types/math3d/ @laszlojakab @jimsmart /types/mathjax/ @rolandzwaga /types/mathjs/ @siavol @andnp @bradbesserman @pawkrol @@ -2965,19 +3172,24 @@ /types/medium-editor/ @keika299 @pascaliske /types/megajs/ @danwbyrne /types/mem/ @SamVerschueren +/types/mem-cache/ @MutterPedro /types/mem-fs/ @MyFoodBag /types/mem-fs-editor/ @MyFoodBag /types/memcached/ @KentarouTakeda /types/memdown/ @MeirionHughes @danwbyrne /types/memjs/ @leizongmin /types/memoize-one/ @karol-majewski @franklixuefei +/types/memoize-one/v3/ @karol-majewski @franklixuefei /types/memoizee/ @juanpicado /types/memory-cache/ @jedigo @thieman /types/memory-fs/ @e-cloud +/types/memory-pager/ @BendingBender +/types/memorystream/ @bangbang93 /types/memwatch-next/ @cyrilschumacher /types/meow/ @KnisterPeter @praxxis @bitjson /types/merge-descriptors/ @danny8002 /types/merge-env/ @BendingBender +/types/merge-images/ @BendingBender /types/merge-stream/ @k-kagurazaka @tomxtobin @daniel-zazula @djcsdy /types/merge2/ @tkrotoff @smac89 /types/merkle/ @kerol2r20 @@ -2986,7 +3198,7 @@ /types/meshblu/ @fnipo /types/mess/ @Nemo157 /types/messenger/ @derekcicerone -/types/meteor/ @barbatus @fullflavedave @orefalo @dagatsoin @birkskyum @ardatan @stefanholzapfel @andrei-markeev @lmachens +/types/meteor/ @barbatus @fullflavedave @orefalo @dagatsoin @birkskyum @ardatan @stefanholzapfel @andrei-markeev @lmachens @gunn /types/meteor-accounts-phone/ @DAB0mB /types/meteor-astronomy/ @Deadly0 /types/meteor-collection-hooks/ @twastvedt @@ -3002,9 +3214,11 @@ /types/mfiles/ @avonwyss /types/micro/ @kaoDev /types/micro-cors/ @CallumDenby -/types/micromatch/v2/ @glen-84 +/types/micro-events/ @AlexanderSychev /types/micromatch/ @glen-84 @vemoo +/types/micromatch/v2/ @glen-84 /types/microrouter/ @mathieudutour +/types/microservice-utilities/ @runebaas /types/microsoft-ajax/ @pjmagee /types/microsoft-live-connect/ @jvilk /types/microsoft-sdk-soap/ @markusmauch @@ -3016,6 +3230,7 @@ /types/mime-db/ @AJamesPhillips /types/mime-types/ @Perlmint /types/mimos/ @AJamesPhillips +/types/min-indent/ @BendingBender /types/mina/ @lhk @mattanja @kant2002 /types/mini-css-extract-plugin/ @JounQin /types/minimal-bit-array/ @jeremejevs @@ -3029,6 +3244,7 @@ /types/mithril-global/ @spacejack @isiahmeadows /types/mitm/ @alejo90 /types/mixpanel/ @hjellek @Manduro +/types/mixpanel-browser/ @karlos1337 /types/mixto/ @vvakame /types/mjml/ @aahoughton @marpstar /types/mjml-react/ @henrinormak @@ -3036,6 +3252,7 @@ /types/mkdirp-promise/ @pluma /types/mkpath/ @optical /types/ml-levenberg-marquardt/ @m93a +/types/mnemonic-words/ @BendingBender /types/mobx-apollo/ @pselden /types/mobx-devtools-mst/ @pluma /types/mocha/ @kazimanzurrashid @otiai10 @jt000 @enlight @cspotcode @1999 @@ -3053,6 +3270,7 @@ /types/mockingoose/ @hirochachacha /types/modernizr/ @borisyankov @theodorejb @leonyu @lucax88x @nhardy /types/modesl/ @neeschit +/types/modular-scale/ @mikefowler /types/module-alias/ @KevinRamharak /types/module-deps/ @TeamworkGuy2 /types/moji/ @yasupeke @@ -3061,24 +3279,25 @@ /types/moment-duration-format/ @SwintDC @TwoStone @leonard-thieu @bendykowski /types/moment-holiday/ @rwdalpe /types/moment-jalaali/ @alitaheri -/types/moment-range/ @Burgov @wilgert @franjuan @MartynasZilinskas +/types/moment-range/ @Burgov @wilgert @franjuan @MartynasZilinskas @chemass /types/moment-round/ @jacobbaskin /types/moment-shortformat/ @whatasoda /types/moment-strftime2/ @dex4er -/types/moment-timezone/ @michelsalib @alanblins +/types/moment-timezone/ @michelsalib @alanblins @asermax /types/money-math/ @taoqf /types/mongo-sanitize/ @CedricCazin -/types/mongodb/v2/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi /types/mongodb/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi @EnricoPicci @AJCStriker @julien-c @daprahamian @denys-bushulyak @BastienAr @sindbach @geraldinelemeur @jishi @various89 @angela-1 @lirbank @hector7 @floric @erikc5000 +/types/mongodb/v2/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi /types/mongodb-memory-server/ @dmitryrogozhny /types/mongodb-uri/ @mernxl -/types/mongoose/v4/ @simonxca @horiuchi @sindrenm @lukasz-zak -/types/mongoose/ @horiuchi @sindrenm @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @jussikinnula @ondratra @alfirin @idandrd @various89 @Fazendaaa @NormanPerrin @danmana @stablio +/types/mongoose/ @horiuchi @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @jussikinnula @ondratra @alfirin @idandrd @various89 @Fazendaaa @NormanPerrin @danmana @stablio @emmanuelgautier @frontendmonster @mingchen +/types/mongoose/v4/ @simonxca @horiuchi @lukasz-zak /types/mongoose-auto-increment/ @AyaMorisawa /types/mongoose-deep-populate/ @AyaMorisawa /types/mongoose-geojson-schema/ @bondz /types/mongoose-mock/ @jt000 /types/mongoose-paginate/ @linusbrolin @simonxca +/types/mongoose-paginate-v2/ @linusbrolin @simonxca @woutgg /types/mongoose-promise/ @simonxca /types/mongoose-seeder/ @Crevil /types/mongoose-sequence/ @linusbrolin @@ -3086,6 +3305,7 @@ /types/mongoose-unique-validator/ @stevehipwell /types/mongorito/ @pinguet62 /types/mongration/ @soulthreads +/types/month-days/ @BendingBender /types/moo/ @deltaidea @MofX /types/moonjs/ @DanielRosenwasser /types/morgan/ @staticfunction @pscanf @@ -3093,8 +3313,9 @@ /types/morris.js/ @mareek @sindilevich /types/mosca/ @GabrielGouv @jerray /types/motor-hat/ @muntyan -/types/mousetrap/ @qcz +/types/mousetrap/ @qcz @alanhchoi /types/move-concurrently/ @mgroenhoff +/types/move-file/ @BendingBender /types/moveto/ @shermendev /types/moviedb/ @basarat @0x6368656174 /types/moxios/ @itoasuka @@ -3109,14 +3330,16 @@ /types/msportalfx-test/ @julioct /types/mssql/ @jaminfarr @buzinas @mrrichar @elhaard @pkeuter @mcdado /types/mu2/ @jedigo +/types/mui-datatables/ @favna /types/muicss/ @samuelneff /types/multer/ @jt000 @DavidBR-SW @mxl @hyunseob -/types/multer-gridfs-storage/v1/ @devconcept -/types/multer-gridfs-storage/v2/ @devconcept /types/multer-gridfs-storage/ @devconcept +/types/multer-gridfs-storage/v2/ @devconcept +/types/multer-gridfs-storage/v1/ @devconcept /types/multer-s3/ @tcaesvk @galtalmor @terski +/types/multi-progress/ @DHBrett /types/multi-typeof/ @mhegazy -/types/multimatch/ @stephenlautier +/types/multimatch/ @stephenlautier @BendingBender /types/multiparty/ @kenfdev /types/multiplexjs/ @KamyarNazeri /types/multisort/ @CzBuCHi @@ -3150,17 +3373,21 @@ /types/navermaps/ @ckboyjiy /types/navigation/ @grahammendick /types/navigation-react/ @grahammendick +/types/navigator-permissions/ @vargavince91 @minddocdev /types/navigo/ @aersamkull @dancespiele @deini /types/nblas/ @erikgerrits -/types/nconf/ @jedigo @jmthibault +/types/nconf/ @jedigo @jmthibault @ew73 /types/ncp/ @bartvds /types/ndarray/ @pawsong @taoqf /types/nearley/ @deltaidea @BendingBender +/types/neat-csv/ @calamitizer /types/nedb/ @reppners @anthonynichols @afharo /types/nedb-logger/ @thisboyiscrazy -/types/needle/v0/ @bigsan +/types/needle/ @bigsan @nikeee @sindilevich @bryanspears /types/needle/v1/ @bigsan @nikeee -/types/needle/ @bigsan @nikeee @sindilevich +/types/needle/v0/ @bigsan +/types/negative-array/ @BendingBender +/types/negative-zero/ @BendingBender /types/negotiator/ @BendingBender /types/neo4j/ @cyrilschumacher /types/nes/ @NoHomey @saboya @@ -3170,15 +3397,20 @@ /types/netlify-identity-widget/ @nkprince007 /types/netmask/ @mhfrantz /types/network-interfaces/ @anderswestberg +/types/new-github-issue-url/ @BendingBender +/types/new-github-release-url/ @BendingBender /types/new-relic-browser/ @renehamburger @piotrkubisa /types/newline-remove/ @OpenByteDev /types/newman/ @LogvinovLeon @Graham42 -/types/newrelic/ @mastermatt @brookspatton +/types/newrelic/ @mastermatt @brookspatton @MichaelRBond /types/nexpect/ @vvakame /types/next/ @dru89 @brikou @jthegedus @resir014 @scottdj92 @joaovieira @ajliv /types/next-redux-saga/ @leocavalcante /types/next-redux-wrapper/ @stevegeek @Jungwoo-An +/types/next-seo/ @ThomasK33 /types/next-server/ @dru89 @brikou @jthegedus @resir014 @scottdj92 @joaovieira @ajliv +/types/next-tick/ @BendingBender +/types/nextgen-events/ @katsanva /types/ng-command/ @stephenlautier /types/ng-cordova/ @ksachdeva /types/ng-dialog/ @stephenlautier @@ -3206,15 +3438,16 @@ /types/nise/ @a-tarasyuk /types/nivo-slider/ @AndersonFriaca /types/noble/ @swook @shantanubhadoria @lukel99 @bioball @keton @thegecko +/types/noble-mac/ @swook @shantanubhadoria @lukel99 @bioball @keton @thegecko /types/nock/ @bonnici @horiuchi @afharo @mastermatt @damour @paambaati /types/nodal/ @charrondev -/types/node/v0/ @Microsoft @DefinitelyTyped -/types/node/v4/ @Microsoft @DefinitelyTyped @eps1lon @Archcry -/types/node/v6/ @Microsoft @DefinitelyTyped @WilcoBakker @inlined @eps1lon @Alorel @KSXGitHub @Archcry -/types/node/v7/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @eps1lon @KSXGitHub @Archcry -/types/node/v8/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @hoo29 @n-e @brunoscheufler @KSXGitHub @islishude @r3nya +/types/node/ @Microsoft @DefinitelyTyped @jkomyno @a-tarasyuk @alvis @r3nya @brunoscheufler @smac89 @tellnes @DeividasBakanas @eyqs @Flarna @Hannes-Magnusson-CK @KSXGitHub @hoo29 @kjin @ajafff @islishude @mwiktorczyk @matthieusieben @mohsen1 @n-e @octo-sniffle @parambirs @eps1lon @SimonSchick @ThomasdenH @WilcoBakker @wwwy3y3 @ZaneHannanAU @jeremiergz @samuela @kuehlein /types/node/v9/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @ajafff @hoo29 @n-e @brunoscheufler @mohsen1 @KSXGitHub @a-tarasyuk @islishude @r3nya @eyqs -/types/node/ @Microsoft @DefinitelyTyped @jkomyno @a-tarasyuk @alvis @r3nya @brunoscheufler @smac89 @tellnes @DeividasBakanas @eyqs @Flarna @Hannes-Magnusson-CK @KSXGitHub @hoo29 @kjin @ajafff @islishude @mwiktorczyk @matthieusieben @mohsen1 @n-e @octo-sniffle @parambirs @eps1lon @SimonSchick @ThomasdenH @WilcoBakker @wwwy3y3 @ZaneHannanAU @jeremiergz @samuela +/types/node/v8/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @hoo29 @n-e @brunoscheufler @KSXGitHub @islishude @r3nya +/types/node/v7/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @eps1lon @KSXGitHub @Archcry +/types/node/v6/ @Microsoft @DefinitelyTyped @WilcoBakker @inlined @eps1lon @Alorel @KSXGitHub @Archcry +/types/node/v4/ @Microsoft @DefinitelyTyped @eps1lon @Archcry +/types/node/v0/ @Microsoft @DefinitelyTyped /types/node-7z/ @erkie /types/node-array-ext/ @Beng89 /types/node-cache/ @chrootsu @dthunell @useltmann @@ -3225,13 +3458,14 @@ /types/node-dijkstra/ @nokutu /types/node-dir/ @panuhorsmalahti /types/node-dogstatsd/ @chrisbobo -/types/node-emoji/ @jonestristand @styu -/types/node-fetch/ @torstenwerner @nikcorg +/types/node-emoji/ @jonestristand @styu @rimiti +/types/node-fetch/ @torstenwerner @nikcorg @vinaybedre /types/node-fibers/ @caryhaynie -/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung @joeflateau @Apologiz @timhwang21 +/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung @joeflateau @Apologiz @timhwang21 @supaiku0 @andersk /types/node-gcm/ @horiuchi /types/node-geocoder/ @rosek86 /types/node-getopt/ @kcauchy +/types/node-gettext/ @sameercaresu /types/node-hid/ @mhegazy @ert78gb @thegecko /types/node-horseman/ @apratheek /types/node-hue-api/ @fjmorel @@ -3243,18 +3477,19 @@ /types/node-memwatch/ @Kroisse /types/node-mysql-wrapper/ @kataras /types/node-notifier/ @tkQubo -/types/node-polyglot/ @timjk +/types/node-polyglot/ @timjk @liamross /types/node-powershell/ @rodrigoff /types/node-pushnotifications/ @menushka /types/node-ral/ @ssddi456 /types/node-red/ @andersea @tbowmo /types/node-redis-pubsub/ @renekeijzer /types/node-resque/ @gordey4doronin -/types/node-rsa/ @alitaheri @xm +/types/node-rsa/ @alitaheri @xm @ffflorian /types/node-schedule/ @cyrilschumacher @flowpl /types/node-slack/ @tkQubo /types/node-snap7/ @heilingbrunner /types/node-sprite-generator/ @Perlmint +/types/node-sql-parser/ @taozhi8833998 /types/node-ssdp/ @OrionNebula /types/node-static/ @Morfent /types/node-statsd/ @alexturek @convoyinc @@ -3263,6 +3498,7 @@ /types/node-validator/ @kengorab /types/node-vault/ @YuJianrong /types/node-wit/ @julienduf +/types/node-xlsx/ @cWatermelon /types/node-xmpp-client/ @PJakcson /types/node-xmpp-core/ @PJakcson /types/node-zookeeper-client/ @plantain-00 @jessezhang91 @@ -3271,8 +3507,8 @@ /types/node_redis/ @borisyankov /types/nodecredstash/ @migstopheles /types/nodegit/ @dolanmiu @tniessen -/types/nodemailer/v3/ @rogierschouten /types/nodemailer/ @rogierschouten @dex4er @bioball +/types/nodemailer/v3/ @rogierschouten /types/nodemailer-direct-transport/ @rogierschouten /types/nodemailer-mailgun-transport/ @otociulis /types/nodemailer-pickup-transport/ @psnider @@ -3286,24 +3522,32 @@ /types/nookies/ @andreasbergqvist /types/nopt/ @jbondc /types/normalize-package-data/ @jdxcode +/types/normalize-path/ @BendingBender /types/normalize-url/ @odin3 @BendingBender @mathieumg /types/notie/ @mateusdemboski /types/notify/ @hellochar /types/notifyjs/ @soundTricker @NateScarlet /types/notifyjs-browser/ @bahman616 /types/notyf/ @gurov -/types/nouislider/v7/ @acoreyj -/types/nouislider/v8/ @bleuarg /types/nouislider/ @bleuarg @lagaffe +/types/nouislider/v8/ @bleuarg +/types/nouislider/v7/ @acoreyj /types/novnc-core/ @smithkl42 @BendingBender /types/npm/ @SomaticIT +/types/npm-email/ @BendingBender +/types/npm-keyword/ @BendingBender +/types/npm-license-crawler/ @ffflorian +/types/npm-name/ @BendingBender /types/npm-package-arg/ @mgroenhoff @OiYouYeahYou /types/npm-packlist/ @ajafff +/types/npm-paths/ @BendingBender +/types/npm-run-path/ @BendingBender +/types/npm-user/ @BendingBender +/types/npm-user-packages/ @BendingBender /types/npmlog/ @DanielMSchmidt @littlepiggy03 /types/ns-api/ @Archcry /types/nslog/ @unindented /types/nsqjs/ @cezaryrk -/types/nuka-carousel/ @Romic @altaudio @matt-sungwook /types/number-is-nan/ @mhegazy /types/number-to-words/ @frederickfogerty /types/numeral/ @vbortone @BehindTheMath @klujanrosas @@ -3332,7 +3576,7 @@ /types/object-keys-mapping/ @newraina /types/object-map/ @wolfgang42 /types/object-merge/ @OpenByteDev -/types/object-path/ @pocesar +/types/object-path/ @pocesar @BendingBender /types/object-refs/ @3fd /types/object.getownpropertydescriptors/ @VitorLuizC /types/oblo-util/ @Oblosys @@ -3343,7 +3587,7 @@ /types/oembed-parser/ @BendingBender /types/ofe/ @Morfent /types/office-js/ @OfficeDev @LanceEA @Zlatkovsky @kbrandl @Rick-Kirkham @AlexJerabek @ElizabethSamuel-MSFT -/types/office-js-preview @OfficeDev @Zlatkovsky @kbrandl @Rick-Kirkham @AlexJerabek @ElizabethSamuel-MSFT +/types/office-js-preview/ @OfficeDev @Zlatkovsky @kbrandl @Rick-Kirkham @AlexJerabek @ElizabethSamuel-MSFT /types/office-runtime/ @Zlatkovsky @mscharlock /types/offline-js/ @cgwrench /types/oibackoff/ @geoffreak @@ -3352,50 +3596,57 @@ /types/okta__okta-vue/ @innovation-team /types/ol/ @yairtawil /types/omggif/ @ffflorian +/types/on-change/ @BendingBender /types/on-finished/ @czechboy0 @BendingBender /types/on-headers/ @jjeffery @BendingBender /types/on-wake-up/ @ajafff /types/once/ @denis-sokolov @BendingBender +/types/one-time/ @BendingBender /types/onesignal-cordova-plugin/ @broder /types/onetime/ @BendingBender /types/oniguruma/ @smhxx /types/onoff/ @marcel-ernst @Kallu609 /types/ontime/ @Hirse /types/open/ @Bartvds +/types/open-editor/ @BendingBender +/types/openapi-factory/ @runebaas /types/opener/ @tikurahul -/types/openfin/v17/ @chrisbarker -/types/openfin/v29/ @chrisbarker @rdepena -/types/openfin/v34/ @chrisbarker @rdepena @whyn07m3 /types/openfin/ @chrisbarker @rdepena @whyn07m3 @licui3936 +/types/openfin/v34/ @chrisbarker @rdepena @whyn07m3 +/types/openfin/v29/ @chrisbarker @rdepena +/types/openfin/v17/ @chrisbarker /types/openjscad/ @danmarshall -/types/openlayers/v2/ @bolhovsky -/types/openlayers/v3/ @osechet @matthiasdailey-ccri /types/openlayers/ @osechet @wb14123 @ailrun @mylen @iamthechad @danmana @yairtawil @pierremarc @hauke96 @gberaudo -/types/openpgp/ @errietta @damonpam @po5i +/types/openlayers/v3/ @osechet @matthiasdailey-ccri +/types/openlayers/v2/ @bolhovsky +/types/openpgp/ @errietta @damonpam @po5i @ecamellini /types/openstack-wrapper/ @sanjaymadane /types/opentok/ @westy92 @CatGuardian /types/opentype.js/ @danmarshall @edzis /types/opn/ @shinnn @SomaticIT @tlent -/types/opossum/ @quinnlangille @merufm @lance +/types/opossum/ @quinnlangille @merufm @lance @mastermatt /types/optics-agent/ @crevil /types/optimist/ @soywiz @chbrown /types/optimize-css-assets-webpack-plugin/ @odnamrataizem -/types/ora/v0/ @basarat @screendriver /types/ora/ @basarat @screendriver @BendingBender @azasypkin +/types/ora/v1/ @basarat @screendriver @BendingBender @azasypkin +/types/ora/v0/ @basarat @screendriver /types/oracle__oraclejet/ @nolakara @jingxwu /types/oracledb/ @Bigous /types/orchestrator/ @tkQubo @TeamworkGuy2 /types/orderedmap/ @bradleyayers /types/orientjs/ @saeedtabrizi +/types/original/ @wcarson /types/os-homedir/ @mhegazy -/types/os-locale/v1/ @AyaMorisawa @BendingBender /types/os-locale/ @AyaMorisawa @BendingBender +/types/os-locale/v1/ @AyaMorisawa @BendingBender /types/os-name/ @BendingBender /types/os-tmpdir/ @mhegazy /types/osmosis/ @jurajkocan @evanshortiss /types/osmtogeojson/ @tkqubo /types/osrm/ @DenisCarriere /types/otplib/ @renjfk +/types/overlayscrollbars/ @KingSora /types/overwatch-api/ @JoshuaHall /types/owasp-password-strength-test/ @stephtr /types/owl.carousel/ @igorissen @KennethanCeyer @@ -3410,6 +3661,8 @@ /types/p-each-series/ @BendingBender /types/p-event/ @BendingBender /types/p-every/ @BendingBender +/types/p-forever/ @BendingBender +/types/p-is-promise/ @BendingBender /types/p-lazy/ @BendingBender /types/p-limit/ @BendingBender @LinusU /types/p-loading/ @renjfk @@ -3418,11 +3671,13 @@ /types/p-map/ @BendingBender /types/p-map-series/ @BendingBender /types/p-memoize/ @forabi +/types/p-min-delay/ @BendingBender /types/p-one/ @BendingBender +/types/p-pipe/ @BendingBender /types/p-progress/ @icopp /types/p-props/ @BendingBender -/types/p-queue/v2/ @BendingBender @evanshortiss /types/p-queue/ @BendingBender @evanshortiss +/types/p-queue/v2/ @BendingBender @evanshortiss /types/p-reduce/ @BendingBender /types/p-reflect/ @BendingBender /types/p-retry/ @BendingBender @@ -3431,19 +3686,23 @@ /types/p-some/ @BendingBender /types/p-tap/ @BendingBender /types/p-throttle/ @BendingBender +/types/p-time/ @BendingBender /types/p-timeout/ @BendingBender +/types/p-times/ @BendingBender /types/p-try/ @BendingBender @LinusU -/types/p-wait-for/v1/ @BendingBender /types/p-wait-for/ @BendingBender +/types/p-wait-for/v1/ @BendingBender +/types/p-waterfall/ @BendingBender /types/p-whilst/ @BendingBender /types/p2/ @clark-stevenson /types/p5/ @p5-types -/types/package-json/ @jinwoo +/types/package-json/ @jinwoo @BendingBender /types/packery/ @piraveen @hanssens /types/pad/ @mhegazy /types/page/ @43081j /types/paho-mqtt/ @amikhalev /types/pako/ @cappellin @calebegg +/types/palx/ @mikefowler /types/pangu/ @plantain-00 /types/papaparse/ @torpedro @rainshen49 @jfloff @johnnyreilly @albertorestifo @BehindTheMath @3af @jliuhtonen /types/paper/ @clark-stevenson @Xakaloz @sebaswebdev @rfried @@ -3452,23 +3711,30 @@ /types/parcel-bundler/ @pinage404 /types/parcel-env/ @fathyb /types/parent-package-json/ @sgmccli +/types/parents/ @TeamworkGuy2 /types/parity-pmd/ @leovujanic @jewbre /types/parity-pmr/ @leovujanic /types/parity-poe/ @leovujanic -/types/parse/v1/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas +/types/park-miller/ @BendingBender /types/parse/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas @agoldis -/types/parse-git-config/ @leonard-thieu @deltaidea +/types/parse/v1/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas +/types/parse-columns/ @BendingBender +/types/parse-filepath/ @BendingBender +/types/parse-git-config/ @leonard-thieu @deltaidea @BendingBender +/types/parse-git-config/v2/ @leonard-thieu @deltaidea /types/parse-github-url/ @ajafff /types/parse-glob/ @glen-84 /types/parse-json/ @mrmlnc /types/parse-link-header/ @zelein /types/parse-mockdb/ @dpoetzsch /types/parse-ms/ @Roaders +/types/parse-numeric-range/ @eoin-obrien +/types/parse-passwd/ @BendingBender /types/parse-torrent/ @niieani @tlaziuk /types/parse-torrent-file/ @tlaziuk /types/parse-unit/ @Jack-Works -/types/parse5/v4/ @inikulin @andnp /types/parse5/ @inikulin +/types/parse5/v4/ @inikulin @andnp /types/parse5-html-rewriting-stream/ @samuelli /types/parse5-htmlparser2-tree-adapter/ @inikulin /types/parse5-parser-stream/ @inikulin @@ -3478,7 +3744,7 @@ /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/ @horiuchi @enaeseth @theigor @tlaziuk @danielpa9708 @kstiehl /types/passport-anonymous/ @0x6368656174 /types/passport-auth0/ @johnbendi @iamvishnusankar @duncanhall /types/passport-azure-ad/ @ShekharNain @@ -3488,18 +3754,19 @@ /types/passport-discord/ @kzay /types/passport-facebook/ @staticfunction @lucasmacosta /types/passport-facebook-token/ @rmartone @mrand01 -/types/passport-github/ @yasupeke -/types/passport-github2/ @yasupeke @mthmulders @codepunkt +/types/passport-github/ @yasupeke @reggaepanda +/types/passport-github2/ @yasupeke @mthmulders @codepunkt @ivan94 /types/passport-google-oauth/ @staticfunction /types/passport-google-oauth2/ @bluehatbrit -/types/passport-http/ @krizalys @tlaziuk @cjbarth +/types/passport-http/ @krizalys @tlaziuk @cjbarth @jamesadarich /types/passport-http-bearer/ @isman-usoh /types/passport-jwt/ @jindev /types/passport-kakao/ @Park9eon @zerocho +/types/passport-linkedin-oauth2/ @andrewvetovitz /types/passport-local/ @SomaticIT /types/passport-local-mongoose/ @linusbrolin /types/passport-naver/ @Park9eon @zerocho -/types/passport-oauth2/ @pasieronen @WangZishi @EduardoAC +/types/passport-oauth2/ @pasieronen @WangZishi @EduardoAC @ivan94 /types/passport-oauth2-client-password/ @akaNightmare /types/passport-remember-me-extended/ @AylaJK /types/passport-saml/ @cjbarth @dassennato @ksamborski @@ -3511,10 +3778,13 @@ /types/passport-windowsauth/ @forivall /types/password-hash/ @mugeso /types/password-hash-and-salt/ @alitaheri -/types/path-exists/v1/ @shiwano /types/path-exists/ @shiwano @BendingBender +/types/path-exists/v1/ @shiwano /types/path-is-absolute/ @mhegazy /types/path-is-inside/ @aomarks +/types/path-key/ @BendingBender +/types/path-regex/ @BendingBender +/types/path-type/ @BendingBender /types/pathfinding/ @BNedry /types/pathjs/ @lokeshpeta /types/pathwatcher/ @GlenCFL @@ -3538,8 +3808,9 @@ /types/permit/ @jannikkeye /types/persona/ @Nycto /types/pet-finder-api/ @me -/types/pg/v6/ @pspeter3 +/types/petit-dom/ @JamesMessinger /types/pg/ @pspeter3 +/types/pg/v6/ @pspeter3 /types/pg-ears/ @bradleyayers /types/pg-escape/ @khell /types/pg-format/ @zopf @@ -3565,6 +3836,7 @@ /types/pick-weight/ @rsxdalv /types/pickadate/ @theodorejb @leonard-thieu /types/picturefill/ @alaz +/types/pid-from-port/ @BendingBender /types/pidusage/ @cyrilschumacher @mx601595686 /types/pify/ @samverschueren @mad-mike @c7hm4r /types/pigpio/ @manerfan @erikma @@ -3572,8 +3844,8 @@ /types/pikaday/ @MidnightDesign @wake42 @mezoistvan /types/pikaday-time/ @Sayan751 /types/pinkyswear/ @chances -/types/pino/v3/ @psnider /types/pino/ @psnider @BendingBender @screendriver @paambaati @alferpal @mortiy +/types/pino/v3/ @psnider /types/pino-http/ @screendriver /types/pino-multi-stream/ @JakeGinnivan /types/pinterest-sdk/ @adamburmister @@ -3584,6 +3856,7 @@ /types/pkg-conf/ @jorgegonzalez /types/pkg-dir/ @NK-WEB-Git /types/pkg-up/ @forivall +/types/pkg-versions/ @BendingBender /types/pkijs/ @microshine /types/platform/ @JakeH /types/playcanvas/ @Neoflash1979 @@ -3606,6 +3879,7 @@ /types/point-in-polygon/ @dyst5422 @kogai /types/pollyjs__adapter/ @feinoujc /types/pollyjs__adapter-fetch/ @feinoujc +/types/pollyjs__adapter-node-http/ @jlmessenger /types/pollyjs__core/ @feinoujc /types/pollyjs__persister/ @feinoujc /types/pollyjs__persister-fs/ @feinoujc @@ -3617,6 +3891,7 @@ /types/polymer-ts/ @lgrignon /types/popcorn/ @grapswiz /types/portscanner/ @douglasduteil +/types/positive-zero/ @BendingBender /types/postal/ @lokeshpeta @myitcv /types/postcss-calc/ @huan086 /types/postcss-icss-values/ @huan086 @@ -3653,10 +3928,13 @@ /types/preloadjs/ @endel /types/prelude-ls/ @AyaMorisawa /types/prettier/ @ikatyang -/types/pretty-bytes/v4/ @plantain-00 /types/pretty-bytes/ @plantain-00 @danielasy +/types/pretty-bytes/v4/ @plantain-00 /types/pretty-format/ @ikatyang -/types/pretty-ms/ @BendingBender @ocboogie +/types/pretty-hrtime/ @BendingBender +/types/pretty-ms/ @BendingBender @ocboogie @silh +/types/pretty-ms/v3/ @BendingBender @ocboogie +/types/preval.macro/ @huan086 /types/printf/ @AluisioASG /types/priorityqueuejs/ @geoffreak /types/prismic-dom/ @nickw444 @sbilstein @@ -3666,7 +3944,7 @@ /types/progress/ @sebastian-lenz /types/progressbar/ @atd-schubert /types/progressjs/ @zaneli -/types/proj4/ @DenisCarriere +/types/proj4/ @DenisCarriere @BendingBender /types/proj4leaflet/ @BendingBender /types/project-oxford/ @scsouthw /types/prometheus-gc-stats/ @danwbyrne @@ -3690,7 +3968,7 @@ /types/prompt-sync/ @MugeSo /types/prompt-sync-history/ @MugeSo /types/promptly/ @danrspencer -/types/prompts/ @Berkays @danielpa9708 +/types/prompts/ @Berkays @danielpa9708 @kamontat /types/prop-types/ @DovydasNavickas @ferdaber /types/proper-lockfile/ @qlonik /types/properties-reader/ @Goldsmith42 @@ -3719,11 +3997,14 @@ /types/proxy-lists/ @BehindTheMath /types/proxy-verifier/ @BehindTheMath /types/proxyquire/ @jt000 +/types/ps-list/ @BendingBender /types/ps-tree/ @alessiopcc +/types/pseudo-audio-param/ @kirbysayshi +/types/psl/ @BendingBender /types/ptomasroos__react-native-multi-slider/ @Slessi /types/pty.js/ @enlight /types/public-ip/ @BendingBender -/types/pubnub/ @bitbankinc @rollymaduk @vitosamson @FlorianDr +/types/pubnub/ @bitbankinc @rollymaduk @vitosamson @FlorianDr @danduh /types/pubsub-js/ @borisyankov /types/pug/ @TonyPythoneer @19majkel94 /types/pulltorefreshjs/ @DanielRosenwasser @humpedli @@ -3731,20 +4012,20 @@ /types/pumpify/ @JustinBeckwith @aoberoi /types/punycode/ @yavanosta /types/pupa/ @nju33 -/types/puppeteer/v0/ @marvinhagemeister @cdeutsch /types/puppeteer/ @marvinhagemeister @cdeutsch @ksm2 @SimonSchick +/types/puppeteer/v0/ @marvinhagemeister @cdeutsch /types/puppeteer-core/ @mtsmfm /types/pure-render-decorator/ @seansfkelley /types/purl/ @danfma /types/pusher-js/ @tkqubo @cainlevy /types/pvutils/ @microshine /types/python-shell/ @dolanmiu @WORMSS -/types/q/v0/ @bnemetchek @johnnyreilly /types/q/ @bnemetchek @AndrewGaspar @johnnyreilly @mboudreau @TeamworkGuy2 +/types/q/v0/ @bnemetchek @johnnyreilly /types/q-io/ @Bartvds /types/q-retry/ @vilic -/types/qhistory/ @Kovensky -/types/qiniu-js/ @taoqf +/types/qhistory/ @Jessidhia +/types/qiniu-js/ @taoqf @qiqizjl /types/qlik/ @RubenSlabbert @AginicX /types/qlik-engineapi/ @konne @richardison /types/qlik-visualizationextensions/ @konne @@ -3752,14 +4033,16 @@ /types/qrcode/ @plantain-00 /types/qrcode.react/ @mleko /types/qs/ @RWander @leonyu @tehbelinda @zyml @artursvonda @CarlosBonetti +/types/qs-middleware/ @davecardwell /types/qtip2/ @Seltzer @leonard-thieu -/types/query-string/ @SamVerschueren @tkrotoff @huhuanming @MadaraUchiha @shssoichiro +/types/query-string/ @SamVerschueren @tkrotoff @huhuanming @MadaraUchiha @shssoichiro @jarrku /types/querystringify/ @ilich /types/quick-lru/ @BendingBender +/types/quick-lru/v1/ @BendingBender /types/quill/ @sumitkm @guillaume-ro-fr @43081j @AnielloFalcone @mhamri /types/quixote/ @greybax -/types/qunit/v1/ @diullei /types/qunit/ @waratuman @mike-north +/types/qunit/v1/ @diullei /types/qunit-dom/ @happycollision /types/quoted-printable/ @pushplay /types/qwest/ @lindsayevans @@ -3769,7 +4052,8 @@ /types/radium/ @alexgorbatchev @nupplaphil @asvetliakov /types/radius/ @codeanimal /types/radix64/ @huan086 -/types/ramda/ @donnut @tycho01 @mdekrey @mrdziuban @sbking @afharo @teves-castro @1M0reBug @hojberg @samsonkeung @angeloocana @raynerd @googol @moshensky @ethanresnick @leighman @CaptJakk @deftomat @deptno @blimusiek @biern @rayhaneh @rgm @drewwyatt +/types/raf/ @BenLorantfy +/types/ramda/ @donnut @tycho01 @mdekrey @mrdziuban @sbking @afharo @teves-castro @1M0reBug @hojberg @samsonkeung @angeloocana @raynerd @googol @moshensky @ethanresnick @leighman @CaptJakk @deftomat @deptno @blimusiek @biern @rayhaneh @rgm @drewwyatt @jottenlips @minitesh /types/random-boolean/ @BendingBender /types/random-float/ @BendingBender /types/random-int/ @BendingBender @@ -3780,6 +4064,7 @@ /types/random-obj-prop/ @BendingBender /types/random-seed/ @endel /types/random-string/ @stpettersens +/types/randoma/ @BendingBender /types/randombytes/ @BendingBender /types/randomcolor/ @feitzi @BradyLiles /types/range-parser/ @tlaziuk @@ -3803,10 +4088,11 @@ /types/raygun/ @UberMouse /types/raygun4js/ @xt0rted @BenjaminHarding @UberMouse /types/rbac-a/ @tlaziuk -/types/rc/ @DanielRosenwasser +/types/rc/ @DanielRosenwasser @BendingBender /types/rc-progress/ @jussikinnula /types/rc-select/ @DenisTirilis /types/rc-slider/ @mantasmarcinkus @mattoni @paustint @j-fro @Deanna2 +/types/rc-switch/ @karol-majewski /types/rc-time-picker/ @Hoff97 /types/rc-tooltip/ @rhysd @ahstro @vsaarinen /types/rc-tree/ @johnnyreilly @Methuselah96 @@ -3816,32 +4102,32 @@ /types/rdflib/ @cenotelie /types/re-base/ @jordandrako /types/reach__router/ @kingdaro +/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei @Jessidhia @pshrmn @threepointone /types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz -/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei @Kovensky /types/react-adal/ @dkorolev1 /types/react-albus/ @sseppola @conradreuter @kuirak -/types/react-alert/v2/ @ssyrell /types/react-alert/ @g1eny0ung +/types/react-alert/v2/ @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-menubutton/ @forabi @crohlfs @karmats /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-beautiful-dnd/ @varHarrie @bradleyayers @paustint @marknelissen @enricoboccadifuoco @lonyele /types/react-better-password/ @mhuynh1 /types/react-big-calendar/ @piotrwitek @paustint @pikpok @eps1lon @strongpauly @janb87 /types/react-blessed/ @me /types/react-body-classname/ @mhegazy -/types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @mretolaza @katbusch @vitosamson @LKay @aaronbeall @jrakotoharisoa @r3nya @t49tran +/types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @mretolaza @katbusch @vitosamson @LKay @aaronbeall @jrakotoharisoa @r3nya @t49tran @bes /types/react-bootstrap-date-picker/ @LKay @ssi-hu-antal-bodnar /types/react-bootstrap-daterangepicker/ @ianks -/types/react-bootstrap-table/v2/ @flaub @alelode @UJosue10 /types/react-bootstrap-table/ @flaub @alelode @UJosue10 @dawnmist @Ogglas -/types/react-bootstrap-typeahead/ @Guymestef @radziksh @PaitoAnderson +/types/react-bootstrap-table/v2/ @flaub @alelode @UJosue10 +/types/react-bootstrap-typeahead/ @Guymestef @radziksh @PaitoAnderson @arichter83 @dalevfenton /types/react-breadcrumbs/ @guoyunhe /types/react-breadcrumbs-dynamic/ @mitsuruog /types/react-broadcast/ @kandros @@ -3857,8 +4143,8 @@ /types/react-coinhive/ @sktbcbbs /types/react-collapse/ @Kimahriman /types/react-collapsible/ @knegusen -/types/react-color/ @LKay @markspolakovs @mntdn -/types/react-confirm/ @santiagodoldan +/types/react-color/ @LKay @markspolakovs @mntdn @nkgrnkgr +/types/react-confirm/ @santiagodoldan @marknelissen /types/react-content-loader/ @alaatm @samwalshnz /types/react-copy-to-clipboard/ @mabels @BernabeFelix /types/react-copy-write/ @samhh @davej @@ -3869,11 +4155,11 @@ /types/react-css-modules/ @KostyaEsmukov @skirsdeda /types/react-css-transition-replace/ @LKay /types/react-currency-formatter/ @pastushenkoy @Jeka-Vasiliev -/types/react-custom-scrollbars/v3/ @David-LeBlanc-git /types/react-custom-scrollbars/ @David-LeBlanc-git @kittimiyo -/types/react-data-grid/v1/ @SupernaviX -/types/react-data-grid/v2/ @SupernaviX @KieranPeat @martinnov92 +/types/react-custom-scrollbars/v3/ @David-LeBlanc-git /types/react-data-grid/ @SupernaviX @KieranPeat @martinnov92 @baso53 +/types/react-data-grid/v2/ @SupernaviX @KieranPeat @martinnov92 +/types/react-data-grid/v1/ @SupernaviX /types/react-datagrid/ @stephenjelfs /types/react-date-range/ @Junbong /types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue @KoalaHuman @seansfkelley @justingrant @jakeboone02 @@ -3884,14 +4170,15 @@ /types/react-dnd-touch-backend/ @mleko @dawnmist @beeequeue /types/react-document-meta/ @ulrichb /types/react-document-title/ @cleverguy25 -/types/react-dom/v15/ @MartynasZilinskas /types/react-dom/ @MartynasZilinskas @theruther4d +/types/react-dom/v15/ @MartynasZilinskas /types/react-dom-factories/ @jgoz -/types/react-draft-wysiwyg/ @imechZhangLY +/types/react-dotdotdot/ @jczyzewski +/types/react-draft-wysiwyg/ @imechZhangLY @brunoMaurice /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 @ekilah +/types/react-dropzone/v3/ @matdube @LynxEyes @goblindegook @benbayard @LKay +/types/react-dropzone/v2/ @matdube @LynxEyes @goblindegook @benbayard /types/react-dynamic-number/ @eugrdn /types/react-easy-chart/ @danzel /types/react-event-listener/ @asvetliakov @@ -3901,39 +4188,44 @@ /types/react-faux-dom/ @alitaheri @cleverguy25 @deviousm @hanai /types/react-file-input/ @dmitryrogozhny /types/react-file-reader-input/ @dmitryrogozhny @alitaheri +/types/react-filepond/ @zposten /types/react-flag-icon-css/ @jonfreedman /types/react-flags-select/ @senukartur /types/react-flatpickr/ @begincalendar @snaveevans /types/react-flex/ @pushplay /types/react-flexr/ @pushplay /types/react-fontawesome/ @timurrustamov @dublicator @vincaslt @gavingregory -/types/react-form/v1/ @cameron-mcateer /types/react-form/ @cameron-mcateer @TiuSh +/types/react-form/v1/ @cameron-mcateer /types/react-foundation/ @danielearwicker +/types/react-frontload/ @rockon404 /types/react-gateway/ @jsonunger /types/react-geosuggest/ @brmenchl /types/react-global-configuration/ @ryokik /types/react-google-login-component/ @koss-lebedev /types/react-google-maps-loader/ @vasilysn /types/react-google-places-suggest/ @vasilysn -/types/react-google-recaptcha/ @KoalaHuman +/types/react-google-recaptcha/ @KoalaHuman @tomsturge /types/react-gravatar/ @invliD -/types/react-grid-layout/ @abirkholz @alitaheri @ZheyangSong @andrewhathaway +/types/react-grid-layout/ @abirkholz @alitaheri @ZheyangSong @andrewhathaway @manav-m /types/react-hamburger-menu/ @grzesie2k -/types/react-hammerjs/v0/ @jsonunger /types/react-hammerjs/ @jsonunger @cecchi -/types/react-helmet/v4/ @evanbb @isman-usoh +/types/react-hammerjs/v0/ @jsonunger +/types/react-headroom/ @zerocho /types/react-helmet/ @evanbb @isman-usoh @lith-light-g @sammkj @yuit +/types/react-helmet/v4/ @evanbb @isman-usoh /types/react-helmet-async/ @forabi +/types/react-highcharts/ @j1r1k /types/react-highlight/ @joshuakgoldberg /types/react-highlight-words/ @mhegazy @diogodca @kellyrmilligan /types/react-highlighter/ @oizie /types/react-holder/ @isman-usoh /types/react-hot-loader/ @jacekjagiello @MartynasZilinskas @DovydasNavickas +/types/react-howler/ @maksimovicdanijel /types/react-hyperscript/ @tock203 /types/react-icon-base/ @apare @LKay /types/react-icons/ @apare @johnnyreilly @LKay -/types/react-image-crop/ @danielasy +/types/react-image-crop/ @danielasy @chaaya /types/react-image-fallback/ @8enSmith /types/react-image-gallery/ @adamwpc /types/react-imageloader/ @stephenjelfs @@ -3943,33 +4235,35 @@ /types/react-infinite-calendar/ @christianchown /types/react-infinite-scroll-component/ @sroy3 @burtek @davidkevork @JoshuaScript /types/react-infinite-scroller/ @Lapanti @psrebniak @WrathZA @daggerjames +/types/react-inlinesvg/ @MyCryptoHQ @nickmccurdy /types/react-input-autosize/ @jsonunger @franklixuefei /types/react-input-calendar/ @stepancar -/types/react-input-mask/v1/ @apare /types/react-input-mask/ @apare @dima7a14 +/types/react-input-mask/v1/ @apare /types/react-instantsearch/ @gburgett @jpowell /types/react-instantsearch-core/ @gburgett @jpowell @davidfurlong /types/react-instantsearch-dom/ @gburgett @jpowell /types/react-instantsearch-native/ @gburgett @jpowell -/types/react-intl/v1/ @bgrieder /types/react-intl/ @bgrieder @cdroulers @gyzerok @tillwolff @LKay @bhouser @kristerkari @formatlos @lukyth @obedm503 +/types/react-intl/v1/ @bgrieder /types/react-intl-redux/ @LKay -/types/react-is/ @AviVahl @christianchown +/types/react-is/ @AviVahl @christianchown @eps1lon /types/react-is-deprecated/ @seansfkelley /types/react-joyride/ @kdy1 @kamranayub /types/react-js-pagination/ @netoisc /types/react-json/ @spielc /types/react-json-pretty/ @LKay -/types/react-json-tree/ @gnestor +/types/react-json-tree/ @gnestor @zainafzal08 /types/react-jsonschema-form/ @iamdanfox @iplus26 @phbou72 @LucianBuzzo @sthenault @sbusch -/types/react-jss/ @eps1lon +/types/react-jss/ @eps1lon @jlaw90 /types/react-lazyload/ @m0a /types/react-lazylog/ @benjaminRomano /types/react-leaflet/ @danzel @davschne @yuit /types/react-leaflet-markercluster/ @Kimahriman /types/react-lifecycle-component/ @pixelshaded +/types/react-lifecycles-compat/ @bySabi /types/react-list/ @buptyyf @tomshen -/types/react-loadable/ @Kovensky @odensc @ianks @tlaziuk @iMobs +/types/react-loadable/ @Jessidhia @odensc @ianks @tlaziuk @iMobs /types/react-loader/ @artfuldev /types/react-lottie/ @Kana00 @Ricki-BumbleDev /types/react-mailchimp-subscribe/ @osdiab @@ -3978,22 +4272,22 @@ /types/react-mce/ @morphologue /types/react-mdl/ @bradzacher /types/react-measure/ @asvetliakov @marcfallows -/types/react-mentions/ @activescott +/types/react-mentions/ @activescott @efedorenko /types/react-mixin/ @tkqubo /types/react-modal/ @radziksh @drewnoakes @homburg @ttamminen @hallowatcher @peterblazejewicz @jpowell /types/react-motion/ @stepancar @asvetliakov @dimitarnestorov /types/react-motion-slider/ @asvetliakov /types/react-motion-ui-pack/ @jsonunger -/types/react-native/ @alloy @huhuanming @iRoachie @skn0tt @timwangdev @kamal @nelyousfi @alexdunne @swissmanu @bm-software @tkrotoff @a-tarasyuk @mvdam @esemesek @mrnickel +/types/react-native/ @alloy @huhuanming @iRoachie @skn0tt @timwangdev @kamal @nelyousfi @alexdunne @swissmanu @bm-software @tkrotoff @a-tarasyuk @mvdam @esemesek @mrnickel @souvik-ghosh /types/react-native-android-taskdescription/ @christianchown -/types/react-native-auth0/ @ascariandrea +/types/react-native-auth0/ @ascariandrea @marknelissen /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 @FabianMeul /types/react-native-communications/ @huhuanming @PaitoAnderson /types/react-native-custom-tabs/ @philnova -/types/react-native-datepicker/ @jacobbaskin +/types/react-native-datepicker/ @jacobbaskin @nossbigg /types/react-native-dialog/ @MrLuje @stackbuilders @ibarrae /types/react-native-dialogflow/ @jasonmerino /types/react-native-doc-viewer/ @iRoachie @@ -4017,20 +4311,24 @@ /types/react-native-keychain/ @DavidFarinha /types/react-native-loading-spinner-overlay/ @fhelwanger /types/react-native-material-design-searchbar/ @iRoachie +/types/react-native-material-dropdown/ @jaydeep987 /types/react-native-material-kit/ @iRoachie @timwangdev /types/react-native-material-textfield/ @mindhivefi @iRoachie /types/react-native-material-ui/ @iRoachie /types/react-native-mauron85-background-geolocation/ @djereg /types/react-native-mixpanel/ @r3nya +/types/react-native-modal-dropdown/ @echoulen /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 +/types/react-native-platform-touchable/ @tngranados /types/react-native-popup-dialog/ @PaitoAnderson @connectdotz @bm-software /types/react-native-push-notification/ @PaitoAnderson @tomSawkins /types/react-native-qrcode/ @plantain-00 +/types/react-native-read-more-text/ @solkaz /types/react-native-referrer/ @christianchown /types/react-native-restart/ @christianchown /types/react-native-safari-view/ @mrand01 @@ -4058,50 +4356,57 @@ /types/react-native-vector-icons/ @iRoachie @timwangdev /types/react-native-version-number/ @VincentLanglet /types/react-native-video/ @huhuanming +/types/react-native-zeroconf/ @mattapet +/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @magrinj @TizioFittizio @stigi @LinusU @jshosomichi @jakebooyah @brunoro @DenisFrezzato @mickaelw @maxdavidson @alechill @builtbyproxy @jkillian @jeroenvervaeke @chagasaway @denissb @skovhus +/types/react-navigation/v2/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @magrinj @TizioFittizio @stigi @LinusU @jshosomichi @jakebooyah @brunoro @DenisFrezzato @mickaelw @maxdavidson @alechill @builtbyproxy @jkillian @jeroenvervaeke @chagasaway /types/react-navigation/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 @magrinj @TizioFittizio @stigi @LinusU @jshosomichi @jakebooyah @brunoro @DenisFrezzato @mickaelw @maxdavidson @alechill @builtbyproxy @jkillian @jeroenvervaeke @chagasaway /types/react-navigation-material-bottom-tabs/ @iRoachie /types/react-no-ssr/ @rafalfilipek /types/react-notification-system/ @GiedriusGrabauskas @DeividasBakanas @LKay @sztobar /types/react-notification-system-redux/ @LKay /types/react-notify-toast/ @klaascuvelier /types/react-numeric-input/ @heatherbooker @akx -/types/react-onclickoutside/v5/ @LKay /types/react-onclickoutside/ @LKay @surgeboris +/types/react-onclickoutside/v5/ @LKay /types/react-onsenui/ @salim7 @jemmyw @lirbank /types/react-outside-click-handler/ @zubivan -/types/react-overlays/ @aaronbeall @vitosamson +/types/react-overlays/ @aaronbeall @vitosamson @aarondancer /types/react-owl-carousel/ @tbounsiar @igorissen @KennethanCeyer -/types/react-paginate/v4/ @deevus @wouterhardeman @pegel03 @archy-bold +/types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke @sugarshin @SPWizard01 /types/react-paginate/v5/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke -/types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke @sugarshin -/types/react-places-autocomplete/ @guilhermehubner @r3nya +/types/react-paginate/v4/ @deevus @wouterhardeman @pegel03 @archy-bold +/types/react-panelgroup/ @qgolsteyn +/types/react-places-autocomplete/ @guilhermehubner @r3nya @ApeNox @azizhk +/types/react-places-autocomplete/v6/ @guilhermehubner @r3nya @ApeNox @azizhk /types/react-plotly.js/ @jonfreedman +/types/react-plyr/ @baorv /types/react-pointable/ @istefo @mdibyo /types/react-popover/ @jacoporicare -/types/react-portal/v3/ @shuntksh /types/react-portal/ @shuntksh @HorusGoul +/types/react-portal/v3/ @shuntksh /types/react-primitives/ @aghoneim92 @davidpett /types/react-props-decorators/ @tkqubo /types/react-qr-reader/ @davidkevork /types/react-radio-group/ @jsonunger +/types/react-rangeslider/ @RichieRock /types/react-recaptcha/ @mhegazy @zzanol /types/react-reconciler/ @Methuselah96 +/types/react-redux/ @tkqubo @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva @kallikrein @val1984 @jrakotoharisoa @apapirovski @surgeboris @soerenbf +/types/react-redux/v6/ @tkqubo @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva @kallikrein @val1984 @jrakotoharisoa @apapirovski @surgeboris /types/react-redux/v5/ @tkqubo @thasner @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva -/types/react-redux/ @tkqubo @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva @kallikrein @val1984 @jrakotoharisoa @apapirovski @surgeboris /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 @kastermester +/types/react-relay/ @graphcool @voxmatt @alloy @npirotte @ckknight @kastermester @mattkrick /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 +/types/react-responsive/v1/ @asvetliakov /types/react-rnd/ @Ragg- @fsubal @zyh825 -/types/react-router/v2/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov -/types/react-router/v3/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @ssorallen @gillchristian @nulladdict /types/react-router/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @tkrotoff @huy-nguyen @grmiade @DaIgeb @egorshulga @neuoy @rraina @pret-a-porter @t49tran @8enSmith +/types/react-router/v3/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @ssorallen @gillchristian @nulladdict +/types/react-router/v2/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov /types/react-router-bootstrap/ @vlesierse @LKay @olmobrutall /types/react-router-config/ @lith-light-g @johnnyreilly @NullMDR /types/react-router-dom/ @tkrotoff @huy-nguyen @p-jackson @johnnyreilly @@ -4110,18 +4415,20 @@ /types/react-router-navigation/ @kaoDev @johnnyreilly /types/react-router-navigation-core/ @kaoDev @johnnyreilly /types/react-router-param-link/ @mtsg -/types/react-router-redux/v3/ @isman-usoh @noah79 @rosendi -/types/react-router-redux/v4/ @isman-usoh @noah79 @rosendi @LKay @DovydasNavickas /types/react-router-redux/ @huy-nguyen @8398a7 @mykolas +/types/react-router-redux/v4/ @isman-usoh @noah79 @rosendi @LKay @DovydasNavickas +/types/react-router-redux/v3/ @isman-usoh @noah79 @rosendi +/types/react-rte/ @jclyons52 /types/react-s-alert/ @mitsuruog /types/react-scroll/ @sudoplz @GiedriusGrabauskas /types/react-scrollbar/ @stephenjelfs -/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-select/v1/ @Hesquibet @giladgray @iebaker @skirsdeda @vujevits @devrelm @MartynasZilinskas @onatm @ninjaferret @tehbi4 @misantronic @darkartur @eps1lon @endurance @RCGuillaume /types/react-share/ @icopp /types/react-show-more/ @naortor /types/react-side-effect/ @remojansen @0xcaff /types/react-sidebar/ @jeroenvervaeke +/types/react-simple-maps/ @thepocp @pronebird /types/react-sketchapp/ @ricokahler @DomiR @saschazar21 /types/react-slick/ @andrewBalekha @GiedriusGrabauskas @r3nya /types/react-slider/ @jsonunger @@ -4129,17 +4436,18 @@ /types/react-sortable-hoc/ @NoHomey @charlesrey /types/react-sortable-pane/ @rhysd /types/react-sortable-tree/ @wouterhardeman @jzoric @kevinsperrine @acemac @dolezel +/types/react-sortable-tree-theme-file-explorer/ @dolezel /types/react-sound/ @koss-lebedev /types/react-sparklines/ @henrinormak -/types/react-spinkit/v1/ @tkqubo @mleko @pelotom /types/react-spinkit/ @tkqubo @mleko @pelotom @zzanol +/types/react-spinkit/v1/ @tkqubo @mleko @pelotom /types/react-splitter-layout/ @snaptags /types/react-star-rating-component/ @marpstar /types/react-sticky/ @curtisw0 @ajhyndman /types/react-sticky-box/ @koss-lebedev /types/react-sticky-el/ @jbraithwaite /types/react-stickynode/ @tstirrat -/types/react-stripe-elements/ @dan-j @santiagodoldan @sonnysangha @9y5 @thchia @yhnavein +/types/react-stripe-elements/ @dan-j @santiagodoldan @sonnysangha @9y5 @thchia @yhnavein @virzak /types/react-svg-inline/ @kiyopikko /types/react-svg-pan-zoom/ @huy-nguyen /types/react-swf/ @stepancar @@ -4155,8 +4463,8 @@ /types/react-tagcloud/ @wassname /types/react-tagsinput/ @mykter /types/react-tap-event-plugin/ @mxl -/types/react-test-renderer/v15/ @arvitaly @lochbrunner @lochbrunner @johnnyreilly /types/react-test-renderer/ @arvitaly @lochbrunner @johnnyreilly @jgoz +/types/react-test-renderer/v15/ @arvitaly @lochbrunner @lochbrunner @johnnyreilly /types/react-tether/ @ryprice /types/react-text-mask/ @guilhermehubner @cavarzan @needpower /types/react-textarea-autosize/ @asvetliakov @zry656565 @@ -4164,49 +4472,52 @@ /types/react-timeout/ @kerwynrg /types/react-toastify/ @icopp /types/react-toastr/ @shssoichiro @DanRegazzi -/types/react-toggle/v2/ @LKay @jsonunger /types/react-toggle/ @LKay -/types/react-tooltip/ @DeividasBakanas +/types/react-toggle/v2/ @LKay @jsonunger +/types/react-tooltip/ @DeividasBakanas @Vijayasingam /types/react-touch/ @grzesie2k /types/react-tracking/ @alloy -/types/react-transition-group/v1/ @LKay /types/react-transition-group/ @LKay @Epskampie @ybiquitous +/types/react-transition-group/v1/ @LKay /types/react-treeview/ @janslow /types/react-truncate/ @mattvperry /types/react-twitter-auth/ @paulfasola @loginwashere +/types/react-ultimate-pagination/ @BenLorantfy /types/react-user-tour/ @ccancellieri /types/react-vertical-timeline-component/ @stephane-monnot /types/react-virtual-keyboard/ @bsurai -/types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @kraenhansen @Stevearzh @mgoszcz2 @brandonhall @sbusch +/types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @Stevearzh @mgoszcz2 @brandonhall @sbusch /types/react-virtualized-select/ @seansfkelley /types/react-visibility-sensor/ @JRasmusBm @gcangussu /types/react-webcam/ @squat /types/react-weui/ @tairan -/types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 @r3nya @MBillemaz @georg94 +/types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 @r3nya @MBillemaz @georg94 @tzarger /types/react-widgets-moment/ @dawnmist /types/react-window/ @martynaskadisa /types/react-window-size/ @jakejrichards -/types/react-youtube/ @kgtkr +/types/react-wow/ @mikepthomas +/types/react-youtube/ @kgtkr @salguerooo /types/react-youtube-embed/ @charles-salmon /types/reactable/ @spielc /types/reactcss/ @chrisgervang @LKay +/types/reactstrap/ @alihammad @mfal @danilobjr @FaithForHumans @timc13 @patrickrgaffney @prabodht @georg94 /types/reactstrap/v4/ @alihammad @mfal @danilobjr @fabiopaiva -/types/reactstrap/ @alihammad @mfal @danilobjr @FaithForHumans @timc13 @patrickrgaffney @prabodht /types/read/ @timjk /types/read-chunk/ @crispybee /types/read-package-tree/ @mgroenhoff /types/read-pkg/ @jdxcode /types/read-pkg-up/ @dudeofawesome @jdxcode +/types/readable-stream/ @TeamworkGuy2 /types/readdir-enhanced/ @mrmlnc /types/readdir-stream/ @Bartvds /types/readline-sync/ @jonestristand /types/readline-transform/ @dex4er /types/reapop/ @Barrokgl -/types/rebass/ @ryee-dev @jamesmckenzie +/types/rebass/ @rhysd @ryee-dev @jamesmckenzie /types/rebass__grid/ @antonvasin @vittorio @lhache @lavoaster /types/recaptcha2/ @l-jonas /types/recase/ @18steps -/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong @richbai90 @caspeco-dan @pkeuter @jrsaunde @paulmelnikow @crusectrl @apalugniok @RobertStigsson +/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong @richbai90 @caspeco-dan @pkeuter @jrsaunde @paulmelnikow @crusectrl @apalugniok @RobertStigsson @kousaku-maron /types/recharts-scale/ @johnnyreilly /types/rechoir/ @BendingBender /types/recluster/ @dex4er @@ -4214,23 +4525,24 @@ /types/reconnect-core/ @thw0rted /types/reconnectingwebsocket/ @nguarracino /types/recorder-js/ @higuri -/types/recursive-readdir/v1/ @elisee /types/recursive-readdir/ @elisee @MicahZoltu -/types/redis/ @soywiz @CodeAnimal @MugeSo @UppaJung @Rokt33r @43081j @barnski @1pete +/types/recursive-readdir/v1/ @elisee +/types/redent/ @BendingBender +/types/redis/ @soywiz @CodeAnimal @MugeSo @UppaJung @Rokt33r @43081j @barnski @1pete @blablapolicja @ferrantejake /types/redis-errors/ @43081j /types/redis-mock/ @BendingBender /types/redis-rate-limiter/ @westy92 @nodify-at /types/redis-scripto/ @westy92 -/types/redlock/v2/ @chrootsu /types/redlock/ @chrootsu @BendingBender +/types/redlock/v2/ @chrootsu /types/redom/ @RauliL @nemoinho -/types/reduce-reducers/ @huy-nguyen +/types/reduce-reducers/ @huy-nguyen @daliusd /types/redux-action/ @newraina /types/redux-action-utils/ @tkqubo /types/redux-actions/ @jaysoo @alexgorbatchev @alechill @alexey-pelykh @7hi4g0 /types/redux-async-queue/ @andreiho -/types/redux-auth-wrapper/v1/ @LKay /types/redux-auth-wrapper/ @LKay +/types/redux-auth-wrapper/v1/ @LKay /types/redux-batched-subscribe/ @mDibyo /types/redux-debounced/ @seansfkelley /types/redux-devtools/ @mc-petry @@ -4241,11 +4553,11 @@ /types/redux-first-router-link/ @janb87 /types/redux-first-router-restore-scroll/ @icopp /types/redux-first-routing/ @tlaziuk +/types/redux-form/ @carsonf @aikoven @LKay @bancek @alsiola @tehbi4 @huwmartin @ethanresnick @reggino @maddijoyce @smifun @mshaaban088 +/types/redux-form/v6/ @carsonf @aikoven @LKay @bancek @mshaaban088 /types/redux-form/v4/ @aikoven -/types/redux-form/v6/ @carsonf @aikoven @LKay @bancek -/types/redux-form/ @carsonf @aikoven @LKay @bancek @alsiola @tehbi4 @huwmartin @ethanresnick @reggino @maddijoyce @smifun -/types/redux-immutable/v3/ @oizie @sebald @gavingregory /types/redux-immutable/ @oizie @sebald @gavingregory @lukyth +/types/redux-immutable/v3/ @oizie @sebald @gavingregory /types/redux-immutable-state-invariant/ @remojansen @highflying @mihai-dinculescu /types/redux-infinite-scroll/ @silkyfray /types/redux-injectable-store/ @unindented @@ -4253,8 +4565,8 @@ /types/redux-localstorage-debounce/ @LKay /types/redux-localstorage-filter/ @LKay /types/redux-logger/ @arusakov @kgroat -/types/redux-mock-store/v0/ @MarianPalkus /types/redux-mock-store/ @MarianPalkus +/types/redux-mock-store/v0/ @MarianPalkus /types/redux-optimistic-ui/ @asvetliakov /types/redux-orm/ @keenondrums /types/redux-pack/ @tansongyang @quicksnap @no-stack-dub-sack @@ -4268,6 +4580,7 @@ /types/redux-sentry-middleware/ @dolezel /types/redux-shortcuts/ @tstirrat /types/redux-socket.io/ @snakeego +/types/redux-state-sync/ @AOHUA @AntonioMendez /types/redux-storage/ @asvetliakov /types/redux-storage-engine-jsurl/ @screendriver /types/redux-storage-engine-localstorage/ @screendriver @@ -4282,18 +4595,21 @@ /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/reflux/v0/ @mauricedb /types/registry-auth-token/ @mauricedb @LiangZugeng +/types/regression/ @MattiasMartens /types/relateurl/ @tkrotoff /types/relaxed-json/ @18steps /types/relay-runtime/ @voxmatt @alloy /types/rellax/ @shermendev -/types/remarkable/ @makepost +/types/remarkable/ @makepost @chigix +/types/remote-origin-url/ @BendingBender /types/remote-redux-devtools/ @ColinEberhardt @unindented @mamodom @colindekker /types/remove-markdown/ @RagibHasin /types/rename/ @Aankhen /types/replace-ext/ @DeividasBakanas +/types/replace-string/ @BendingBender /types/replacestream/ @dex4er /types/req-cwd/ @Alorel /types/request/ @soywiz @bonnici @Bartvds @joeskeen @ccurrens @lookfirst @mastermatt @josecolella @murbanowicz @@ -4301,6 +4617,7 @@ /types/request-ip/ @mrhen /types/request-promise/ @cglantschnig @joeskeen @AyaMorisawa @mastermatt /types/request-promise-native/ @gustavohenke @mastermatt +/types/request-stats/ @BendingBender /types/requestidlecallback/ @hax /types/requestretry/ @EricByers @trainerbill /types/require-dir/ @weekens @@ -4309,28 +4626,35 @@ /types/require-relative/ @MattiasBuelens /types/requirejs/ @jbaldwin /types/requirejs-domready/ @lefb766 +/types/requires-port/ @BendingBender /types/resemblejs/ @pimterry /types/reservoir/ @danvk /types/resize-img/ @higuri /types/resolve/ @marionebl @ajafff -/types/resolve-from/ @unional +/types/resolve-cwd/ @BendingBender +/types/resolve-from/ @unional @BendingBender +/types/resolve-from/v2/ @unional +/types/resolve-global/ @BendingBender +/types/resolve-pkg/ @mabels @BendingBender /types/resourcejs/ @shaunluttin /types/response-time/ @urossmolnik @TonyPythoneer @danmana +/types/responselike/ @BendingBender /types/rest/ @Nemo157 /types/restangular/ @borisyankov /types/restful.js/ @tkqubo -/types/restify/v4/ @blittle @stevehipwell -/types/restify/v5/ @blittle @stevehipwell @leanazulyoro /types/restify/ @blittle @stevehipwell @leanazulyoro @mgebundy +/types/restify/v5/ @blittle @stevehipwell @leanazulyoro +/types/restify/v4/ @blittle @stevehipwell /types/restify-cookies/ @weekens /types/restify-cors-middleware/ @dthunell /types/restify-errors/ @stevehipwell /types/restify-plugins/ @KostyaTretyak /types/restler/ @cyrilschumacher /types/restling/ @loghorn +/types/restore-cursor/ @BendingBender /types/resumablejs/ @DanielMcAssey /types/rethinkdb/ @alexgorbatchev @AdrianFarmadin @kondi @hoishin -/types/retry/ @krenor +/types/retry/ @krenor @BendingBender /types/retry-as-promised/ @Raigen /types/rev-hash/ @ikatyang /types/revalidate/ @alex3165 @@ -4338,8 +4662,9 @@ /types/reveal/ @robertop87 @Nava2 /types/rewire/ @borislavjivkov @CaselIT /types/rfc2047/ @mugifly +/types/rgb-hex/ @BendingBender /types/rgrove__parse-xml/ @petejohanson -/types/rheostat/ @SashaBayan @kourge +/types/rheostat/ @SashaBayan @kourge @StefanWerW /types/rickshaw/ @niemyjski /types/rimraf/ @soywiz @e-cloud @bash /types/riot/ @Stubb0rn @@ -4353,12 +4678,19 @@ /types/rivets/ @TrevorDev @matjanos /types/rmc-drawer/ @Hoff97 /types/rmfr/ @pluma +/types/rn-fetch-blob/ @pengcao1 /types/roads/ @dancespiele /types/roads-server/ @dancespiele /types/rocksdb/ @MeirionHughes @danwbyrne /types/roll/ @icopp /types/rolling-rate-limiter/ @l-jonas +/types/rollup-plugin-commonjs/ @eoin-obrien +/types/rollup-plugin-delete/ @vladshcherbin /types/rollup-plugin-json/ @asmockler @hotell +/types/rollup-plugin-node-builtins/ @Kocal +/types/rollup-plugin-node-globals/ @kocal +/types/rollup-plugin-node-resolve/ @eoin-obrien +/types/rollup-plugin-sourcemaps/ @eoin-obrien /types/roman-numerals/ @pluma /types/ronomon__crypto-async/ @BendingBender /types/rosie/ @abner @subvertallchris @abukurov @adam187 @@ -4417,9 +4749,15 @@ /types/sanitize-filename/ @Nemo157 /types/sanitize-html/ @rogierschouten @afshin @BehindTheMath @biermeester @WillGibson @sirMerr /types/sap__xsenv/ @mad-mike +/types/sarif/ @rscrivens /types/sasl-anonymous/ @BendingBender +/types/sasl-digest-md5/ @BendingBender +/types/sasl-external/ @BendingBender +/types/sasl-plain/ @BendingBender +/types/sasl-scram-sha-1/ @BendingBender /types/saslmechanisms/ @BendingBender -/types/sass/ @lenovouser +/types/saslprep/ @BendingBender +/types/sass/ @lenovouser @jleider /types/sass-graph/ @marvinhagemeister /types/sass-webpack-plugin/ @AepKill /types/sat/ @omni360 @@ -4429,7 +4767,10 @@ /types/sc-broker/ @DanielRose /types/sc-broker-cluster/ @DanielRose /types/sc-channel/ @DanielRose +/types/sc-framework-health-check/ @DanielRose +/types/sc-hot-reboot/ @DanielRose /types/scalike/ @ryoppy +/types/scc-broker-client/ @DanielRose /types/schedule/ @Methuselah96 /types/scheduler/ @Methuselah96 /types/schema-registry/ @bonzzy @@ -4438,6 +4779,7 @@ /types/screenfull/ @icholy @lionelb @joelshepherd /types/screeps/ @MarkoSulamagi @NhanHo @bryanbecker @resir014 @Arcath @dmarcuse /types/screeps-profiler/ @ramblurr +/types/script-ext-html-webpack-plugin/ @davecardwell /types/scriptjs/ @ssttevee /types/scroll-into-view/ @zivni /types/scroller/ @haskellcamargo @@ -4447,22 +4789,24 @@ /types/scrypt-async/ @xStrom @stesix /types/scrypt-js/ @danwbyrne /types/scryptsy/ @micksatana +/types/sdbm/ @BendingBender /types/sdp-transform/ @loc /types/seamless/ @danmana -/types/seamless-immutable/ @alex3165 @xsburg @geirsagberg @RMHonor +/types/seamless-immutable/ @alex3165 @xsburg @geirsagberg @RMHonor @pheromonez /types/season/ @dex4er /types/secp256k1/ @anler /types/seed-random/ @l-jonas /types/seededshuffle/ @urish /types/seedrandom/ @kernhanda /types/segment-analytics/ @fongandrew -/types/select2/v3/ @borisyankov /types/select2/ @borisyankov @denisname +/types/select2/v3/ @borisyankov /types/selectables/ @renjfk /types/selectize/ @adidahiya @naBausch /types/selenium-standalone/ @SanderDeWaal1992 +/types/selenium-webdriver/ @BillArmstrong @Kuniwak @cnishina @SupernaviX @bendxn @oddui /types/selenium-webdriver/v2/ @BillArmstrong @Kuniwak @cnishina -/types/selenium-webdriver/ @BillArmstrong @Kuniwak @cnishina @SupernaviX @bendxn +/types/semantic-release/ @lgaticaq /types/semantic-ui/ @leonard-thieu /types/semantic-ui-accordion/ @leonard-thieu /types/semantic-ui-api/ @leonard-thieu @@ -4488,21 +4832,23 @@ /types/semver/ @Bartvds @BendingBender @LucianBuzzo /types/semver-compare/ @vincekovacs /types/semver-diff/ @chrismbarr +/types/semver-regex/ @BendingBender /types/semver-sort/ @LogvinovLeon +/types/semver-truncate/ @BendingBender /types/sencha_touch/ @brian428 /types/send/ @MikeJerred /types/seneca/ @psnider @kevynb +/types/sequelize/ @samuelneff @codeanimal @drinchev @babolivier @kukoo1 @oktapodia @morpheusxaut @TitaneBoy @zjy01 @nidzov @Raigen @todd @nrschultz @thomas-b @Antoine38660 @smff /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 @Antoine38660 /types/sequelize-cursor-pagination/ @pilagod /types/sequelize-fixtures/ @cschwarz /types/sequencify/ @npenin /types/sequester/ @Strate /types/serialize-error/ @thomasthiebaud /types/serialize-javascript/ @lith-light-g @Pochodaydayup -/types/serialport/v4/ @codefoster -/types/serialport/v6/ @codefoster @apearson /types/serialport/ @codefoster @apearson +/types/serialport/v6/ @codefoster @apearson +/types/serialport/v4/ @codefoster /types/serve-favicon/ @urossmolnik /types/serve-index/ @tkrotoff /types/serve-static/ @urossmolnik @LinusU @@ -4511,34 +4857,40 @@ /types/serverless/ @hassankhan /types/servicenow/ @bryceg /types/session-file-store/ @blendsdk @rokt33r -/types/set-cookie-parser/ @nickp10 +/types/set-cookie-parser/ @nickp10 @ilyaztsv /types/set-value/ @DanielRosenwasser /types/setasap/ @djcsdy /types/settings/ @shreyjain1994 +/types/sha/ @oBusk /types/sha.js/ @BendingBender /types/sha1/ @arcdev1 /types/sha256/ @nhardy /types/shallow-equals/ @rsolomon -/types/shallowequal/ @seansfkelley +/types/shallowequal/ @seansfkelley @BendingBender +/types/shallowequal/v0/ @seansfkelley /types/shapefile/ @DenisCarriere @Thw0rted /types/sharedb/ @soney /types/sharedworker/ @nakakura /types/sharepoint/ @gandjustas @andrei-markeev @baywet @teroarvola @dennispg -/types/sharp/ @lith-light-g @wooseopkim @BTOdell +/types/sharp/ @lith-light-g @wooseopkim @BTOdell @JamieWoodbury +/types/shasum/ @TeamworkGuy2 +/types/shebang-command/ @BendingBender +/types/shebang-regex/ @BendingBender /types/sheetify/ @toddself /types/shell-escape/ @nenadalm -/types/shell-quote/ @jason0x43 -/types/shelljs/ @nikeee @voy @gkalpak @pheromonez +/types/shell-quote/ @jason0x43 @CameronDiver +/types/shelljs/ @nikeee @voy @gkalpak @pheromonez @aldafu /types/shelljs-exec-proxy/ @qlonik /types/shimmer/ @kjin /types/shipit/ @cyrilschumacher /types/shipit-utils/ @cyrilschumacher /types/shopify-buy/ @openminder @straiforos @totemika +/types/shorten-repo-url/ @BendingBender /types/shortid/ @stpettersens @despairblue -/types/shot/v3/ @AJamesPhillips @SimonSchick /types/shot/ @AJamesPhillips @SimonSchick +/types/shot/v3/ @AJamesPhillips @SimonSchick /types/should-sinon/ @Arylo -/types/showdown/ @cbowdon @tan9 @arielsaldana +/types/showdown/ @hamedbaatour @cbowdon @tan9 @arielsaldana /types/shpjs/ @littlebtc /types/shrink-ray/ @forabi /types/shuffle-seed/ @LeartS @@ -4546,52 +4898,62 @@ /types/siesta/ @bquarmby /types/sigmajs/ @qinfchen /types/sigmund/ @BendingBender +/types/signal-exit/ @BendingBender /types/signale/ @resir014 @kingdaro @rjoydip /types/signalr/ @borisyankov @keesey @GiedriusGrabauskas /types/signalr-no-jquery/ @gjoshevski /types/signals/ @diullei /types/signature_pad/ @AbubakerB @jrmihalick @leejaedus +/types/simpl-schema/ @arichter83 @Qkramer @deskoh /types/simple-assign/ @NoHomey /types/simple-cw-node/ @vvakame /types/simple-lru/ @NN--- /types/simple-mock/ @leonyu -/types/simple-oauth2/v1/ @mad-mike @troy-lamerton @netux /types/simple-oauth2/ @mad-mike @troy-lamerton @netux @LinusU +/types/simple-oauth2/v1/ @mad-mike @troy-lamerton @netux /types/simple-peer/ @tlaziuk /types/simple-url-cache/ @a-lucas /types/simple-websocket/ @dex4er /types/simple-xml/ @notVitaliy -/types/simplebar/v1/ @gregonnet @leonard-thieu /types/simplebar/ @gregonnet @leonard-thieu +/types/simplebar/v1/ @gregonnet @leonard-thieu /types/simplemde/ @Scalesoft /types/simplesmtp/ @rogierschouten /types/simplestorage.js/ @axelcostaspena @mxl +/types/sindresorhus__class-names/ @BendingBender /types/sindresorhus__df/ @whatknight +/types/sindresorhus__djb2a/ @BendingBender +/types/sindresorhus__fnv1a/ @BendingBender +/types/sindresorhus__slugify/ @cprecioso +/types/sindresorhus__string-hash/ @BendingBender +/types/sindresorhus__to-milliseconds/ @BendingBender /types/single-line-log/ @ffflorian -/types/single-spa-react/ @Garrett-Smith-iq -/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg @gjednaszewski @johnjesse +/types/single-spa-react/ @Garrett-Smith-iq @chrisdopuch +/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg @gjednaszewski @johnjesse @alecf @SimonSchick /types/sinon-as-promised/ @igrayson -/types/sinon-chai/v2/ @kazimanzurrashid @jedmao /types/sinon-chai/ @kazimanzurrashid @jedmao @elpdpt +/types/sinon-chai/v2/ @kazimanzurrashid @jedmao /types/sinon-chrome/ @pimterry @crimx @kobanyan /types/sinon-express-mock/ @jpchip @tlaziuk /types/sinon-mongoose/ @stevehipwell /types/sinon-stub-promise/ @vintem @tstackhouse /types/sinon-test/ @mummybot -/types/sip.js/ @decyrus /types/sipml/ @chookies /types/sitemap2/ @shundy /types/six-runtime/ @493636333 /types/sizzle/ @leonard-thieu /types/sjcl/ @Evgenus /types/skatejs/ @Hotell +/types/sketchapp/ @manekinekko /types/ski/ @AyaMorisawa +/types/skin-tone/ @BendingBender /types/skyway/ @nakakura @izmhr /types/slack-mock/ @kkalavantavanich /types/slack-node/ @geoffreak /types/slack-winston/ @BlueHatbRit /types/slackdown/ @nju33 /types/slackify-html/ @hypexr +/types/slash/ @BendingBender /types/slate/ @andykent @majelbstoat @JanLoebel @YangusKhan @kalley @Kornil @isubasti @sgreav /types/slate-base64-serializer/ @YangusKhan /types/slate-html-serializer/ @YangusKhan @@ -4606,21 +4968,22 @@ /types/slocket/ @BendingBender /types/slug/ @mhegazy /types/smart-fox-server/ @ChanceM +/types/smart-truncate/ @oyalhi /types/smooth-scroll/ @andreiho /types/smoothscroll-polyfill/ @kryops -/types/smtp-server/v1/ @markisme @Taisiias /types/smtp-server/ @markisme @Taisiias @dex4er +/types/smtp-server/v1/ @markisme @Taisiias /types/smtpapi/ @a-morales /types/snakecase-keys/ @BendingBender /types/snappy/ @reconbot -/types/snapsvg/ @lhk @mattanja @kant2002 +/types/snapsvg/ @lhk @mattanja @kant2002 @terrymun /types/snazzy-info-window/ @milosd92 /types/snekfetch/ @ANekoIsFineToo @ShayBox @Dev-Yukine -/types/snoowrap/ @vitosamson @TheAppleFreak +/types/snoowrap/ @vitosamson @TheAppleFreak @willwull /types/snowball-stemmers/ @ryanvolum /types/snowboy/ @dolanmiu -/types/socket.io/v1/ @progre @divillysausages @florentpoujol @KentarouTakeda @gigi @BrainMaestro /types/socket.io/ @progre @divillysausages @florentpoujol @KentarouTakeda @gigi @BrainMaestro +/types/socket.io/v1/ @progre @divillysausages @florentpoujol @KentarouTakeda @gigi @BrainMaestro /types/socket.io-client/ @progre @divillysausages @florentpoujol /types/socket.io-p2p/ @saenglert /types/socket.io-parser/ @plantain-00 @@ -4649,16 +5012,17 @@ /types/space-pen/ @vvakame /types/spark-md5/ @bastienmoulia /types/sparkly/ @BendingBender -/types/sparkpost/v1/ @geoffreak /types/sparkpost/ @geoffreak @bondz @vvu +/types/sparkpost/v1/ @geoffreak /types/sparqljs/ @AlexeyMz +/types/sparse-bitfield/ @BendingBender /types/spatialite/ @atd-schubert /types/spdx-correct/ @jinwoo /types/spdx-satisfies/ @jinwoo /types/spdy/ @tony19 /types/speakeasy/ @legendecas @mrOlorin @xeoneux /types/speakingurl/ @Goldsmith42 -/types/spectacle/ @zmaybury @kale-stew +/types/spected/ @benneq /types/spectrum/ @M-Zuber @Ailrun /types/split/ @marcinporebski /types/split.js/ @icholy @@ -4676,6 +5040,7 @@ /types/sqlite3/ @nmalaguti @dpyro @BehindTheMath /types/sqlstring/ @marvinhagemeister /types/squirejs/ @bradleyayers +/types/srcset/ @BendingBender /types/srp/ @Patman64 /types/ssh-key-decrypt/ @BendingBender /types/ssh2/ @tkQubo @rbuckton @wrboyce @lucasmotta @@ -4687,8 +5052,8 @@ /types/stack-utils/ @BendingBender /types/stacktrace-js/ @exceptionless @pilagod /types/stale-lru-cache/ @cxcorp -/types/stampit/v2/ @koresar /types/stampit/ @koresar @lummish +/types/stampit/v2/ @koresar /types/stamplay-js-sdk/ @ridermansb /types/standard-error/ @roblabat /types/standard-http-error/ @roblabat @@ -4704,7 +5069,8 @@ /types/steam-totp/ @phenomax /types/steamid/ @Slessi /types/steed/ @Paul-Isache -/types/stellar-sdk/ @carl-foster @tristonj @pselden @maxbause @charlie-wasp +/types/stellar-base/ @carl-foster @tristonj @pselden @maxbause @charlie-wasp @Akuukis +/types/stellar-sdk/ @carl-foster @tristonj @pselden @maxbause @charlie-wasp @Akuukis /types/stemmer/ @will-ockmore /types/sticky-cluster/ @paustint /types/stompit/ @DanielRose @@ -4716,18 +5082,20 @@ /types/storybook-readme/ @lonyele /types/storybook__addon-a11y/ @hyunseob /types/storybook__addon-actions/ @joscha @jicjjang -/types/storybook__addon-backgrounds/ @hyunseob +/types/storybook__addon-backgrounds/ @hyunseob @adhrinae /types/storybook__addon-centered/ @kiyopikko /types/storybook__addon-info/ @mkornblum @fyrkant /types/storybook__addon-jest/ @halfmatthalfcat -/types/storybook__addon-knobs/ @joscha @martynaskadisa @amacleay +/types/storybook__addon-knobs/ @joscha @martynaskadisa @amacleay @MLoughry /types/storybook__addon-links/ @joscha @jessepinho -/types/storybook__addon-notes/ @joscha @amacleay +/types/storybook__addon-notes/ @joscha @amacleay @MLoughry /types/storybook__addon-options/ @joscha @simonhn @amacleay @gaetanmaisse @adam187 /types/storybook__addon-storyshots/ @bradleyayers +/types/storybook__addon-viewport/ @Vinnl /types/storybook__react/ @joscha @wapgear @dandean /types/storybook__react-native/ @joscha @wapgear @alechill @iRoachie @ceyhuno /types/storybook__vue/ @pntgupta +/types/strange/ @wanganjun /types/stream-array/ @Tyler-Murphy /types/stream-buffers/ @Jason3S /types/stream-chain/ @uhop @@ -4738,8 +5106,8 @@ /types/stream-series/ @k-kagurazaka /types/stream-shift/ @djcsdy /types/stream-throttle/ @danwbyrne -/types/stream-to-array/v0/ @Bartvds /types/stream-to-array/ @Bartvds @BendingBender +/types/stream-to-array/v0/ @Bartvds /types/stream-to-promise/ @Alorel /types/stream-to-string/ @BendingBender /types/streaming-json-stringify/ @BendingBender @@ -4751,19 +5119,24 @@ /types/string-argv/ @vladimir-tikhonov /types/string-format/ @lal12 /types/string-hash/ @ethanrubio +/types/string-length/ @BendingBender /types/string-replace-webpack-plugin/ @pd4d10 -/types/string-similarity/ @ragtime +/types/string-similarity/ @ragtime @BendingBender +/types/string-similarity/v1/ @ragtime /types/string-template/ @TonyPythoneer /types/string-width/ @jacobbubu /types/string_score/ @marcinporebski +/types/stringify-attributes/ @BendingBender /types/stringify-object/ @khoomeister /types/strip-ansi/ @mhegazy /types/strip-bom/ @mhegazy +/types/strip-color/ @BendingBender +/types/strip-indent/ @BendingBender /types/strip-json-comments/ @dmoonfire -/types/stripe/ @wjohnsto @codeanimal @sampsonjoliver @LinusU @brannon @kkamperschroer @starhoshi @bruun @galtalmor @htunnicliff @squirly @tzarger @ifiokjr +/types/stripe/ @wjohnsto @codeanimal @sampsonjoliver @LinusU @brannon @kkamperschroer @starhoshi @bruun @galtalmor @htunnicliff @squirly @tzarger @ifiokjr @SimonSchick @yultyyev @cpsoinos /types/stripe-checkout/ @cgwrench /types/stripe-v2/ @ejsmith @amritk @adamcmiel @jleider @galuszkak -/types/stripe-v3/ @ejsmith @amritk @adamcmiel @jleider @galuszkak +/types/stripe-v3/ @ejsmith @amritk @adamcmiel @jleider @galuszkak @slangeder /types/stripejs/ @RobinvanTienhoven @mattferderer /types/strong-cluster-control/ @shuntksh /types/strong-error-handler/ @blankstar85 @@ -4771,19 +5144,20 @@ /types/strophe/ @DavidKDeutsch /types/strophe.js/ @DavidKDeutsch /types/structured-source/ @azu +/types/styled-components/ @Igorbek @Igmat @lavoaster @Jessidhia /types/styled-components/v3/ @Igorbek @Igmat -/types/styled-components/ @Igorbek @Igmat @lavoaster @Kovensky /types/styled-jsx/ @R1ZZU /types/styled-react-modal/ @Lavoaster -/types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh @lavoaster @jschuler +/types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh @lavoaster @jschuler @adam187 @gretzky /types/styled-theming/ @ArjanJ -/types/stylelint/v7/ @alan-agius4 /types/stylelint/ @alan-agius4 @filipsalpe +/types/stylelint/v7/ @alan-agius4 /types/stylelint-webpack-plugin/ @bahlo /types/stylenames/ @bengry /types/stylus/ @SomaticIT /types/subscribe-ui-event/ @wangcheng678 /types/subsume/ @BendingBender +/types/subsume/v1/ @BendingBender /types/subtitle/ @jenglamlow /types/succinct/ @EnableSoftware /types/sudo-block/ @BendingBender @@ -4791,8 +5165,8 @@ /types/summernote/ @wstaelens @nusantara-cloud /types/sumo-logger/ @forabi @clementallen /types/suncalc/ @horiuchi -/types/superagent/v2/ @varju @NicoZelaya @mxl /types/superagent/ @NicoZelaya @mxl @paplorinc @shreyjain1994 @zopf @beeequeue @lukaselmer +/types/superagent/v2/ @varju @NicoZelaya @mxl /types/superagent-bunyan/ @bricka /types/superagent-no-cache/ @mxl /types/superagent-prefix/ @mxl @@ -4800,8 +5174,8 @@ /types/superstruct/ @edwardsnare /types/supertest/ @varju @pietu /types/supertest-as-promised/ @tkrotoff -/types/supports-color/v3/ @mgroenhoff /types/supports-color/ @mgroenhoff @mtraynham +/types/supports-color/v3/ @mgroenhoff /types/svg-injector/ @poke /types/svg-parser/ @mrmlnc /types/svg-path-bounding-box/ @NotWoods @@ -4836,13 +5210,15 @@ /types/swig/ @CodeAnimal @soywiz /types/swig-email-templates/ @mrhen @micksatana /types/swipe/ @kant2002 +/types/swiper/ @sgaliano @lucax88x @ematseruk @odahcam @jmca @daem0ndev /types/swiper/v3/ @sgaliano @lucax88x -/types/swiper/ @sgaliano @lucax88x @ematseruk @odahcam @jmca /types/swipeview/ @borisyankov /types/switchery/ @bgrieder @claylaut /types/swiz/ @jedigo /types/sylvester/ @StephaneAlie +/types/symlink-or-copy/ @BendingBender /types/synaptic/ @ToastHawaii @austincummings +/types/syntax-error/ @TeamworkGuy2 /types/systeminformation/ @PixelcrabAT /types/systemjs/ @ludohenin @NathanWalker @GiedriusGrabauskas @aluanhaddad /types/tabbable/ @mokkan @@ -4853,13 +5229,14 @@ /types/tabtab/ @vojtechhabarta @kamontat /types/tabulator/ @euginio /types/tail/ @spacejack -/types/tapable/v0/ @e-cloud /types/tapable/ @e-cloud @johnnyreilly -/types/tape/ @Bartvds @sodatea @DennisSchwartz @mikehenrty +/types/tapable/v0/ @e-cloud +/types/tape/ @Bartvds @sodatea @DennisSchwartz @mikehenrty @rostrowski /types/tar/ @SomaticIT @connor4312 /types/tar-fs/ @Umoxfo /types/tar-stream/ @glicht /types/task-graph-runner/ @mgroenhoff +/types/task-worklet/ @karol-majewski /types/tcp-ping/ @stegano /types/tcp-port-used/ @gautejohan /types/teddy/ @lannonbr @@ -4867,12 +5244,18 @@ /types/tedious-connection-pool/ @sandorfr /types/telebot/ @mariotsi /types/temp/ @DanielRosenwasser +/types/temp-dir/ @BendingBender /types/temp-write/ @BendingBender /types/tempfile/ @SamVerschueren @BendingBender /types/tempy/ @douglasduteil @maistho +/types/term-size/ @BendingBender +/types/terminal-image/ @BendingBender +/types/terminal-kit/ @katsanva +/types/terminal-link/ @BendingBender /types/terminal-menu/ @aravindarun /types/tern/ @nkappler /types/terser/ @JordiAnderl +/types/terser-webpack-plugin/ @Danscho /types/test-console/ @roberto @guidoux @gbmoretti /types/test-listen/ @stephenmathieson /types/testingbot-api/ @timbru31 @@ -4880,10 +5263,12 @@ /types/tether-drop/ @adidahiya /types/tether-shepherd/ @mtgibbs /types/text-buffer/ @GlenCFL +/types/text-clipper/ @krzysztof-grzybek /types/text-encoding/ @pine @mohsen1 @nwmqpa /types/text-encoding-utf-8/ @trxcllnt /types/text-table/ @saadq /types/textarea-caret/ @shiftkey +/types/textextensions/ @BendingBender /types/textract/ @lal12 /types/textversionjs/ @aaronosher /types/texzilla/ @m93a @@ -4891,15 +5276,15 @@ /types/theming/ @eps1lon /types/theo/ @petekp /types/thepiratebay/ @jsorrell -/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas @NotWoods @sethk @elk941 @Methuselah96 @Dukuo @JulianSSS @devilsparta @KonstantinLukaschenko +/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas @NotWoods @sethk @elk941 @Methuselah96 @Dukuo @JulianSSS @devilsparta @KonstantinLukaschenko @danyim /types/three-tds-loader/ @KonstantinLukaschenko @sschoensee /types/thrift/ @kamek-pf @kevin-greene-ck @jessezhang91 /types/throng/ @cyrilschumacher @tatethurston /types/throttle/ @BendingBender /types/throttle-debounce/ @czbuchi @franklixuefei /types/through/ @AndrewGaspar -/types/through2/v0/ @Bartvds @jedmao /types/through2/ @Bartvds @jedmao @valotas @TeamworkGuy2 @Alorel +/types/through2/v0/ @Bartvds @jedmao /types/through2-concurrent/ @Alorel /types/through2-map/ @LucasHill /types/tildify/ @BendingBender @@ -4931,6 +5316,7 @@ /types/to-absolute-glob/ @ajafff /types/to-camel-case/ @j-f1 /types/to-markdown/ @SuperPaintman +/types/to-semver/ @BendingBender /types/to-snake-case/ @LogvinovLeon /types/to-title-case-gouch/ @stpettersens /types/toastr/ @borisyankov @@ -4938,6 +5324,7 @@ /types/tokgen/ @l-jonas /types/toobusy-js/ @atd-schubert @BendingBender /types/tooltipster/ @stephenlautier @pjmagee @VorobeY1326 @leonard-thieu @janhi @joeskeen +/types/topo/ @BendingBender /types/topojson/ @ricardo-mello @chenzhutian @denisname /types/topojson-client/ @denisname @ricardo-mello /types/topojson-simplify/ @denisname @ricardo-mello @@ -4954,18 +5341,23 @@ /types/transducers-js/ @colinkahn @dphilipson @NaridaL /types/transducers.js/ @dphilipson /types/transliteration/ @tony19 -/types/trash/ @matthew-matvei @hoishin +/types/trash/ @matthew-matvei @hoishin @BendingBender /types/traverse/ @newclear /types/traverson/ @marcinporebski /types/travis-fold/ @andy-ms /types/trayballoon/ @korve +/types/treeify/ @mike-north /types/tress/ @sindilevich +/types/trezor-connect/ @federicobond /types/trianglify/ @unindented +/types/trie-prefix-tree/ @jlismore /types/trim/ @skysteve /types/triple-beam/ @danwbyrne /types/triplesec/ @threesquared /types/trunk8/ @niemyjski +/types/trusted-types/ @vrana /types/tryer/ @bengry +/types/ts-nameof/ @dsherret /types/tspromise/ @soywiz /types/ttf2woff2/ @ThomasdenH /types/tunnel/ @BendingBender @@ -4974,33 +5366,38 @@ /types/tween.js/ @Amos47 @sunetos @jzarnikov @alexburner /types/tweenjs/ @evilangelist @jcyuan /types/tweezer.js/ @praxxis -/types/twig/ @soywiz @enko +/types/twig/ @soywiz @enko @mtizziani /types/twilio/ @nickiannone @ashleybrener /types/twilio-common/ @gatimus /types/twilio-video/ @minddocdev @darioblanco /types/twit/ @Volox @sapphiredev @abraham @siwalikm @plhery /types/twitch-ext/ @beheh -/types/twitter/ @chitoku-k +/types/twitter/ @BendingBender +/types/twitter-for-web/ @chitoku-k /types/twitter-stream-channels/ @adrianbardan /types/twitter-text/ @rhysd /types/twix/ @j3ko +/types/two.js/ @cprecioso /types/type-check/ @hansrwindhoff -/types/type-detect/v0/ @Bartvds /types/type-detect/ @Bartvds +/types/type-detect/v0/ @Bartvds /types/type-is/ @BendingBender /types/type-name/ @armorik83 /types/typeahead/ @igochkov @gjunge /types/typedarray-pool/ @pawsong /types/typeof/ @OpenByteDev /types/typescript-deferred/ @DirtyHairy -/types/typography/ @boyeborg +/types/typography/ @boyeborg @krzysztofzuraw @dominicfallows +/types/typpy/ @BendingBender /types/tz-format/ @samverschueren /types/ua-parser-js/ @superduper @legendecas @MeLlamoPablo +/types/ua-string/ @BendingBender /types/uglify-es/ @alan-agius4 -/types/uglify-js/v2/ @tkrotoff /types/uglify-js/ @alan-agius4 @tkrotoff @johnnyreilly +/types/uglify-js/v2/ @tkrotoff /types/uglifycss/ @blendsdk /types/uglifyjs-webpack-plugin/ @vajkayrene +/types/ui-box/ @nettofarah /types/ui-grid/ @btesser @joeskeen @pbojanczyk /types/ui-router-extras/ @mputters @marcel-k @LaserUnicorns /types/ui-select/ @nkovacic @@ -5011,6 +5408,7 @@ /types/umbraco/ @DeCareSystemsIreland /types/umd/ @TeamworkGuy2 /types/umzug/ @drinchev @mlamp @trodi @emmanuelgautier +/types/unc-path-regex/ @BendingBender /types/underscore/ @borisyankov @jbaldwin @ccurrens @clottman @confususs /types/underscore-ko/ @MagicMau /types/underscore.string/ @rygine @@ -5022,19 +5420,19 @@ /types/unique-hash-stream/ @BendingBender /types/unique-random/ @Kuniwak /types/unique-random-array/ @BendingBender +/types/unique-string/ @BendingBender /types/unist/ @bizen241 @lujun2 @hrajchert @wooorm @rokt33r /types/unist-util-is/ @rokt33r /types/unity-webapi/ @jmvrbanac /types/universal-analytics/ @Bartvds @DarkerTV /types/universal-cookie/ @tomi -/types/universal-router/ @jtmthf @tlaziuk @Lodin /types/unorm/ @chbrown /types/untildify/ @BendingBender /types/unused-filename/ @BendingBender /types/unzip/ @coding2012 /types/unzipper/ @s73obrien @natemara @bartje321 -/types/update-notifier/v1/ @vvakame @nchen63 /types/update-notifier/ @vvakame @nchen63 @bitjson @grinich +/types/update-notifier/v1/ @vvakame @nchen63 /types/uploadcare/ @jineshshah36 /types/upng-js/ @plantain-00 @pineapplemachine /types/uppercamelcase/ @plantain-00 @@ -5042,21 +5440,25 @@ /types/uri-templates/ @Bartvds @barnski /types/urijs/ @RodneyJT @xt0rted @petejohanson /types/uritemplate/ @teyc @rubensworks +/types/urix/ @BendingBender /types/url-assembler/ @wolfgang42 -/types/url-join/ @rogierschouten @devrelm +/types/url-join/ @rogierschouten @devrelm @BendingBender +/types/url-join/v0/ @rogierschouten @devrelm /types/url-metadata/ @mrkmg /types/url-params/ @danielsogl -/types/url-parse/ @ChernenkoPaul @harisiva @DimitryDushkin +/types/url-parse/ @ChernenkoPaul @harisiva @DimitryDushkin @davidgoli /types/url-regex/ @unindented @sosukesuzuki /types/url-safe-base64/ @johngeorgewright /types/url-search-params/ @nick121212 @nrathi /types/url-template/ @marcinporebski +/types/urlencode/ @kimcoder /types/urllib/ @sorayama /types/urlparser/ @OpenByteDev /types/urlrouter/ @soywiz /types/urlsafe-base64/ @tkrotoff /types/usage/ @pvomhoff /types/usb/ @underscorebrody @thegecko +/types/user-event/ @whtsky /types/user-home/ @mhegazy /types/useragent/ @geoffreak /types/username/ @kayahr @krivachy @@ -5069,6 +5471,7 @@ /types/uuid-js/ @mhegazy /types/uuid-parse/ @screendriver /types/uuid-validate/ @HiromiShikata +/types/uuidv4/ @Hinaser /types/uws/ @plantain-00 @orblazer /types/v-chart-plugin/ @natemara /types/v8flags/ @BendingBender @@ -5079,15 +5482,16 @@ /types/valiant/ @whatasoda /types/valid-url/ @stevehipwell /types/validator/ @tgfjt @chrootsu @IOAyman @louy @kacepe @deptno @builtinnya @qqilihq -/types/validatorjs/ @LKay @danmana +/types/validatorjs/ @LKay @danmana @MatiasOlivera /types/vanilla-modal/ @samnau /types/vanilla-tilt/ @BrunnerLivio /types/varint/ @dbrockman /types/vary/ @BendingBender -/types/vast-client/ @jgainfort +/types/vast-client/ @jgainfort @kobawan /types/vec3/ @xstoudi /types/vectorious/ @erikgerrits /types/velocity-animate/ @smrq +/types/venn/ @marcwjj /types/verror/ @svi3c @max4t /types/vertx3-eventbus-client/ @oddeirik /types/vex-js/ @gdcohan @@ -5096,7 +5500,7 @@ /types/vfile/ @bizen241 @rokt33r /types/vfile-location/ @ikatyang @rokt33r /types/vfile-message/ @rokt33r -/types/victory/ @asvetliakov @snerks @Havret @alredyExist +/types/victory/ @asvetliakov @snerks @Havret @alredyExist @jlismore /types/video.js/ @vbortone @scleriot @SWBennett06 @IgelCampus @giofreitas @gjanblaszczyk @sroucheray @AkxeOne @meikidd /types/viewability-helper/ @lironzluf /types/viewerjs/ @lrh3321 @@ -5104,16 +5508,18 @@ /types/viewporter/ @borisyankov /types/vimeo/ @DazWilkin /types/vimeo__player/ @denisyilmaz @timc13 @terrymun -/types/vinyl/v0/ @jedmao /types/vinyl/ @vvakame @jedmao @thorn0 +/types/vinyl/v0/ @jedmao /types/vinyl-buffer/ @tkQubo -/types/vinyl-fs/ @vvakame @remisery +/types/vinyl-fs/ @vvakame @remisery @TeamworkGuy2 +/types/vinyl-fs/v1/ @vvakame @remisery +/types/vinyl-fs/v0/ @vvakame @remisery /types/vinyl-paths/ @tkQubo /types/virtual-dom/ @chbrown /types/virtual-keyboard/ @bsurai /types/vis/ @MichaelBitard @macleodbroad-wf @adripanico @seveves @kaktus40 @mmaitre314 @supercargo @takato1314 @alex-kachura @dcop @avrahamcool @divideby -/types/vision/v4/ @jasonswearingen @AJamesPhillips /types/vision/ @jasonswearingen @AJamesPhillips @lenovouser +/types/vision/v4/ @jasonswearingen @AJamesPhillips /types/vitalsigns/ @cyrilschumacher /types/vivus/ @DanielRosenwasser @lekhmanrus /types/vkbeautify/ @sch3lp @@ -5130,18 +5536,21 @@ /types/vue-scrollto/ @vincekovacs /types/vue-select/ @silh /types/vue2-datepicker/ @ChristianStornowski -/types/vuelidate/ @janesser +/types/vuelidate/ @janesser @jubairsaidi /types/vuex-i18n/ @jaeggerr @noamkfir @barahliush /types/w2ui/ @Ptival +/types/w3c-css-typed-object-model-level-1/ @yavanosta /types/w3c-generic-sensor/ @kenchris /types/w3c-image-capture/ @cosium /types/w3c-permissions/ @jberube /types/w3c-screen-orientation/ @kenchris /types/w3c-web-usb/ @larsgk +/types/wait-for-localhost/ @BendingBender /types/waitme/ @totpero /types/wake_on_lan/ @SrTobi /types/walk/ @poppa /types/wallabyjs/ @andrewconnell +/types/wallop/ @leemcd56 /types/wallpaper/ @BendingBender /types/wampy/ @KSDaemon /types/warning/ @cvle @@ -5155,12 +5564,12 @@ /types/wcag-contrast/ @plantain-00 /types/wcwidth/ @rokt33r /types/weak/ @int0h -/types/weapp-api/ @vargeek +/types/weapp-api/ @vargeek @pbestz /types/web-animations-js/ @kritollm /types/web-bluetooth/ @urish /types/web-push/ @paullessing /types/web-resource-inliner/ @BendingBender -/types/web3/ @simon-jentzsch @nitzantomer @zurbo @yxliang01 @phra @naddison36 @icaroharry @linusnorton @jpeletier @anneau @matrushka @andrevmatos @levino @zlumer @archangel-irk @sogasg @donamk @dkent600 @nerddan +/types/web3/ @simon-jentzsch @nitzantomer @zurbo @yxliang01 @phra @naddison36 @icaroharry @linusnorton @jpeletier @anneau @matrushka @andrevmatos @levino @zlumer @archangel-irk @sogasg @donamk @dkent600 @nerddan @alexkvak /types/web3-eth-abi/ @LogvinovLeon /types/web3-provider-engine/ @LogvinovLeon /types/webappsec-credential-management/ @iainmcgin @@ -5169,22 +5578,21 @@ /types/webcl/ @NCARalph /types/webcomponents.js/ @adidahiya /types/webcrypto/ @iislucas -/types/webdriverio/ @nmalaguti @timbru31 @fsmedberg-tc @tanvirislam06 @daveparslow @phil-lgr /types/webfontloader/ @doskallemaskin /types/webgl-ext/ @zenmumbler /types/webgl2/ @nkemnitz @karhu /types/webidl2/ @saschanaz /types/webmidi/ @lostfictions +/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @dennispg @christophehurpeau @ZSkycat @johnnyreilly @rwaskiewicz @kuehlein @grgur /types/webpack/v3/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @christophehurpeau @rwaskiewicz @kuehlein -/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @dennispg @christophehurpeau @ZSkycat @johnnyreilly @rwaskiewicz @kuehlein /types/webpack-assets-manifest/ @FranklinWhale /types/webpack-bundle-analyzer/ @kryops /types/webpack-chain/ @eirikurn @psachs21 /types/webpack-chunk-hash/ @mtraynham /types/webpack-cleanup-plugin/ @malj /types/webpack-config-utils/ @hotell -/types/webpack-dev-middleware/v1/ @bumbleblym @reduckted /types/webpack-dev-middleware/ @bumbleblym @reduckted @chrisabrams +/types/webpack-dev-middleware/v1/ @bumbleblym @reduckted /types/webpack-dev-server/ @maestroh @daveparslow @ZheyangSong @alan-agius4 @arturovt /types/webpack-dotenv-plugin/ @kryops /types/webpack-env/ @use-strict @rhonsby @@ -5192,12 +5600,12 @@ /types/webpack-hot-client/ @rynclark @ZSkycat /types/webpack-hot-middleware/ @bumbleblym @icylace @chrisabrams /types/webpack-manifest-plugin/ @r3nya -/types/webpack-merge/v0/ @deevus /types/webpack-merge/ @deevus @mtraynham +/types/webpack-merge/v0/ @deevus /types/webpack-node-externals/ @mtraynham /types/webpack-notifier/ @bumbleblym -/types/webpack-serve/v1/ @rynclark @Jokcy @ZSkycat /types/webpack-serve/ @rynclark @Jokcy @ZSkycat +/types/webpack-serve/v1/ @rynclark @Jokcy @ZSkycat /types/webpack-sources/ @e-cloud @chriseppstein /types/webpack-stream/ @iclanton @bumbleblym /types/webpack-subresource-integrity/ @huan086 @@ -5226,8 +5634,10 @@ /types/whatwg-url/ @aomarks /types/wheel/ @BTOdell /types/when/ @derekcicerone @Nemo157 +/types/when-dom-ready/ @BendingBender /types/which/ @vvakame @cspotcode /types/which-pm/ @jorgegonzalez +/types/whitelist-object/ @BendingBender /types/wicg-mediasession/ @jucrouzet /types/wif/ @danwbyrne /types/wiiu/ @mzsm @@ -5237,16 +5647,16 @@ /types/windows-1251/ @RomanGolovanov /types/windows-script-host/ @zspitz /types/windows-service/ @rogierschouten -/types/winjs/v1/ @adamhewitt627 @craigktreasure @xirzec -/types/winjs/v2/ @adamhewitt627 @craigktreasure @xirzec /types/winjs/ @adamhewitt627 @craigktreasure @xirzec +/types/winjs/v2/ @adamhewitt627 @craigktreasure @xirzec +/types/winjs/v1/ @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/v1/ @cjbarth /types/winston-syslog/ @cjbarth @felix-hoc +/types/winston-syslog/v1/ @cjbarth /types/wiring-pi/ @NoHomey /types/wnumb/ @acoreyj /types/wonder.js/ @yyc-git @@ -5255,12 +5665,14 @@ /types/wordcloud/ @joeskeen /types/words-to-numbers/ @James-Frowen /types/workbox-sw/ @wessberg +/types/workbox-webpack-plugin/ @kgroat +/types/worker-threads-pool/ @BendingBender /types/workerpool/ @Alorel /types/wpapi/ @guoyunhe -/types/wrap-ansi/v2/ @kayahr /types/wrap-ansi/ @kayahr -/types/wreck/v7/ @marcinporebski +/types/wrap-ansi/v2/ @kayahr /types/wreck/ @marcinporebski @saboya +/types/wreck/v7/ @marcinporebski /types/wrench/ @soywiz /types/write-file-atomic/ @BendingBender /types/write-file-atomically/ @Aankhen @@ -5283,25 +5695,26 @@ /types/xmldoc/ @Xstoudi @ajsheehan @notlaforge /types/xmldom/ @tkqubo /types/xmlpoke/ @garthk +/types/xmlserializer/ @eoin-obrien /types/xmltojson/ @traviscrowe /types/xmpp__jid/ @PJakcson @BendingBender /types/xmpp__xml/ @BendingBender /types/xregexp/ @Bartvds @jfahrenkrug @sigo -/types/xrm/v7/ @daryllabar -/types/xrm/v8/ @6ix4our @mattngan @markusmauch @daryllabar @clownwilleatme @mariusagur /types/xrm/ @6ix4our @mattngan @markusmauch @daryllabar @clownwilleatme @scottdurow +/types/xrm/v8/ @6ix4our @mattngan @markusmauch @daryllabar @clownwilleatme @mariusagur +/types/xrm/v7/ @daryllabar /types/xsd-schema-validator/ @Goldsmith42 /types/xsockets/ @pushplay -/types/xxhashjs/ @mDibyo +/types/xxhashjs/ @mDibyo @Manc /types/yallist/ @BendingBender /types/yaml/ @ikatyang @ColinBradley -/types/yandex-maps/ @Delagen +/types/yandex-maps/ @Delagen @gastwork13 /types/yandex-money-sdk/ @chrootsu /types/yar/ @SimonSchick -/types/yargs/v8/ @poelstra @mizunashi-mana @pushplay @jeffkenney -/types/yargs/v10/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC +/types/yargs/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC @steffenvv /types/yargs/v11/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC -/types/yargs/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC @tkazec +/types/yargs/v10/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC +/types/yargs/v8/ @poelstra @mizunashi-mana @pushplay @jeffkenney /types/yargs-interactive/ @szeck87 /types/yargs-parser/ @milesj /types/yauzl/ @ffflorian @@ -5309,10 +5722,12 @@ /types/yayson/ @Codesleuth /types/yazl/ @taoqf @seangenabe /types/ydn-db/ @yathit @gabrielmaldi +/types/year-days/ @BendingBender /types/yeoman-assert/ @Toilal /types/yeoman-generator/ @armorik83 @janslow @ikatyang @tasadar2 /types/yeoman-test/ @ikatyang /types/yesql/ @Sumolari +/types/yn/ @BendingBender /types/yoctodelay/ @seangenabe /types/yog-bigpipe/ @ssddi456 /types/yog-log/ @ssddi456 @@ -5320,9 +5735,9 @@ /types/yoga-layout/ @tnobody /types/yosay/ @armorik83 /types/youtube/ @DazWilkin @JoshuaKGoldberg @eliotfallon213 @terrymun @paulhobbel -/types/youtube-dl/ @bsurai +/types/youtube-dl/ @bsurai @moshfeu /types/yui/ @giabao -/types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola @YashdalfTheGray @vincentjames501 +/types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola @YashdalfTheGray @vincentjames501 @robertbullen @sat0yu @dancrumb /types/z-schema/ @pgonzal /types/zapier-platform-core/ @bradleyayers /types/zeit__next-typescript/ @icopp @@ -5330,8 +5745,8 @@ /types/zen-push/ @daprahamian /types/zenscroll/ @HamedFathi /types/zepto/ @jbaldwin -/types/zeroclipboard/v1/ @ejsmith @niemyjski @balassy @leonyu /types/zeroclipboard/ @ejsmith @niemyjski @balassy @leonyu +/types/zeroclipboard/v1/ @ejsmith @niemyjski @balassy @leonyu /types/zeromq/ @davemckeown @erikma @TitaneBoy /types/zip-webpack-plugin/ @blaise-io /types/zip.js/ @lgrignon diff --git a/README.md b/README.md index 026994fdd5..bbf2a6f16e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,4 @@ -# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) - -[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +# DefinitelyTyped > The repository for *high quality* TypeScript type definitions. @@ -8,6 +6,19 @@ Also see the [definitelytyped.org](http://definitelytyped.org) website, although *You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!* +## Current status + +This section tracks the health of the repository and publishing process. +It may be helpful for contributors experiencing any issues with their PRs and packages. + +* All packages are type-checking/linting cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) +* All packages are being published to npm in under 10,000 seconds: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) +* [typescript-bot](https://github.com/typescript-bot) has been active on DefinitelyTyped [![Activity Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) + +If anything here seems wrong, or any of the above are failing, please raise an issue in [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped). + +[![Join the chat at https://gitter.im/DefinitelyTyped/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/DefinitelyTyped/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + ## What are declaration files? See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). @@ -244,17 +255,71 @@ Here are the [currently requested definitions](https://github.com/DefinitelyType If types are part of a web standard, they should be contributed to [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) so that they can become part of the default `lib.dom.d.ts`. +#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports? + +Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function. + +Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error: + +> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct + +This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged. +This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter. + +It is more appropriate to import the module using the `import foo = require("foo");` syntax. +Nevertheless, if you want to use a default import like `import foo from "foo";` you have two options: +- you can use the [`--allowSyntheticDefaultImports` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) if your module runtime supports an interop scheme for non-ECMAScript modules, i.e. if default imports work in your environment (e.g. Webpack, SystemJS, esm). +- you can use the [`--esModuleInterop` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) if you want TypeScript to take care of non-ECMAScript interop (since Typescript 2.7). + #### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`? -If you are using TypeScript 2.7 or later, use `--esModuleInterop` in your project. -Otherwise, if default imports work in your environment (e.g. Webpack, SystemJS, esm), consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option. +Like in the previous question, refer to using either the [`--allowSyntheticDefaultImports`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) +or [`--esModuleInterop`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) +compiler options. + Do not change the type definition if it is accurate. -For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export. +For an NPM package, `export =` is accurate if `node -p 'require("foo")'` works to import a module, and `export default` is accurate if `node -p 'require("foo").default'` works to import a module. #### I want to use features from TypeScript 2.1 or above. Then you will have to add a comment to the last line of your definition header (after `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`. +#### I want to use features from TypeScript 3.1 or above. + +You can use the same `// TypeScript Version: 3.1` comment as above. +However, if your project needs to maintain types that are compatible with 3.1 and above *at the same time as* types that are compatible with 3.0 or below, you will need to use the `typesVersions` feature, which is available in TypeScript 3.1 and above. +You can find a detailed explanation of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions). + +Here's a short explanation to get you started: + +1. You'll have to add a `package.json` file to your package definition, with the following contents: + +```json +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] } + } +} +``` + +2. Create the sub-directory mentioned in the `typesVersions` field inside your types directory (`ts3.1/` in this example) +and add the types and tests specific for the new TypeScript version. You don't need the typical definition header +in any of the files from the `ts3.1/` directory. + +3. Set the `baseUrl` and `typeRoots` options in `ts3.1/tsconfig.json` to the correct paths, they should look something like this: +```json +{ + "compilerOptions": { + "baseUrl": "../../", + "typeRoots": ["../../"] + } +} +``` + +You can look [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/debounce-promise) and [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/create-html-element) for examples. + #### I want to add a DOM API not present in TypeScript by default. This may belong in [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). See the guidelines there. @@ -322,19 +387,6 @@ When `dts-gen` is used to scaffold a scoped package, the `paths` property has to GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead. -#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports? - -Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function. - -Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error: - -> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct - -This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged. -This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter. - -It is more appropriate to import the module using the `import foo = require("foo");` syntax, or to use a default import like `import foo from "foo";` if using the `--allowSyntheticDefaultImports` flag if your module runtime supports an interop scheme for non-ECMAScript modules as such. - ## License This project is licensed under the MIT license. @@ -342,6 +394,3 @@ This project is licensed under the MIT license. Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file. [![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) - -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Are packages being published to npm in less than 10,000 seconds on average? -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Has typescript-bot been active on DefinitelyTyped in the last two hours? diff --git a/README.ru.md b/README.ru.md index b90bdeac7c..9186c2ddd5 100644 --- a/README.ru.md +++ b/README.ru.md @@ -8,7 +8,7 @@ Также посетите веб-сайт [definitelytyped.org](http://definitelytyped.org), хотя информация в этом README более свежая. -*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).* +*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) и [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).* ## Что такое файлы декларации (файлы описания/объявления типов)? @@ -101,9 +101,9 @@ DefinitelyTyped работает только благодаря вкладу т // John ``` -* Если есть `tslint.json`, запустите `npm run lint package-name`. В противном случае запустите `tsc` in в директории пакета. +* Если есть `tslint.json`, запустите `npm run lint package-name`. В противном случае запустите `tsc` в директории пакета. -Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить previous authors. +Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить предыдущих авторов. Если этого не произойдет, вы можете сделать это самостоятельно в комментарии, связанном с PR. @@ -124,7 +124,7 @@ DefinitelyTyped работает только благодаря вкладу т | tsconfig.json | Позволяет вам запускать `tsc` внутри пакета. | | tslint.json | Включает linting. | -Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае. +Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас npm ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае. Посмотреть все варианты на [dts-gen](https://github.com/Microsoft/dts-gen). Вы можете отредактировать `tsconfig.json` чтобы добавить новые файлы, добавить `"target": "es6"` (необходимо для асинхронных функций), добавить в `"lib"`, или добавить опцию компилятора `"jsx"`. @@ -283,7 +283,7 @@ f("one"); "typeRoots": ["../../"], "paths": { "history": [ "history/v2" ] - }, + } }, "files": [ "index.d.ts", diff --git a/notNeededPackages.json b/notNeededPackages.json index 4acd790e24..701978da24 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -564,6 +564,12 @@ "sourceRepoURL": "https://www.npmjs.com/package/fast-simplex-noise", "asOfVersion": "3.0.0" }, + { + "libraryName": "Fastify-JWT", + "typingsPackageName": "fastify-jwt", + "sourceRepoURL": "https://github.com/fastify/fastify-jwt", + "asOfVersion": "0.8.1" + }, { "libraryName": "fecha", "typingsPackageName": "fecha", @@ -1068,6 +1074,12 @@ "sourceRepoURL": "https://github.com/paularmstrong/normalizr", "asOfVersion": "2.0.18" }, + { + "libraryName": "Nuka Carousel", + "typingsPackageName": "nuka-carousel", + "sourceRepoURL": "https://github.com/FormidableLabs/nuka-carousel/", + "asOfVersion": "4.4.6" + }, { "libraryName": "Numbro", "typingsPackageName": "numbro", @@ -1656,6 +1668,12 @@ "sourceRepoURL": "https://github.com/dpa99c/phonegap-launch-navigator", "asOfVersion": "4.0.0" }, + { + "libraryName": "Universal Router", + "typingsPackageName": "universal-router", + "sourceRepoURL": "https://github.com/kriasoft/universal-router", + "asOfVersion": "8.0.0" + }, { "libraryName": "upper-case", "typingsPackageName": "upper-case", @@ -1716,6 +1734,12 @@ "sourceRepoURL": "https://github.com/tgdwyer/WebCola", "asOfVersion": "3.2.0" }, + { + "libraryName": "WebdriverIO", + "typingsPackageName": "webdriverio", + "sourceRepoURL": "git@github.com:webdriverio/webdriverio.git", + "asOfVersion": "5.0.0" + }, { "libraryName": "webgme", "typingsPackageName": "webgme", diff --git a/types/accept-language-parser/accept-language-parser-tests.ts b/types/accept-language-parser/accept-language-parser-tests.ts index 586a31cb93..6f308b5315 100644 --- a/types/accept-language-parser/accept-language-parser-tests.ts +++ b/types/accept-language-parser/accept-language-parser-tests.ts @@ -20,11 +20,17 @@ const l3: AcceptLanguageParser.Language = { quality: 0.9 }; +type Lang = "en-US" | "ko-KR"; +const enUs: Lang = "en-US"; +const koKr: Lang = "ko-KR"; + const parsed1: AcceptLanguageParser.Language[] = AcceptLanguageParser.parse(''); const pick1: string | null = AcceptLanguageParser.pick([''], ''); const pick2: string | null = AcceptLanguageParser.pick([''], [l1, l2, l3]); const pick3: string | null = AcceptLanguageParser.pick([''], '', {}); const pick4: string | null = AcceptLanguageParser.pick([''], '', { loose: true }); +const pick5: Lang | null = AcceptLanguageParser.pick([enUs, koKr], [l1, l2, l3]); +const pick6: Lang | null = AcceptLanguageParser.pick([enUs, koKr], [l1, l2, l3]); const pickOptions: AcceptLanguageParser.PickOptions = { loose: true diff --git a/types/accept-language-parser/index.d.ts b/types/accept-language-parser/index.d.ts index c47969c940..4bec11b89c 100644 --- a/types/accept-language-parser/index.d.ts +++ b/types/accept-language-parser/index.d.ts @@ -1,17 +1,18 @@ // Type definitions for accept-language-parser 1.5 // Project: https://github.com/opentable/accept-language-parser // Definitions by: Niklas Wulf +// Wooram Jun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -// https://github.com/opentable/accept-language-parser/blob/v1.4.1/index.js +// https://github.com/opentable/accept-language-parser/blob/v1.5.0/index.js export function parse(acceptLanguage: string): Language[]; -export function pick( - supportedLanguages: string[], +export function pick( + supportedLanguages: T[], acceptLanguage: string | Language[], options?: PickOptions -): string | null; +): T | null; export interface Language { code: string; diff --git a/types/activestorage/activestorage-tests.ts b/types/activestorage/activestorage-tests.ts new file mode 100644 index 0000000000..ac9622e2d8 --- /dev/null +++ b/types/activestorage/activestorage-tests.ts @@ -0,0 +1,28 @@ +import * as ActiveStorage from 'activestorage'; + +ActiveStorage.start(); + +const delegate: ActiveStorage.DirectUploadDelegate = { + directUploadWillCreateBlobWithXHR(xhr) { + console.log(xhr.status); + }, + + directUploadWillStoreFileWithXHR(xhr) { + console.log(xhr.status); + }, +}; + +const d = new ActiveStorage.DirectUpload( + new File([], 'blank.txt'), + '/rails/active_storage/direct_uploads', + delegate +); + +d.create((error, blob) => { + if (error) { + console.log(error.message); + } else { + const { byte_size, checksum, content_type, filename, signed_id } = blob; + console.log({ byte_size, checksum, content_type, filename, signed_id }); + } +}); diff --git a/types/activestorage/index.d.ts b/types/activestorage/index.d.ts new file mode 100644 index 0000000000..2d749c84ec --- /dev/null +++ b/types/activestorage/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for ActiveStorage 5.2 +// Project: https://github.com/rails/rails/tree/master/activestorage/app/javascipt +// Definitions by: Cameron Bothner +// Definitions: https://github.com/cbothner/DefinitelyTyped +// TypeScript Version: 2.1 + +export as namespace ActiveStorage + +export function start(): void; + +export class DirectUpload { + id: number; + file: File; + url: string; + + constructor(file: File, url: string, delegate: DirectUploadDelegate) + + create(callback: (error: Error, blob: Blob) => void): void; +} + +export interface DirectUploadDelegate { + directUploadWillCreateBlobWithXHR?: (xhr: XMLHttpRequest) => void; + + directUploadWillStoreFileWithXHR?: (xhr: XMLHttpRequest) => void; +} + +export interface Blob { + byte_size: number; + checksum: string; + content_type: string; + filename: string; + signed_id: string; +} diff --git a/types/activestorage/tsconfig.json b/types/activestorage/tsconfig.json new file mode 100644 index 0000000000..326c2c7401 --- /dev/null +++ b/types/activestorage/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", "activestorage-tests.ts"] +} diff --git a/node-gettext/tslint.json b/types/activestorage/tslint.json similarity index 100% rename from node-gettext/tslint.json rename to types/activestorage/tslint.json diff --git a/types/adlib/adlib-tests.ts b/types/adlib/adlib-tests.ts new file mode 100644 index 0000000000..1f745d071a --- /dev/null +++ b/types/adlib/adlib-tests.ts @@ -0,0 +1,40 @@ +/* + | Copyright 2018 Esri + | + | Licensed under the Apache License, Version 2.0 (the "License"); + | you may not use this file except in compliance with the License. + | You may obtain a copy of the License at + | + | http://www.apache.org/licenses/LICENSE-2.0 + | + | Unless required by applicable law or agreed to in writing, software + | distributed under the License is distributed on an "AS IS" BASIS, + | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + | See the License for the specific language governing permissions and + | limitations under the License. + */ + +import * as adlib from "adlib"; + +const transform1: adlib.TransformFunction = + (key: string, value: any, settings: any, param?: any): any => { + return null; + }; + +const transformsList: adlib.TransformsList = { + firstXform: transform1 +}; + +const template = { + value: '{{ instance.color }}' +}; + +const settings = { + instance: { + color: 'red' + } +}; + +const interpolated = adlib.adlib(template, settings, transformsList); + +const list: string[] = adlib.listDependencies(template); diff --git a/types/adlib/index.d.ts b/types/adlib/index.d.ts new file mode 100644 index 0000000000..8866ab7809 --- /dev/null +++ b/types/adlib/index.d.ts @@ -0,0 +1,75 @@ +// Type definitions for adlib 3.0 +// Project: https://github.com/Esri/adlib +// Definitions by: Esri +// Mike Tschudi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/* + | Copyright 2018 Esri + | + | Licensed under the Apache License, Version 2.0 (the "License"); + | you may not use this file except in compliance with the License. + | You may obtain a copy of the License at + | + | http://www.apache.org/licenses/LICENSE-2.0 + | + | Unless required by applicable law or agreed to in writing, software + | distributed under the License is distributed on an "AS IS" BASIS, + | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + | See the License for the specific language governing permissions and + | limitations under the License. + */ + +/** + * Transform function to apply to interpolated value. + * + * @param key Path within a handlebar-style expression to attempt to replace; e.g., `s.animal.type` in + * https://github.com/Esri/adlib#transforms + * @param value Value to replace expression with + * @param settings Hash providing values to insert into template; see https://github.com/Esri/adlib#general-pattern + * @param param Parameter for transform function; e.g., the `optional` transform accepts a count of levels + * to delete if the value is not found (default is 0--just the current level); + * see https://github.com/Esri/adlib#optional-transform + */ +export interface TransformFunction { + ( + key: string, + value: any, + settings: any, + param?: any + ): any; +} + +/** + * Set of transformation functions keyed by the transform function's name. + */ +export interface TransformsList { + [ transformFnName: string ]: TransformFunction; +} + +/** + * A JavaScript library for interpolating property values in JSON Objects. + * + * @param template A template that possibly containing handlebar-style property values to replace; + * see https://github.com/Esri/adlib#general-pattern + * @param settings Hash providing values to insert into template; see https://github.com/Esri/adlib#general-pattern + * @param transforms Set of transformation functions + * @return Copy of template with replacements performed + */ +export function adlib( + template: any, + settings: any, + transforms?: TransformsList +): any; + +/** + * Reads a template and spits out unique handlebar-style property values. + * + * @param template A template that possibly containing handlebar-style property values to replace; + * see https://github.com/Esri/adlib#general-pattern + * @return List of unique property values in template + */ +export function listDependencies( + template: any +): string []; diff --git a/types/fastify-jwt/tsconfig.json b/types/adlib/tsconfig.json similarity index 86% rename from types/fastify-jwt/tsconfig.json rename to types/adlib/tsconfig.json index a0149e0fe8..570be96b8d 100644 --- a/types/fastify-jwt/tsconfig.json +++ b/types/adlib/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "fastify-jwt-tests.ts" + "adlib-tests.ts" ] } diff --git a/types/fastify-jwt/tslint.json b/types/adlib/tslint.json similarity index 100% rename from types/fastify-jwt/tslint.json rename to types/adlib/tslint.json diff --git a/types/adm-zip/adm-zip-tests.ts b/types/adm-zip/adm-zip-tests.ts index 2418597087..bd17c098be 100644 --- a/types/adm-zip/adm-zip-tests.ts +++ b/types/adm-zip/adm-zip-tests.ts @@ -1,62 +1,69 @@ - -import AdmZip = require("adm-zip"); +import AdmZip = require('adm-zip'); // reading archives -var zip = new AdmZip("./my_file.zip"); -var zipEntries: AdmZip.IZipEntry[] = zip.getEntries(); // an array of ZipEntry records +const zip = new AdmZip('./my_file.zip'); +const zipEntries: AdmZip.IZipEntry[] = zip.getEntries(); // an array of ZipEntry records -zipEntries.forEach(function (zipEntry) { +zipEntries.forEach(zipEntry => { console.log(zipEntry.toString()); // outputs zip entries information - if (zipEntry.entryName == "my_file.txt") { + if (zipEntry.entryName === 'my_file.txt') { console.log(zipEntry.getData().toString('utf8')); } }); // outputs the content of some_folder/my_file.txt -console.log(zip.readAsText("some_folder/my_file.txt")); +console.log(zip.readAsText('some_folder/my_file.txt')); // extracts the specified file to the specified location -zip.extractEntryTo(/*entry name*/"some_folder/my_file.txt", /*target path*/"/home/me/tempfolder", /*overwrite*/true) +zip.extractEntryTo( + /*entry name*/ 'some_folder/my_file.txt', + /*target path*/ '/home/me/tempfolder', + /*overwrite*/ true +); // extracts everything -zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true); +zip.extractAllTo(/*target path*/ '/home/me/zipcontent/', /*overwrite*/ true); // extracts everything and calls callback -> async extracction -zip.extractAllToAsync(/*target path*/"/home/me/zipcontent/", /*overwrite*/true, (error: Error)=> {}); +zip.extractAllToAsync( + /*target path*/ '/home/me/zipcontent/', + /*overwrite*/ true, + (error: Error) => {} +); // creating archives -var zip = new AdmZip(); +new AdmZip(); // add file directly -zip.addFile("test.txt", new Buffer("inner content of the file"), "entry comment goes here"); +zip.addFile('test.txt', new Buffer('inner content of the file'), 'entry comment goes here'); // add local file -zip.addLocalFile("/home/me/some_picture.png"); +zip.addLocalFile('/home/me/some_picture.png'); // get everything as a buffer -var willSendthis = zip.toBuffer(); +const willSendthis = zip.toBuffer(); // or write everything to disk -zip.writeZip(/*target file name*/"/home/me/files.zip"); +zip.writeZip(/*target file name*/ '/home/me/files.zip'); function processZipEntry(zipEntry: AdmZip.IZipEntry) { console.log('comment', zipEntry.comment); } -//tests taken from examples at https://github.com/cthackers/adm-zip/wiki/ADM-ZIP -import Zip = require("adm-zip"); +// tests taken from examples at https://github.com/cthackers/adm-zip/wiki/ADM-ZIP +import Zip = require('adm-zip'); // loads and parses existing zip file local_file.zip -var zip = new Zip("local_file.zip"); +new Zip('local_file.zip'); // creates new in memory zip -zip = new Zip(); +new Zip(); // loads and parses existing zip file local_file.zip -zip = new Zip("local_file.zip"); +new Zip('local_file.zip'); // get all entries and iterate them -zip.getEntries().forEach((entry) => { - var entryName = entry.entryName; - var decompressedData = zip.readFile(entry); // decompressed buffer of the entry - console.log(zip.readAsText(entry)); // outputs the decompressed content of the entry +zip.getEntries().forEach(entry => { + const entryName = entry.entryName; + const decompressedData = zip.readFile(entry); // decompressed buffer of the entry + console.log(zip.readAsText(entry)); // outputs the decompressed content of the entry }); // will extract the file myfile.txt from the archive to /home/user/folder/subfolder/myfile.txt -zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", true, true); +zip.extractEntryTo('folder/subfolder/myfile.txt', '/home/user/', true, true); // will extract the file myfile.txt from the archive to /home/user/myfile.txt -zip.extractEntryTo("folder/subfolder/myfile.txt", "/home/user/", false, true); +zip.extractEntryTo('folder/subfolder/myfile.txt', '/home/user/', false, true); function isAdmZipEntry(obj: any): obj is AdmZip.IZipEntry { - return obj !== null && typeof obj === "object" && typeof obj['entryName'] === 'string'; + return obj !== null && typeof obj === 'object' && typeof obj['entryName'] === 'string'; } diff --git a/types/adm-zip/index.d.ts b/types/adm-zip/index.d.ts index 39725932fc..52fd86a9e0 100644 --- a/types/adm-zip/index.d.ts +++ b/types/adm-zip/index.d.ts @@ -1,90 +1,56 @@ -// Type definitions for adm-zip v0.4.4 +// Type definitions for adm-zip 0.4 // Project: https://github.com/cthackers/adm-zip -// Definitions by: John Vilk , Abner Oliveira +// Definitions by: John Vilk +// Abner Oliveira +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - declare class AdmZip { /** - * Create a new, empty archive. + * @param fileNameOrRawData If provided, reads an existing archive. Otherwise creates a new, empty archive. */ - constructor(); + constructor(fileNameOrRawData?: string | Buffer); /** - * Read an existing archive. + * Extracts the given entry from the archive and returns the content. + * @param entry The full path of the entry or a `IZipEntry` object. + * @return `Buffer` or `null` in case of error. */ - constructor(fileName: string); - constructor(rawData: Buffer); + readFile(entry: string | AdmZip.IZipEntry): Buffer | null; /** - * Extracts the given entry from the archive and returns the content as a - * Buffer object. - * @param entry String with the full path of the entry - * @return Buffer or Null in case of error + * Asynchronous `readFile`. + * @param entry The full path of the entry or a `IZipEntry` object. + * @param callback Called with a `Buffer` or `null` in case of error. */ - readFile(entry: string): Buffer; - /** - * Extracts the given entry from the archive and returns the content as a - * Buffer object. - * @param entry ZipEntry object - * @return Buffer or Null in case of error - */ - readFile(entry: AdmZip.IZipEntry): Buffer; - /** - * Asynchronous readFile - * @param entry String with the full path of the entry - * @param callback Called with a Buffer or Null in case of error - */ - readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void; - /** - * Asynchronous readFile - * @param entry ZipEntry object - * @param callback Called with a Buffer or Null in case of error - * @return Buffer or Null in case of error - */ - readFileAsync(entry: AdmZip.IZipEntry, callback: (data: Buffer, err: string) => any): void; + readFileAsync( + entry: string | AdmZip.IZipEntry, + callback: (data: Buffer | null, err: string) => any + ): void; /** * Extracts the given entry from the archive and returns the content as - * plain text in the given encoding - * @param entry String with the full path of the entry - * @param encoding Optional. If no encoding is specified utf8 is used - * @return String + * plain text in the given encoding. + * @param entry The full path of the entry or a `IZipEntry` object. + * @param encoding If no encoding is specified `"utf8"` is used. */ - readAsText(fileName: string, encoding?: string): string; + readAsText(fileName: string | AdmZip.IZipEntry, encoding?: string): string; /** - * Extracts the given entry from the archive and returns the content as - * plain text in the given encoding - * @param entry ZipEntry object - * @param encoding Optional. If no encoding is specified utf8 is used - * @return String - */ - readAsText(fileName: AdmZip.IZipEntry, encoding?: string): string; - /** - * Asynchronous readAsText - * @param entry String with the full path of the entry + * Asynchronous `readAsText`. + * @param entry The full path of the entry or a `IZipEntry` object. * @param callback Called with the resulting string. - * @param encoding Optional. If no encoding is specified utf8 is used + * @param encoding If no encoding is specified `"utf8"` is used. */ - readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void; - /** - * Asynchronous readAsText - * @param entry ZipEntry object - * @param callback Called with the resulting string. - * @param encoding Optional. If no encoding is specified utf8 is used - */ - readAsTextAsync(fileName: AdmZip.IZipEntry, callback: (data: string) => any, encoding?: string): void; + readAsTextAsync( + fileName: string | AdmZip.IZipEntry, + callback: (data: string) => any, + encoding?: string + ): void; /** * Remove the entry from the file or the entry and all its nested directories - * and files if the given entry is a directory - * @param entry String with the full path of the entry + * and files if the given entry is a directory. + * @param entry The full path of the entry or a `IZipEntry` object. */ - deleteFile(entry: string): void; - /** - * Remove the entry from the file or the entry and all its nested directories - * and files if the given entry is a directory - * @param entry A ZipEntry object. - */ - deleteFile(entry: AdmZip.IZipEntry): void; + deleteFile(entry: string | AdmZip.IZipEntry): void; /** * Adds a comment to the zip. The zip must be rewritten after * adding the comment. @@ -92,72 +58,55 @@ declare class AdmZip { */ addZipComment(comment: string): void; /** - * Returns the zip comment * @return The zip comment. */ getZipComment(): string; /** - * Adds a comment to a specified zipEntry. The zip must be rewritten after + * Adds a comment to a specified file or `IZipEntry`. The zip must be rewritten after * adding the comment. * The comment cannot exceed 65535 characters in length. - * @param entry String with the full path of the entry + * @param entry The full path of the entry or a `IZipEntry` object. * @param comment The comment to add to the entry. */ - addZipEntryComment(entry: string, comment: string): void; - /** - * Adds a comment to a specified zipEntry. The zip must be rewritten after - * adding the comment. - * The comment cannot exceed 65535 characters in length. - * @param entry ZipEntry object. - * @param comment The comment to add to the entry. - */ - addZipEntryComment(entry: AdmZip.IZipEntry, comment: string): void; + addZipEntryComment(entry: string | AdmZip.IZipEntry, comment: string): void; /** * Returns the comment of the specified entry. - * @param entry String with the full path of the entry. - * @return String The comment of the specified entry. + * @param entry The full path of the entry or a `IZipEntry` object. + * @return The comment of the specified entry. */ - getZipEntryComment(entry: string): string; - /** - * Returns the comment of the specified entry - * @param entry ZipEntry object. - * @return String The comment of the specified entry. - */ - getZipEntryComment(entry: AdmZip.IZipEntry): string; + getZipEntryComment(entry: string | AdmZip.IZipEntry): string; /** * Updates the content of an existing entry inside the archive. The zip - * must be rewritten after updating the content - * @param entry String with the full path of the entry. + * must be rewritten after updating the content. + * @param entry The full path of the entry or a `IZipEntry` object. * @param content The entry's new contents. */ - updateFile(entry: string, content: Buffer): void; - /** - * Updates the content of an existing entry inside the archive. The zip - * must be rewritten after updating the content - * @param entry ZipEntry object. - * @param content The entry's new contents. - */ - updateFile(entry: AdmZip.IZipEntry, content: Buffer): void; + updateFile(entry: string | AdmZip.IZipEntry, content: Buffer): void; /** * Adds a file from the disk to the archive. * @param localPath Path to a file on disk. * @param zipPath Path to a directory in the archive. Defaults to the empty * string. + * @param zipName Name for the file. */ - addLocalFile(localPath: string, zipPath?: string): void; + addLocalFile(localPath: string, zipPath?: string, zipName?: string): void; /** * Adds a local directory and all its nested files and directories to the * archive. * @param localPath Path to a folder on disk. - * @param zipPath Path to a folder in the archive. Defaults to an empty - * string. + * @param zipPath Path to a folder in the archive. Default: `""`. + * @param filter RegExp or Function if files match will be included. */ - addLocalFolder(localPath: string, zipPath?: string): void; + addLocalFolder( + localPath: string, + zipPath?: string, + filter?: RegExp | ((filename: string) => boolean) + ): void; /** * Allows you to create a entry (file or directory) in the zip file. - * If you want to create a directory the entryName must end in / and a null + * If you want to create a directory the `entryName` must end in `"/"` and a `null` * buffer should be provided. - * @param entryName Entry path + * @param entryName Entry path. * @param content Content to add to the entry; must be a 0-length buffer * for a directory. * @param comment Comment to add to the entry. @@ -165,89 +114,81 @@ declare class AdmZip { */ addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void; /** - * Returns an array of ZipEntry objects representing the files and folders - * inside the archive + * Returns an array of `IZipEntry` objects representing the files and folders + * inside the archive. */ getEntries(): AdmZip.IZipEntry[]; /** - * Returns a ZipEntry object representing the file or folder specified by - * ``name``. + * Returns a `IZipEntry` object representing the file or folder specified by `name`. * @param name Name of the file or folder to retrieve. - * @return ZipEntry The entry corresponding to the name. + * @return The entry corresponding to the `name`. */ getEntry(name: string): AdmZip.IZipEntry; /** - * Extracts the given entry to the given targetPath. + * Extracts the given entry to the given `targetPath`. * If the entry is a directory inside the archive, the entire directory and * its subdirectories will be extracted. - * @param entry String with the full path of the entry - * @param targetPath Target folder where to write the file - * @param maintainEntryPath If maintainEntryPath is true and the entry is - * inside a folder, the entry folder will be created in targetPath as - * well. Default is TRUE + * @param entry The full path of the entry or a `IZipEntry` object. + * @param targetPath Target folder where to write the file. + * @param maintainEntryPath If maintainEntryPath is `true` and the entry is + * inside a folder, the entry folder will be created in `targetPath` as + * well. Default: `true`. * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - * - * @return Boolean + * will be overwriten if this is `true`. Default: `false`. */ - extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; + extractEntryTo( + entryPath: string | AdmZip.IZipEntry, + targetPath: string, + maintainEntryPath?: boolean, + overwrite?: boolean + ): boolean; /** - * Extracts the given entry to the given targetPath. - * If the entry is a directory inside the archive, the entire directory and - * its subdirectories will be extracted. - * @param entry ZipEntry object - * @param targetPath Target folder where to write the file - * @param maintainEntryPath If maintainEntryPath is true and the entry is - * inside a folder, the entry folder will be created in targetPath as - * well. Default is TRUE + * Extracts the entire archive to the given location. + * @param targetPath Target location. * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - * @return Boolean - */ - extractEntryTo(entryPath: AdmZip.IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; - /** - * Extracts the entire archive to the given location - * @param targetPath Target location - * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE + * will be overwriten if this is `true`. Default: `false`. */ extractAllTo(targetPath: string, overwrite?: boolean): void; /** - * Extracts the entire archive to the given location - * @param targetPath Target location + * Extracts the entire archive to the given location. + * @param targetPath Target location. * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - * @param callback The callback function will be called afeter extraction + * will be overwriten if this is `true`. Default: `false`. + * @param callback The callback function will be called after extraction. */ - extractAllToAsync(targetPath: string, overwrite: boolean, callback: (error: Error) => void): void; + extractAllToAsync( + targetPath: string, + overwrite?: boolean, + callback?: (error: Error) => void + ): void; /** * Writes the newly created zip file to disk at the specified location or - * if a zip was opened and no ``targetFileName`` is provided, it will - * overwrite the opened zip - * @param targetFileName + * if a zip was opened and no `targetFileName` is provided, it will + * overwrite the opened zip. */ - writeZip(targetPath?: string): void; + writeZip(targetFileName?: string, callback?: (error: Error | null) => void): void; /** - * Returns the content of the entire zip file as a Buffer object - * @return Buffer + * Returns the content of the entire zip file. */ toBuffer(): Buffer; } declare namespace AdmZip { /** - * The ZipEntry is more than a structure representing the entry inside the + * The `IZipEntry` is more than a structure representing the entry inside the * zip file. Beside the normal attributes and headers a entry can have, the * class contains a reference to the part of the file where the compressed * data resides and decompresses it when requested. It also compresses the * data and creates the headers required to write in the zip file. */ + // disable warning about the I-prefix in interface name to prevent breaking stuff for users without a major bump + // tslint:disable-next-line:interface-name interface IZipEntry { /** * Represents the full name and path of the file */ entryName: string; - rawEntryName: Buffer; + readonly rawEntryName: Buffer; /** * Extra data associated with this entry. */ @@ -256,15 +197,16 @@ declare namespace AdmZip { * Entry comment. */ comment: string; - name: string; + readonly name: string; /** * Read-Only property that indicates the type of the entry. */ - isDirectory: boolean; + readonly isDirectory: boolean; /** * Get the header associated with this ZipEntry. */ header: Buffer; + attr: number; /** * Retrieve the compressed data for this entry. Note that this may trigger * compression if any properties were modified. @@ -278,11 +220,7 @@ declare namespace AdmZip { /** * Set the (uncompressed) data to be associated with this entry. */ - setData(value: string): void; - /** - * Set the (uncompressed) data to be associated with this entry. - */ - setData(value: Buffer): void; + setData(value: string | Buffer): void; /** * Get the decompressed data associated with this entry. */ diff --git a/types/adm-zip/tsconfig.json b/types/adm-zip/tsconfig.json index 8e998c6f38..7bcb8d3644 100644 --- a/types/adm-zip/tsconfig.json +++ b/types/adm-zip/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "adm-zip-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/adm-zip/tslint.json b/types/adm-zip/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/adm-zip/tslint.json +++ b/types/adm-zip/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/aes-js/aes-js-tests.ts b/types/aes-js/aes-js-tests.ts new file mode 100644 index 0000000000..4f9d582630 --- /dev/null +++ b/types/aes-js/aes-js-tests.ts @@ -0,0 +1,10 @@ +import * as aesjs from 'aes-js'; + +const key = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + +const data: Uint8Array = aesjs.utils.utf8.toBytes('hello world'); + +const ecb = new aesjs.ModeOfOperation.ecb(key); +ecb.decrypt(ecb.encrypt(data)); + +const hex: string = aesjs.utils.hex.fromBytes(data); diff --git a/types/aes-js/index.d.ts b/types/aes-js/index.d.ts new file mode 100644 index 0000000000..142e03f7d9 --- /dev/null +++ b/types/aes-js/index.d.ts @@ -0,0 +1,134 @@ +// Type definitions for aes-js 3.1 +// Project: https://github.com/ricmoo/aes-js +// Definitions by: Federico Bond +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type ByteSource = ArrayBuffer | Uint8Array | number[]; + +export class AES { + /** + * Create a new AES block cipher. + * @param key The cipher key. + */ + constructor(key: ByteSource) + encrypt(v: ByteSource): ByteSource; +} + +/** + * Create a new Counter state for CTR cipher mode. + * @param initialValue The Counter initial value. + */ +export class Counter { + constructor(initialValue: number) + setValue(value: number): void; + setBytes(bytes: ByteSource): void; + increment(): void; +} + +export namespace ModeOfOperation { + class ModeOfOperationECB { + /** + * Create a new ECB stream cipher. + * @param key The cipher key. + */ + constructor(key: ByteSource) + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + class ModeOfOperationCBC { + /** + * Create a new CBC stream cipher. + * @param key The cipher key. + * @param iv The cipher initialization vector. + */ + constructor(key: ByteSource, iv: ByteSource); + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + class ModeOfOperationCFB { + /** + * Create a new CFB stream cipher. + * @param key The cipher key. + * @param iv The cipher initialization vector. + * @param segmentSize The cipher segment size. + */ + constructor(key: ByteSource, iv: ByteSource, segmentSize: number); + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + class ModeOfOperationOFB { + /** + * Create a new OFB stream cipher. + * @param key The cipher key. + * @param iv The cipher initialization vector. + */ + constructor(key: ByteSource, iv: ByteSource); + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + class ModeOfOperationCTR { + /** + * Create a new CTR stream cipher. + * @param key The cipher key. + * @param counter The cipher counter state. + */ + constructor(key: ByteSource, counter?: Counter) + encrypt(v: ByteSource): Uint8Array; + decrypt(v: ByteSource): Uint8Array; + } + + const ecb: typeof ModeOfOperationECB; + const cbc: typeof ModeOfOperationCBC; + const cfb: typeof ModeOfOperationCFB; + const ofb: typeof ModeOfOperationOFB; + const ctr: typeof ModeOfOperationCTR; +} + +export namespace utils { + namespace utf8 { + /** + * Convert a UTF8 encoded string to a Uint8Array. + * @param data The input string. + */ + function toBytes(data: string): Uint8Array; + + /** + * Convert an array-like object containing UTF8 data to a string. + * @param data The input data. + */ + function fromBytes(data: ByteSource): string; + } + namespace hex { + /** + * Convert a hexadecimal string to a Uint8Array. + * @param data The input string. + */ + function toBytes(data: string): Uint8Array; + + /** + * Convert an array-like object to a hexadecimal string. + * @param data The input data. + */ + function fromBytes(data: ByteSource): string; + } +} + +export namespace padding { + namespace pkcs7 { + /** + * Add standard PKCS7 padding to an array. + * @param data The input data. + */ + function pad(data: ByteSource): Uint8Array; + + /** + * Remove standard PKCS7 padding from an array. + * @param data The input data. + */ + function strip(data: ByteSource): Uint8Array; + } +} diff --git a/types/aes-js/tsconfig.json b/types/aes-js/tsconfig.json new file mode 100644 index 0000000000..10f3720c1e --- /dev/null +++ b/types/aes-js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aes-js-tests.ts" + ] +} diff --git a/types/aes-js/tslint.json b/types/aes-js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/aes-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index 0a3ba3c133..67257c6f65 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -358,7 +358,7 @@ export interface Utils { // Definitions // used as mixins to register functions to create classes (newable functions) in A-Frame -export type ComponentDefinition = T & Partial; +export type ComponentDefinition = T & Partial & ThisType; export type GeometryDefinition = T & Partial>; export type NodeDefinition = T & Partial; export interface PrimitiveDefinition { diff --git a/types/aframe/test/aframe-io-tests.ts b/types/aframe/test/aframe-io-tests.ts index 1120b50be8..a846976b80 100644 --- a/types/aframe/test/aframe-io-tests.ts +++ b/types/aframe/test/aframe-io-tests.ts @@ -30,7 +30,7 @@ AFRAME.registerComponent('set-image', { init: function() { var data = this.data; - var el = this.el!; + var el = this.el; this.setupFadeAnimation(); @@ -133,14 +133,14 @@ AFRAME.registerComponent('arrow-key-rotation', { if (!this.data.enabled) { return; } - var rotation = this.el!.getAttribute('rotation'); + 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); + this.el.setAttribute('rotation', rotation); } } }); @@ -164,10 +164,10 @@ AFRAME.registerComponent('hide-once-playing', { } }, onPlaying: function() { - this.el!.setAttribute('visible', false); + this.el.setAttribute('visible', false); }, onPause: function() { - this.el!.setAttribute('visible', true); + this.el.setAttribute('visible', true); } }); @@ -178,10 +178,10 @@ AFRAME.registerComponent('play-on-vrdisplayactivate-or-enter-vr', { }, play: function() { window.addEventListener('vrdisplayactivate', this.playVideo); - this.el!.sceneEl!.addEventListener('enter-vr', this.playVideoNextTick); + this.el.sceneEl!.addEventListener('enter-vr', this.playVideoNextTick); }, pause: function() { - this.el!.sceneEl!.removeEventListener('enter-vr', this.playVideoNextTick); + this.el.sceneEl!.removeEventListener('enter-vr', this.playVideoNextTick); window.removeEventListener('vrdisplayactivate', this.playVideo); }, playVideoNextTick: function() { @@ -189,7 +189,7 @@ AFRAME.registerComponent('play-on-vrdisplayactivate-or-enter-vr', { }, playVideo: function() { // TODO improve type - var video = (this.el! as Entity).components.material.material.map.image; + var video = (this.el as Entity).components.material.material.map.image; if (!video) { return; } @@ -208,7 +208,7 @@ AFRAME.registerComponent('play-on-window-click', { window.removeEventListener('click', this.onClick); }, onClick: function() { - var video = (this.el! as Entity).components.material.material.map.image; + var video = (this.el as Entity).components.material.material.map.image; if (!video) { return; } @@ -227,7 +227,7 @@ AFRAME.registerComponent('toggle-play-on-window-click', { window.removeEventListener('click', this.onClick); }, onClick: function() { - var video = (this.el! as Entity).components.material.material.map.image; + var video = (this.el as Entity).components.material.material.map.image; if (!video) { return; } @@ -359,7 +359,7 @@ AFRAME.registerComponent('audioanalyser-levels-scale', { return; } - children = this.el!.children; + children = this.el.children; for (var i = 0; i < children.length; i++) { (children[i] as ANode).setAttribute('scale', { x: 1, @@ -382,7 +382,7 @@ AFRAME.registerComponent('audioanalyser-volume-bind', { tick: function() { var analyserComponent; var data = this.data; - var el = this.el!; + var el = this.el; var value; analyserComponent = data.analyserEl.components.audioanalyser; @@ -404,7 +404,7 @@ AFRAME.registerComponent('audioanalyser-volume-scale', { tick: function() { var analyserEl = this.data.analyserEl || this.el; var analyserComponent; - var el = this.el!; + var el = this.el; var volume; analyserComponent = analyserEl.components.audioanalyser; @@ -542,7 +542,7 @@ AFRAME.registerComponent('audioanalyser-waveform', { }, remove: function() { - this.el!.removeObject3D('waveformContainer'); + this.el.removeObject3D('waveformContainer'); } }); @@ -874,7 +874,7 @@ AFRAME.registerComponent('color-on-beat', { init: function() { var analyserEl = this.data.analyserEl || this.el; - var el = this.el!; + var el = this.el; analyserEl.addEventListener('audioanalyser-beat', function() { el.setAttribute( @@ -909,12 +909,12 @@ AFRAME.registerComponent('remove-on-event', { removeEventListener: function() { var data = this.data; - var el = this.el!; + var el = this.el; el.removeEventListener(data.event, this._removeEntity); }, _removeEntity: function() { - var el = this.el!; + var el = this.el; if ((el as any).parentEl) { (el as any).parentEl.removeChild(el); } @@ -1016,7 +1016,7 @@ function rgbToHex(r: number, g: number, b: number) { AFRAME.registerComponent('random-material', { init: function() { - this.el!.setAttribute('material', { + this.el.setAttribute('material', { color: this.getRandomColor(), metalness: Math.random(), roughness: Math.random() @@ -1034,7 +1034,7 @@ AFRAME.registerComponent('random-material', { AFRAME.registerComponent('random-torus-knot', { init: function() { - this.el!.setAttribute('geometry', { + this.el.setAttribute('geometry', { primitive: 'torusKnot', radius: Math.random() * 10, radiusTubular: Math.random() * 0.75, diff --git a/types/aframe/test/aframe-tests.ts b/types/aframe/test/aframe-tests.ts index 2d6ff5bb7e..ac61f7f806 100644 --- a/types/aframe/test/aframe-tests.ts +++ b/types/aframe/test/aframe-tests.ts @@ -75,6 +75,7 @@ const Component = registerComponent('test-component', { }, init() { this.data.num = 0; + this.el.setAttribute('custom-attribute', 'custom-value'); }, update() {}, tick() {}, diff --git a/types/airbnb-prop-types/airbnb-prop-types-tests.ts b/types/airbnb-prop-types/airbnb-prop-types-tests.ts new file mode 100644 index 0000000000..7b79086848 --- /dev/null +++ b/types/airbnb-prop-types/airbnb-prop-types-tests.ts @@ -0,0 +1,206 @@ +import * as React from 'react'; +import * as PropTypes from 'prop-types'; +import * as AirbnbPropTypes from 'airbnb-prop-types'; + +class ClassComp extends React.Component { + render() { + return null; + } +} + +function FuncComp() { + return null; +} + +// $ExpectType Requireable +AirbnbPropTypes.and([PropTypes.number]); +// $ExpectType Requireable +AirbnbPropTypes.and([PropTypes.number, AirbnbPropTypes.nonNegativeInteger]); +// $ExpectType Validator +AirbnbPropTypes.and([PropTypes.number, AirbnbPropTypes.integer()], 'foo').isRequired; + +// $ExpectType Requireable +AirbnbPropTypes.between({ lt: 1 }); +// $ExpectType Requireable +AirbnbPropTypes.between({ lte: 2 }); +// $ExpectType Requireable +AirbnbPropTypes.between({ gt: 3 }); +// $ExpectType Requireable +AirbnbPropTypes.between({ gte: 4 }); +// $ExpectType Requireable +AirbnbPropTypes.between({ lt: 1, gt: 0 }); + +// $ExpectType Requireable +AirbnbPropTypes.booleanSome('foo', 'bar', 'baz'); + +// $ExpectType Requireable +AirbnbPropTypes.childrenHavePropXorChildren('foo'); + +// $ExpectType Requireable +AirbnbPropTypes.childrenOf(PropTypes.string); + +// $ExpectType Requireable +AirbnbPropTypes.childrenOfType(ClassComp); +// $ExpectType Requireable +AirbnbPropTypes.childrenOfType(FuncComp); +// $ExpectType Requireable +AirbnbPropTypes.childrenOfType('div'); +// $ExpectType Requireable +AirbnbPropTypes.childrenOfType(ClassComp, FuncComp, 'div'); + +// $ExpectType Requireable +AirbnbPropTypes.childrenSequenceOf({ validator: PropTypes.number }); +// $ExpectType Requireable +AirbnbPropTypes.childrenSequenceOf({ validator: PropTypes.string, max: 100 }); +// $ExpectType Requireable +AirbnbPropTypes.childrenSequenceOf({ validator: PropTypes.bool, min: 0 }); + +// $ExpectType Requireable +AirbnbPropTypes.componentWithName('Foo'); +// $ExpectType Requireable +AirbnbPropTypes.componentWithName(/Foo/); +// $ExpectType Requireable +AirbnbPropTypes.componentWithName('Foo', { stripHOCs: ['connect'] }); + +// $ExpectType Requireable +AirbnbPropTypes.disallowedIf(PropTypes.number, 'foo', PropTypes.string); + +// $ExpectType Requireable +AirbnbPropTypes.elementType(ClassComp); +// $ExpectType Requireable +AirbnbPropTypes.elementType(FuncComp); +// $ExpectType Requireable +AirbnbPropTypes.elementType('div'); +// $ExpectType Requireable +AirbnbPropTypes.elementType('*'); +// $ExpectError +AirbnbPropTypes.elementType(ClassComp, FuncComp, 'div'); + +// $ExpectType Requireable +AirbnbPropTypes.explicitNull(); +// $ExpectType Validator +AirbnbPropTypes.explicitNull().isRequired; + +interface ForbidShape { + foo: string; + bar: number; + baz?: boolean | null; +} + +// $ExpectType ValidationMap<{ foo: string | null; bar: number; baz: boolean | null; }> +AirbnbPropTypes.forbidExtraProps({ + foo: PropTypes.string, + bar: PropTypes.number.isRequired, + baz: PropTypes.bool, +}); + +// $ExpectType ValidationMap +AirbnbPropTypes.forbidExtraProps({ + foo: PropTypes.string.isRequired, + bar: PropTypes.number.isRequired, + baz: PropTypes.bool, +}); + +// $ExpectType Requireable +AirbnbPropTypes.integer(); + +// $ExpectType Requireable<{}> +AirbnbPropTypes.keysOf(PropTypes.number); +// $ExpectType Requireable<{}> +AirbnbPropTypes.keysOf(PropTypes.number, 'foo'); +// $ExpectType Requireable<{}> +AirbnbPropTypes.keysOf(PropTypes.oneOf(['foo', 'bar'])); + +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.number); +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.number, 'foo'); +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.string, 'foo', 'bar'); + +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveTrueProps('foo'); +// $ExpectType Requireable +AirbnbPropTypes.mutuallyExclusiveTrueProps('foo', 'bar'); + +// $ExpectType Requireable +AirbnbPropTypes.nChildren(1, PropTypes.number); +// $ExpectType Requireable +AirbnbPropTypes.nChildren(1, AirbnbPropTypes.childrenOfType('span')); + +// $ExpectType Requireable +AirbnbPropTypes.nonNegativeInteger; + +// $ExpectType Requireable +AirbnbPropTypes.nonNegativeNumber(); + +// $ExpectType Requireable +AirbnbPropTypes.numericString(); + +// $ExpectType Requireable<{}> +AirbnbPropTypes.object(); +// $ExpectType Requireable<{ foo: string; }> +AirbnbPropTypes.object<{ foo: string }>(); + +AirbnbPropTypes.or([PropTypes.bool.isRequired, AirbnbPropTypes.explicitNull().isRequired]); +AirbnbPropTypes.or([PropTypes.bool, PropTypes.number, PropTypes.arrayOf(PropTypes.string)]); +AirbnbPropTypes.or([PropTypes.number, PropTypes.string, PropTypes.bool], 'foo'); + +// $ExpectType Requireable +AirbnbPropTypes.range(0, 10); +// $ExpectType Requireable<5> +AirbnbPropTypes.range<5>(0, 10); + +// $ExpectType Requireable +AirbnbPropTypes.requiredBy('foo', PropTypes.string); +// $ExpectType Validator +AirbnbPropTypes.requiredBy('bar', PropTypes.number, 42).isRequired; + +// $ExpectType Requireable<{}> +AirbnbPropTypes.restrictedProp(); +// $ExpectType Requireable<{}> +AirbnbPropTypes.restrictedProp(() => 'Error'); +// $ExpectType Requireable<{}> +AirbnbPropTypes.restrictedProp(() => new Error('Error')); + +// $ExpectType Requireable<{}> +AirbnbPropTypes.sequenceOf({ validator: PropTypes.number }); +// $ExpectType Requireable<{}> +AirbnbPropTypes.sequenceOf({ validator: PropTypes.number }, { validator: PropTypes.string }); +// $ExpectType Requireable<{}> +AirbnbPropTypes.sequenceOf( + { validator: PropTypes.number, min: 0, max: 10 }, + { validator: PropTypes.string }, + { validator: PropTypes.bool }, +); + +interface ShapeShape { + foo: string; + bar?: number | null; +} + +// $ExpectType Requireable<{ foo: string | null; }> +AirbnbPropTypes.shape({ + foo: PropTypes.string, +}); +// $ExpectType Requireable<{ foo: string | null; bar: number | null; }> +AirbnbPropTypes.shape({ + foo: PropTypes.string, + bar: PropTypes.number, +}); +// $ExpectType Requireable +AirbnbPropTypes.shape({ + foo: PropTypes.string.isRequired, + bar: PropTypes.number, +}); + +// $ExpectType Requireable +AirbnbPropTypes.stringStartsWith('foo'); + +// $ExpectType Requireable +AirbnbPropTypes.uniqueArray(); +// $ExpectType Requireable +AirbnbPropTypes.uniqueArray(); + +// $ExpectType Requireable<{ [key: string]: number | null; }> +AirbnbPropTypes.valuesOf(PropTypes.number); diff --git a/types/airbnb-prop-types/index.d.ts b/types/airbnb-prop-types/index.d.ts new file mode 100644 index 0000000000..10c58556c7 --- /dev/null +++ b/types/airbnb-prop-types/index.d.ts @@ -0,0 +1,198 @@ +// Type definitions for airbnb-prop-types 2.11 +// Project: https://github.com/airbnb/prop-types +// Definitions by: Miles Johnson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import * as PropTypes from 'prop-types'; + +export interface ReactComponentLike { + setState(...args: any[]): any; + forceUpdate(...args: any[]): any; + render(): PropTypes.ReactNodeLike; + props: any; + state: any; + context: any; + refs: any; +} + +export interface ReactClassComponentLike { + new (...args: any[]): ReactComponentLike; +} + +export type ReactFunctionComponentLike = (...args: any[]) => PropTypes.ReactNodeLike; + +export type ReactTypeLike = string | ReactClassComponentLike | ReactFunctionComponentLike; + +export interface Specifier { + max?: number; + min?: number; + validator: PropTypes.Validator; +} + +export function and( + propTypes: [PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function and( + propTypes: [PropTypes.Validator, PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function and( + propTypes: [PropTypes.Validator, PropTypes.Validator, PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function and( + propTypes: Array>, + name?: string, +): PropTypes.Requireable; + +export function between(options: { + lt?: number; + lte?: number; + gt?: number; + gte?: number; +}): PropTypes.Requireable; + +export function booleanSome(...props: string[]): PropTypes.Requireable; + +export function childrenHavePropXorChildren( + prop: string | symbol, +): PropTypes.Requireable; + +export function childrenOf( + propType: PropTypes.Validator

, +): PropTypes.Requireable; + +export function childrenOfType( + ...types: ReactTypeLike[] +): PropTypes.Requireable; + +export function childrenSequenceOf( + ...specifiers: Specifier[] +): PropTypes.Requireable; + +export function componentWithName( + name: string | RegExp, + options?: { stripHOCs: ReadonlyArray }, +): PropTypes.Requireable; + +export function disallowedIf( + propType: PropTypes.Requireable, + otherPropName: string, + otherPropType: PropTypes.Validator, +): PropTypes.Requireable; + +export function elementType( + type: ReactTypeLike, +): PropTypes.Requireable; + +export function explicitNull(): PropTypes.Requireable; + +export function forbidExtraProps( + propTypes: PropTypes.ValidationMap, +): PropTypes.ValidationMap; + +export function integer(): PropTypes.Requireable; + +export function keysOf( + propType: PropTypes.Validator

, + name?: string, +): PropTypes.Requireable; + +export function mutuallyExclusiveProps( + propType: PropTypes.Requireable, + ...propNames: string[] +): PropTypes.Requireable; + +export function mutuallyExclusiveProps( + // tslint:disable-next-line:unified-signatures + propType: PropTypes.Validator, + ...propNames: string[] +): PropTypes.Requireable; + +export function mutuallyExclusiveTrueProps(...propNames: string[]): PropTypes.Requireable; + +export function nChildren( + n: number, + propType?: PropTypes.Validator

, +): PropTypes.Requireable; + +export const nonNegativeInteger: PropTypes.Requireable; + +export function nonNegativeNumber(): PropTypes.Requireable; + +export function numericString(): PropTypes.Requireable; + +export function object(): PropTypes.Requireable; + +export function or(propTypes: [PropTypes.Validator], name?: string): PropTypes.Requireable; + +export function or( + propTypes: [PropTypes.Validator, PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function or( + propTypes: [PropTypes.Validator, PropTypes.Validator, PropTypes.Validator], + name?: string, +): PropTypes.Requireable; + +export function or( + propTypes: Array>, + name?: string, +): PropTypes.Requireable; + +export function or( + // tslint:disable-next-line:unified-signatures + propTypes: Array>, + name?: string, +): PropTypes.Requireable; + +export function range(min?: number, max?: number): PropTypes.Requireable; + +export function range(min?: number, max?: number): PropTypes.Requireable; + +export function requiredBy

( + requiredByPropName: string, + propType: PropTypes.Validator

, + defaultValue?: any, +): PropTypes.Requireable

; + +export function restrictedProp( + messageFunction?: ( + props: object, + propName: string, + componentName: string, + location: string, + propFullName: string, + ) => string | Error | undefined, +): PropTypes.Requireable; + +export function sequenceOf(...specifiers: Specifier[]): PropTypes.Requireable; + +export function shape( + propTypes: PropTypes.ValidationMap, +): PropTypes.Requireable; + +export function stringStartsWith(string: string): PropTypes.Requireable; + +export function uniqueArray(): PropTypes.Requireable; + +export function uniqueArrayOf( + propType: PropTypes.Validator

, + mapperOrName: ((value: any) => any) | string, + name?: string, +): PropTypes.Requireable; + +export function valuesOf( + propType: PropTypes.Validator, +): PropTypes.Requireable<{ [key: string]: T }>; + +export function withShape( + propType: PropTypes.Validator

, + propTypes: PropTypes.ValidationMap, +): PropTypes.Requireable; diff --git a/types/airbnb-prop-types/tsconfig.json b/types/airbnb-prop-types/tsconfig.json new file mode 100644 index 0000000000..ccefe4943c --- /dev/null +++ b/types/airbnb-prop-types/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "airbnb-prop-types-tests.ts"] +} diff --git a/types/airbnb-prop-types/tslint.json b/types/airbnb-prop-types/tslint.json new file mode 100644 index 0000000000..71ee04c4e1 --- /dev/null +++ b/types/airbnb-prop-types/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/all-keys/all-keys-tests.ts b/types/all-keys/all-keys-tests.ts new file mode 100644 index 0000000000..6bbb6021c7 --- /dev/null +++ b/types/all-keys/all-keys-tests.ts @@ -0,0 +1,5 @@ +import allKeys = require('all-keys'); + +allKeys(Symbol.prototype); // $ExpectType Set +allKeys(Symbol.prototype, { includeObjectPrototype: false }); // $ExpectType Set +allKeys(Symbol.prototype, { includeSymbols: false }); // $ExpectType Set diff --git a/types/all-keys/index.d.ts b/types/all-keys/index.d.ts new file mode 100644 index 0000000000..9301c8f929 --- /dev/null +++ b/types/all-keys/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for all-keys 2.0 +// Project: https://github.com/sindresorhus/all-keys#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = allKeys; + +/** + * Get all property keys of an object including non-enumerable and inherited ones. + * Like [Reflect.ownKeys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys) + * but traverses up the prototype-chain. + */ +declare function allKeys(obj: object, options?: allKeys.Options): Set; + +declare namespace allKeys { + interface Options { + /** + * Include `Object.prototype` properties like `isPrototypeOf`. + * @default true + */ + includeObjectPrototype?: boolean; + /** + * Include [Symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) keys. + * @default true + */ + includeSymbols?: boolean; + } +} diff --git a/types/all-keys/tsconfig.json b/types/all-keys/tsconfig.json new file mode 100644 index 0000000000..a6f20f786f --- /dev/null +++ b/types/all-keys/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "all-keys-tests.ts" + ] +} diff --git a/types/all-keys/tslint.json b/types/all-keys/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/all-keys/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/amap-js-sdk/amap-js-sdk-tests.ts b/types/amap-js-sdk/amap-js-sdk-tests.ts new file mode 100644 index 0000000000..f09bca3760 --- /dev/null +++ b/types/amap-js-sdk/amap-js-sdk-tests.ts @@ -0,0 +1,22 @@ +const aMap = new AMap.Map('id', { + resizeEnable: true, + animateEnable: true +}); + +aMap.setCenter(new AMap.LngLat(0, 0)); + +AMap.plugin(['someplugin'], () => { + console.log('plugin loaded'); +}); + +AMap.convertFrom([116.3, 39.9], 'gps', (status, result) => { + if (result.info === 'ok') { + const _ = result.locations; + } +}); + +new AMap.Marker({ + map: aMap, + title: '', + position: new AMap.LngLat(0, 0), +}); diff --git a/types/amap-js-sdk/index.d.ts b/types/amap-js-sdk/index.d.ts new file mode 100644 index 0000000000..a1b93e6cb3 --- /dev/null +++ b/types/amap-js-sdk/index.d.ts @@ -0,0 +1,1392 @@ +// Type definitions for amap-js-sdk 1.4 +// Project: http://lbs.amap.com/api/javascript-api/summary/ +// Definitions by: Bian Zhongjie +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace AMap { + type EventCallback = (...args: any[]) => void; + type GenericEventCallback = (res: T) => void; + + /** + * 加载插件 + * @param pluginNames + * @param ready + */ + function plugin(pluginNames: string[], ready?: () => void): void; + + /** + * 加载服务 + * @param serviceName + * @param ready + */ + function service(serviceName: string, ready?: () => void): void; + + namespace event { + /** + * 注册DOM对象事件:给DOM对象注册事件,并返回eventListener。运行AMap.event.removeListener(eventListener)可以删除该事件的监听器。 + * @param instance:需注册事件的DOM对象(必填) + * @param eventName:事件名称(必填) + * @param handler:事件功能函数(必填) + * @param context:事件上下文(可选,缺省时,handler中this指向参数instance引用的对象,否则this指向context引用的对象) + */ + const addDomListener: (instance: any, eventName: string, handler: EventCallback, context?: any) => EventListener; + + /** + * 注册对象事件:给对象注册事件,并返回eventListener。运行AMap.event.removeListener(eventListener)可以删除该事件的监听器。 + * @param instance:需注册事件的对象(必填) + * @param eventName:事件名称(必填) + * @param handler:事件功能函数(必填) + * @param context:事件上下文(可选,缺省时,handler中this指向参数instance引用的对象,否则this指向context引用的对象) + */ + const addListener: (instance: any, eventName: string, handler: EventCallback, context?: any) => EventListener; + + /** + * 类似于addListener,但处理程序会在处理完第一个事件后将自已移除。 + */ + const addListenerOnce: (instance: any, eventName: string, handler: EventCallback, context?: any) => EventListener; + + /** + * 删除由上述 event.addDomListener 和 event.addListener 传回的指定侦听器。 + */ + const removeListener: (listener: EventListener) => void; + + /** + * 触发非DOM事件:触发非DOM事件eventName,extArgs将扩展到事件监听函数(handler)接受到的event参数中。如:在extArgs内写入{m:10,p:2},eventName监听函数(handler)可以接收到包含m,p两个key值的event对象。 + */ + const trigger: (instance: any, eventName: string, extArgs: any) => void; + } + + /** + * 此对象用于表示地图、覆盖物、叠加层上的各种鼠标事件返回,包含以下字段: + */ + interface MapsEventOptions { + lnglat: LngLat; + pixel: Pixel; + type: string; + target: any; + } + + abstract class EventBindable { + on(eventName: string, callback: EventCallback): void; + off(eventName: string, callback: EventCallback): void; + } + + /* --------------------------- 基础类 --------------------------- */ + /* 参考地址:http://lbs.amap.com/api/javascript-api/reference/core */ + + /** + * 像素坐标,确定地图上的一个像素点。 + */ + class Pixel { + /** + * 构造一个像素坐标对象。 + */ + constructor(x: number, y: number); + /** + * 获得X方向像素坐标 + */ + getX(): number; + + /** + * 获得Y方向像素坐标 + */ + getY(): number; + + /** + * 当前像素坐标与传入像素坐标是否相等 + */ + equals(point: Pixel): boolean; + + /** + * 以字符串形式返回像素坐标对象 + */ + toString(): string; + } + + /** + * 地物对象的像素尺寸 + */ + class Size { + /** + * 构造尺寸对象 + * @param width 宽度,单位:像素 + * @param height 高度,单位:像素 + */ + constructor(width: number, height: number); + + /** + * 获得宽度 + */ + getWidth(): number; + + /** + * 获得高度 + */ + getHeight(): number; + + /** + * 以字符串形式返回尺寸大小对象 + */ + toString(): string; + } + + /** + * 经纬度坐标,确定地图上的一个点 + */ + class LngLat { + /** + * 构造一个地理坐标对象 + * @param lng 经度 + * @param lat 纬度 + */ + constructor(lng: number, lat: number); + + /** + * 当前经纬度坐标值经度移动w,纬度移动s,得到新的坐标。 + * + * @param w 经度,向右移为正值,单位:米 + * @param s 纬度,向上移为正值,单位:米 + */ + offset(w: number, s: number): LngLat; + + /** + * 计算当前经纬度和传入经纬度或者经纬度数组连线之间的地面距离,单位为米 + * + * @param lnglat 传入的经纬度 + */ + distance(lnglat: LngLat | [number, number]): number; + + /** + * 获取经度值 + */ + getLng(): number; + + /** + * 获取纬度值 + */ + getLat(): number; + + /** + * 判断当前坐标对象与传入坐标对象是否相等 + * + * @param lnglat 传入坐标对象 + */ + equals(lnglat: LngLat): boolean; + + /** + * LngLat对象以字符串的形式返回 + */ + toString(): string; + } + + /** + * 地物对象的经纬度矩形范围 + */ + class Bounds { + /** + * 构造一个矩形范围 + * @param southWest 西南角经纬度坐标 + * @param northEast 东北角经纬度坐标 + */ + constructor(southWest: LngLat, northEast: LngLat); + + /** + * 判断指定点坐标是否在矩形范围内 + * @param point 指定点 + */ + contains(point: LngLat): boolean; + + /** + * 获取当前Bounds的中心点经纬度坐标 + */ + getCenter(): LngLat; + + /** + * 获取西南角坐标 + */ + getSouthWest(): LngLat; + + /** + * 获取东北角坐标 + */ + getNorthEast(): LngLat; + + /** + * 以字符串形式返回地物对象的矩形范围 + */ + toString(): string; + } + + interface TileLayerOptions { + map: Map; + tileSize: number; + tileUrl: string; + errorUrl: string; + getTileUrl: (x: number, y: number, z: number) => string; + zIndex: number; + opacity: number; + zooms: number[]; + detectRetina: boolean; + } + + abstract class Layer extends EventBindable { + setOpacity(alpha: number): void; + show(): void; + hide(): void; + getTiles(): string[]; + reload(): void; + setTileUrl(): void; + getZooms(): number[]; + setzIndex(index: number): void; + setMap(map: Map): void; + } + + class TileLayer extends Layer { + constructor(tileOpt?: { + map: Map, + tileSize?: number, + tileUrl?: string, + errorUrl?: string, + getTileUrl?: (x: number, y: number, z: number) => string, + zIndex?: number, + opacity?: number, + zooms?: number[], + detectRetina?: boolean + }); + } + + namespace TileLayer { + abstract class MapTypeLayer extends Layer { + constructor(options?: { + map: Map, + zIndex?: number, + opacity?: number, + zooms?: number[], + detectRetina?: boolean + }); + } + + class Satellite extends MapTypeLayer { + } + + class RoadNet extends MapTypeLayer { + } + + class Traffic extends MapTypeLayer { + constructor(options?: { + map: Map, + zIndex?: number, + opacity?: number, + zooms?: number[], + detectRetina?: boolean, + autoRefresh?: boolean, + interval?: number + }); + + interval: number; + autoRefresh: boolean; + } + } + + class IndoorMap { + constructor(opts: { + zIndex?: number, + opacity?: number, + cursor?: string, + hideFloorBar?: boolean, + alwaysShow?: boolean + }); + + showIndoorMap(indoorid: string, floor: number, shopid: string): void; + + showFloor(floor: number, noMove: boolean): void; + + setMap(map: Map): void; + + show(): void; + + hide(): void; + + setzIndex(): void; + + showFloorBar(): void; + + hideFloorBar(): void; + + setOpacity(alpha: number): void; + + getOpacity(): number; + + showLabels(): void; + + hideLabels(): void; + + getSelectedBuildingId(): string; + + getSelectedBuilding(): string; + } + + interface MapOptions { + view?: View2D; + layers?: TileLayer[]; + level?: number; + center?: LngLat; + labelzIndex?: number; + zooms?: number[]; + lang?: string; + cursor?: string; + crs?: string; + animateEnable?: boolean; + isHotspot?: boolean; + defaultLayer?: TileLayer; + rotateEnable?: boolean; + resizeEnable?: boolean; + showIndoorMap?: boolean; + indoorMap?: IndoorMap; + expandZoomRange?: boolean; + dragEnable?: boolean; + zoomEnable?: boolean; + doubleClickZoom?: boolean; + keyboardEnable?: boolean; + jogEnable?: boolean; + scrollWheel?: boolean; + touchZoom?: boolean; + mapStyle?: string; + features?: string[]; + } + + class View2D { + constructor(opt: { + center?: LngLat, + rotation?: number, + zoom?: number, + crs?: 'EPSG3857'|'EPSG3395'|'EPSG4326' + }); + + /** + * To silence lint error, this class has to be exists. + */ + toString(): string; + } + + class Map extends EventBindable { + constructor(mapDiv: string, opts?: MapOptions); + + getZoom(): number; + + getLayers(): TileLayer[]; + + getCenter(): LngLat; + + getCity(callback: (result: { + provice: string, + city: string, + citycode: string, + district: string + }) => void): void; + + getBounds(): Bounds; + getlabelzIndex(): number; + getLimitBounds(): Bounds; + getLang(): string; + getSize(): Size; + getRotation(): number; + getStatus(): any; + getDefaultCursor(): string; + getResolution(point: LngLat): number; + getScale(dpi: number): number; + setZoom(level: number): void; + setlabelzIndex(index: number): void; + setLayers(layers: TileLayer[]): void; + add(overlayers: any[]): void; + remove(overlayers: any[]): void; + getAllOverlays(type: string): Marker[] | Circle[] | Polygon[] | Polyline[]; + setCenter(position: LngLat): void; + setZoomAndCenter(zoomLevel: number, center: LngLat): void; + setCity(city: string, callback: () => void): void; + setBounds(bound: Bounds): void; + setLimitBounds(bound: Bounds): void; + clearLimitBounds(): void; + setLang(lang: string): void; + setRotation(rotation: number): void; + setStatus(status: any): void; + setDefaultCursor(cursor: string): void; + zoomIn(): void; + zoomOut(): void; + panTo(position: LngLat): void; + panBy(x: number, y: number): void; + setFitView(overlayList?: any[]): void; + clearMap(): void; + destroy(): void; + plugin(name: string| string[], callback: () => void): void; + addControl(obj: any): void; + removeControl(obj: any): void; + clearInfoWindow(): void; + pixelToLngLat(pixel: Pixel, level: number): LngLat; + lnglatToPixel(lnglat: LngLat, level: number): Pixel; + containerToLngLat(pixel: Pixel, level: number): LngLat; + lngLatToContainer(lnglat: LngLat, level: number): Pixel; + setMapStyle(style: string): void; + getMapStyle(): string; + setFeatures(features: string[]): void; + getFeatures(): string[]; + setDefaultLayer(layer: TileLayer): void; + } + + class Icon { + constructor(options?: { + size?: Size, + imageOffset?: Pixel, + image?: string, + imageSize?: Size + }); + + getImageSize(): Size; + setImageSize(size: Size): void; + } + + /** + * MarkerShape用于划定Marker的可点击区域范围。需要注意的是,在IE浏览器中图标透明区域默认为不触发事件,因此MarkerShape在IE中不起作用。 + */ + class MarkerShape { + constructor(options: { + /** + * + * 可点击区域组成元素数组,存放图形的像素坐标等信息,该数组元素由type决定: + * - circle:coords格式为 [x1, y1, r],x1,y1为圆心像素坐标,r为圆半径 + * - poly: coords格式为 [x1, y1, x2, y2 … xn, yn],各x,y表示多边形边界像素坐标 + * - rect: coords格式为 [x1, y1, x2, y2],x1,y1为矩形左上角像素坐标,x2,y2为矩形右下角像素坐标 + * Markshape的像素坐标是指相对于marker的左上角的像素坐标偏移量 + */ + coords?: number[], + + /** + * 可点击区域类型,可选值: + * - circle:圆形 + * - poly:多边形 + * - rect:矩形 + */ + type?: string + }); + + /** + * To silence lint error, this class has to be exists. + */ + toString(): string; + } + + interface MarkerOptions { + map?: Map; + position?: LngLat; + offset?: Pixel; + icon?: string|Icon; + content?: string| HTMLElement; + topWhenClick?: boolean; + topWhenMouseOver?: boolean; + draggable?: boolean; + raiseOnDrag?: boolean; + cursor?: string; + visible?: boolean; + zIndex?: number; + angle?: number; + autoRotation?: boolean; + animation?: string; + shadow?: Icon; + title?: string; + clickable?: boolean; + shape?: MarkerShape; + extData?: any; + label?: { content: string, offset: Pixel }; + } + + /** + * 点标记。 + */ + class Marker extends EventBindable { + constructor(options?: MarkerOptions); + + markOnAMAP(obj: { + name: string, + position: LngLat + }): void; + + getOffset(): Pixel; + setOffset(offset: Pixel): void; + + setAnimation(animate: string): void; + getAnimation(): string; + + setClickable(clickable: boolean): void; + getClickable(): boolean; + + getPosition(): LngLat; + setPosition(lnglat: LngLat): void; + + setAngle(angle: number): void; + getAngle(): number; + + setLabel(label: { + content?: string, + offset?: Pixel + }): void; + getLabel(): { + content?: string, + offset?: Pixel + }; + + setzIndex(index: number): void; + + getIcon(): string|Icon; + setIcon(content: string|Icon): void; + + setDraggable(draggable: boolean): void; + getDraggable(): boolean; + + hide(): void; + show(): void; + + setCursor(cursor: string): void; + + setContent(content: string| HTMLElement): void; + getContent(): string; + + moveAlong(lnglatlist: LngLat[], speed?: number, f?: (k: number) => number, circlable?: boolean): void; + moveTo(lnglat: LngLat, speed?: number, f?: (k: number) => number): void; + stopMove(): void; + setMap(map: Map): void; + getMap(): Map; + setTitle(title: string): void; + getTitle(): string; + setTop(isTop: boolean): void; + getTop(): boolean; + setShadow(icon: Icon): void; + getShadow(): Icon; + setShape(shape: MarkerShape): void; + getShape(): MarkerShape; + setExtData(ext: any): void; + getExtData(): any; + } + + interface MarkerClustererOptions { + gridSize?: number; + minClusterSize?: number; + maxZoom?: number; + averageCenter?: boolean; + styles?: any[]; + renderCluserMarker?: (obj: any) => void; + zoomOnClick?: boolean; + } + + /** + * 用于地图上加载大量点标记,提高地图的绘制和显示性能。 + */ + class MarkerClusterer extends EventBindable { + constructor(map: Map, markers: Marker[], opt?: MarkerClustererOptions); + + /** + * 添加一个需进行聚合的点标记 + * @param marker + */ + addMarker(marker: Marker): void; + + /** + * 删除一个聚合的点标记 + * @param marker 点标记 + */ + removeMarker(marker: Marker): void; + + /** + * 获取聚合点的总数量 + */ + getClustersCount(): number; + + /** + * 获取聚合网格的像素大小 + */ + getGridSize(): number; + + /** + * 获取地图中点标记的最大聚合级别 + */ + getMaxZoom(): number; + + /** + * 获取单个聚合的最小数量 + */ + getMinClusterSize(): number; + + /** + * 获取聚合的样式风格集合 + */ + getStyles(): any[]; + + /** + * 设置聚合网格的像素大小 + * @param size + */ + setGridSize(size: number): void; + + /** + * 设置地图中点标记的最大聚合级别 + * @param zoom + */ + setMaxZoom(zoom: number): void; + + /** + * 设置单个聚合的最小数量 + * @param size + */ + setMinClusterSize(size: number): void; + + /** + * 设置聚合的样式风格 + * @param styles + */ + setStyles(styles: any[]): void; + + /** + * 从地图上彻底清除所有聚合点标记 + */ + clearMarkers(): void; + + /** + * 设置将进行点聚合的地图对象 + * @param map + */ + setMap(map: Map): void; + + /** + * 设置将进行点聚合显示的点标记集合 + * @param markers + */ + setMarkers(markers: Marker[]): void; + + /** + * 获取该点聚合的地图对象 + */ + getMap(): Map; + + /** + * 获取该点聚合中的点标记集合 + */ + getMarkers(): Marker[]; + + /** + * 添加一组需进行聚合的点标记 + */ + addMarkers(markers: Marker[]): void; + + /** + * 删除一组聚合的点标记 + * @param markers + */ + removeMarkers(markers: Marker[]): void; + + /** + * 获取单个聚合点位置是否是聚合内所有标记的平均中心 + */ + isAverageCenter(): boolean; + + /** + * 设置单个聚合点位置是否是聚合内所有标记的平均中心 + * @param averageCenter + */ + setAverageCenter(averageCenter: boolean): void; + } + + interface CircleOptions { + map: Map; + zIndex?: number; + center: LngLat; + radius?: number; + strokeColor?: string; + strokeOpacity?: number; + fillColor?: string; + fillOpacity?: string; + strokeStyle?: string; + extData?: any; + strokeDasharray?: number[]; + } + + class Circle { + constructor(options?: CircleOptions); + setCenter(lnglat: LngLat): void; + getCenter(): LngLat; + getBounds(): Bounds; + setRadius(radius: number): void; + getRadius(): number; + setOptions(circleopt: CircleOptions): void; + getOptions(): CircleOptions; + hide(): void; + show(): void; + setMap(map: Map): void; + setExtData(ext: any): void; + getExtData(): any; + contains(point: LngLat): boolean; + } + + interface PolygonOptions { + map?: Map; + zIndex?: number; + path?: LngLat[]|LngLat[][]; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + fillColor?: string; + fillOpacity?: number; + extData?: any; + strokeStyle?: string; + strokeDasharray?: number[]; + } + + class Polygon extends EventBindable { + constructor(options?: PolygonOptions); + + setPath(path: LngLat[]|LngLat[][]): void; + getPath(): LngLat[]|LngLat[][]; + setOptions(opt: PolygonOptions): void; + getOptions(): PolygonOptions; + getBounds(): Bounds; + getArea(): number; + hide(): void; + show(): void; + setMap(map: Map): void; + setExtData(ext: any): void; + getExtData(): any; + contains(point: LngLat): boolean; + } + + interface PolylineOptions { + map?: Map; + zIndex?: number; + geodesic?: boolean; + isOutline?: boolean; + outlineColor?: string; + path?: LngLat[]; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + strokeStyle?: string; + strokeDasharray?: number[]; + extData?: any; + } + + class Polyline extends EventBindable { + constructor(options?: PolylineOptions); + + setPath(path: LngLat[]): void; + getPath(): LngLat[]; + + setOptions(opt: PolylineOptions): void; + getOptions(): PolylineOptions; + + getLength(): number; + getBounds(): Bounds; + hide(): void; + show(): void; + + setMap(map: Map): void; + setExtData(ext: any): void; + getExtData(): any; + } + + interface MapControl { + show(): void; + hide(): void; + } + + class MapType implements MapControl { + constructor(options?: { + defaultType?: number; + showTraffic?: boolean; + showRoad?: boolean; + }); + + show(): void; + hide(): void; + } + + class OverView extends EventBindable implements MapControl { + constructor(options?: { + tileLayer?: TileLayer[], + isOpen?: boolean, + visible?: boolean + }); + + open(): void; + close(): void; + setTileLayer(layer: TileLayer): void; + getTileLayer(): TileLayer; + show(): void; + hide(): void; + } + + class Scale extends EventBindable implements MapControl { + offset: Pixel; + position: string; + + show(): void; + hide(): void; + } + + class ToolBar extends EventBindable implements MapControl { + constructor(options?: { + offset?: Pixel, + position?: string, + ruler?: boolean, + noIpLocate?: boolean, + locate?: boolean, + liteStyle?: boolean, + direction?: boolean, + autoPosition?: boolean, + locationMarker?: Marker, + useNative?: boolean + }); + + getOffset(): Pixel; + setOffset(offset: Pixel): void; + hideRuler(): void; + showRuler(): void; + hideDirection(): void; + showDirection(): void; + hideLocation(): void; + showLocation(): void; + doLocation(): void; + getLocation(): { lng: number, lat: number }; + show(): void; + hide(): void; + } + + class InfoWindow extends EventBindable { + constructor(options?: { + isCustom?: boolean, + autoMove?: boolean, + closeWhenClickMap?: boolean, + content?: string | HTMLElement, + size?: Size, + offset?: Pixel, + position?: LngLat, + showShadow?: boolean + }); + + open(map: Map, pos: LngLat): void; + close(): void; + getIsOpen(): boolean; + setPosition(lnglat: LngLat): void; + getPosition(): LngLat; + setSize(size: Size): void; + getSize(): Size; + getContent(): string; + setContent(content: string|HTMLElement): void; + } + + class AdvancedInfoWindow extends EventBindable { + constructor(options?: { + autoMove?: boolean, + closeWhenClickMap?: boolean, + content?: string|HTMLElement, + offset?: Pixel, + position?: LngLat, + panel?: string|HTMLElement, + searchRadius?: number, + placeSearch?: boolean, + driving?: boolean, + walking?: boolean, + transit?: boolean, + asOrigin?: boolean, + asDestination?: boolean + }); + + open(map: Map, pos: LngLat): void; + close(): void; + getIsOpen(): boolean; + setPosition(lnglat: LngLat): void; + getPosition(): LngLat; + setContent(content: string|HTMLElement): void; + getContent(): string; + } + + class Geolocation extends EventBindable { + constructor(options: { + enableHighAccuracy?: boolean, + timeout?: number, + noIpLocate?: boolean, + maximumAge?: number, + convert?: boolean, + showButton?: boolean, + buttonDom?: string|HTMLElement, + buttonPosition?: string, + buttonOffset?: Pixel, + showMarker?: boolean, + markerOptions?: MarkerOptions, + showCircle?: boolean, + circleOptions?: CircleOptions, + panToLocation?: boolean, + zoomToAccuracy?: boolean, + useNative?: boolean + }); + + isSupported(): boolean; + getCurrentPosition(): void; + watchPosition(): number; + clearWatch(watchId: number): number; + } + + interface GeolocationResult { + position: LngLat; + accuracy: number; + isConverted: boolean; + info: string; + } + + interface GeolocationError { + info: string; + } + + interface BusinessArea { + id: string; + name: string; + location: string; + } + + interface Road { + id: string; + name: string; + distance: number; + location: LngLat; + direction: string; + } + + interface Cross { + distance: number; + direction: string; + location: LngLat; + first_id: string; + first_name: string; + second_id: string; + second_name: string; + } + + interface AddressComponent { + province: string; + city: string; + citycode: string; + district: string; + adcode: string; + township: string; + street: string; + streetNumber: string; + neighborhood: string; + neighborhoodType: string; + building: string; + buildingType: string; + businessAreas: BusinessArea[]; + } + + interface Geocode { + addressComponent: AddressComponent; + formattedAddress: string; + location: LngLat; + adcode: string; + level: string; + } + + interface ReGeocode { + addressComponent: AddressComponent; + formattedAddress: string; + roads: Road[]; + crosses: Cross[]; + pois: ReGeocodePoi[]; + } + + interface ReGeocodePoi { + id: string; + name: string; + type: string; + tel: string; + distance: number; + direction: string; + address: string; + location: LngLat; + businessArea: string; + } + + interface GeocodeResult { + info: string; + geocodes: LngLat[]; + resultNum: number; + } + + interface ReGeocodeResult { + info: string; + regeocode: ReGeocode; + } + + class Geocoder { + constructor(opts?: { + city?: string, + radius?: number, + batch?: boolean, + extensions?: string + }); + + getLocation(address: string, callback?: (status?: string, result?: string | GeocodeResult) => void): void; + + setCity(city: string): void; + + getAddress(location: LngLat|LngLat[], callback: (status?: string, result?: string | ReGeocodeResult) => void): void; + } + + /** + * 坐标转换结果 + */ + interface ConvertorResult { + info: string; + locations: LngLat[]; + } + + /** + * 坐标转换 + */ + function convertFrom(lnglat: LngLat | LngLat[] | [number, number], type: string, result: (status: string, result: ConvertorResult) => void): void; + + interface Poi { + id: string; + name: string; + type: string; + location: LngLat; + address: string; + distance: number; + tel: string; + + website: string; + pcode: string; + citycode: string; + adcode: string; + postcode: string; + pname: string; + cityname: string; + adname: string; + email: string; + entr_location: LngLat; + exit_location: LngLat; + groupbuy: boolean; + discount: boolean; + } + + interface CitySearchResult { + city: string; + bounds: Bounds; + } + + class CitySearch extends EventBindable { + getLocalCity(callback: (status: string, result: string | CitySearchResult) => void): void; + getCityByIp(ip: string, callback: (status: string, result: string | CitySearchResult) => void): void; + } + + enum DrivingPolicy { + LEAST_TIME, + LEAST_FEE, + LEAST_DISTANCE, + REAL_TRAFFIC + } + + interface ViaCity { + name: string; + citycode: string; + adcode: string; + districts: District[]; + } + + interface District { + name: string; + adcode: string; + } + + interface TMC { + lcode: string; + distance: number; + status: string; + } + + interface DriveStep { + start_location: LngLat; + end_location: LngLat; + instruction: string; + action: string; + assist_action: string; + orientation: string; + road: string; + distance: number; + tolls: number; + tolls_distance: number; + toll_road: string; + time: number; + path: LngLat[]; + cities?: ViaCity[]; + tmcs?: TMC[]; + } + + interface DriveRoute { + distance: number; + time: number; + policy: string; + tolls: number; + tolls_distance: number; + steps: DriveStep[]; + } + + interface DrivingResult { + info: string; + origin: LngLat; + destination: LngLat|Poi; + start: Poi; + waypoints: Poi; + taxi_cost: number; + routes: DriveRoute[]; + } + + class Driving extends EventBindable { + constructor(options?: { + policy?: DrivingPolicy, + extensions?: string, + map?: Map, + panel?: string|HTMLElement, + hideMarkers?: boolean, + showTraffic?: boolean + }); + + search(origin: LngLat, destination: LngLat, opts?: { + waypoints: LngLat[] + }, callback?: (status: string, result: string|DrivingResult) => void): void; + + search(point: Array<{ + keyword: string, + city: string + }>, callback: (status: string, result: string|DrivingResult) => void): void; + + setPolicy(policy: DrivingPolicy): void; + setAvoidPolygons(path: LngLat[][]): void; + setAvoidRoad(road: string): void; + clearAvoidRoad(): void; + clearAvoidPolygons(): void; + getAvlidPolygons(): LngLat[][]; + getAvoidRoad(): string; + clear(): void; + searchOnAMAP(obj: { + origin?: LngLat, + originName?: string, + destination?: LngLat, + destinationName?: string + }): void; + } + + // 天气插件 + + interface WeatherLiveResult { + info: string; + province: string; + city: string; + adcode: string; + weather: string; + temperature: number; + windDirection: string; + windPower: number; + humidity: string; + reportTime: string; + } + + interface Forecast { + date: string; + week: string; + dayWeather: string; + nightWeather: string; + dayTemp: number; + nightTemp: number; + dayWindDir: string; + nightWindDir: string; + dayWindPower: string; + nightWindPower: string; + } + + interface WeatherForecastResult { + info: string; + province: string; + city: string; + adcode: string; + reportTime: string; + forecasts: Forecast[]; + } + + class Weather { + /** + * 查询实时天气信息 + * @param district 支持城市名称/区域编码(如:“杭州市”/“330100”) + * @param callback 当请求成功时ErrorStatus为null,当请求不成功时ErrorStatus为Obj + */ + getLive(district: string, callback: (errorStatus: any, result: WeatherLiveResult) => void): void; + + /** + * 查询四天预报天气,包括查询当天天气信息 + * @param district 支持城市名称/区域编码(如:“杭州市”/“330100”) + * @param callback 当请求成功时ErrorStatus为null,当请求不成功时ErrorStatus为Obj + */ + getForecast(district: string, callback: (errorStatus: any, result: WeatherForecastResult) => void): void; + } + + interface Tip { + name: string; + district: string; + adcode: string; + } + + interface AutocompleteResult { + info: string; + count: number; + tips: Tip[]; + } + + class Autocomplete { + constructor(opts: { + type?: string, + city?: string, + datatype?: string, + citylimit?: boolean, + input?: string + }); + + search(keyword: string, callback: (status: string, result: string | AutocompleteResult) => void): void; + } + + interface SelectChangeEvent { + type: string; + id: string; + marker: Marker; + listElement: HTMLLIElement; + data: Poi; + } + + interface PoiList { + pois: Poi[]; + pageIndex: number; + pageSize: number; + count: number; + } + + interface CityInfo { + name: string; + citycode: string; + adcode: string; + count: number; + } + + interface SearchResult { + info: string; + poiList: PoiList; + keywordList: string[]; + cityList: CityInfo[]; + } + + interface Photo { + title: string; + url: string; + } + + interface Content { + id: string; + name: string; + } + + interface Discount { + title: string; + detail: string; + start_time: string; + end_time: string; + sold_num: string; + photos: Photo[]; + url: string; + provider: string; + } + + interface Groupbuy { + title: string; + type_code: string; + type: string; + detail: string; + stime: string; + etime: string; + count: number; + sold_num: number; + original_price: number; + groupbuy_price: number; + discount: number; + ticket_address: string; + ticket_tel: string; + photos: Photo[]; + url: string; + provider: string; + } + + class PlaceSearch { + constructor(opts: { + city?: string, + citylimit?: boolean, + children?: number, + type?: string, + lang?: string, + pageSize?: number, + pageIndex?: number, + extensions?: string, + map?: Map, + panel?: string|HTMLElement, + showCover?: boolean, + renderStyle?: string, + autoFitView?: boolean + }); + + search(keyword: string, callback: (status: string, result: string | SearchResult) => void): void; + searchNearBy(keyword: string, center: LngLat, radius: number, callback: (status: string, result: string|SearchResult) => void): void; + searchInBounds(keyword: string, bounds: Bounds|Polygon, callback: (status: string, result: string|SearchResult) => void): void; + getDetails(POIID: string, callback: (status: string, result: string|SearchResult) => void): void; + setType(type: string): void; + setCityLimit(p: boolean): void; + setPageIndex(pageIndex: number): void; + setPageSize(setPageSize: number): void; + setCity(city: string): void; + setLang(lang: string): string; + getLang(): string; + clear(): void; + poiOnAMAP(obj: any): void; + detailOnAMAP(obj: any): void; + } + + interface DistrictSearchOptions { + level: string; + showbiz?: boolean; + extensions?: string; + subdistrict?: number; + } + + interface DistrictSearchResult { + info: string; + districtList: District[]; + } + + interface District { + name: string; + center: LngLat; + citycode: string; + adcode: string; + level: string; + boundaries: LngLat[]; + districtList: District[]; + } + + class DistrictSearch { + constructor(opts: DistrictSearchOptions); + + search(keywords: string, callback?: (status: string, result: string| DistrictSearchResult) => void, opts?: DistrictSearchOptions): void; + setLevel(level: string): void; + setSubdistrict(district: number): void; + } + } diff --git a/types/universal-router/tsconfig.json b/types/amap-js-sdk/tsconfig.json similarity index 78% rename from types/universal-router/tsconfig.json rename to types/amap-js-sdk/tsconfig.json index 8ad0ee94ef..ba4581a859 100644 --- a/types/universal-router/tsconfig.json +++ b/types/amap-js-sdk/tsconfig.json @@ -1,14 +1,13 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,7 +19,6 @@ }, "files": [ "index.d.ts", - "generateUrls.d.ts", - "universal-router-tests.ts" + "amap-js-sdk-tests.ts" ] } diff --git a/types/amap-js-sdk/tslint.json b/types/amap-js-sdk/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/amap-js-sdk/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/amplitude-js/amplitude-js-tests.ts b/types/amplitude-js/amplitude-js-tests.ts index c5ffbe9898..0b6bb49751 100644 --- a/types/amplitude-js/amplitude-js-tests.ts +++ b/types/amplitude-js/amplitude-js-tests.ts @@ -1,5 +1,7 @@ // Tests for Amplitude SDK TypeScript definitions +import amplitude = require('amplitude-js'); + module Amplitude.Tests { function all() { diff --git a/types/amplitude-js/index.d.ts b/types/amplitude-js/index.d.ts index 1cdb843589..10465f6647 100644 --- a/types/amplitude-js/index.d.ts +++ b/types/amplitude-js/index.d.ts @@ -4,143 +4,142 @@ // Dan Manastireanu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module amplitude { +export as namespace amplitude; - type Callback = (responseCode: number, responseBody: string, details?: { reason: string; }) => void; - type LogReturn = number | void; +type Callback = (responseCode: number, responseBody: string, details?: { reason: string; }) => void; +type LogReturn = number | void; - interface Config { - apiEndpoint?: string; - batchEvents?: boolean; - cookieExpiration?: number; - cookieName?: string; - userId?: string; - deviceId?: string; - deviceIdFromUrlParam?: boolean; - domain?: string; - eventUploadPeriodMillis?: number; - eventUploadThreshold?: number; - forceHttps?: boolean; - includeGclid?: boolean; - includeReferrer?: boolean; - includeUtm?: boolean; - language?: string; - logLevel?: 'DISABLE' | 'ERROR' | 'WARN' | 'INFO'; - optOut?: boolean; - platform?: string; - saveEvents?: boolean; - savedMaxCount?: number; - saveParamsReferrerOncePerSession?: boolean; - sessionTimeout?: number; - trackingOptions?: { - city?: boolean; - country?: boolean; - device_model?: boolean; - dma?: boolean; - ip_address?: boolean; - language?: boolean; - os_name?: boolean; - os_version?: boolean; - platform?: boolean; - region?: boolean; - version_name?: boolean; - }, - unsentKey?: string; - unsentIdentifyKey?: string; - uploadBatchSize?: number; - } - - export class Identify { - set(key: string, value: any): Identify; - setOnce(key: string, value: any): Identify; - add(key: string, value: number | string): Identify; - append(key: string, value: any): Identify; - prepend(key: string, value: any): Identify; - - unset(key: string): Identify; - } - - export class Revenue { - - setProductId(productId: string): Revenue; - setQuantity(quantity: number): Revenue; - setPrice(price: number): Revenue; - setRevenueType(revenueType: string): Revenue; - setEventProperties(eventProperties: any): Revenue; - } - - export class AmplitudeClient { - - constructor(instanceName?: string); - - options: Config; - - init(apiKey: string, userId?: string, config?: Config, callback?: (client: AmplitudeClient) => void): void; - - setVersionName(versionName: string): void; - - isNewSession(): boolean; - setSessionId(sessionId: number): void; - getSessionId(): number; - - setDomain(domain: string): void; - setUserId(userId: string): void; - - setDeviceId(id: string): void; - regenerateDeviceId(): void; - - identify(identify_obj: Identify, opt_callback?: Callback): void; - - setUserProperties(properties: any): void; - setGlobalUserProperties(properties: any): void; - clearUserProperties(): void; - - setOptOut(enable: boolean): void; - - setGroup(groupType: string, groupName: string | string[]): void; - - logEvent(event: string, data?: any, callback?: Callback): LogReturn; - logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn; - logRevenueV2(revenue_obj: Revenue): LogReturn; - logRevenue(pric: number, quantity: number, product: string): LogReturn; - logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn; - } - - // Proxy methods that get executed on the default AmplitudeClient instance (not all client methods are proxied) - - export function init(apiKey: string, userId?: string, options?: Config, callback?: (client: AmplitudeClient) => void): void; - - export function setVersionName(version: string): void; - - export function isNewSession(): boolean; - export function getSessionId(): number; - - export function setDomain(domain: string): void; - - export function setUserId(userId: string): void; - - export function setDeviceId(id: string): void; - export function regenerateDeviceId(): void; - - export function identify(identify: Identify, callback?: Callback): void; - - export function setUserProperties(properties: any): void; - export function setGlobalUserProperties(properties: any): void; - export function clearUserProperties(): void; - - export function setOptOut(optOut: boolean): void; - - export function setGroup(groupType: string, groupName: string | string[]): void; - - export function logEvent(event: string, data?: any, callback?: Callback): LogReturn; - export function logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn; - export function logRevenueV2(revenue_obj: Revenue): LogReturn; - export function logRevenue(pric: number, quantity: number, product: string): LogReturn; - export function logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn; - - - - export function getInstance(instanceName?: string): AmplitudeClient; - export const __VERSION__: string; - export var options: Config; +interface Config { + apiEndpoint?: string; + batchEvents?: boolean; + cookieExpiration?: number; + cookieName?: string; + userId?: string; + deviceId?: string; + deviceIdFromUrlParam?: boolean; + domain?: string; + eventUploadPeriodMillis?: number; + eventUploadThreshold?: number; + forceHttps?: boolean; + includeGclid?: boolean; + includeReferrer?: boolean; + includeUtm?: boolean; + language?: string; + logLevel?: 'DISABLE' | 'ERROR' | 'WARN' | 'INFO'; + optOut?: boolean; + platform?: string; + saveEvents?: boolean; + savedMaxCount?: number; + saveParamsReferrerOncePerSession?: boolean; + sessionTimeout?: number; + trackingOptions?: { + city?: boolean; + country?: boolean; + device_model?: boolean; + dma?: boolean; + ip_address?: boolean; + language?: boolean; + os_name?: boolean; + os_version?: boolean; + platform?: boolean; + region?: boolean; + version_name?: boolean; + }, + unsentKey?: string; + unsentIdentifyKey?: string; + uploadBatchSize?: number; } + +export class Identify { + set(key: string, value: any): Identify; + setOnce(key: string, value: any): Identify; + add(key: string, value: number | string): Identify; + append(key: string, value: any): Identify; + prepend(key: string, value: any): Identify; + + unset(key: string): Identify; +} + +export class Revenue { + + setProductId(productId: string): Revenue; + setQuantity(quantity: number): Revenue; + setPrice(price: number): Revenue; + setRevenueType(revenueType: string): Revenue; + setEventProperties(eventProperties: any): Revenue; +} + +export class AmplitudeClient { + + constructor(instanceName?: string); + + options: Config; + + init(apiKey: string, userId?: string, config?: Config, callback?: (client: AmplitudeClient) => void): void; + + setVersionName(versionName: string): void; + + isNewSession(): boolean; + setSessionId(sessionId: number): void; + getSessionId(): number; + + setDomain(domain: string): void; + setUserId(userId: string): void; + + setDeviceId(id: string): void; + regenerateDeviceId(): void; + + identify(identify_obj: Identify, opt_callback?: Callback): void; + + setUserProperties(properties: any): void; + setGlobalUserProperties(properties: any): void; + clearUserProperties(): void; + + setOptOut(enable: boolean): void; + + setGroup(groupType: string, groupName: string | string[]): void; + + logEvent(event: string, data?: any, callback?: Callback): LogReturn; + logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn; + logRevenueV2(revenue_obj: Revenue): LogReturn; + logRevenue(pric: number, quantity: number, product: string): LogReturn; + logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn; +} + +// Proxy methods that get executed on the default AmplitudeClient instance (not all client methods are proxied) + +export function init(apiKey: string, userId?: string, options?: Config, callback?: (client: AmplitudeClient) => void): void; + +export function setVersionName(version: string): void; + +export function isNewSession(): boolean; +export function getSessionId(): number; + +export function setDomain(domain: string): void; + +export function setUserId(userId: string): void; + +export function setDeviceId(id: string): void; +export function regenerateDeviceId(): void; + +export function identify(identify: Identify, callback?: Callback): void; + +export function setUserProperties(properties: any): void; +export function setGlobalUserProperties(properties: any): void; +export function clearUserProperties(): void; + +export function setOptOut(optOut: boolean): void; + +export function setGroup(groupType: string, groupName: string | string[]): void; + +export function logEvent(event: string, data?: any, callback?: Callback): LogReturn; +export function logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn; +export function logRevenueV2(revenue_obj: Revenue): LogReturn; +export function logRevenue(pric: number, quantity: number, product: string): LogReturn; +export function logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn; + + + +export function getInstance(instanceName?: string): AmplitudeClient; +export const __VERSION__: string; +export var options: Config; diff --git a/types/analytics-node/analytics-node-tests.ts b/types/analytics-node/analytics-node-tests.ts index 6740aaccff..a7dc5336ec 100644 --- a/types/analytics-node/analytics-node-tests.ts +++ b/types/analytics-node/analytics-node-tests.ts @@ -1,10 +1,10 @@ import Analytics = require("analytics-node"); -var analytics: Analytics; +let analytics: Analytics; function testConfig(): void { analytics = new Analytics('YOUR_WRITE_KEY', { flushAt: 20, - flushAfter: 10000, + flushInterval: 10000, host: "http://example.com", enable: true }); @@ -33,7 +33,7 @@ function testIdentify(): void { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } @@ -59,7 +59,7 @@ function testTrack(): void { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } @@ -91,20 +91,20 @@ function testPage(): void { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } function testAlias(): void { // the anonymous user does actions ... - analytics.track({ userId: 'anonymous_user', event: 'Anonymous Event' }) + analytics.track({ userId: 'anonymous_user', event: 'Anonymous Event' }); // the anonymous user signs up and is aliased - analytics.alias({ previousId: 'anonymous_user', userId: 'identified@gmail.com' }) + analytics.alias({ previousId: 'anonymous_user', userId: 'identified@gmail.com' }); // the identified user is identified - analytics.identify({ userId: 'identified@gmail.com', traits: { plan: 'Free' } }) + analytics.identify({ userId: 'identified@gmail.com', traits: { plan: 'Free' } }); // the identified user does actions ... - analytics.track({ userId: 'identified@gmail.com', event: 'Identified Action' }) + analytics.track({ userId: 'identified@gmail.com', event: 'Identified Action' }); } function testGroup(): void { @@ -128,35 +128,41 @@ function testGroup(): void { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } function testIntegrations(): void { analytics.track({ - event: 'Upgraded Membershipt', + event: 'Upgraded Membership', userId: '97234974', integrations: { - 'All': false, - 'Vero': true, - 'Google Analytics': false + All: false, + Vero: true, + 'Google Analytics': false, + AppsFlyer: { + appsflyer_id: 'example-id' + } } }); analytics.track({ - event: 'Upgraded Membershipt', + event: 'Upgraded Membership', userId: '97234974', integrations: { - 'All': false, - 'Vero': true, - 'Google Analytics': false + All: false, + Vero: true, + 'Google Analytics': false, + AppsFlyer: { + appsflyer_id: 'example-id' + } } }, (err, data) => { if (err) { console.error(err); } else { - data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)); } }); } @@ -164,8 +170,10 @@ function testIntegrations(): void { function testFlush(): void { analytics.flush(); analytics.flush((err, batch) => { - if (err) { alert("Oh nos!"); } - else { console.log(batch.batch[0].type); } + if (err) { + alert("Oh nos!"); + } else { + console.log(batch.batch[0].type); + } }); } - diff --git a/types/analytics-node/index.d.ts b/types/analytics-node/index.d.ts index cc9e5386e2..168e0f17ea 100644 --- a/types/analytics-node/index.d.ts +++ b/types/analytics-node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Segment's analytics.js for Node.js +// Type definitions for analytics-node 3.1 // Project: https://segment.com/docs/libraries/node/ // Definitions by: Andrew Fong // Thomas Thiebaud @@ -19,7 +19,7 @@ declare namespace AnalyticsNode { _metadata: { nodeVersion: string; [key: string]: any; - }, + }; timestamp?: Date; messageId?: string; anonymousId?: string | number; @@ -27,19 +27,21 @@ declare namespace AnalyticsNode { } interface Data { - batch: Message[], + batch: Message[]; timestamp: Date; sentAt: Date; } interface Integrations { - [index: string]: boolean; + [integration_name: string]: IntegrationValue; } - export class Analytics { + type IntegrationValue = boolean | { [integration_key: string]: any }; + + class Analytics { constructor(writeKey: string, opts?: { flushAt?: number, - flushAfter?: number, + flushInterval?: number, host?: string, enable?: boolean }); @@ -49,9 +51,9 @@ declare namespace AnalyticsNode { identify(message: { userId?: string | number; anonymousId?: string | number; - traits?: Object; + traits?: any; timestamp?: Date; - context?: Object; + context?: any; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; @@ -60,9 +62,9 @@ declare namespace AnalyticsNode { userId?: string | number; anonymousId?: string | number; event: string; - properties?: Object; + properties?: any; timestamp?: Date; - context?: Object; + context?: any; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; @@ -73,9 +75,9 @@ declare namespace AnalyticsNode { anonymousId?: string | number; category?: string; name?: string; - properties?: Object; + properties?: any; timestamp?: Date; - context?: Object; + context?: any; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; @@ -93,8 +95,8 @@ declare namespace AnalyticsNode { userId?: string | number; anonymousId?: string | number; groupId: string | number; - traits?: Object; - context?: Object; + traits?: any; + context?: any; timestamp?: Date; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; diff --git a/types/analytics-node/tslint.json b/types/analytics-node/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/analytics-node/tslint.json +++ b/types/analytics-node/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 9202829175..19c6dcc9e5 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -344,6 +344,7 @@ declare module 'angular' { } interface IMenuService { + close(): void; hide(response?: any, options?: any): IPromise; open(event?: MouseEvent): void; } diff --git a/types/angular-resource/angular-resource-tests.ts b/types/angular-resource/angular-resource-tests.ts index c35f27a98d..f7b8db579c 100644 --- a/types/angular-resource/angular-resource-tests.ts +++ b/types/angular-resource/angular-resource-tests.ts @@ -90,6 +90,7 @@ angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactorySe responseError() {} }; actionDescriptor.cancellable = true; + actionDescriptor.hasBody = true; }); /////////////////////////////////////// diff --git a/types/angular-resource/index.d.ts b/types/angular-resource/index.d.ts index 1ebd198b82..c298001533 100644 --- a/types/angular-resource/index.d.ts +++ b/types/angular-resource/index.d.ts @@ -88,6 +88,7 @@ declare module 'angular' { withCredentials?: boolean; responseType?: string; interceptor?: IResourceInterceptor; + hasBody?: boolean; } // Allow specify more resource methods diff --git a/types/array-move/array-move-tests.ts b/types/array-move/array-move-tests.ts new file mode 100644 index 0000000000..0bf720b751 --- /dev/null +++ b/types/array-move/array-move-tests.ts @@ -0,0 +1,8 @@ +import arrayMove = require('array-move'); + +const input = ['a', 'b', 'c']; +const input2 = [1, 2, 3]; + +arrayMove(input, 1, 2); // $ExpectType string[] +arrayMove(input2, 1, 2); // $ExpectType number[] +arrayMove.mut(input, 1, 2); // $ExpectType void diff --git a/types/array-move/index.d.ts b/types/array-move/index.d.ts new file mode 100644 index 0000000000..9b9aae938a --- /dev/null +++ b/types/array-move/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for array-move 1.0 +// Project: https://github.com/sindresorhus/array-move +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = arrayMove; + +/** + * Move an array item to a different position. + * + * @param from Index of item to move. If negative, it will begin that many elements from the end. + * @param to Index of where to move the item. If negative, it will begin that many elements from the end. + * @returns A new array with the item moved to the new position. + */ +declare function arrayMove(input: T, from: number, to: number): T; + +declare namespace arrayMove { + /** + * Moves the item to the new position in the input array. + * + * Useful for huge arrays where absolute performance is needed. + * + * @param from Index of item to move. If negative, it will begin that many elements from the end. + * @param to Index of where to move the item. If negative, it will begin that many elements from the end. + */ + function mut(input: any[], from: number, to: number): void; +} diff --git a/types/array-move/tsconfig.json b/types/array-move/tsconfig.json new file mode 100644 index 0000000000..6b4a5d5bb0 --- /dev/null +++ b/types/array-move/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", + "array-move-tests.ts" + ] +} diff --git a/types/array-move/tslint.json b/types/array-move/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/array-move/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/asn1/asn1-tests.ts b/types/asn1/asn1-tests.ts new file mode 100644 index 0000000000..f37541b03e --- /dev/null +++ b/types/asn1/asn1-tests.ts @@ -0,0 +1,88 @@ +import { Ber, BerReader, BerWriter } from 'asn1'; + +let buf: Buffer = Buffer.alloc(0); +let bool = false; +let str = ''; +let num = 0; +let numOrNull: number | null = 0; +const roStrArray: ReadonlyArray = [str]; + +const reader = new BerReader(buf); +numOrNull = reader.peek(); +bool = reader.readBoolean(); +numOrNull = reader.readByte(bool); +num = reader.readEnumeration(); +num = reader.readInt(); +num = reader.readLength(); +num = reader.readLength(num); +str = reader.readOID(); +str = reader.readOID(num); +numOrNull = reader.readSequence(); +numOrNull = reader.readSequence(num); +str = reader.readString(); +str = reader.readString(num); +buf = reader.readString(num, bool); +num = reader._readTag(); +num = reader._readTag(num); + +let writer = new BerWriter(); +writer = new BerWriter({ + size: num, + growthFactor: num, +}); + +buf = writer.buffer; +buf = writer._buf; +num = writer._size; +num = writer._offset; + +writer.endSequence(); +writer.startSequence(); +writer.startSequence(num); +writer.writeBoolean(bool); +writer.writeBoolean(bool, num); +writer.writeBuffer(buf, num); +writer.writeByte(num); +writer.writeEnumeration(num); +writer.writeEnumeration(num, num); +writer.writeInt(num); +writer.writeInt(num, num); +writer.writeLength(num); +writer.writeNull(); +writer.writeOID(str, num); +writer.writeString(str); +writer.writeString(str, num); +writer.writeStringArray(roStrArray); +writer._ensure(num); + +num = Ber.BMPString; +num = Ber.BitString; +num = Ber.Boolean; +num = Ber.CharacterString; +num = Ber.Constructor; +num = Ber.Context; +num = Ber.EOC; +num = Ber.Enumeration; +num = Ber.External; +num = Ber.GeneralString; +num = Ber.GeneralizedTime; +num = Ber.GraphicString; +num = Ber.IA5String; +num = Ber.Integer; +num = Ber.Null; +num = Ber.NumericString; +num = Ber.OID; +num = Ber.ObjectDescriptor; +num = Ber.OctetString; +num = Ber.PDV; +num = Ber.PrintableString; +num = Ber.Real; +num = Ber.RelativeOID; +num = Ber.Sequence; +num = Ber.Set; +num = Ber.T61String; +num = Ber.UTCTime; +num = Ber.UniversalString; +num = Ber.Utf8String; +num = Ber.VideotexString; +num = Ber.VisibleString; diff --git a/types/asn1/index.d.ts b/types/asn1/index.d.ts new file mode 100644 index 0000000000..3f7de44af8 --- /dev/null +++ b/types/asn1/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for asn1 0.2 +// Project: https://github.com/joyent/node-asn1 +// Definitions by: Jim Geurts +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +/// + +export class BerReader { + readonly buffer: Buffer; + readonly offset: number; + readonly length: number; + readonly remain: number; + readonly _buf: Buffer; + _size: number; + _offset: number; + + constructor(data: Buffer); + + peek(): number | null; + readBoolean(): boolean; + readByte(peek: boolean): number | null; + readEnumeration(): number; + readInt(): number; + readLength(offset?: number): number; + readOID(tag?: number): string; + readSequence(tag?: number): number | null; + readString(tag?: number): string; + readString(tag: number, retbuf: boolean): Buffer; + _readTag(tag?: number): number; +} + +export class BerWriter { + readonly buffer: Buffer; + readonly _buf: Buffer; + readonly _size: number; + _offset: number; + + constructor(options?: { + size: number; + growthFactor: number; + }); + + endSequence(): void; + startSequence(tag?: number): void; + writeBoolean(b: boolean, tag?: number): void; + writeBuffer(buf: Buffer, tag: number): void; + writeByte(b: number): void; + writeEnumeration(i: number, tag?: number): void; + writeInt(i: number, tag?: number): void; + writeLength(len: number): void; + writeNull(): void; + writeOID(s: string, tag: number): void; + writeString(s: string, tag?: number): void; + writeStringArray(strings: ReadonlyArray): void; + _ensure(length: number): void; +} + +export namespace Ber { + const BMPString: number; + const BitString: number; + const Boolean: number; + const CharacterString: number; + const Constructor: number; + const Context: number; + const EOC: number; + const Enumeration: number; + const External: number; + const GeneralString: number; + const GeneralizedTime: number; + const GraphicString: number; + const IA5String: number; + const Integer: number; + const Null: number; + const NumericString: number; + const OID: number; + const ObjectDescriptor: number; + const OctetString: number; + const PDV: number; + const PrintableString: number; + const Real: number; + const RelativeOID: number; + const Sequence: number; + const Set: number; + const T61String: number; + const UTCTime: number; + const UniversalString: number; + const Utf8String: number; + const VideotexString: number; + const VisibleString: number; +} +/* +declare enum BerType { + EOC = 0, + Boolean = 1, + Integer = 2, + BitString = 3, + OctetString = 4, + Null = 5, + OID = 6, + ObjectDescriptor = 7, + External = 8, + Real = 9, // float + Enumeration = 10, + PDV = 11, + Utf8String = 12, + RelativeOID = 13, + Sequence = 16, + Set = 17, + NumericString = 18, + PrintableString = 19, + T61String = 20, + VideotexString = 21, + IA5String = 22, + UTCTime = 23, + GeneralizedTime = 24, + GraphicString = 25, + VisibleString = 26, + GeneralString = 28, + UniversalString = 29, + CharacterString = 30, + BMPString = 31, + Constructor = 32, + Context = 128, +} + +*/ diff --git a/types/asn1/tsconfig.json b/types/asn1/tsconfig.json new file mode 100644 index 0000000000..fd1bdc45d9 --- /dev/null +++ b/types/asn1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noUnusedParameters": true, + + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "asn1-tests.ts" + ] +} \ No newline at end of file diff --git a/types/asn1/tslint.json b/types/asn1/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/asn1/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/async/index.d.ts b/types/async/index.d.ts index e6cfd3bcaa..05d99e5968 100644 --- a/types/async/index.d.ts +++ b/types/async/index.d.ts @@ -1,13 +1,18 @@ -// Type definitions for Async 2.0.1 +// Type definitions for Async 2.4 // Project: https://github.com/caolan/async -// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman , Angus Fenying , Pascal Martin +// Definitions by: Boris Yankov +// Arseniy Maximov +// Joe Herman +// Angus Fenying +// Pascal Martin +// Dmitri Trofimov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 export as namespace async; export interface Dictionary { [key: string]: T; } -export type IterableCollection = T[] | IterableIterator | Dictionary +export type IterableCollection = T[] | IterableIterator | Dictionary; export interface ErrorCallback { (err?: E | null): void; } export interface AsyncBooleanResultCallback { (err?: E | null, truthValue?: boolean): void; } @@ -26,30 +31,40 @@ export interface AsyncBooleanIterator { (item: T, callback: AsyncB export interface AsyncWorker { (task: T, callback: ErrorCallback): void; } export interface AsyncVoidFunction { (callback: ErrorCallback): void; } -export type AsyncAutoTasks, E> = { [K in keyof R]: AsyncAutoTask } -export type AsyncAutoTask, E> = AsyncAutoTaskFunctionWithoutDependencies | (keyof R | AsyncAutoTaskFunction)[]; +export type AsyncAutoTasks, E> = { [K in keyof R]: AsyncAutoTask }; +export type AsyncAutoTask, E> = AsyncAutoTaskFunctionWithoutDependencies | Array>; export interface AsyncAutoTaskFunctionWithoutDependencies { (cb: AsyncResultCallback | ErrorCallback): void; } export interface AsyncAutoTaskFunction, E = Error> { (results: R, cb: AsyncResultCallback | ErrorCallback): void; } +export interface DataContainer { + data: T; +} + +export interface CallbackContainer { + callback: Function; +} + +export interface PriorityContainer { + priority: number; +} + export interface AsyncQueue { length(): number; started: boolean; running(): number; idle(): boolean; concurrency: number; - push(task: T | T[], callback?: AsyncResultCallback): void; + push(task: T | T[], callback?: AsyncResultCallback): void; unshift(task: T | T[], callback?: ErrorCallback): void; + remove(filter: (node: DataContainer) => boolean): void; saturated: () => any; empty: () => any; drain: () => any; paused: boolean; - pause(): void + pause(): void; resume(): void; kill(): void; - workersList(): { - data: T, - callback: Function - }[]; + workersList, CallbackContainer>(): TWorker[]; error(error: Error, data: any): void; unsaturated(): void; buffer: number; @@ -60,7 +75,7 @@ export interface AsyncPriorityQueue { concurrency: number; started: boolean; paused: boolean; - push(task: T | T[], priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T | T[], priority: number, callback?: AsyncResultArrayCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -69,11 +84,7 @@ export interface AsyncPriorityQueue { pause(): void; resume(): void; kill(): void; - workersList(): { - data: T, - priority: number, - callback: Function - }[]; + workersList, CallbackContainer, PriorityContainer>(): TWorker[]; error(error: Error, data: any): void; unsaturated(): void; buffer: number; @@ -82,7 +93,7 @@ export interface AsyncPriorityQueue { export interface AsyncCargo { length(): number; payload?: number; - push(task: any, callback? : Function): void; + push(task: any, callback?: Function): void; saturated(): void; empty(): void; drain(): void; @@ -105,11 +116,17 @@ export function forEachOfLimit(obj: IterableCollection, limit: export const eachOf: typeof forEachOf; export const eachOfSeries: typeof forEachOf; export const eachOfLimit: typeof forEachOfLimit; -export function map(arr: T[] | IterableIterator, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; -export function map(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; +export function map(arr: T[] | IterableIterator | Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; export const mapSeries: typeof map; export function mapLimit(arr: IterableCollection, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; -export function mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; + +export function mapValuesLimit( + obj: Dictionary, + limit: number, + iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, + callback: AsyncResultObjectCallback + ): void; + export function mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; export const mapValuesSeries: typeof mapValues; export function filter(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; @@ -151,7 +168,7 @@ export function concatLimit(arr: IterableCollection, limit: export const concatSeries: typeof concat; // Control Flow -export function series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; +export function series(tasks: Array>, callback?: AsyncResultArrayCallback): void; export function series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; export function parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; export function parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; @@ -161,9 +178,9 @@ export function whilst(test: () => boolean, fn: AsyncVoidFunction, export function doWhilst(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; export function until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; export function doUntil(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; -export function during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; +export function during(test: (testCallback: AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; export function doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; -export function forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; +export function forever(next: (next: ErrorCallback) => void, errBack: ErrorCallback): void; export function waterfall(tasks: Function[], callback?: AsyncResultCallback): void; export function compose(...fns: Function[]): Function; export function seq(...fns: Function[]): Function; @@ -172,34 +189,52 @@ export function applyEachSeries(fns: Function[], ...argsAndCallback: any[]): voi export function queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; export function queue(worker: AsyncResultIterator, concurrency?: number): AsyncQueue; export function priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; -export function cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; +export function cargo(worker: (tasks: any[], callback: ErrorCallback) => void, payload?: number): AsyncCargo; export function auto, E = Error>(tasks: AsyncAutoTasks, concurrency?: number, callback?: AsyncResultCallback): void; export function auto, E = Error>(tasks: AsyncAutoTasks, callback?: AsyncResultCallback): void; export function autoInject(tasks: any, callback?: AsyncResultCallback): void; -export function retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: AsyncResultCallback): void; -export function retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: AsyncResultCallback): void; + +export function retry( + opts: number | { + times: number, + interval: number | ((retryCount: number) => number) + }, + task: (callback: AsyncResultCallback, results: any) => void, + callback: AsyncResultCallback + ): void; + export function retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; -export function apply(fn: Function, ...args: any[]): AsyncFunction; +export function apply(fn: Function, ...args: any[]): AsyncFunction; export function nextTick(callback: Function, ...args: any[]): void; export const setImmediate: typeof nextTick; -export function reflect(fn: AsyncFunction) : (callback: (err: null, result: {error?: E, value?: T}) => void) => void; -export function reflectAll(tasks: AsyncFunction[]): ((callback: (err: null, result: {error?: E, value?: T}) => void) => void)[]; +export function reflect(fn: AsyncFunction): (callback: (err: null, result: {error?: E, value?: T}) => void) => void; +export function reflectAll(tasks: Array>): Array<(callback: (err: null, result: {error?: E, value?: T}) => void) => void>; export function timeout(fn: AsyncFunction, milliseconds: number, info?: any): AsyncFunction; export function timeout(fn: AsyncResultIterator, milliseconds: number, info?: any): AsyncResultIterator; -export function times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; +export function times(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; export function timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; export function timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; export function transform(arr: T[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback): void; export function transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback): void; -export function transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback): void; -export function transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback): void; +export function transform( + arr: {[key: string]: T}, + iteratee: (acc: {[key: string]: R}, item: T, key: string, callback: (error?: E) => void) => void, + callback?: AsyncResultObjectCallback + ): void; -export function race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; +export function transform( + arr: {[key: string]: T}, + acc: {[key: string]: R}, + iteratee: (acc: {[key: string]: R}, item: T, key: string, callback: (error?: E) => void) => void, + callback?: AsyncResultObjectCallback + ): void; + +export function race(tasks: Array>, callback: AsyncResultCallback): void; // Utils export function memoize(fn: Function, hasher?: Function): Function; diff --git a/types/async/test/es6-generators.ts b/types/async/test/es6-generators.ts index b67e7daad7..e0008d7d5e 100644 --- a/types/async/test/es6-generators.ts +++ b/types/async/test/es6-generators.ts @@ -10,45 +10,45 @@ function eachOfIterator(item: T, key: K, callback: (err: Error) => void function concatIterator(item: T, callback: (err: E, res: R[]) => void) { } -async.map(collectionGenerator(), funcMapIterator, funcMapComplete) -async.mapSeries(collectionGenerator(), funcMapIterator, funcMapComplete) -async.mapLimit(collectionGenerator(), 2, funcMapIterator, funcMapComplete) +async.map(collectionGenerator(), funcMapIterator, funcMapComplete); +async.mapSeries(collectionGenerator(), funcMapIterator, funcMapComplete); +async.mapLimit(collectionGenerator(), 2, funcMapIterator, funcMapComplete); -async.filter(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.filterSeries(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.filterLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, results: any[]) { }) -async.select(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.selectSeries(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.selectLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, results: any[]) { }) +async.filter(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.filterSeries(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.filterLimit(collectionGenerator(), 2, booleanIterator, (err: Error, results: any[]) => { }); +async.select(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.selectSeries(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.selectLimit(collectionGenerator(), 2, booleanIterator, (err: Error, results: any[]) => { }); -async.reject(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.rejectSeries(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { }) -async.rejectLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, results: any[]) { }) +async.reject(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.rejectSeries(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { }); +async.rejectLimit(collectionGenerator(), 2, booleanIterator, (err: Error, results: any[]) => { }); -async.each(collectionGenerator(), eachIterator, function (err: Error) { }) -async.eachLimit(collectionGenerator(), 2, eachIterator, function (err: Error) { }) -async.eachSeries(collectionGenerator(), eachIterator, function (err: Error) { }) -async.eachOf(collectionGenerator(), eachOfIterator, function (err: Error) { }) -async.eachOfLimit(collectionGenerator(), 2, eachOfIterator, function (err: Error) { }) -async.eachOfSeries(collectionGenerator(), eachOfIterator, function (err: Error) { }) -async.forEach(collectionGenerator(), eachIterator, function (err: Error) { }) -async.forEachLimit(collectionGenerator(), 2, eachIterator, function (err: Error) { }) -async.forEachSeries(collectionGenerator(), eachIterator, function (err: Error) { }) -async.forEachOf(collectionGenerator(), eachOfIterator, function (err: Error) { }) -async.forEachOfLimit(collectionGenerator(), 2, eachOfIterator, function (err: Error) { }) -async.forEachOfSeries(collectionGenerator(), eachOfIterator, function (err: Error) { }) +async.each(collectionGenerator(), eachIterator, (err: Error) => { }); +async.eachLimit(collectionGenerator(), 2, eachIterator, (err: Error) => { }); +async.eachSeries(collectionGenerator(), eachIterator, (err: Error) => { }); +async.eachOf(collectionGenerator(), eachOfIterator, (err: Error) => { }); +async.eachOfLimit(collectionGenerator(), 2, eachOfIterator, (err: Error) => { }); +async.eachOfSeries(collectionGenerator(), eachOfIterator, (err: Error) => { }); +async.forEach(collectionGenerator(), eachIterator, (err: Error) => { }); +async.forEachLimit(collectionGenerator(), 2, eachIterator, (err: Error) => { }); +async.forEachSeries(collectionGenerator(), eachIterator, (err: Error) => { }); +async.forEachOf(collectionGenerator(), eachOfIterator, (err: Error) => { }); +async.forEachOfLimit(collectionGenerator(), 2, eachOfIterator, (err: Error) => { }); +async.forEachOfSeries(collectionGenerator(), eachOfIterator, (err: Error) => { }); -async.every(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) -async.everyLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, res: boolean) { }) -async.everySeries(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) +async.every(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); +async.everyLimit(collectionGenerator(), 2, booleanIterator, (err: Error, res: boolean) => { }); +async.everySeries(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); -async.some(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) -async.someLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, res: boolean) { }) -async.someSeries(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) +async.some(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); +async.someLimit(collectionGenerator(), 2, booleanIterator, (err: Error, res: boolean) => { }); +async.someSeries(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); -async.detect(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) -async.detectLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, res: boolean) { }) -async.detectSeries(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { }) +async.detect(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); +async.detectLimit(collectionGenerator(), 2, booleanIterator, (err: Error, res: boolean) => { }); +async.detectSeries(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { }); -async.concat(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { }) -async.concatSeries(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { }) +async.concat(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { }); +async.concatSeries(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { }); diff --git a/types/async/test/explicit.ts b/types/async/test/explicit.ts index 0c0e1a44ee..ae97888531 100644 --- a/types/async/test/explicit.ts +++ b/types/async/test/explicit.ts @@ -1,74 +1,58 @@ - - interface StringCallback { (err?: Error, result?: string): void; } interface AsyncStringGetter { (callback: StringCallback): void; } -var taskArray: AsyncStringGetter[] = [ - function (callback) { - setTimeout(function () { - callback(undefined, 'one'); - }, 200); - }, - function (callback) { - setTimeout(function () { - callback(undefined, 'two'); - }, 100); - }, +const taskArray: AsyncStringGetter[] = [ + callback => { setTimeout(() => { callback(undefined, 'one'); }, 200); }, + callback => { setTimeout(() => { callback(undefined, 'two'); }, 100); } ]; -async.series(taskArray, function (err, results) { +async.series(taskArray, (err, results) => { if (results) { - let first = results[0]; + const first = results[0]; if (first) { - console.log(first.match(/o/)) - } - } -}); -async.parallel(taskArray, function (err, results) { - if (results) { - let first = results[0]; - if (first) { - console.log(first.match(/o/)) - } - } -}); -async.parallelLimit(taskArray, 3, function (err, results) { - if (results) { - let first = results[0]; - if (first) { - console.log(first.match(/o/)) + console.log(first.match(/o/)); } } }); +async.parallel(taskArray, (err, results) => { + if (results) { + const first = results[0]; + if (first) { + console.log(first.match(/o/)); + } + } +}); + +async.parallelLimit(taskArray, 3, (err, results) => { + if (results) { + const first = results[0]; + if (first) { + console.log(first.match(/o/)); + } + } +}); interface Lookup { [key: string]: T; } interface NumberCallback { (err?: Error, result?: number): void; } interface AsyncNumberGetter { (callback: NumberCallback): void; } -var taskDict: Lookup = { - one: function(callback) { - setTimeout(function() { - callback(undefined, 1); - }, 200); - }, - two: function(callback) { - setTimeout(function() { - callback(undefined, 2); - }, 100); - } -} +const taskDict: Lookup = { + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } +}; -async.series(taskDict, function(err, results) { - let one = results['one']; - console.log(one && one.toFixed(1)) -}); -async.parallel(taskDict, function(err, results) { - let one = results['one']; - console.log(one && one.toFixed(1)) -}); -async.parallelLimit(taskDict, 3, function(err, results) { - let one = results['one']; - console.log(one && one.toFixed(1)) +async.series(taskDict, (err, results) => { + const one = results['one']; + console.log(one && one.toFixed(1)); }); +async.parallel(taskDict, (err, results) => { + const one = results['one']; + console.log(one && one.toFixed(1)); +}); + +async.parallelLimit(taskDict, 3, (err, results) => { + const one = results['one']; + console.log(one && one.toFixed(1)); +}); diff --git a/types/async/test/index.ts b/types/async/test/index.ts index 574a5ed8b9..97e888870b 100644 --- a/types/async/test/index.ts +++ b/types/async/test/index.ts @@ -9,406 +9,272 @@ declare var path: { exists: (path: string, callback?: (err: Error, exists: boolean) => any) => void; }; -function funcStringCbErrBoolean(v:string, cb:(err:Error,res:boolean) => void) {} +function funcStringCbErrBoolean(v: string, cb: (err: Error, res: boolean) => void) {} function callback() { } -async.map(['file1', 'file2', 'file3'], fs.stat, function (err:Error, results:Array) { }); -async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err:Error, results:Array) { }); -async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err:Error, results:Array) { }); +async.map(['file1', 'file2', 'file3'], fs.stat, (err: Error, results: fs.Stats[]) => { }); +async.mapSeries(['file1', 'file2', 'file3'], fs.stat, (err: Error, results: fs.Stats[]) => { }); +async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, (err: Error, results: fs.Stats[]) => { }); -async.filter(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.filterSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.filterLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.select(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.selectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.selectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.filter(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.filterSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.filterLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.select(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.selectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.selectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, results: string[]) => { }); -async.reject(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.rejectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.rejectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.reject(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.rejectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, results: string[]) => { }); +async.rejectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, results: string[]) => { }); async.parallel([ - function () { }, - function () { } + () => { }, + () => { } ], callback); async.series([ - function () { }, - function () { } + () => { }, + () => { } ]); -var data: any[] = []; +const data: any[] = []; function asyncProcess(item: any, callback: (err: Error, result: any) => void) { } -async.map(data, asyncProcess, function (err, results) { - console.log(results); -}); +async.map(data, asyncProcess, (err, results) => { console.log(results); }); -var openFiles = ['file1', 'file2']; -var openFilesObj = { +const openFiles = ['file1', 'file2']; +const openFilesObj = { file1: "fileOne", file2: "fileTwo" -} +}; -var saveFile = function (file:string,cb:(err:Error)=>void) { } -async.each(openFiles, saveFile, function (err:Error) { }); -async.eachSeries(openFiles, saveFile, function (err:Error) { }); +const saveFile = (file: string, cb: (err: Error) => void) => { }; +async.each(openFiles, saveFile, (err: Error) => { }); +async.eachSeries(openFiles, saveFile, (err: Error) => { }); -var documents: any, requestApi: any; -async.eachLimit(documents, 20, requestApi, function (err) { }); +const documents: any[] = []; +const requestApi: async.AsyncIterator = () => { }; +async.eachLimit(documents, 20, requestApi, err => { }); // forEachOf* functions. May accept array or object. function forEachOfIterator(item: string, key: string, forEachOfIteratorCallback: any) { - console.log("ForEach: item=" + item + ", key=" + key); + console.log(`ForEach: item=${item}, key=${key}`); forEachOfIteratorCallback(); } -async.forEachOf(openFiles, forEachOfIterator, function (err) { }); -async.forEachOf(openFilesObj, forEachOfIterator, function (err) { }); -async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { }); -async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { }); -async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { }); -async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { }); +async.forEachOf(openFiles, forEachOfIterator, err => { }); +async.forEachOf(openFilesObj, forEachOfIterator, err => { }); +async.forEachOfSeries(openFiles, forEachOfIterator, err => { }); +async.forEachOfSeries(openFilesObj, forEachOfIterator, err => { }); +async.forEachOfLimit(openFiles, 2, forEachOfIterator, err => { }); +async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, err => { }); -var numArray = [1, 2, 3]; +const numArray = [1, 2, 3]; function reducer(memo: any, item: any, callback: any) { - process.nextTick(function () { - callback(null, memo + item) - }); + process.nextTick(() => { callback(null, memo + item); }); } -async.reduce(numArray, 0, reducer, function (err, result) { }); -async.inject(numArray, 0, reducer, function (err, result) { }); -async.foldl(numArray, 0, reducer, function (err, result) { }); -async.reduceRight(numArray, 0, reducer, function (err, result) { }); -async.foldr(numArray, 0, reducer, function (err, result) { }); -async.detect(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err: Error,result:string) { }); -async.detectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err,result) { }); -async.detectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err,result) { }); +async.reduce(numArray, 0, reducer, (err, result) => { }); +async.inject(numArray, 0, reducer, (err, result) => { }); +async.foldl(numArray, 0, reducer, (err, result) => { }); +async.reduceRight(numArray, 0, reducer, (err, result) => { }); +async.foldr(numArray, 0, reducer, (err, result) => { }); -async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { - fs.stat(file, function (err, stats) { - callback(err, stats.mtime); - }); -}, function (err, results) { }); +async.detect(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: string) => { }); +async.detectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err, result) => { }); +async.detectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err, result) => { }); -async.some(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.someLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.any(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.sortBy(['file1', 'file2', 'file3'], (file, callback) => { + fs.stat(file, (err, stats) => { callback(err, stats.mtime); }); +}, (err, results) => { }); -async.every(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.everyLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.all(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.some(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.someLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.any(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: boolean) => { }); -async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); -async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); +async.every(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.everyLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.all(['file1', 'file2', 'file3'], funcStringCbErrBoolean, (err: Error, result: boolean) => { }); +async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, (err, files) => { }); +async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, (err, files) => { }); // Control Flow // -async.series([ - function (callback) { - callback(undefined, 'one'); - }, - function (callback) { - callback(undefined, 'two'); - }, -], -function (err, results) { }); - -async.series([ - function (callback) { - callback(undefined, 'one'); - }, - function (callback) { - callback(undefined, 'two'); - }, -], -function (err, results) { }); +async.series([callback => { callback(undefined, 'one'); }, callback => { callback(undefined, 'two'); }], (err, results) => { }); +async.series([callback => { callback(undefined, 'one'); }, callback => { callback(undefined, 'two'); }], (err, results) => { }); async.series({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, -function (err, results) { }); + (err, results) => { }); async.series({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, -function (err, results) { }); + (err, results) => { }); -async.times(5, function(n, next) { - next(undefined as any, n) -}, function(err, results) { - console.log(results) -}) +async.times(5, (n, next) => { next(undefined as any, n); }, (err, results) => { console.log(results); }); -async.timesSeries(5, function(n, next) { - next(undefined as any, n) -}, function(err, results) { - console.log(results) -}) +async.timesSeries(5, (n, next) => { next(undefined as any, n); }, (err, results) => { console.log(results); }); async.parallel([ - function (callback) { - setTimeout(function () { - callback(undefined, 'one'); - }, 200); - }, - function (callback) { - setTimeout(function () { - callback(undefined, 'two'); - }, 100); - }, -], -function (err, results) { }); + callback => { setTimeout(() => { callback(undefined, 'one'); }, 200); }, + callback => { setTimeout(() => { callback(undefined, 'two'); }, 100); } + ], + (err, results) => { }); async.parallel([ - function (callback) { - setTimeout(function () { - callback(undefined, 'one'); - }, 200); - }, - function (callback) { - setTimeout(function () { - callback(undefined, 'two'); - }, 100); - }, -], -function (err, results) { }); - + callback => { setTimeout(() => { callback(undefined, 'one'); }, 200); }, + callback => { setTimeout(() => { callback(undefined, 'two'); }, 100); } + ], + (err, results) => { }); async.parallel({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, -function (err, results) { }); + (err, results) => { }); async.parallel({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, - function (err, results) { }); + (err, results) => { }); async.parallelLimit({ - one: function (callback) { - setTimeout(function () { - callback(undefined, 1); - }, 200); + one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); }, + two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); } }, - two: function (callback) { - setTimeout(function () { - callback(undefined, 2); - }, 100); - }, -}, 2, - function (err, results) { } + (err, results) => { } ); - function whileFn(callback: any) { setTimeout(() => callback(null, ++count), 1000); } function whileTest() { return count < 5; } function doWhileTest(count: number) { return count < 5; } -var count = 0; -async.whilst(whileTest, whileFn, function (err) { }); -async.until(whileTest, whileFn, function (err) { }); -async.doWhilst(whileFn, doWhileTest, function (err) { }); -async.doUntil(whileFn, doWhileTest, function (err) { }); -async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) }); -async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) }); -async.forever(function (errBack) { - errBack(new Error("Not going on forever.")); -}, - function (error) { - console.log(error); - } -); +let count = 0; +async.whilst(whileTest, whileFn, err => { }); +async.until(whileTest, whileFn, err => { }); +async.doWhilst(whileFn, doWhileTest, err => { }); +async.doUntil(whileFn, doWhileTest, err => { }); + +async.during(testCallback => { testCallback(new Error(), false); }, callback => { callback(); }, error => { console.log(error); }); +async.doDuring(callback => { callback(); }, testCallback => { testCallback(new Error(), false); }, error => { console.log(error); }); +async.forever(errBack => { errBack(new Error("Not going on forever.")); }, error => { console.log(error); }); async.waterfall([ - function (callback: any) { - callback(null, 'one', 'two'); - }, - function (arg1: any, arg2: any, callback: any) { - callback(null, 'three'); - }, - function (arg1: any, callback: any) { - callback(null, 'done'); - } -], function (err, result) { }); + (callback: any) => { callback(null, 'one', 'two'); }, + (arg1: any, arg2: any, callback: any) => { callback(null, 'three'); }, + (arg1: any, callback: any) => { callback(null, 'done'); } + ], + (err, result) => { }); - -var q = async.queue(function (task: any, callback: (err?:Error,msg?:string) => void) { +const q = async.queue((task: any, callback: (err?: Error, msg?: string) => void) => { console.log('hello ' + task.name); - callback(undefined,'a message.'); + callback(undefined, 'a message.'); }, 2); - -q.drain = function () { - console.log('all items have been processed'); -} +q.drain = () => { console.log('all items have been processed'); }; q.push({ name: 'foo' }); - -q.push({ name: 'bar' }, function (err) { - console.log('finished processing bar'); -}); - -q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { - console.log('finished processing bar'); -}); - -q.push({name: 'foo'}, function (err, msg) { - console.log('foo finished with a message "'+ msg! + '"'); -}); +q.push({ name: 'bar' }, err => { console.log('finished processing bar'); }); +q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], err => { console.log('finished processing bar'); }); +q.push({name: 'foo'}, (err, msg) => { console.log(`foo finished with a message "${msg!}"`); }); q.unshift({ name: 'foo' }); +q.unshift({ name: 'bar' }, err => { console.log('finished processing bar'); }); +q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], err => { console.log('finished processing bar'); }); -q.unshift({ name: 'bar' }, function (err) { - console.log('finished processing bar'); -}); +const qLength: number = q.length(); +const qStarted: boolean = q.started; +const qPaused: boolean = q.paused; +const qProcessingCount: number = q.running(); +const qIsIdle: boolean = q.idle(); -q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { - console.log('finished processing bar'); -}); +q.saturated = () => { console.log('queue is saturated.'); }; -var qLength : number = q.length(); -var qStarted : boolean = q.started; -var qPaused : boolean = q.paused; -var qProcessingCount : number = q.running(); -var qIsIdle : boolean = q.idle(); +q.empty = () => { console.log('queue is empty.'); }; -q.saturated = function() { - console.log('queue is saturated.'); -} - -q.empty = function() { - console.log('queue is empty.'); -} - -q.drain = function() { - console.log('queue was drained.'); -} +q.drain = () => { console.log('queue was drained.'); }; q.pause(); q.resume(); q.kill(); // tests for strongly typed tasks -var q2 = async.queue(function (task: string, callback: () => void) { +const q2 = async.queue((task: string, callback: () => void) => { console.log('Task: ' + task); callback(); }, 1); q2.push('task1'); - -q2.push('task2', function (error) { - console.log('Finished tasks'); -}); - -q2.push(['task3', 'task4', 'task5'], function (error) { - console.log('Finished tasks'); -}); +q2.push('task2', error => { console.log('Finished tasks'); }); +q2.push(['task3', 'task4', 'task5'], error => { console.log('Finished tasks'); }); q2.unshift('task1'); +q2.unshift('task2', error => { console.log('Finished tasks'); }); +q2.unshift(['task3', 'task4', 'task5'], error => { console.log('Finished tasks'); }); -q2.unshift('task2', function (error) { - console.log('Finished tasks'); -}); +const q2Length = q2.length(); +q2.push('testRemovalTask'); +q2.remove(x => x.data === 'testTaskRemoval'); +if (q2Length !== q2.length()) { + throw new Error('Failed to remove a task from queue.'); +} -q2.unshift(['task3', 'task4', 'task5'], function (error) { - console.log('Finished tasks'); -}); - - -var aq = async.queue(function (level: number, callback: (error?: Error, newLevel?: number) => void) { +const aq = async.queue((level: number, callback: (error?: Error, newLevel?: number) => void) => { console.log('hello ' + level); - callback(undefined, level+1); + callback(undefined, level + 1); }); -aq.push(1, function (err : Error, newLevel : number) { +aq.push(1, (err: Error, newLevel: number) => { console.log('finished processing bar' + newLevel); }); // create a cargo object with payload 2 -var cargo = async.cargo(function (tasks, callback) { - for (var i = 0; i < tasks.length; i++) { - console.log('hello ' + tasks[i].name); +const cargo = async.cargo((tasks, callback) => { + for (const task of tasks) { + console.log('hello ' + task.name); } callback(); }, 2); - // add some items -cargo.push({ name: 'foo' }, function (err: Error) { - console.log('finished processing foo'); -}); -cargo.push({ name: 'bar' }, function (err: Error) { - console.log('finished processing bar'); -}); -cargo.push({ name: 'baz' }, function (err: Error) { - console.log('finished processing baz'); -}); +cargo.push({ name: 'foo' }, (err: Error) => { console.log('finished processing foo'); }); +cargo.push({ name: 'bar' }, (err: Error) => { console.log('finished processing bar'); }); +cargo.push({ name: 'baz' }, (err: Error) => { console.log('finished processing baz'); }); -var filename = ''; +const filename = ''; async.auto({ - get_data: function (callback: AsyncResultCallback) { }, - make_folder: function (callback: AsyncResultCallback) { }, - //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { + get_data: (callback: AsyncResultCallback) => { }, + make_folder: (callback: AsyncResultCallback) => { }, + + // arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', ((callback: AsyncResultCallback) => { callback(null, filename); - } as any], - //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] + }) as any], + + // arrays with different types are not accepted by TypeScript. + email_link: ['write_file', ((callback: AsyncResultCallback, results: any) => { }) as any] }); async.auto({ - get_data: function (callback: AsyncResultCallback) { }, - make_folder: function (callback: AsyncResultCallback) { }, - //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { - callback(null, filename); - } as any], - //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] -}, function (err, results) { - console.log('finished auto'); -}); + get_data: (callback: AsyncResultCallback) => { }, + make_folder: (callback: AsyncResultCallback) => { }, + + // arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', ((callback: AsyncResultCallback) => { callback(null, filename); }) as any], + + // arrays with different types are not accepted by TypeScript. + email_link: ['write_file', ((callback: AsyncResultCallback, results: any) => { }) as any] + }, + (err, results) => { console.log('finished auto'); } +); interface A { get_data: any; @@ -418,32 +284,28 @@ interface A { } async.auto({ - get_data: function (callback: AsyncResultCallback) { }, - make_folder: function (callback: AsyncResultCallback) { }, - //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { - callback(null, filename); - } as any], - //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] -}, 1, function (err, results) { - console.log('finished auto'); -}); + get_data: (callback: AsyncResultCallback) => { }, + make_folder: (callback: AsyncResultCallback) => { }, -async.retry(3, function (callback, results) { }, function (err, result) { }); -async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { }); -async.retry({ times: 3, interval: (retryCount) => { return 200 * retryCount; } }, function (callback, results) { }, function (err, result) { }); + // arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', ((callback: AsyncResultCallback) => { callback(null, filename); }) as any], + // arrays with different types are not accepted by TypeScript. + email_link: ['write_file', ((callback: AsyncResultCallback, results: any) => { }) as any] + }, + 1, + (err, results) => { console.log('finished auto'); } +); + +async.retry(3, (callback, results) => { }, (err, result) => { }); +async.retry({ times: 3, interval: 200 }, (callback, results) => { }, (err, result) => { }); +async.retry({ times: 3, interval: (retryCount) => 200 * retryCount }, (callback, results) => { }, (err, result) => { }); async.parallel([ - function (callback: ( err:Error, val:string ) => void ) { }, - function (callback) { } -], -function (err:Error,results:Array) { - async.series([ - function (callback) { }, - function email_link(callback) { } - ]); + (callback: (err: Error, val: string) => void) => { }, + callback => { } + ], + (err: Error, results: string[]) => { async.series([callback => { }, function email_link(callback) { }]); }); async.parallel([ @@ -451,428 +313,281 @@ async.parallel([ async.apply(fs.writeFile, 'testfile2', 'test2'), ]); - async.parallel([ - function (callback) { - fs.writeFile('testfile1', 'test1', callback); - }, - function (callback) { - fs.writeFile('testfile2', 'test2', callback); - }, + callback => { fs.writeFile('testfile1', 'test1', callback); }, + callback => { fs.writeFile('testfile2', 'test2', callback); } ]); -var call_order: string[] = []; -async.nextTick(function () { - call_order.push('two'); -}); +const call_order: string[] = []; +async.nextTick(() => { call_order.push('two'); }); call_order.push('one'); -var slow_fn = function (name: string, callback: any) { - callback(null, 123); -}; -var fn = async.memoize(slow_fn); -fn('some name', function () {}); +const slow_fn = (name: string, callback: any) => { callback(null, 123); }; +const fn = async.memoize(slow_fn); + +fn('some name', () => { }); async.unmemoize(fn); -async.ensureAsync(function () { }); +async.ensureAsync(() => { }); async.constant(42); -async.asyncify(function () { }); +async.asyncify(() => { }); -async.log(function (name: any, callback: any) { - setTimeout(function () { - callback(null, 'hello ' + name); - }, 0); -}, "world" - ); +async.log( + (name: any, callback: any) => { setTimeout(() => { callback(null, 'hello ' + name); }, 0); }, + "world"); -async.dir(function (name: string, callback: any) { - setTimeout(function () { - callback(null, { hello: name }); - }, 1000); -}, "world"); +async.dir((name: string, callback: any) => { setTimeout(() => { callback(null, { hello: name }); }, 1000); }, "world"); // each -async.each({ - "a": 1, - "b": 2 -}, function(val: number, next: ErrorCallback): void { +async.each( + { a: 1, b: 2 }, + (val: number, next: ErrorCallback) => { + setTimeout(() => { + console.log(`async.each: ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.each: done."); } +); - setTimeout(function(): void { +async.eachSeries( + { a: 1, b: 2 }, + (val: number, next: ErrorCallback) => { + setTimeout( + () => { + console.log(`async.eachSeries: ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.eachSeries: done."); } +); - console.log(`async.each: ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.each: done."); - -}); - -async.eachSeries({ - "a": 1, - "b": 2 -}, function(val: number, next: ErrorCallback): void { - - setTimeout(function(): void { - - console.log(`async.eachSeries: ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.eachSeries: done."); - -}); - -async.eachLimit({ - "a": 1, - "b": 2, - "c": 3, - "d": 4, - "e": 5, - "f": 6 -}, 2, function(val: number, next: ErrorCallback): void { - - setTimeout(function(): void { - - console.log(`async.eachLimit: ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.eachLimit: done."); - -}); +async.eachLimit( + { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }, + 2, + (val: number, next: ErrorCallback) => { + setTimeout(() => { + console.log(`async.eachLimit: ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.eachLimit: done."); } +); // forEachOf/eachOf -async.eachOf({ - "a": 1, - "b": 2 -}, function(val: number, key: string, next: ErrorCallback): void { +async.eachOf( + { a: 1, b: 2 }, + (val: number, key: string, next: ErrorCallback) => { + setTimeout( + () => { + console.log(`async.forEachOf/eachOf: ${key} = ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.forEachOf/eachOf: done."); } +); - setTimeout(function(): void { +async.forEachOfSeries( + { a: 1, b: 2 }, + (val: number, key: string, next: ErrorCallback) => { + setTimeout( + () => { + console.log(`async.forEachOfSeries: ${key} = ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.forEachOfSeries: done."); } +); - console.log(`async.forEachOf/eachOf: ${key} = ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.forEachOf/eachOf: done."); - -}); - -async.forEachOfSeries({ - "a": 1, - "b": 2 -}, function(val: number, key: string, next: ErrorCallback): void { - - setTimeout(function(): void { - - console.log(`async.forEachOfSeries: ${key} = ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.forEachOfSeries: done."); - -}); - -async.forEachOfLimit({ - "a": 1, - "b": 2, - "c": 3, - "d": 4, - "e": 5, - "f": 6 -}, 2, function(val: number, key: string, next: ErrorCallback): void { - - setTimeout(function(): void { - - console.log(`async.forEachOfLimit: ${key} = ${val}`); - - next(); - - }, 500); - -}, function(err?: Error): void { - - console.log("async.forEachOfLimit: done."); - -}); +async.forEachOfLimit( + { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }, + 2, + (val: number, key: string, next: ErrorCallback) => { + setTimeout( + () => { + console.log(`async.forEachOfLimit: ${key} = ${val}`); + next(); + }, + 500); + }, + (err?: Error) => { console.log("async.forEachOfLimit: done."); } +); // map -async.map({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, next: AsyncResultCallback): void { +async.map( + { a: 1, b: 2, c: 3 }, + (val: number, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.map: ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: string[]) => { console.log("async.map: done with results", results); } +); - setTimeout(function(): void { +async.mapSeries( + { a: 1, b: 2, c: 3 }, + (val: number, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.mapSeries: ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: string[]) => { console.log("async.mapSeries: done with results", results); } +); - console.log(`async.map: ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: string[]): void { - - console.log("async.map: done with results", results); - -}); - -async.mapSeries({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, next: AsyncResultCallback): void { - - setTimeout(function(): void { - - console.log(`async.mapSeries: ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: string[]): void { - - console.log("async.mapSeries: done with results", results); - -}); - -async.mapLimit({ - "a": 1, - "b": 2, - "c": 3, - "d": 4, - "e": 5, - "f": 6 -}, 2, function(val: number, next: AsyncResultCallback): void { - - setTimeout(function(): void { - - console.log(`async.mapLimit: ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: string[]): void { - - console.log("async.mapLimit: done with results", results); - -}); +async.mapLimit( + { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }, + 2, + (val: number, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.mapLimit: ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: string[]) => { console.log("async.mapLimit: done with results", results); } +); // mapValues -async.mapValues({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, key: string, next: AsyncResultCallback): void { +async.mapValues( + { a: 1, b: 2, c: 3 }, + (val: number, key: string, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.mapValues: ${key} = ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: Dictionary) => { console.log("async.mapValues: done with results", results); } +); - setTimeout(function(): void { - - console.log(`async.mapValues: ${key} = ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: Dictionary): void { - - console.log("async.mapValues: done with results", results); - -}); - -async.mapValuesSeries({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, key: string, next: AsyncResultCallback): void { - - setTimeout(function(): void { - - console.log(`async.mapValuesSeries: ${key} = ${val}`); - - next(undefined as any, val.toString()); - - }, 500); - -}, function(err: Error, results: Dictionary): void { - - console.log("async.mapValuesSeries: done with results", results); - -}); +async.mapValuesSeries( + { a: 1, b: 2, c: 3 }, + (val: number, key: string, next: AsyncResultCallback) => { + setTimeout( + () => { + console.log(`async.mapValuesSeries: ${key} = ${val}`); + next(undefined as any, val.toString()); + }, + 500); + }, + (err: Error, results: Dictionary) => { console.log("async.mapValuesSeries: done with results", results); } +); // filter/select/reject -async.filter({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, next: AsyncBooleanResultCallback): void { +async.filter( + { a: 1, b: 2, c: 3 }, + (val: number, next: AsyncBooleanResultCallback) => { + setTimeout( + () => { + console.log(`async.filter/select: ${val}`); + next(undefined as any, val % 2 === 0); + }, + 500); + }, + (err: Error, results: number[]) => { console.log("async.filter/select: done with results", results); } +); - setTimeout(function(): void { - - console.log(`async.filter/select: ${val}`); - - next(undefined as any, val % 2 === 0); - - }, 500); - -}, function(err: Error, results: number[]): void { - - console.log("async.filter/select: done with results", results); - -}); - -async.reject({ - "a": 1, - "b": 2, - "c": 3 -}, function(val: number, next: AsyncBooleanResultCallback): void { - - setTimeout(function(): void { - - console.log(`async.reject: ${val}`); - - next(undefined as any, val % 2 === 0); - - }, 500); - -}, function(err: Error, results: number[]): void { - - console.log("async.reject: done with results", results); - -}); +async.reject( + { a: 1, b: 2, c: 3 }, + (val: number, next: AsyncBooleanResultCallback) => { + setTimeout( + () => { + console.log(`async.reject: ${val}`); + next(undefined as any, val % 2 === 0); + }, + 500); + }, + (err: Error, results: number[]) => { console.log("async.reject: done with results", results); } +); // concat -async.concat({ - "a": "1", - "b": "2", - "c": "3" -}, function(item: string, next: AsyncResultCallback): void { - - console.log(`async.concat: ${item}`); - - next(undefined as any, [item, item, item]); - -}, function(err: Error, results: string[]) { - - console.log("async.concat: done with results", results); - -}); +async.concat( + { a: "1", b: "2", c: "3" }, + (item: string, next: AsyncResultCallback) => { + console.log(`async.concat: ${item}`); + next(undefined as any, [item, item, item]); + }, + (err: Error, results: string[]) => { console.log("async.concat: done with results", results); } +); // detect/find -async.detect({ - "a": 1, - "b": 2, - "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { - - console.log(`async.detect/find: ${item}`); - - next(undefined as any, item > 1); - -}, function(err: Error, result: number) { - - if (err) { - - console.log(err); - - } else { - - console.log("async.detect/find: done with result", result); +async.detect( + { a: 1, b: 2, c: 3 }, + (item: number, next: AsyncBooleanResultCallback) => { + console.log(`async.detect/find: ${item}`); + next(undefined as any, item > 1); + }, + (err: Error, result: number) => { + if (err) { + console.log(err); + } else { + console.log("async.detect/find: done with result", result); + } } - -}); +); // every/all -async.every({ - "a": 1, - "b": 2, - "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { - - console.log(`async.every/all: ${item}`); - - next(undefined as any, item > 0); - -}, function(err: Error, result: boolean) { - - console.log("async.every/all: done with result", result); - -}); +async.every( + { a: 1, b: 2, c: 3 }, + (item: number, next: AsyncBooleanResultCallback) => { + console.log(`async.every/all: ${item}`); + next(undefined as any, item > 0); + }, + (err: Error, result: boolean) => { console.log("async.every/all: done with result", result); } +); // some/any -async.some({ - "a": 1, - "b": 2, - "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { - - console.log(`async.some/any: ${item}`); - - next(undefined as any, item > 2); - -}, function(err: Error, result: boolean) { - - console.log("async.some/any: done with result", result); - -}); +async.some( + { a: 1, b: 2, c: 3 }, + (item: number, next: AsyncBooleanResultCallback) => { + console.log(`async.some/any: ${item}`); + next(undefined as any, item > 2); + }, + (err: Error, result: boolean) => { console.log("async.some/any: done with result", result); } +); // timeout -function myFunction1(foo : any, callback: (err?: Error, result?: any) => void ) : void { +function myFunction1(foo: any, callback: (err?: Error, result?: any) => void): void { console.log(`async.timeout 1 ${foo}`); - return callback(undefined, foo); + callback(undefined, foo); } -var wrapped1 = async.timeout(myFunction1, 1000); -wrapped1({ bar: 'bar' }, function(err : Error, data : any) { - console.log(`async.timeout 1 end ${data}`); -}); +const wrapped1 = async.timeout(myFunction1, 1000); +wrapped1({ bar: 'bar' }, (err: Error, data: any) => { console.log(`async.timeout 1 end ${data}`); }); - -function myFunction2(callback: (err?: Error, result?: any) => void ) : void { +function myFunction2(callback: (err?: Error, result?: any) => void): void { console.log(`async.timeout 2`); - return callback(undefined, { bar: 'bar' }); + callback(undefined, { bar: 'bar' }); } -var wrapped2 = async.timeout(myFunction2, 1000); -wrapped2( function(err : Error, data : any) { - console.log(`async.timeout 2 end ${data}`); -}); +const wrapped2 = async.timeout(myFunction2, 1000); +wrapped2((err: Error, data: any) => { console.log(`async.timeout 2 end ${data}`); }); -function myFunction3(callback: (err?: Error, result?: any) => void ) : void { +function myFunction3(callback: (err?: Error, result?: any) => void): void { console.log(`async.timeout 3`); - return callback(undefined, { bar: 'bar' }); + callback(undefined, { bar: 'bar' }); } -var wrapped3 = async.timeout(myFunction3, 1000, { bar: 'bar' }); -wrapped3( function(err : Error, data : any) { - console.log(`async.timeout 3 end ${data}`); -}); - +const wrapped3 = async.timeout(myFunction3, 1000, { bar: 'bar' }); +wrapped3((err: Error, data: any) => { console.log(`async.timeout 3 end ${data}`); }); diff --git a/types/async/tslint.json b/types/async/tslint.json index 9380375afa..5612ed6657 100644 --- a/types/async/tslint.json +++ b/types/async/tslint.json @@ -1,34 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - // TODOs - "arrow-return-shorthand": false, - "array-type": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "max-line-length": false, - "no-consecutive-blank-lines": false, - "no-padding": false, - "no-unnecessary-generics": false, - "no-var-keyword": false, - "no-void-expression": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-const": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "trim-file": false, - "typedef-whitespace": false, - "unified-signatures": false, - "whitespace": false + "ban-types": true, // PRODUCES ERRORS WHEN REMOVED + "callable-types": false, // HAS ISSUES + "no-unnecessary-generics": false // HAS ISSUES } } diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index a38c928333..7e43da1c89 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -569,6 +569,14 @@ export type SpecErrorCodes = export interface Auth0Error { error: LibErrorCodes | SpecErrorCodes | string; errorDescription: string; + // Need to include non-intuitive error fields that Auth0 uses + code?: string; + description?: string; + name?: string; + policy?: string; + original?: any; + statusCode?: number; + statusText?: string; } export type Auth0ParseHashError = Auth0Error & { @@ -812,6 +820,8 @@ export interface AuthorizeOptions { login_hint?: string; prompt?: string; mode?: "login" | "signUp"; + accessType?: string; + approvalPrompt?: string; } export interface CheckSessionOptions extends AuthorizeOptions { diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 6e23e81d5e..53c50dd98f 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -130,7 +130,8 @@ const otherOptions : Auth0LockConstructorOptions = { hashCleanup: false, leeway: 30, _enableImpersonation: true, - _enableIdPInitiatedLogin: false + _enableIdPInitiatedLogin: false, + defaultADUsernameFromEmailPrefix: false }; new Auth0Lock(CLIENT_ID, DOMAIN, otherOptions); diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 2916ec58c8..32a3228e56 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -130,7 +130,7 @@ interface Auth0LockConstructorOptions { closable?: boolean; configurationBaseUrl?: string; container?: string; - defaultADUsernameFromEmailPrefix?: string; + defaultADUsernameFromEmailPrefix?: boolean; defaultDatabaseConnection?: string; defaultEnterpriseConnection?: string; flashMessage?: Auth0LockFlashMessageOptions; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index 60bbf86823..cca6bf8373 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -147,11 +147,21 @@ management management .updateUser({id: "user_id"}, {"email": "hi@me.co"}, (err: Error, users: auth0.User) => {}); - // Update user metadata management .updateUserMetadata({id: "user_id"}, {"key": "value"}); +// Update user metadata with JSON object +management + .updateUserMetadata({id: "user_id"}, { + key: "value", + numKey: 123, + objKey: { + foo: "bar", + another: "value" + } + }); + // Update user metadata using callback management .updateUserMetadata({id: "user_id"}, {"key": "value"}, (err: Error, users: auth0.User) => {}); diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 39d9d36fd7..c2df7dee7c 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for auth0 2.9.2 +// Type definitions for auth0 2.9.3 // Project: https://github.com/auth0/node-auth0 // Definitions by: Seth Westphal +// Ian Howe +// Alex Bjørlig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -32,7 +34,7 @@ export interface RetryOptions { } export interface UserMetadata { - [propName: string]: string + [propName: string]: any } export interface AppMetadata { @@ -46,7 +48,10 @@ export interface UserData { verify_email?: boolean; password?: string; phone_number?: string; - phone_verified?: boolean, + phone_verified?: boolean; + given_name?: string; + family_name?: string; + name?: string; user_metadata?: UserMetadata; app_metadata?: AppMetadata; } diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 92f0a6999b..ba6ebdc5ac 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -1056,3 +1056,113 @@ const firehoseEventHandler: AWSLambda.FirehoseTransformationHandler = ( ] }); }; + +declare let lexEvent: AWSLambda.LexEvent; +lexEvent = { + currentIntent: { + name: 'intent-name', + slots: { + slot1: null, + slot2: 'value2', + }, + slotDetails: { + slot1: { + resolutions: [ + { value: 'value1' }, + ], + originalValue: 'originalValue', + } + }, + confirmationStatus: 'None', + }, + bot: { + name: 'bot name', + alias: 'bot alias', + version: 'bot version', + }, + userId: 'User ID specified in the POST request to Amazon Lex.', + inputTranscript: 'Text used to process the request', + invocationSource: 'FulfillmentCodeHook', + outputDialogMode: 'Text', + messageVersion: '1.0', + sessionAttributes: { + key1: 'value1', + key2: 'value2', + }, + requestAttributes: { + key1: 'value1', + key2: 'value2', + } +}; + +declare let lexResult: AWSLambda.LexResult; +declare let lexDialogAction: AWSLambda.LexDialogAction; +declare let lexDialogActionBase: AWSLambda.LexDialogActionBase; +declare let lexDialogActionClose: AWSLambda.LexDialogActionClose; +declare let lexDialogActionConfirmIntent: AWSLambda.LexDialogActionConfirmIntent; +declare let lexDialogActionDelegate: AWSLambda.LexDialogActionDelegate; +declare let lexDialogActionElicitIntent: AWSLambda.LexDialogActionElicitIntent; +declare let lexDialogActionElicitSlot: AWSLambda.LexDialogActionElicitSlot; +declare let lexGenericAttachment: AWSLambda.LexGenericAttachment; + +lexResult = { + sessionAttributes: { + attrib1: 'Value One', + }, + dialogAction: { + type: 'Close', + fulfillmentState: 'Failed', + }, +}; + +str = lexGenericAttachment.title; +str = lexGenericAttachment.subTitle; +str = lexGenericAttachment.imageUrl; +str = lexGenericAttachment.attachmentLinkUrl; +str = lexGenericAttachment.buttons[0].text; +str = lexGenericAttachment.buttons[0].value; + +lexDialogAction.type === 'Close'; +lexDialogAction.type === 'ConfirmIntent'; +lexDialogAction.type === 'Delegate'; +lexDialogAction.type === 'ElicitIntent'; +lexDialogAction.type === 'ElicitSlot'; + +lexDialogActionBase.message!.contentType === 'CustomPayload'; +lexDialogActionBase.message!.contentType === 'PlainText'; +lexDialogActionBase.message!.contentType === 'SSML'; +str = lexDialogActionBase.message!.content; +num = lexDialogActionBase.responseCard!.version; +lexDialogActionBase.responseCard!.contentType === 'application/vnd.amazonaws.card.generic'; +// $ExpectType LexGenericAttachment +lexDialogActionBase.responseCard!.genericAttachments[0]; + +lexDialogActionClose.type === 'Close'; +lexDialogActionClose.fulfillmentState === 'Failed'; +lexDialogActionClose.fulfillmentState === 'Fulfilled'; + +lexDialogActionConfirmIntent.type === 'ConfirmIntent'; +str = lexDialogActionConfirmIntent.intentName; +strOrNull = lexDialogActionConfirmIntent.slots['example']; + +lexDialogActionDelegate.type === 'Delegate'; +strOrNull = lexDialogActionDelegate.slots['example']; + +lexDialogActionElicitIntent.type === 'ElicitIntent'; +lexDialogActionElicitSlot.type === 'ElicitSlot'; +strOrNull = lexDialogActionElicitSlot.slots['example']; +str = lexDialogActionElicitSlot.slotToElicit; +str = lexDialogActionElicitSlot.intentName; + +const lexEventHandler: AWSLambda.LexHandler = async ( + event: AWSLambda.LexEvent, + context: AWSLambda.Context, +) => { + // $ExpectType LexEvent + event; + + // $ExpectType Context + context; + str = context.functionName; + return lexResult; +}; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 4cafe3d2da..52314529bc 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -876,6 +876,100 @@ export interface SQSMessageAttributes { [name: string]: SQSMessageAttribute; } +// Lex +// https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html#supported-event-source-lex +export interface LexEvent { + currentIntent: { + name: string; + slots: { [name: string]: string | null }; + slotDetails: LexSlotDetails; + confirmationStatus: 'None' | 'Confirmed' | 'Denied'; + }; + bot: { + name: string; + alias: string; + version: string; + }; + userId: string; + inputTranscript: string; + invocationSource: 'DialogCodeHook' | 'FulfillmentCodeHook'; + outputDialogMode: 'Text' | 'Voice'; + messageVersion: '1.0'; + sessionAttributes: { [key: string]: string }; + requestAttributes: { [key: string]: string } | null; +} + +export interface LexSlotResolution { + value: string; +} + +export interface LexSlotDetails { + [name: string]: { + // The following line only works in TypeScript Version: 3.0, The array should have at least 1 and no more than 5 items + // resolutions: [LexSlotResolution, LexSlotResolution?, LexSlotResolution?, LexSlotResolution?, LexSlotResolution?]; + resolutions: LexSlotResolution[] + originalValue: string; + }; +} + +export interface LexGenericAttachment { + title: string; + subTitle: string; + imageUrl: string; + attachmentLinkUrl: string; + buttons: Array<{ + text: string; + value: string; + }>; +} + +export interface LexDialogActionBase { + type: 'Close' | 'ElicitIntent' | 'ElicitSlot' | 'ConfirmIntent'; + message?: { + contentType: 'PlainText' | 'SSML' | 'CustomPayload'; + content: string; + }; + responseCard?: { + version: number; + contentType: 'application/vnd.amazonaws.card.generic'; + genericAttachments: LexGenericAttachment[]; + }; +} + +export interface LexDialogActionClose extends LexDialogActionBase { + type: 'Close'; + fulfillmentState: 'Fulfilled' | 'Failed'; +} + +export interface LexDialogActionElicitIntent extends LexDialogActionBase { + type: 'ElicitIntent'; +} + +export interface LexDialogActionElicitSlot extends LexDialogActionBase { + type: 'ElicitSlot'; + intentName: string; + slots: { [name: string]: string | null }; + slotToElicit: string; +} + +export interface LexDialogActionConfirmIntent extends LexDialogActionBase { + type: 'ConfirmIntent'; + intentName: string; + slots: { [name: string]: string | null }; +} + +export interface LexDialogActionDelegate { + type: 'Delegate'; + slots: { [name: string]: string | null }; +} + +export type LexDialogAction = LexDialogActionClose | LexDialogActionElicitIntent | LexDialogActionElicitSlot | LexDialogActionConfirmIntent | LexDialogActionDelegate; + +export interface LexResult { + sessionAttributes?: { [key: string]: string }; + dialogAction: LexDialogAction; +} + /** * AWS Lambda handler function. * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html @@ -938,6 +1032,9 @@ export type ScheduledHandler = Handler; // TODO: Alexa +export type LexHandler = Handler; +export type LexCallback = Callback; + export type APIGatewayProxyHandler = Handler; export type APIGatewayProxyCallback = Callback; export type ProxyHandler = APIGatewayProxyHandler; // Old name diff --git a/types/axios-case-converter/axios-case-converter-tests.ts b/types/axios-case-converter/axios-case-converter-tests.ts new file mode 100644 index 0000000000..77fa927976 --- /dev/null +++ b/types/axios-case-converter/axios-case-converter-tests.ts @@ -0,0 +1,6 @@ +import axios from "axios"; +import applyConverters from "axios-case-converter"; + +applyConverters(); // $ExpectError + +applyConverters(axios.create()); // $ExpectType AxiosInstance diff --git a/types/axios-case-converter/index.d.ts b/types/axios-case-converter/index.d.ts new file mode 100644 index 0000000000..2071ee4dbc --- /dev/null +++ b/types/axios-case-converter/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for axios-case-converter 0.3 +// Project: https://github.com/mpyw/axios-case-converter +// Definitions by: Derek Kniffin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import { AxiosInstance } from "axios"; + +export default function applyConverters(axios: AxiosInstance): AxiosInstance; diff --git a/types/fastify-jwt/package.json b/types/axios-case-converter/package.json similarity index 54% rename from types/fastify-jwt/package.json rename to types/axios-case-converter/package.json index 5eb77c39fa..ab98e74e0b 100644 --- a/types/fastify-jwt/package.json +++ b/types/axios-case-converter/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "fastify": ">=1.13.1 || 2.0.0-rc.1" + "axios": "^0.16.1" } } diff --git a/types/axios-case-converter/tsconfig.json b/types/axios-case-converter/tsconfig.json new file mode 100644 index 0000000000..fb3102b6eb --- /dev/null +++ b/types/axios-case-converter/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", + "axios-case-converter-tests.ts" + ] +} diff --git a/types/axios-case-converter/tslint.json b/types/axios-case-converter/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/axios-case-converter/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/azure-sb/azure-sb-tests.ts b/types/azure-sb/azure-sb-tests.ts index 14d2ba9054..e1703c8086 100644 --- a/types/azure-sb/azure-sb-tests.ts +++ b/types/azure-sb/azure-sb-tests.ts @@ -80,3 +80,14 @@ nh.wns.send('tag', '', 'wns/toast', { headers: {} }, Response nh.wns.sendToastText01('tag', '', ResponseCallback); nh.wns.sendToastText01(['tag'], '', ResponseCallback); nh.wns.sendToastText01('tag', '', { headers: {} }, ResponseCallback); +nh.createOrUpdateInstallation({ + "installationId":"123-123-123-123", + "platform":"gcm", + "pushChannel":"aXhytc4zD=", +}, () => {}); +nh.createOrUpdateInstallation({ + installationId:"123-123-123-123", + platform:"gcm", + pushChannel:"aXhytc4zD=", + tags:["tag1","tag2"] +}, {}, () => {}); \ No newline at end of file diff --git a/types/azure-sb/index.d.ts b/types/azure-sb/index.d.ts index bd62e100ab..acb0bed06a 100644 --- a/types/azure-sb/index.d.ts +++ b/types/azure-sb/index.d.ts @@ -140,6 +140,32 @@ export namespace Azure.ServiceBus { WnsHeaders?: any; } + export interface NotificationHubInstallation { + installationId: string; + readonly lastActiveOn?: string; + readonly expirationTime?: string; + readonly lastUpdate?: string; + platform: "apns" | "wns" | "mpns" | "adm" | "gcm"; + pushChannel: string; + readonly expiredPushChannel?: string; + tags?: Array; + templates?: { + [name: string]: { + body: string; + headers?: any; + expiry?: string; + tags?: Array; + }; + }; + secondaryTile?: { + [titleId: string]: { + pushChannel: string; + tags?: Array; + templates?: any; + }; + }; + } + export interface Response { body: Dictionary; headers: Dictionary; diff --git a/types/azure-sb/lib/notificationhubservice.d.ts b/types/azure-sb/lib/notificationhubservice.d.ts index d56b53d9d5..ab2cf0f3ee 100644 --- a/types/azure-sb/lib/notificationhubservice.d.ts +++ b/types/azure-sb/lib/notificationhubservice.d.ts @@ -2,6 +2,7 @@ import { Azure } from 'azure-sb'; import Callback = Azure.ServiceBus.ResponseCallback; import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration; import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions; +import NotificationHubInstallation = Azure.ServiceBus.NotificationHubInstallation; import ApnsService = require('./apnsservice'); import GcmService = require('./gcmservice'); @@ -29,10 +30,10 @@ declare class NotificationHubService { options: { headers: object }, callback: Callback): void; - public createOrUpdateInstallation(installation: string, + public createOrUpdateInstallation(installation: NotificationHubInstallation, callback: Callback): void; - public createOrUpdateInstallation(installation: string, + public createOrUpdateInstallation(installation: NotificationHubInstallation, options: any, callback: Callback): void; diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 70f8c5f0b6..98a0338021 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -150,3 +150,8 @@ const VisitorStateTest: Visitor = { } } }; + +const VisitorAliasTest: Visitor = { + Function() {}, + Expression() {}, +}; diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 89e242129b..fe817d5daf 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -145,6 +145,8 @@ export class Binding { export type Visitor = VisitNodeObject & { [Type in Node["type"]]?: VisitNode>; +} & { + [K in keyof t.Aliases]?: VisitNode }; export type VisitNode = VisitNodeFunction | VisitNodeObject; diff --git a/types/babel__traverse/package.json b/types/babel__traverse/package.json index 2442a952db..47a2d3dc48 100644 --- a/types/babel__traverse/package.json +++ b/types/babel__traverse/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "@babel/types": "^7.0.0" + "@babel/types": "^7.3.0" } } diff --git a/types/backbone-relational/backbone-relational-tests.ts b/types/backbone-relational/backbone-relational-tests.ts index 90433cd153..6e0135fcd9 100644 --- a/types/backbone-relational/backbone-relational-tests.ts +++ b/types/backbone-relational/backbone-relational-tests.ts @@ -74,6 +74,7 @@ paul.get('livesIn'); // === ourHouse // You can control which relations get serialized to JSON, using the 'includeInJSON' // property on a Relation. Also, each object will only get serialized once to prevent loops. alert(JSON.stringify(paul.get('user').toJSON(), null, '\t')); +alert(JSON.stringify(paul.get('user').toJSON({ option1: 'value1' }), null, '\t')); // Load occupants 'person-2' and 'person-5', which don't exist yet, from the server ourHouse.fetchRelated('occupants'); diff --git a/types/backbone-relational/index.d.ts b/types/backbone-relational/index.d.ts index 403759ac97..84406fb60a 100644 --- a/types/backbone-relational/index.d.ts +++ b/types/backbone-relational/index.d.ts @@ -34,7 +34,7 @@ declare module 'backbone' { fetchRelated(key:string, options?:any, update?:boolean):any; - toJSON():any; + toJSON(options?: any):any; static setup(); diff --git a/types/badgen/badgen-tests.ts b/types/badgen/badgen-tests.ts new file mode 100644 index 0000000000..1b795b3d72 --- /dev/null +++ b/types/badgen/badgen-tests.ts @@ -0,0 +1,24 @@ +import badgen from 'badgen'; + +// $ExpectType string +badgen({ + subject: 'SUBJECT', + status: 'STATUS' +}); + +// $ExpectType string +badgen({ + subject: 'SUBJECT', + status: 'STATUS', + color: 'green' +}); + +// $ExpectType string +badgen({ + subject: 'SUBJECT', + status: 'STATUS', + color: '#FF0000', + style: 'flat', + icon: 'data:image/svg+xml;base64,...', + iconWidth: 20 +}); diff --git a/types/badgen/index.d.ts b/types/badgen/index.d.ts new file mode 100644 index 0000000000..cc6aa1fe54 --- /dev/null +++ b/types/badgen/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for badgen 2.6 +// Project: https://github.com/amio/badgen +// Definitions by: m5d215 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +type ColorPresets = + | 'green' + | 'blue' + | 'red' + | 'yellow' + | 'orange' + | 'purple' + | 'pink' + | 'grey' + | 'gray' + | 'cyan' + | 'black'; + +interface BadgeCreationParams { + /** + * Text representing the subject. + */ + subject: string; + + /** + * Text representing the status. + */ + status: string; + + /** + * Color RGB or Color Name, optional. + */ + color?: ColorPresets | string; + + /** + * 'flat' or undefined, optional. + */ + style?: 'flat'; + + /** + * Use icon, optional. + */ + icon?: string; + + /** + * Use this if icon is not square. + * @default 13 + */ + iconWidth?: number; +} + +declare function badgen(params: BadgeCreationParams): string; + +export = badgen; diff --git a/types/badgen/tsconfig.json b/types/badgen/tsconfig.json new file mode 100644 index 0000000000..8e915b8aac --- /dev/null +++ b/types/badgen/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, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "badgen-tests.ts" + ] +} diff --git a/types/universal-router/tslint.json b/types/badgen/tslint.json similarity index 100% rename from types/universal-router/tslint.json rename to types/badgen/tslint.json diff --git a/types/beeper/beeper-tests.ts b/types/beeper/beeper-tests.ts new file mode 100644 index 0000000000..b3f6f8d60b --- /dev/null +++ b/types/beeper/beeper-tests.ts @@ -0,0 +1,7 @@ +import beeper = require('beeper'); + +beeper(); +beeper(3); +beeper(3, () => {}); +beeper('****-*-*'); +beeper('****-*-*', () => {}); diff --git a/types/beeper/index.d.ts b/types/beeper/index.d.ts new file mode 100644 index 0000000000..3e17e4be1c --- /dev/null +++ b/types/beeper/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for beeper 1.1 +// Project: https://github.com/sindresorhus/beeper#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = beeper; + +declare function beeper(count?: number, cb?: () => void): void; +declare function beeper(melody: string, cb?: () => void): void; diff --git a/types/beeper/tsconfig.json b/types/beeper/tsconfig.json new file mode 100644 index 0000000000..54614ad773 --- /dev/null +++ b/types/beeper/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", + "beeper-tests.ts" + ] +} diff --git a/types/beeper/tslint.json b/types/beeper/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/beeper/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bell/bell-tests.ts b/types/bell/bell-tests.ts index 26a29670a0..8a091f005c 100644 --- a/types/bell/bell-tests.ts +++ b/types/bell/bell-tests.ts @@ -16,7 +16,7 @@ async function run() { clientSecret: '', scope(request) { const scopes = ['public_profile', 'email']; - if ((request.query as RequestQuery).wantsSharePermission) { + if (request.query.wantsSharePermission) { scopes.push('publish_actions'); } return scopes; diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts index dddd69bea8..f5a6c0e070 100644 --- a/types/better-sqlite3/better-sqlite3-tests.ts +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -69,3 +69,12 @@ trans.default('name'); trans.deferred('name'); trans.immediate('name'); trans.exclusive('name'); + +const transTyped = db.transaction((param: number) => stmt.all(param)); +transTyped(1); +trans.default(1); +trans.deferred(1); +trans.immediate(1); +trans.exclusive(1); +// $ExpectError +transTyped('name'); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts index 2c027ff6e6..32a71d96af 100644 --- a/types/better-sqlite3/index.d.ts +++ b/types/better-sqlite3/index.d.ts @@ -4,10 +4,17 @@ // Mathew Rumsey // Santiago Aguilar // Alessandro Vergani +// Andrew Kaiser // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 import Integer = require("integer"); +type VariableArgFunction = (...params: any[]) => any; +type ArgumentTypes = F extends (...args: infer A) => any + ? A + : never; + declare namespace BetterSqlite3 { interface Statement { database: Database; @@ -34,12 +41,12 @@ declare namespace BetterSqlite3 { type: string | null; } - interface Transaction { - (...params: any[]): any; - default(...params: any[]): any; - deferred(...params: any[]): any; - immediate(...params: any[]): any; - exclusive(...params: any[]): any; + interface Transaction { + (...params: ArgumentTypes): any; + default(...params: ArgumentTypes): any; + deferred(...params: ArgumentTypes): any; + immediate(...params: ArgumentTypes): any; + exclusive(...params: ArgumentTypes): any; } interface Database { @@ -50,7 +57,7 @@ declare namespace BetterSqlite3 { inTransaction: boolean; prepare(source: string): Statement; - transaction(fn: (...params: any[]) => any): Transaction; + transaction(fn: F): Transaction; exec(source: string): this; pragma(source: string, options?: Database.PragmaOptions): any; checkpoint(databaseName?: string): this; @@ -113,7 +120,7 @@ declare namespace Database { type SqliteError = typeof SqliteError; type Statement = BetterSqlite3.Statement; type ColumnDefinition = BetterSqlite3.ColumnDefinition; - type Transaction = BetterSqlite3.Transaction; + type Transaction = BetterSqlite3.Transaction; type Database = BetterSqlite3.Database; } diff --git a/types/bip32/index.d.ts b/types/bip32/index.d.ts index 99a1b8dffd..c536f741af 100644 --- a/types/bip32/index.d.ts +++ b/types/bip32/index.d.ts @@ -17,6 +17,7 @@ export class BIP32 { identifier: Buffer; fingerprint: Buffer; + chainCode: Buffer; privateKey: Buffer; publicKey: Buffer; diff --git a/types/bn.js/bn.js-tests.ts b/types/bn.js/bn.js-tests.ts index a5d37dfdeb..738d5220d4 100644 --- a/types/bn.js/bn.js-tests.ts +++ b/types/bn.js/bn.js-tests.ts @@ -8,3 +8,11 @@ bn.byteLength; bn.toArrayLike(Buffer, 'le', 2); const test = new BN(1, 'le'); + +const ctx = BN.red('p224'); +ctx.prime.name; + +const red = bn.toRed(ctx); +const newRed = red.redAdd(new BN(1)); +newRed.cmp(bn); +newRed.fromRed(); diff --git a/types/bn.js/index.d.ts b/types/bn.js/index.d.ts index db4c9f8b9e..be04dbcc5f 100644 --- a/types/bn.js/index.d.ts +++ b/types/bn.js/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/indutny/bn.js // Definitions by: Leonid Logvinov // Henry Nguyen +// Gaylor Bosson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,36 +10,16 @@ type Endianness = 'le' | 'be'; type IPrimeName = 'k256' | 'p224' | 'p192' | 'p25519'; -declare class RedBN { - redAdd(b: RedBN): RedBN; - redIAdd(b: RedBN): RedBN; - redSub(b: RedBN): RedBN; - redISub(b: RedBN): RedBN; - redShl(num: number): RedBN; - redMul(b: RedBN): RedBN; - redIMul(b: RedBN): RedBN; - redSqr(): RedBN; - redISqr(): RedBN; - /** - * @description square root modulo reduction context's prime - */ - redSqrt(): RedBN; - /** - * @description modular inverse of the number - */ - redInvm(): RedBN; - redNeg(): RedBN; - /** - * @description modular exponentiation - */ - redPow(b: RedBN): RedBN; - fromRed(): BN; +interface MPrime { + name: string; + p: BN; + n: number; + k: BN; } -// FIXME: not sure how to specify the reduction context here interface ReductionContext { m: number; - prime: any; + prime: MPrime; [key: string]: any; } @@ -78,11 +59,6 @@ declare class BN { */ static min(left: BN, right: BN): BN; - /** - * @description Convert number to red - */ - toRed(reductionContext: ReductionContext): RedBN; - /** * @description clone number */ @@ -522,6 +498,87 @@ declare class BN { * @description inverse `a` modulo `b` */ invm(b: BN): BN; + + /** + * @description Convert number to red + */ + toRed(reductionContext: ReductionContext): RedBN; +} + +/** + * Big-Number class with additionnal methods that are using modular + * operation. + */ +declare class RedBN extends BN { + /** + * @description Convert back a number using a reduction context + */ + fromRed(): BN; + + /** + * @description modular addition + */ + redAdd(b: BN): RedBN; + + /** + * @description in-place modular addition + */ + redIAdd(b: BN): RedBN; + + /** + * @description modular subtraction + */ + redSub(b: BN): RedBN; + + /** + * @description in-place modular subtraction + */ + redISub(b: BN): RedBN; + + /** + * @description modular shift left + */ + redShl(num: number): RedBN; + + /** + * @description modular multiplication + */ + redMul(b: BN): RedBN; + + /** + * @description in-place modular multiplication + */ + redIMul(b: BN): RedBN; + + /** + * @description modular square + */ + redSqr(): RedBN; + + /** + * @description in-place modular square + */ + redISqr(): RedBN; + + /** + * @description modular square root + */ + redSqrt(): RedBN; + + /** + * @description modular inverse of the number + */ + redInvm(): RedBN; + + /** + * @description modular negation + */ + redNeg(): RedBN; + + /** + * @description modular exponentiation + */ + redPow(b: BN): RedBN; } export = BN; diff --git a/types/body-scroll-lock/body-scroll-lock-tests.ts b/types/body-scroll-lock/body-scroll-lock-tests.ts new file mode 100644 index 0000000000..4d716e7355 --- /dev/null +++ b/types/body-scroll-lock/body-scroll-lock-tests.ts @@ -0,0 +1,11 @@ +import { enableBodyScroll, disableBodyScroll, clearAllBodyScrollLocks } from 'body-scroll-lock'; + +const dom: HTMLDivElement = new HTMLDivElement(); + +disableBodyScroll(dom, { + reserveScrollBarGap: false, +}); + +enableBodyScroll(dom); + +clearAllBodyScrollLocks(); diff --git a/types/body-scroll-lock/index.d.ts b/types/body-scroll-lock/index.d.ts new file mode 100644 index 0000000000..5af6c3fbdb --- /dev/null +++ b/types/body-scroll-lock/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for body-scroll-lock 2.6 +// Project: https://github.com/willmcpo/body-scroll-lock +// Definitions by: kimcoder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface BodyScrollOptions { + reserveScrollBarGap?: boolean; + allowTouchMove?: (el: HTMLElement) => void; +} + +export function disableBodyScroll(targetElement: HTMLElement, options?: BodyScrollOptions): void; +export function enableBodyScroll(targetElement: HTMLElement): void; +export function clearAllBodyScrollLocks(): void; + +export as namespace bodyScrollLock; diff --git a/types/body-scroll-lock/tsconfig.json b/types/body-scroll-lock/tsconfig.json new file mode 100644 index 0000000000..d94754517f --- /dev/null +++ b/types/body-scroll-lock/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", + "body-scroll-lock-tests.ts" + ] +} diff --git a/types/body-scroll-lock/tslint.json b/types/body-scroll-lock/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/body-scroll-lock/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bootstrap-colorpicker/bootstrap-colorpicker-tests.ts b/types/bootstrap-colorpicker/bootstrap-colorpicker-tests.ts new file mode 100644 index 0000000000..a8be275b39 --- /dev/null +++ b/types/bootstrap-colorpicker/bootstrap-colorpicker-tests.ts @@ -0,0 +1,77 @@ +$(() => { + $('#cp1').colorpicker(); + + $('#cp2').colorpicker(); + + $('#cp3').colorpicker({ + color: '#AA3399', + format: 'rgb' + }); + + $('#cp4').colorpicker().on('changeColor', (e) => { + $('body')[0].style.backgroundColor = e.color.toString('rgba'); + }); + + $('#cp5').colorpicker({ + color: "transparent", + format: "hex" + }); + + $('#cp6').colorpicker({ + color: "#88cc33", + horizontal: true + }); + + $('#cp7').colorpicker({ + color: '#ffaa00', + container: true, + inline: true + }); + + $('#cp8').colorpicker({ + colorSelectors: { + black: '#000000', + white: '#ffffff', + red: '#FF0000', + default: '#777777', + primary: '#337ab7', + success: '#5cb85c', + info: '#5bc0de', + warning: '#f0ad4e', + danger: '#d9534f' + } + }); + + $('#cp9').colorpicker({ + customClass: 'colorpicker-2x', + sliders: { + saturation: { + maxLeft: 200, + maxTop: 200 + }, + hue: { + maxTop: 200 + }, + alpha: { + maxTop: 200 + } + } + }); + + $('.disable-button').click((e) => { + e.preventDefault(); + + $('#cp10').colorpicker('disable'); + }); + + $('.enable-button').click((e) => { + e.preventDefault(); + + $('#cp10').colorpicker('enable'); + }); + + $('#cp10').colorpicker(); + + + $('#cp11').colorpicker(); +}); \ No newline at end of file diff --git a/types/bootstrap-colorpicker/index.d.ts b/types/bootstrap-colorpicker/index.d.ts new file mode 100644 index 0000000000..d4a9fa9870 --- /dev/null +++ b/types/bootstrap-colorpicker/index.d.ts @@ -0,0 +1,270 @@ +// Type definitions for bootstrap-colorpicker 2.5 +// Project: https://github.com/farbelous/bootstrap-colorpicker/tree/v2.x +// Definitions by: Aleksandar Manukov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +type ColorFormat = 'hex' | 'rgb' | 'rgba'; + +type ColorPickerAlignOptions = 'right' | 'left'; + +type ColorPickerEvents = 'create' | + 'showPicker' | + 'hidePicker' | + 'changeColor' | + 'disable' | + 'enable' | + 'destroy'; + +/** + * You can set colorpicker options either as a plugin parameter or data-* attributes + */ +interface ColorPickerOptions { + /** + * If not false, forces the color format to be hex, rgb or rgba, otherwise the format is automatically detected. + * + * Default: false + */ + format?: ColorFormat; + + /** + * If not false, sets the color to this value. + * + * Default: false + */ + color?: string; + + /** + * If not false, the picker will be contained inside this element, otherwise it will be appended to the document body. + * + * Default: false + */ + container?: boolean; + + /** + * Children selector for the component or element that trigger the colorpicker and which background color will change (needs an inner element). + * + * Default: '.add-on, .input-group-addon' + */ + component?: string | JQuery; + + /** + * Children selector for the input that will store the picker selected value. + * + * Default: 'input' + */ + input?: string | JQuery; + + /** + * If true, put a '#' (number sign) before hex strings. + * + * Default: true + */ + hexNumberSignPrefix?: boolean; + + /** + * If true, the hue and alpha channel bars will be rendered horizontally, above the saturation selector. + * + * Default: false + */ + horizontal?: boolean; + + /** + * If true, forces to show the colorpicker as an inline element. + * + * Default: false + */ + inline?: boolean; + + /** + * Vertical sliders configuration (read source code if you really need to tweak this). + */ + sliders?: object; + + /** + * Horizontal sliders configuration (read source code if you really need to tweak this). + */ + slidersHorz?: object; + + /** + * Customizes the default colorpicker HTML template. + */ + template?: string; + + /** + * By default, the colorpicker is aligned to the right of the input. If you need to switch it to the left, set align to 'left'. + * + * Default: 'right' + */ + align?: ColorPickerAlignOptions; + + /** + * Adds this class to the colorpicker widget. + * + * Default: null + */ + customClass?: string; + + /** + * List of pre selected colors (hex format). If you choose one of these colors, the alias is returned instead of the hex code. + * + * Default: null + */ + colorSelectors?: object; + + /** + * Fallback color string that will be applied when the color failed to be parsed. If null, it will keep the current color if any. + * + * Default: null + */ + fallbackColor?: string; + + /** + * Fallback color format (e.g. when not specified or for alias mode, when selecting non aliased colors) + * + * Default: hex + */ + fallbackFormat?: string; +} + +interface Color { + colors: {}; + fallbackFormat: string; + fallbackValue: string; + hexNumberSignPrefix: boolean; + origFormat: string; + predefinedColors: {}; + value: { + h: number; + s: number; + b: number; + a: number; + }; + + /** + * Set a new color. The value is parsed and tries to do a quess on the format. + */ + setColor(value: string): void; + + /** + * Set the HUE with a value between 0 and 1. + */ + setHue(value: number): void; + + /** + * Set the saturation with a value between 0 and 1. + */ + setSaturation(value: number): void; + + /** + * Set the brightness with a value between 0 and 1. + */ + setBrightness(value: number): void; + + /** + * Set the transparency with a value between 0 and 1. + */ + setAlpha(value: number): void; + + /** + * Returns a hash with red, green, blue and alpha. + */ + toRGB(): string; + + /** + * Returns a string with HEX format for the current color. + */ + toHex(): string; + + /** + * Returns a hash with HSLA values. + */ + toHSL(): string; + + /** + * Returns current color as string in specified format. + */ + toString(format: ColorFormat): string; +} + +interface ColorPicker { + color: Color; + component: boolean; + container: boolean; + disabled: boolean; + element: JQuery; + format: string; + input: JQuery; + options: ColorPickerOptions; + picker: JQuery; +} + +interface ColorPickerEventObject extends JQueryEventObject { + color: Color; +} + +interface JQuery { + /** + * Initializes an colorpicker. + */ + colorpicker(options?: ColorPickerOptions): JQuery; + + /** + * Gets the value from the input or the data attribute (if has no input), otherwise returns the default value, which defaults to #000000 if not specified. + */ + colorpicker(methodName: 'getValue', defaultValue: string): string; + + /** + * Set a new value for the color picker (also updates everything). Triggers 'changeColor' event. + */ + colorpicker(methodName: 'setValue', value: any): any; + + /** + * Show the color picker + */ + colorpicker(methodName: 'show'): void; + + /** + * Hide the color picker + */ + colorpicker(methodName: 'hide'): void; + + /** + * Updates the color picker's position relative to the element + */ + colorpicker(methodName: 'reposition'): void; + + /** + * Refreshes the widget colors (this is done automatically) + */ + colorpicker(methodName: 'update'): void; + + /** + * Enable the color picker. + */ + colorpicker(methodName: 'enable'): void; + + /** + * Disable the color picker. + */ + colorpicker(methodName: 'disable'): void; + + /** + * Destroys the colorpicker widget and unbind all .colorpicker events from the element and component + */ + colorpicker(methodName: 'destroy'): void; + + /** + * Access to the colorpicker API directly + */ + data(methodName: 'colorpicker'): ColorPicker; + + off(events: ColorPickerEvents, selector?: string, handler?: (event: ColorPickerEventObject) => any): JQuery; + off(events: ColorPickerEvents, handler: (event: ColorPickerEventObject) => any): JQuery; + + on(events: ColorPickerEvents, selector: string, data: any, handler?: (event: ColorPickerEventObject) => any): JQuery; + on(events: ColorPickerEvents, selector: string, handler: (event: ColorPickerEventObject) => any): JQuery; + on(events: ColorPickerEvents, handler: (event: ColorPickerEventObject) => any): JQuery; +} \ No newline at end of file diff --git a/types/bootstrap-colorpicker/tsconfig.json b/types/bootstrap-colorpicker/tsconfig.json new file mode 100644 index 0000000000..6b8f8a5d47 --- /dev/null +++ b/types/bootstrap-colorpicker/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bootstrap-colorpicker-tests.ts" + ] +} diff --git a/types/bootstrap-colorpicker/tslint.json b/types/bootstrap-colorpicker/tslint.json new file mode 100644 index 0000000000..8be13c2695 --- /dev/null +++ b/types/bootstrap-colorpicker/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-consecutive-blank-lines": false, + "eofline": false, + "unified-signatures": false, + "no-trailing-whitespace": [true, "ignore-comments"] + } +} diff --git a/types/bootstrap/index.d.ts b/types/bootstrap/index.d.ts index e8cea54f58..d42cf5c524 100755 --- a/types/bootstrap/index.d.ts +++ b/types/bootstrap/index.d.ts @@ -152,7 +152,7 @@ export interface DropdownOption { export interface ModalOption { /** * Includes a modal-backdrop element. - * Alternatively, specify static for a backdrop which doesn't close the modal on click. + * Alternatively, specify `static` for a backdrop which doesn't close the modal on click. * * @default true */ @@ -182,8 +182,8 @@ export interface ModalOption { export interface PopoverOption extends TooltipOption { /** - * Default content value if data-content attribute isn't present. - * If a function is given, it will be called with its this reference + * Default content value if `data-content` attribute isn't present. + * If a function is given, it will be called with its `this` reference * set to the element that the popover is attached to. * * @default "" @@ -280,10 +280,11 @@ export interface TooltipOption { /** * How to position the tooltip or popover - auto | top | bottom | left | right. - * When auto is specified, it will dynamically reorient the tooltip or popover. + * When "auto" is specified, it will dynamically reorient the tooltip or popover. + * * When a function is used to determine the placement, it is called with * the tooltip or popover DOM node as its first argument and the triggering element DOM node as its second. - * The this context is set to the tooltip or popover instance. + * The `this` context is set to the tooltip or popover instance. * * @default tooltip: "top", popover: "right" */ @@ -298,8 +299,9 @@ export interface TooltipOption { selector?: string | false; /** - * Base HTML to use when creating the tooltip or popover. The tooltip's (resp., popover's) title will be injected into - * the `.tooltip-inner` (resp., `.popover-header`). The `.arrow` will become the tooltip's (resp., popover's) arrow. + * Base HTML to use when creating the tooltip or popover. + * The tooltip's (resp., popover's) title will be injected into the `.tooltip-inner` (resp., `.popover-header`). + * The `.arrow` will become the tooltip's (resp., popover's) arrow. * The outermost wrapper element should have the `.tooltip` (resp., .popover) class and `role="tooltip"`. * * @default '

' @@ -309,7 +311,7 @@ export interface TooltipOption { /** * Default title value if title attribute isn't present. - * If a function is given, it will be called with its this reference set to the element + * If a function is given, it will be called with its `this` reference set to the element * that the tooltip or popover is attached to. * * @default "" @@ -445,26 +447,26 @@ declare global { * If no _method_ is specified, makes an alert listen for click events on descendant elements which have the `data-dismiss="alert"` attribute. * (Not necessary when using the data-api's auto-initialization.) * Otherwise, call the method on the alert element: - * * `close` — Closes an alert by removing it from the DOM. If the `.fade` and `.show` classes are present on the element, the alert will fade out before it is removed. - * * `dispose` — Destroys an element's alert. + * * `close` – Closes an alert by removing it from the DOM. If the `.fade` and `.show` classes are present on the element, the alert will fade out before it is removed. + * * `dispose` – Destroys an element's alert. */ alert(action?: "close" | "dispose"): this; /** * Call a method on the button element: - * * `toggle` — Toggles push state. Gives the button the appearance that it has been activated. - * * `dispose` — Destroys an element's button. + * * `toggle` – Toggles push state. Gives the button the appearance that it has been activated. + * * `dispose` – Destroys an element's button. */ button(action: "toggle" | "dispose"): this; /** * Call a method on the carousel element: - * * `cycle` — Cycles through the carousel items from left to right. - * * `pause` — Stops the carousel from cycling through items. - * * _number_ — Cycles the carousel to a particular frame (0 based, similar to an array). - * * `prev` — Cycles to the previous item. - * * `next` — Cycles to the next item. - * * `dispose` — Destroys an element's carousel. + * * `cycle` – Cycles through the carousel items from left to right. + * * `pause` – Stops the carousel from cycling through items. + * * _number_ – Cycles the carousel to a particular frame (0 based, similar to an array). + * * `prev` – Cycles to the previous item. + * * `next` – Cycles to the next item. + * * `dispose` – Destroys an element's carousel. * * Returns to the caller before the target item has been shown (i.e. before the `slid.bs.carousel` event occurs). */ @@ -493,7 +495,7 @@ declare global { * Call a method on the dropdown element: * * `toggle` – Toggles the dropdown menu of a given navbar or tabbed navigation. * * `update` – Updates the position of an element's dropdown. - * * `dispose` — Destroys an element's dropdown. + * * `dispose` – Destroys an element's dropdown. */ dropdown(action: "toggle" | "update" | "dispose"): this; /** @@ -521,7 +523,7 @@ declare global { /** * Call a method on the popover element: - * * `show` – Reveals an element's popover. + * * `show` – Reveals an element's popover. Popovers whose both title and content are zero-length are never displayed. * * `hide` – Hides an element's popover. * * `toggle` – Toggles an element's popover. * * `dispose` – Hides and destroys an element's popover. @@ -532,7 +534,7 @@ declare global { * * `update` – Updates the position of an element's popover. * * Returns to the caller before the popover has actually been shown or hidden (i.e. before the `shown.bs.popover` or `hidden.bs.popover` event occurs). - * This is considered a "manual" triggering of the popover. Popovers whose both title and content are zero-length are never displayed. + * This is considered a "manual" triggering of the popover. */ popover(action: "show" | "hide" | "toggle" | "dispose" | "enable" | "disable" | "toggleEnabled" | "update"): this; /** @@ -586,7 +588,7 @@ $('[data-spy="scroll"]').each(function () { /** * Call a method on the tooltip element: - * * `show` – Reveals an element's tooltip. + * * `show` – Reveals an element's tooltip. Tooltips with zero-length titles are never displayed. * * `hide` – Hides an element's tooltip. * * `toggle` – Toggles an element's tooltip. * * `dispose` – Hides and destroys an element's tooltip. diff --git a/types/bootstrap/v3/bootstrap-tests.ts b/types/bootstrap/v3/bootstrap-tests.ts index 00a8fa44fd..e834903867 100644 --- a/types/bootstrap/v3/bootstrap-tests.ts +++ b/types/bootstrap/v3/bootstrap-tests.ts @@ -1,9 +1,21 @@ +declare let aHtmlElement: HTMLElement; + +// -------------------------------------------------------------------------------------- +// jQuery backward compatibility +// -------------------------------------------------------------------------------------- + +$(".dropdown").on("affixed.bs.affix", (e) => { + e.stopPropagation(); +}); + // -------------------------------------------------------------------------------------- // Modal // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".modal").modal(); +// $ExpectType JQuery $(".modal").modal("show"); $(".modal").modal("toggle"); @@ -25,16 +37,24 @@ $(".modal").modal({ // Dropdown // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".dropdown").dropdown(); +// $ExpectType JQuery $(".dropdown").dropdown("toggle"); +$(".dropdown").on("show.bs.dropdown", (e) => { + aHtmlElement = e.relatedTarget; +}); + // -------------------------------------------------------------------------------------- // Scrollspy // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".navbar").scrollspy(); +// $ExpectType JQuery $(".navbar").scrollspy("refresh"); $(".navbar").scrollspy({ @@ -42,15 +62,36 @@ $(".navbar").scrollspy({ offset: 10, }); +$(".navbar").on("activate.bs.scrollspy", () => { + // do something... +}); + +// -------------------------------------------------------------------------------------- +// Togglable tabs +// -------------------------------------------------------------------------------------- + +// $ExpectType JQuery +$(".tab").tab(); + +// $ExpectType JQuery +$(".tab").tab("show"); + +$(".tab").on("shown.bs.tab", (e) => { + aHtmlElement = e.target; // newly activated tab + aHtmlElement = e.relatedTarget; // previous active tab +}); + // -------------------------------------------------------------------------------------- // Tooltip // -------------------------------------------------------------------------------------- -$("#element").tooltip(); +// $ExpectType JQuery +$(".tooltip").tooltip(); -$("#element").tooltip("show"); +// $ExpectType JQuery +$(".tooltip").tooltip("show"); -$("#element").tooltip({ +$(".tooltip").tooltip({ animation: true, container: false, delay: 0, @@ -63,26 +104,26 @@ $("#element").tooltip({ viewport: { selector: "body", padding: 0 }, }); -$("#element").tooltip({ +$(".tooltip").tooltip({ container: "body", }); -$("#element").tooltip({ +$(".tooltip").tooltip({ delay: { show: 500, hide: 100 }, }); -$("#element").tooltip({ +$(".tooltip").tooltip({ placement() { return "top"; }, }); -$("#element").tooltip({ +$(".tooltip").tooltip({ placement(tooltip: HTMLElement, trigger: Element) { console.log(this.options.delay); return "top"; }, }); -$("#element").tooltip({ +$(".tooltip").tooltip({ placement(tooltip: HTMLElement, trigger: Element) { // $ExpectError console.log(this.options.content); // only for PopoverOption, not TooltipOption @@ -90,23 +131,29 @@ $("#element").tooltip({ }, }); -$("#element").tooltip({ +$(".tooltip").tooltip({ title() { return this.id; }, }); -$("#element").tooltip({ +$(".tooltip").tooltip({ viewport: "body", }); +$(".tooltip").on("hidden.bs.tooltip", () => { + // do something... +}); + // -------------------------------------------------------------------------------------- // Popover // -------------------------------------------------------------------------------------- -$("#element").popover(); +// $ExpectType JQuery +$(".popover").popover(); -$("#element").popover("show"); +// $ExpectType JQuery +$(".popover").popover("show"); -$("#element").popover({ +$(".popover").popover({ animation: true, container: false, content: "content", @@ -120,51 +167,60 @@ $("#element").popover({ viewport: { selector: "body", padding: 0 }, }); -$("#element").popover({ +$(".popover").popover({ container: "body", }); -$("#element").popover({ +$(".popover").popover({ content() { return `Elem id: ${this.id}`; }, }); -$("#element").popover({ +$(".popover").popover({ delay: { show: 500, hide: 100 }, }); -$("#element").popover({ +$(".popover").popover({ placement() { return "top"; }, }); -$("#element").popover({ +$(".popover").popover({ placement(tooltip: HTMLElement, trigger: Element) { console.log(this.options.content); return "top"; }, }); -$("#element").popover({ +$(".popover").popover({ title() { return `Elem id: ${this.id}`; }, }); -$("#element").popover({ +$(".popover").popover({ viewport: "body", }); +$(".popover").on("hidden.bs.popover", () => { + // do something... +}); + // -------------------------------------------------------------------------------------- // Alert // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".alert").alert(); +// $ExpectType JQuery $(".alert").alert("close"); +$(".alert").on("closed.bs.alert", () => { + // do something... +}); + // -------------------------------------------------------------------------------------- // Button // -------------------------------------------------------------------------------------- -$(".btn").button(); - +// $ExpectType JQuery $(".btn").button("toggle"); $(".btn").button("reset"); @@ -175,8 +231,10 @@ $(".btn").button("Swaps text to any data defined text state."); // Collapse // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".collapse").collapse(); +// $ExpectType JQuery $(".collapse").collapse("toggle"); $(".collapse").collapse({ @@ -184,12 +242,18 @@ $(".collapse").collapse({ toggle: false, }); +$(".collapse").on("hidden.bs.collapse", () => { + // do something... +}); + // -------------------------------------------------------------------------------------- // Carousel // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".carousel").carousel(); +// $ExpectType JQuery $(".carousel").carousel("cycle"); $(".carousel").carousel(200); @@ -209,12 +273,19 @@ $(".carousel").carousel({ pause: null, }); +$("#myCarousel").on("slide.bs.carousel", (e) => { + const dir: "left" | "right" = e.direction; + aHtmlElement = e.relatedTarget; +}); + // -------------------------------------------------------------------------------------- // Affix // -------------------------------------------------------------------------------------- +// $ExpectType JQuery $(".affix").affix(); +// $ExpectType JQuery $(".affix").affix("checkPosition"); $(".affix").affix({ diff --git a/types/bootstrap/v3/index.d.ts b/types/bootstrap/v3/index.d.ts index a6ddbeb1f8..d3b80a0529 100644 --- a/types/bootstrap/v3/index.d.ts +++ b/types/bootstrap/v3/index.d.ts @@ -7,6 +7,16 @@ /// +// -------------------------------------------------------------------------- +// For jQuery v1 and v2 backward compatibility +// -------------------------------------------------------------------------- + +/** + * Same as jQuery v3 `JQuery.EventHandlerBase`. + */ +type JQueryEventHandlerBase = + (this: TContext, t: T, ...args: any[]) => void | false; + // -------------------------------------------------------------------------- // Some Types and Interfaces // -------------------------------------------------------------------------- @@ -43,86 +53,431 @@ interface TooltipInstance { // -------------------------------------------------------------------------------------- interface ModalOptions { + /** + * Includes a modal-backdrop element. + * Alternatively, specify `static` for a backdrop which doesn't close the modal on click. + * + * @default true + */ backdrop?: boolean | "static"; + + /** + * Closes the modal when escape key is pressed. + * + * @default true + */ keyboard?: boolean; + + /** + * Shows the modal when initialized. + * + * @default true + */ show?: boolean; + + /** + * If a remote URL is provided, **content will be loaded one time** via jQuery's `load` method and injected into the `.modal-content` div. + * + * @default false + * @deprecated Use client-side templating or a data binding framework instead, or call `jQuery.load` yourself. + */ remote?: string; } interface ScrollSpyOptions { + /** + * Pixels to offset from top when calculating position of scroll. + * + * @default 10 + */ offset?: number; + + /** + * The ID or class of the parent element of any Bootstrap `.nav` component. + * + * @default "" + */ target?: string; } interface TooltipOptions { + /** + * Apply a CSS fade transition to the tooltip or popover. + * + * @default true + */ animation?: boolean; + + /** + * Appends the tooltip or popover to a specific element. Example: `container: 'body'`. + * This option is particularly useful in that it allows you to position the tooltip or popover + * in the flow of the document near the triggering element - which will prevent + * it from floating away from the triggering element during a window resize. + * + * @default false + */ container?: string | false; + + /** + * Delay showing and hiding the tooltip or popover (ms) - does not apply to manual trigger type. + * If a number is supplied, delay is applied to both hide/show. + * Object structure is: `delay: { "show": 500, "hide": 100 }`. + * + * @default 0 + */ delay?: number | BootstrapDelay; + + /** + * Insert HTML into the tooltip or popover. If false, jQuery's text method will be used to insert content into the DOM. + * Use text if you're worried about XSS attacks. + * + * @default false + */ html?: boolean; + + /** + * How to position the tooltip or popover - top | bottom | left | right | auto. + * When "auto" is specified, it will dynamically reorient the tooltip or popover. + * For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right. + * + * When a function is used to determine the placement, it is called with + * the tooltip or popover DOM node as its first argument and the triggering element DOM node as its second. + * The `this` context is set to the tooltip or popover instance. + * + * @default tooltip: "top", popover: "right" + */ placement?: BootstrapPlacement | ((this: TooltipInstance, tooltip: HTMLElement, trigger: Element) => BootstrapPlacement); + + /** + * If a selector is provided, tooltip or popover objects will be delegated to the specified targets. + * In practice, this is used to enable dynamic HTML content to have popovers added. + * + * @default false + */ selector?: string; + + /** + * Base HTML to use when creating the tooltip or popover. + * The tooltip's (resp., popover's) title will be injected into the `.tooltip-inner` (resp., `.popover-title`). + * The popover's content will be injected into the `.popover-content`. + * The `.tooltip-arrow` (resp., `.arrow`) will become the tooltip's (resp., popover's) arrow. + * The outermost wrapper element should have the `.tooltip` (resp., `.popover`) class. + * + * @default '' + * @default '' + */ template?: string; + + /** + * Default title value if title attribute isn't present. + * If a function is given, it will be called with its `this` reference set to the element + * that the tooltip or popover is attached to. + * + * @default "" + */ title?: string | ((this: Element) => string); + + /** + * How tooltip or popover is triggered - click | hover | focus | manual. You may pass multiple triggers; separate them with a space. + * "manual" cannot be combined with any other trigger. + * + * @default tooltip: "hover focus", popover: "click" + */ trigger?: BootstrapTrigger; + + /** + * Keeps the tooltip within the bounds of this element. Example: viewport: `#viewport` or `{"selector": "#viewport", "padding": 0}`. + * If a function is given in the object, it is called with the triggering element DOM node as its only argument. + * The `this` context is set to the tooltip instance. + * + * @default {selector: 'body', padding: 0} + */ viewport?: string | BootstrapViewport; } interface PopoverOptions extends TooltipOptions { + /** + * Default content value if `data-content` attribute isn't present. + * If a function is given, it will be called with its `this` reference + * set to the element that the popover is attached to. + * + * @default "" + */ content?: string | ((this: Element) => string); } interface CollapseOptions { + /** + * If a selector is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown. + * + * @default false + */ parent?: string | false; + + /** + * Toggles the collapsible element on invocation. + * + * @default true + */ toggle?: boolean; } interface CarouselOptions { + /** + * The amount of time to delay between automatically cycling an item. If false, carousel will not automatically cycle. + * + * @default 5000 + */ interval?: number | false; + + /** + * If set to "hover", pauses the cycling of the carousel on `mouseenter` and resumes the cycling of the carousel on `mouseleave`. + * If set to null, hovering over the carousel won't pause it. + * + * @default "hover" + */ pause?: "hover" | null; + + /** + * Whether the carousel should cycle continuously or have hard stops. + * + * @default true + */ wrap?: boolean; + + /** + * Whether the carousel should react to keyboard events. + * + * @default true + */ keyboard?: boolean; } interface AffixOptions { + /** + * Pixels to offset from screen when calculating position of scroll. If a single number is provided, the offset will be applied in both top and bottom directions. + * To provide a unique, bottom and top offset just provide an object offset: `{top: 7, bottom: 5}`. + * Use a function in the object when you need to dynamically calculate an offset. + * + * @default 10 + */ offset?: number | BootstrapOffset; + + /** + * Specifies the target element of the affix. + * + * @default window + */ target?: string | Node | JQuery | Window; } +// -------------------------------------------------------------------------------------- +// Events +// -------------------------------------------------------------------------------------- + +interface CarouselEventHandler extends JQueryEventObject { + /** + * The direction in which the carousel is sliding. + */ + direction: "left" | "right"; + + /** + * The DOM element that is being slid into place as the active item. + */ + relatedTarget: HTMLElement; +} + +interface DropdownsEventHandler extends JQueryEventObject { + /** + * The toggling anchor element. + */ + relatedTarget: HTMLElement; +} + +interface TapEventHandler extends JQueryEventObject { + /** + * * For `show.bs.tab` and `shown.bs.tab`, is the new active tab. + * * For `hide.bs.tab`, is the current active tab. + * * For `hidden.bs.tab`, is the previous active tab. + */ + target: HTMLElement; // overridden only for better JsDoc + + /** + * * For `show.bs.tab` and `shown.bs.tab`, is the previous active tab, if available. + * * For `hide.bs.tab`, is the new soon-to-be-active tab. + * * For `hidden.bs.tab`, is the new active tab. + */ + relatedTarget: HTMLElement; +} + +type AffixEvent = "affix.bs.affix" | "affixed.bs.affix" | "affix-top.bs.affix" | "affixed-top.bs.affix" | "affix-bottom.bs.affix" | "affixed-bottom.bs.affix"; +type AlertEvent = "close.bs.alert" | "closed.bs.alert"; +type CarouselEvent = "slide.bs.carousel" | "slid.bs.carousel"; +type CollapseEvent = "show.bs.collapse" | "shown.bs.collapse" | "hide.bs.collapse" | "hidden.bs.collapse"; +type DropdownEvent = "show.bs.dropdown" | "shown.bs.dropdown" | "hide.bs.dropdown" | "hidden.bs.dropdown"; +type PopoverEvent = "show.bs.popover" | "shown.bs.popover" | "hide.bs.popover" | "hidden.bs.popover" | "inserted.bs.popover"; +type ScrollspyEvent = "activate.bs.scrollspy"; +type TapEvent = "show.bs.tab" | "shown.bs.tab" | "hide.bs.tab" | "hidden.bs.tab"; +type TooltipEvent = "show.bs.tooltip" | "shown.bs.tooltip" | "hide.bs.tooltip" | "hidden.bs.tooltip" | "inserted.bs.tooltip"; + // -------------------------------------------------------------------------------------- // jQuery // -------------------------------------------------------------------------------------- -interface JQuery { - modal(action?: "toggle" | "show" | "hide" | "handleUpdate"): JQuery; - modal(options: ModalOptions): JQuery; +interface JQuery { + /** + * Call a method on the modal element: + * * `toggle` – Manually toggles a modal. + * * `show` – Manually opens a modal. + * * `hide` – Manually hides a modal. + * * `handleUpdate` – Readjusts the modal's positioning to counter a scrollbar in case one should appear, which would make the modal jump to the left. + * Only needed when the height of the modal changes while it is open. + * + * Returns to the caller before the modal has actually been shown or hidden (i.e. before the `shown.bs.modal` or `hidden.bs.modal` event occurs). + */ + modal(action: "toggle" | "show" | "hide" | "handleUpdate"): this; + /** + * Activates a content as a modal. + */ + modal(options?: ModalOptions): this; - dropdown(action?: "toggle"): JQuery; + /** + * If no _method_ is specified, toggle contextual overlays for displaying lists of links. + * The data-api, `data-toggle="dropdown"` is always required to be present on the dropdown's trigger element. + * + * When _method_ `toggle` is specified, toggles the dropdown menu of a given navbar or tabbed navigation. + */ + dropdown(action?: "toggle"): this; - scrollspy(action?: "refresh"): JQuery; - scrollspy(options: ScrollSpyOptions): JQuery; +// tslint:disable:jsdoc-format + /** + * When using scrollspy in conjunction with adding or removing of elements from the DOM, you'll need to call the refresh, see example. + * @example +```javascript +$('[data-spy="scroll"]').each(function () { + var $spy = $(this).scrollspy('refresh') +}) +``` + */ +// tslint:enable:jsdoc-format + scrollspy(action: "refresh"): this; + /** + * Add scrollspy behavior to a topbar navigation. + */ + scrollspy(options?: ScrollSpyOptions): this; - tab(action?: "show"): JQuery; + /** + * If no _method_ is specified, activates a tab element and content container. Tab should have either a `data-target` or an `href` targeting a container node in the DOM. + * + * When _method_ `show` is specified, selects the given tab and shows its associated content. + * Any other tab that was previously selected becomes unselected and its associated content is hidden. + * + * Returns to the caller before the tab pane has actually been shown (i.e. before the `shown.bs.tab` event occurs). + */ + tab(action?: "show"): this; - tooltip(action?: "show" | "hide" | "toggle" | "destroy"): JQuery; - tooltip(options: TooltipOptions): JQuery; + /** + * Call a method on the tooltip element: + * * `show` – Reveals an element's tooltip. Tooltips with zero-length titles are never displayed. + * * `hide` – Hides an element's tooltip. + * * `toggle` – Toggles an element's tooltip. + * * `destroy` – Hides and destroys an element's tooltip. + * Tooltips that use delegation (which are created using `selector` option) cannot be individually destroyed on descendant trigger elements. + * + * Returns to the caller before the tooltip has actually been shown or hidden (i.e. before the `shown.bs.tooltip` or `hidden.bs.tooltip` event occurs). + * This is considered a "manual" triggering of the tooltip. + */ + tooltip(action: "show" | "hide" | "toggle" | "destroy"): this; + /** + * Attaches a tooltip handler to an element collection. + */ + tooltip(options?: TooltipOptions): this; - popover(action?: "show" | "hide" | "toggle" | "destroy"): JQuery; - popover(options: PopoverOptions): JQuery; + /** + * Call a method on the popover element: + * * `show` – Reveals an element's popover. Popovers whose both title and content are zero-length are never displayed. + * * `hide` – Hides an element's popover. + * * `toggle` – Toggles an element's popover. + * * `destroy` – Hides and destroys an element's popover. + * Popovers that use delegation (which are created using the `selector` option) cannot be individually destroyed on descendant trigger elements. + * + * Returns to the caller before the popover has actually been shown or hidden (i.e. before the `shown.bs.popover` or `hidden.bs.popover` event occurs). + * This is considered a "manual" triggering of the popover. + */ + popover(action: "show" | "hide" | "toggle" | "destroy"): this; + /** + * Initializes popovers for an element collection. + */ + popover(options?: PopoverOptions): this; - alert(action?: "close"): JQuery; + /** + * If no _method_ is specified, makes an alert listen for click events on descendant elements which have the `data-dismiss="alert"` attribute. + * (Not necessary when using the data-api's auto-initialization.) + * + * When _method_ `close` is specified, closes an alert by removing it from the DOM. If the `.fade` and `.in` classes are present on the element, + * the alert will fade out before it is removed. + */ + alert(action?: "close"): this; - button(action?: "toggle" | "reset" | string): JQuery; + /** + * Call a method on the button element: + * * `toggle` – Toggles push state. Gives the button the appearance that it has been activated. + * * `reset` – Resets button state: swaps text to original text. This method is asynchronous and returns before the resetting has actually completed. + * * _string_ – Swaps text to any data defined text state. + */ + button(action: "toggle" | "reset" | string): this; - collapse(action?: "toggle" | "show" | "hide"): JQuery; - collapse(options: CollapseOptions): JQuery; + /** + * Call a method on the collapsible element: + * * `toggle` – Toggles a collapsible element to shown or hidden. + * * `show` – Shows a collapsible element. + * * `hide` – Hides a collapsible element. + * + * Returns to the caller before the collapsible element has actually been shown or hidden (i.e. before the `shown.bs.collapse` or `hidden.bs.collapse` event occurs). + */ + collapse(action: "toggle" | "show" | "hide"): this; + /** + * Activates a content as a collapsible element. + */ + collapse(options?: CollapseOptions): this; - carousel(action?: "cycle" | "pause" | number | "prev" | "next"): JQuery; - carousel(options: CarouselOptions): JQuery; + /** + * Call a method on the carousel element: + * * `cycle` – Cycles through the carousel items from left to right. + * * `pause` – Stops the carousel from cycling through items. + * * _number_ – Cycles the carousel to a particular frame (0 based, similar to an array). + * * `prev` – Cycles to the previous item. + * * `next` – Cycles to the next item. + * + * Returns to the caller before the target item has been shown (i.e. before the `slid.bs.carousel` event occurs). + */ + carousel(action: "cycle" | "pause" | number | "prev" | "next"): this; + /** + * Initializes the carousel and starts cycling through items. + */ + carousel(options?: CarouselOptions): this; - affix(action?: "checkPosition"): JQuery; - affix(options: AffixOptions): JQuery; + /** + * Recalculates the state of the affix based on the dimensions, position, and scroll position of the relevant elements. + * The `.affix`, `.affix-top`, and `.affix-bottom` classes are added to or removed from the affixed content according to the new state. + * This method needs to be called whenever the dimensions of the affixed content or the target element are changed, to ensure correct positioning of the affixed content. + */ + affix(action: "checkPosition"): this; + /** + * Activates your content as affixed content. + */ + affix(options?: AffixOptions): this; - emulateTransitionEnd(duration: number): JQuery; + on(events: CarouselEvent, handler: JQueryEventHandlerBase): this; + on(events: DropdownEvent, handler: JQueryEventHandlerBase): this; + on(events: TapEvent, handler: JQueryEventHandlerBase): this; + on( + events: AffixEvent | AlertEvent | CollapseEvent | PopoverEvent | ScrollspyEvent | TooltipEvent, + handler: JQueryEventHandlerBase + ): this; + + /** @deprecated */ + emulateTransitionEnd(duration: number): this; } // -------------------------------------------------------------------------------------- diff --git a/types/browserslist-useragent/browserslist-useragent-tests.ts b/types/browserslist-useragent/browserslist-useragent-tests.ts new file mode 100644 index 0000000000..83103178e5 --- /dev/null +++ b/types/browserslist-useragent/browserslist-useragent-tests.ts @@ -0,0 +1,30 @@ +import { + matchesUA, + resolveUserAgent, + normalizeQuery +} from 'browserslist-useragent'; + +// $ExpectType boolean +matchesUA( + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' +); + +// $ExpectType boolean +matchesUA( + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', + { + browsers: ['defaults'], + env: 'production', + ignorePath: true, + ignoreMinor: false, + allowHigherVersions: false + } +); + +// $ExpectType ResolvedUserAgent +resolveUserAgent( + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' +); + +// $ExpectType string +normalizeQuery('defaults'); diff --git a/types/browserslist-useragent/index.d.ts b/types/browserslist-useragent/index.d.ts new file mode 100644 index 0000000000..4c7e548a4a --- /dev/null +++ b/types/browserslist-useragent/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for browserslist-useragent 3.0 +// Project: https://github.com/browserslist/browserslist-useragent (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: nju33 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ResolvedUserAgent { + family: string; + version: string; +} + +export interface BrowserslistUseragentOptions { + browsers?: string[]; + env?: string; + ignorePath?: boolean; + ignoreMinor?: boolean; + allowHigherVersions?: boolean; +} + +export function matchesUA( + uaString: string, + opts?: BrowserslistUseragentOptions +): boolean; +export function resolveUserAgent(uaString: string): ResolvedUserAgent; +export function normalizeQuery(query: string): string; diff --git a/types/browserslist-useragent/tsconfig.json b/types/browserslist-useragent/tsconfig.json new file mode 100644 index 0000000000..849531b901 --- /dev/null +++ b/types/browserslist-useragent/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": ["index.d.ts", "browserslist-useragent-tests.ts"] +} diff --git a/types/browserslist-useragent/tslint.json b/types/browserslist-useragent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/browserslist-useragent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/btoa/btoa-tests.ts b/types/btoa/btoa-tests.ts index d09cdad23a..7ce230fcf7 100644 --- a/types/btoa/btoa-tests.ts +++ b/types/btoa/btoa-tests.ts @@ -1,3 +1,3 @@ -import btoa from 'btoa'; +import btoa = require('btoa'); btoa('foo'); diff --git a/types/btoa/index.d.ts b/types/btoa/index.d.ts index cc311ed836..bdb02b5b59 100644 --- a/types/btoa/index.d.ts +++ b/types/btoa/index.d.ts @@ -1,7 +1,10 @@ // Type definitions for btoa 1.2 // Project: https://git.coolaj86.com/coolaj86/btoa.js // Definitions by: John Wright +// Alex Brick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -export default function(str: string): string; +declare function btoa(str: string): string; + +export = btoa; diff --git a/types/buble/buble-tests.ts b/types/buble/buble-tests.ts new file mode 100644 index 0000000000..cebb373415 --- /dev/null +++ b/types/buble/buble-tests.ts @@ -0,0 +1,77 @@ +import * as buble from 'buble'; + +const input = 'const answer = () => 42;'; + +// Simple transform +(() => { + const output = buble.transform(input); + + console.log(output.code); + console.log(output.map.toString()); + console.log(output.map.toUrl()); +})(); + +// Transform for Chrome & Firefox +(() => { + const output = buble.transform(input, { + target: { + chrome: 71, + firefox: 64, + }, + }); +})(); + +// Transform with sourcemaps support +(() => { + const output = buble.transform(input, { + source: 'input.js', + file: 'output.js', + includeContent: true, + }); +})(); + +// Transform for Preact +(() => { + const output = buble.transform(input, { + jsx: 'h' + }); +})(); + +// Transform with Object assign/spread support +(() => { + let output = buble.transform(input, { + objectAssign: true, + }); + output = buble.transform(input, { + objectAssign: 'MyCustomObjectAssign', + }); +})(); + +// Transform with every transforms +(() => { + const output = buble.transform(input, { + transforms: { + arrow: true, + classes: false, + collections: true, + computedProperty: false, + conciseMethodProperty: true, + constLoop: false, + dangerousForOf: true, + dangerousTaggedTemplateString: false, + defaultParameter: true, + destructuring: false, + forOf: true, + generator: false, + letConst: true, + modules: false, + numericLiteral: true, + parameterDestructuring: false, + reservedProperties: true, + spreadRest: false, + stickyRegExp: true, + templateString: false, + unicodeRegExp: true, + } + }); +})(); diff --git a/types/buble/index.d.ts b/types/buble/index.d.ts new file mode 100644 index 0000000000..db3cb0a7b7 --- /dev/null +++ b/types/buble/index.d.ts @@ -0,0 +1,65 @@ +// Type definitions for buble 0.19 +// Project: https://github.com/Rich-Harris/buble#README +// Definitions by: Hugo Alliaume +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { SourceMap } from "magic-string"; + +export interface TransformOptions { + // source: https://github.com/Rich-Harris/buble/blob/master/src/support.js + target?: { + chrome?: 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71; + firefox?: 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64; + safari?: 8 | 9 | 10 | 10.1 | 11 | 11.1 | 12; + ie?: 8 | 9 | 10 | 11; + edge?: 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19; + node?: 0.10 | 0.12 | 4 | 5 | 6 | 8 | 8.3 | 8.7 | 8.10; + }; + + // used for sourcemaps + source?: string; // input + file?: string; // output + includeContent?: boolean; + + // custom JSX pragma (https://buble.surge.sh/guide/#jsx) + jsx?: string; // default: 'React.createElement' + + // custom `Object.assign` (https://buble.surge.sh/guide/#object-spread-and-rest) + objectAssign?: string | boolean; + + // transforms + transforms?: { + arrow?: boolean; + classes?: boolean; + collections?: boolean; + computedProperty?: boolean; + conciseMethodProperty?: boolean; + constLoop?: boolean; + dangerousForOf?: boolean; + dangerousTaggedTemplateString?: boolean; + defaultParameter?: boolean; + destructuring?: boolean; + forOf?: boolean; + generator?: boolean; + letConst?: boolean; + modules?: boolean; + numericLiteral?: boolean; + parameterDestructuring?: boolean; + reservedProperties?: boolean; + spreadRest?: boolean; + stickyRegExp?: boolean; + templateString?: boolean; + unicodeRegExp?: boolean; + }; + + // others + namedFunctionExpressions?: boolean; +} + +export interface TransformOutput { + code: string; + map: SourceMap; +} + +export function transform(content: string, options?: TransformOptions): TransformOutput; diff --git a/types/universal-router/package.json b/types/buble/package.json similarity index 60% rename from types/universal-router/package.json rename to types/buble/package.json index 0ab257c45a..d2f8119c0a 100644 --- a/types/universal-router/package.json +++ b/types/buble/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "path-to-regexp": "^2.2.0" + "magic-string": "^0.25.0" } } diff --git a/types/buble/tsconfig.json b/types/buble/tsconfig.json new file mode 100644 index 0000000000..0196ebd845 --- /dev/null +++ b/types/buble/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", + "buble-tests.ts" + ] +} diff --git a/types/buble/tslint.json b/types/buble/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/buble/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/build-output-script/build-output-script-tests.ts b/types/build-output-script/build-output-script-tests.ts new file mode 100644 index 0000000000..719c6301d5 --- /dev/null +++ b/types/build-output-script/build-output-script-tests.ts @@ -0,0 +1,11 @@ +import buildOutputScript = require('build-output-script'); + +// $ExpectType string +buildOutputScript([{ address: '1LukeQU5jwebXbMLDVydeH4vFSobRV9rkj', value: 100000000 }]); +// $ExpectType string +buildOutputScript([ + { address: '1LukeQU5jwebXbMLDVydeH4vFSobRV9rkj', value: 100000000 }, + { address: '1BitcoinEaterAddressDontSendf59kuE', value: 100000000 }, +]); +// $ExpectError +buildOutputScript([]); diff --git a/types/build-output-script/index.d.ts b/types/build-output-script/index.d.ts new file mode 100644 index 0000000000..5c90083e34 --- /dev/null +++ b/types/build-output-script/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for build-output-script 1.0 +// Project: https://github.com/lukechilds/build-output-script#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +export = buildOutputScript; + +/** + * Builds a P2PKH Bitcoin transaction output script from an array of P2PKH addresses and amounts. + * Will also work with any Bitcoin derived cryptocurrencies with a single byte pubkey hash address prefix. + * + * The output script is returned as a hex string and can be passed directly in to ledgerjs. + * + * @param outputs An array of one or more output objects. + * @returns A (hex string) P2PKH transaction output script. + */ +declare function buildOutputScript( + outputs: [buildOutputScript.Output, ...buildOutputScript.Output[]] +): string; + +declare namespace buildOutputScript { + interface Output { + /** + * A valid P2PKH address. + */ + address: string; + /** + * Value to send to `address` in satoshis. + */ + value: number; + } +} diff --git a/types/build-output-script/tsconfig.json b/types/build-output-script/tsconfig.json new file mode 100644 index 0000000000..1fc0da7de0 --- /dev/null +++ b/types/build-output-script/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "build-output-script-tests.ts" + ] +} diff --git a/types/build-output-script/tslint.json b/types/build-output-script/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/build-output-script/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 2419afee8f..bbafa0301c 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -36,6 +36,8 @@ declare namespace Bull { max: number; /** Per duration in milliseconds */ duration: number; + /** When jobs get rate limited, they stay in the waiting queue and are not moved to the delayed queue */ + bounceBack?: boolean; } interface QueueOptions { @@ -68,6 +70,11 @@ declare namespace Bull { */ lockDuration?: number; + /** + * Interval in milliseconds on which to acquire the job lock. + */ + lockRenewTime?: number; + /** * How often check for stalled jobs (use 0 for never checking) */ @@ -129,6 +136,25 @@ declare namespace Bull { */ finishedOn?: number; + /** + * Which queue this job was part of + */ + queue: Queue; + + timestamp: number; + + /** + * The named processor name + */ + name: string; + + /** + * The stacktrace for any errors + */ + stacktrace: string[]; + + returnvalue: any; + /** * Report progress on a job */ @@ -340,6 +366,11 @@ declare namespace Bull { } interface Queue { + /** + * The name of the queue + */ + name: string; + /** * Returns a promise that resolves when Redis is connected and the queue is ready to accept jobs. * This replaces the `ready` event emitted on Queue in previous verisons. @@ -554,6 +585,11 @@ declare namespace Bull { */ getJobCounts(): Promise; + /** + * Returns a promise that resolves with the job counts for the given queue of the given types. + */ + getJobCountByTypes(types: string[] | string): Promise; + /** * Returns a promise that resolves with the quantity of completed jobs. */ diff --git a/types/byte-range/byte-range-tests.ts b/types/byte-range/byte-range-tests.ts new file mode 100644 index 0000000000..150d6b0fc2 --- /dev/null +++ b/types/byte-range/byte-range-tests.ts @@ -0,0 +1,10 @@ +import byteRange = require('byte-range'); + +byteRange(1); // $ExpectType [number, number] +byteRange(1, { signed: false }); // $ExpectType [number, number] +byteRange.uint8; // $ExpectType [number, number] +byteRange.uint16; // $ExpectType [number, number] +byteRange.uint32; // $ExpectType [number, number] +byteRange.int8; // $ExpectType [number, number] +byteRange.int16; // $ExpectType [number, number] +byteRange.int32; // $ExpectType [number, number] diff --git a/types/byte-range/index.d.ts b/types/byte-range/index.d.ts new file mode 100644 index 0000000000..120889ad90 --- /dev/null +++ b/types/byte-range/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for byte-range 1.0 +// Project: https://github.com/lukechilds/byte-range#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = byteRange; + +/** + * Calculates integer ranges for a given number of bytes. + * + * @param bytes Number of bytes to return the integer range for. Must be a positive integer. + */ +declare function byteRange(bytes: number, options?: byteRange.Options): byteRange.ByteRange; + +declare namespace byteRange { + /** + * Precomputed byte range for an unsigned 8 bit integer. + */ + const uint8: ByteRange; + /** + * Precomputed byte range for an unsigned 16 bit integer. + */ + const uint16: ByteRange; + /** + * Precomputed byte range for an unsigned 32 bit integer. + */ + const uint32: ByteRange; + /** + * Precomputed byte range for an signed 8 bit integer. + */ + const int8: ByteRange; + /** + * Precomputed byte range for an signed 16 bit integer. + */ + const int16: ByteRange; + /** + * Precomputed byte range for an signed 32 bit integer. + */ + const int32: ByteRange; + + interface Options { + /** + * @default false + */ + signed?: boolean; + } + + type ByteRange = [number, number]; +} diff --git a/types/byte-range/tsconfig.json b/types/byte-range/tsconfig.json new file mode 100644 index 0000000000..13d4b78f5d --- /dev/null +++ b/types/byte-range/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", + "byte-range-tests.ts" + ] +} diff --git a/types/byte-range/tslint.json b/types/byte-range/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/byte-range/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bytebuffer/index.d.ts b/types/bytebuffer/index.d.ts index bafed6edf8..eaa1a509d5 100644 --- a/types/bytebuffer/index.d.ts +++ b/types/bytebuffer/index.d.ts @@ -127,7 +127,7 @@ declare class ByteBuffer * Calculates the number of UTF8 characters of a string.JavaScript itself uses UTF- 16, so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF. */ static calculateUTF8Chars( str: string ): number; - + /** * Calculates the number of UTF8 bytes of a string. This is an alias of ByteBuffer#calculateUTF8Bytes. */ @@ -574,6 +574,11 @@ declare class ByteBuffer */ writeInt8( value: number, offset?: number ): ByteBuffer; + /** + * Write a 64bit signed integer. This is an alias of ByteBuffer#writeInt64. + */ + writeLong( value: number | Long, offset?: number ): ByteBuffer; + /** * Writes a 16bit signed integer. This is an alias of ByteBuffer#writeInt16. */ diff --git a/types/cacheable-request/cacheable-request-tests.ts b/types/cacheable-request/cacheable-request-tests.ts new file mode 100644 index 0000000000..95458c14b7 --- /dev/null +++ b/types/cacheable-request/cacheable-request-tests.ts @@ -0,0 +1,28 @@ +import * as http from 'http'; +import * as https from 'https'; +import CacheableRequest = require('cacheable-request'); +import QuickLRU = require('quick-lru'); + +// You can do +let cacheableRequest = new CacheableRequest(http.request); +const cacheReq = cacheableRequest('http://example.com', res => { + res; // $ExpectType ServerResponse | ResponseLike +}); +cacheReq.on('request', req => req.end()); + +cacheableRequest = new CacheableRequest(https.request); + +cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379'); +cacheableRequest = new CacheableRequest(http.request, new Map()); +cacheableRequest = new CacheableRequest(http.request, new QuickLRU({ maxSize: 1000 })); + +cacheableRequest('example.com', res => { + res; // $ExpectType ServerResponse | ResponseLike +}) + .on('error', err => { + err; // $ExpectType RequestErrorCls | CacheErrorCls + }) + .on('request', req => { + req.on('error', () => {}); + req.end(); + }); diff --git a/types/cacheable-request/index.d.ts b/types/cacheable-request/index.d.ts new file mode 100644 index 0000000000..98d858d3f6 --- /dev/null +++ b/types/cacheable-request/index.d.ts @@ -0,0 +1,134 @@ +// Type definitions for cacheable-request 6.0 +// Project: https://github.com/lukechilds/cacheable-request#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { request, RequestOptions, ClientRequest, ServerResponse } from 'http'; +import { URL } from 'url'; +import { EventEmitter } from 'events'; +import { Store } from 'keyv'; +import { Options as CacheSemanticsOptions } from 'http-cache-semantics'; +import ResponseLike = require('responselike'); + +export = CacheableRequest; + +declare const CacheableRequest: CacheableRequest; + +type RequestFn = typeof request; + +interface CacheableRequest { + new (requestFn: RequestFn, storageAdapter?: string | Store): ( + opts: string | URL | (RequestOptions & CacheSemanticsOptions), + cb?: (response: ServerResponse | ResponseLike) => void + ) => CacheableRequest.Emitter; + + RequestError: typeof RequestErrorCls; + CacheError: typeof CacheErrorCls; +} + +declare namespace CacheableRequest { + interface Options { + /** + * If the cache should be used. Setting this to `false` will completely bypass the cache for the current request. + * @default true + */ + cache?: boolean; + + /** + * If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. + * + * If set to `false`, after a cached resource's TTL expires it is kept in the cache and will be revalidated + * on the next request with `If-None-Match`/`If-Modified-Since` headers. + * @default false + */ + strictTtl?: boolean; + + /** + * Limits TTL. The `number` represents milliseconds. + * @default undefined + */ + maxTtl?: number; + + /** + * When set to `true`, if the DB connection fails we will automatically fallback to a network request. + * DB errors will still be emitted to notify you of the problem even though the request callback may succeed. + * @default false + */ + automaticFailover?: boolean; + + /** + * Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a + * new request and override the cache instead. + * @default false + */ + forceRefresh?: boolean; + } + + interface Emitter extends EventEmitter { + addListener(event: 'request', listener: (request: ClientRequest) => void): this; + addListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + addListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + on(event: 'request', listener: (request: ClientRequest) => void): this; + on(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + on(event: 'error', listener: (error: RequestError | CacheError) => void): this; + once(event: 'request', listener: (request: ClientRequest) => void): this; + once(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + once(event: 'error', listener: (error: RequestError | CacheError) => void): this; + prependListener(event: 'request', listener: (request: ClientRequest) => void): this; + prependListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + prependListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + prependOnceListener(event: 'request', listener: (request: ClientRequest) => void): this; + prependOnceListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + prependOnceListener( + event: 'error', + listener: (error: RequestError | CacheError) => void + ): this; + removeListener(event: 'request', listener: (request: ClientRequest) => void): this; + removeListener( + event: 'response', + listener: (response: ServerResponse | ResponseLike) => void + ): this; + removeListener(event: 'error', listener: (error: RequestError | CacheError) => void): this; + off(event: 'request', listener: (request: ClientRequest) => void): this; + off(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this; + off(event: 'error', listener: (error: RequestError | CacheError) => void): this; + removeAllListeners(event?: 'request' | 'response' | 'error'): this; + listeners(event: 'request'): Array<(request: ClientRequest) => void>; + listeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>; + listeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; + rawListeners(event: 'request'): Array<(request: ClientRequest) => void>; + rawListeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>; + rawListeners(event: 'error'): Array<(error: RequestError | CacheError) => void>; + emit(event: 'request', request: ClientRequest): boolean; + emit(event: 'response', response: ServerResponse | ResponseLike): boolean; + emit(event: 'error', error: RequestError | CacheError): boolean; + eventNames(): Array<'request' | 'response' | 'error'>; + listenerCount(type: 'request' | 'response' | 'error'): number; + } + + type RequestError = RequestErrorCls; + type CacheError = CacheErrorCls; +} + +declare class RequestErrorCls extends Error { + readonly name: 'RequestError'; + + constructor(error: Error); +} +declare class CacheErrorCls extends Error { + readonly name: 'CacheError'; + + constructor(error: Error); +} diff --git a/types/cacheable-request/tsconfig.json b/types/cacheable-request/tsconfig.json new file mode 100644 index 0000000000..635a5b1689 --- /dev/null +++ b/types/cacheable-request/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", + "cacheable-request-tests.ts" + ] +} diff --git a/types/cacheable-request/tslint.json b/types/cacheable-request/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cacheable-request/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cadesplugin/index.d.ts b/types/cadesplugin/index.d.ts new file mode 100644 index 0000000000..6b93a9514d --- /dev/null +++ b/types/cadesplugin/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for cadesplugin 2.1 +// Project: https://www.npmjs.com/package/cadesplugin +// Definitions by: Delagen , +// kvmi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +declare const cadesplugin: any; diff --git a/types/cadesplugin/package.json b/types/cadesplugin/package.json new file mode 100644 index 0000000000..bb80441dc0 --- /dev/null +++ b/types/cadesplugin/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] } + } +} diff --git a/types/cadesplugin/ts3.1/cadescom.d.ts b/types/cadesplugin/ts3.1/cadescom.d.ts new file mode 100644 index 0000000000..a721b54d97 --- /dev/null +++ b/types/cadesplugin/ts3.1/cadescom.d.ts @@ -0,0 +1,97 @@ +declare namespace CAdESCOM { + interface CPSigner { + Certificate: CAPICOM.Certificate; + CheckCertificate: boolean; + + KeyPin: string; + Options: CADES_Common.ValuesOf; + readonly SignatureTimeStampTime: CADES_Common.VarDate; + readonly SigningTime: CADES_Common.VarDate; + TSAAddress: string; + + Display(hwndParent?: number, title?: string): void; + + Load(fileName: string, password?: string): void; + } + + interface CadesSignedData { + readonly Certificates: CAPICOM.Certificates; + Content: string; + ContentEncoding: CADES_Common.ValuesOf; + + DisplayData: CADES_Common.ValuesOf; + + Display(hwndParent?: number, title?: string): void; + + EnhanceCades(cadesType?: CADES_Common.ValuesOf, TSAAddress?: string, encodingType?: CADES_Common.ValuesOf): string; + + SignCades(signer?: CPSigner, CadesType?: CADES_Common.ValuesOf, bDetached?: boolean, EncodingType?: CADES_Common.ValuesOf): string; + + VerifyCades(SignedMessage: string, CadesType?: CADES_Common.ValuesOf, bDetached?: boolean): void; + } + + interface Version { + readonly BuildVersion: number; + readonly MajorVersion: number; + readonly MinorVersion: number; + readonly toStringDefault: string; + + toString(): string; + } + + interface About { + readonly BuildVersion: number; + readonly MajorVersion: number; + readonly MinorVersion: number; + readonly PluginVersion: Version; + readonly Version: string; + + CSPName(ProviderType?: number): string; + + CSPVersion(ProviderName?: string, ProviderType?: number): Version; + + ProviderVersion(ProviderName?: string, ProviderType?: number): string; + + toString(): string; + } + + interface CPSigners { + readonly Count: number; + + Item(index: number): CPSigner; + } + + interface SignedXML { + Content: string; + DigestMethod: string; + SignatureMethod: string; + SignatureType: CADES_Common.ValuesOf; + readonly Signers: CAPICOM.Signers; + + Sign(signer?: CPSigner, XPath?: string): string; + + Verify(SignedMessage: string, XPath?: string): void; + } + + interface CPHashedData { + Algorithm: CADES_Common.ValuesOf; + DataEncoding: CADES_Common.ValuesOf; + Value: string; + + Hash(newVal: string): void; + + SetHashValue(newVal: string): void; + } + + interface CPAttribute { + Name: CADES_Common.ValuesOf; + Value: any; + ValueEncoding: CADES_Common.ValuesOf; + } + + interface RawSignature { + SignHash(hash: CPHashedData, certificate?: string): string; + + VerifyHash(hash: CPHashedData, certificate: CAPICOM.Certificate, signature: string): void; + } +} diff --git a/types/cadesplugin/ts3.1/cadescom_async.d.ts b/types/cadesplugin/ts3.1/cadescom_async.d.ts new file mode 100644 index 0000000000..94e95b2acc --- /dev/null +++ b/types/cadesplugin/ts3.1/cadescom_async.d.ts @@ -0,0 +1,57 @@ +declare namespace CAdESCOM { + interface CPSignerAsync extends CADES_Common.Async { + propset_Certificate(certificate: CAPICOM.CertificateAsync): Promise; + + propset_CheckCertificate(checkCertificate: boolean): Promise; + + propset_KeyPin(keyPin: string): Promise; + + propset_Options(options: CADES_Common.ValuesOf): Promise; + + propset_TSAAddress(TSAAddress: string): Promise; + } + + interface CadesSignedDataAsync extends CADES_Common.Async { + propset_DisplayData(displayData: CADES_Common.ValuesOf): Promise; + + propset_Content(content: string): Promise; + + propset_ContentEncoding(contentEncoding: CADES_Common.ValuesOf): Promise; + } + + interface VersionAsync extends CADES_Common.Async { + } + + interface AboutAsync extends CADES_Common.Async { + } + + interface CPSignersAsync extends CADES_Common.Async { + } + + interface SignedXMLAsync extends CADES_Common.Async { + propset_Content(content: string): Promise; + + propset_DigestMethod(digestMethod: string): Promise; + + propset_SignatureMethod(signatureMethod: string): Promise; + + propset_SignatureType(signatureType: CADES_Common.ValuesOf): Promise; + } + + interface CPHashedDataAsync extends CADES_Common.Async { + propset_Algorithm(algorithm: CADES_Common.ValuesOf): Promise; + + propset_DataEncoding(dataEncoding: CADES_Common.ValuesOf): Promise; + } + + interface CPAttributeAsync extends CADES_Common.Async { + propset_Name(name: CADES_Common.ValuesOf): Promise; + + propset_Value(value: any): Promise; + + propset_ValueEncoding(valueEncoding: CADES_Common.ValuesOf): Promise; + } + + interface RawSignatureAsync extends CADES_Common.Async { + } +} diff --git a/types/cadesplugin/ts3.1/cadescom_enums.d.ts b/types/cadesplugin/ts3.1/cadescom_enums.d.ts new file mode 100644 index 0000000000..918803a47d --- /dev/null +++ b/types/cadesplugin/ts3.1/cadescom_enums.d.ts @@ -0,0 +1,74 @@ +declare namespace CAdESCOM { + interface StoreLocationPlugin { + readonly CADESCOM_LOCAL_MACHINE_STORE: 1; + readonly CADESCOM_CURRENT_USER_STORE: 2; + readonly CADESCOM_CONTAINER_STORE: 100; + } + + interface CADESCOM_STORE_LOCATION extends StoreLocationPlugin { + readonly CADESCOM_MEMORY_STORE: 0; + readonly CADESCOM_ACTIVE_DIRECTORY_USER_STORE: 3; + readonly CADESCOM_SMART_CARD_USER_STORE: 4; + } + + interface CADESCOM_CADES_TYPE { + readonly CADESCOM_CADES_BES: 1; + readonly CADESCOM_CADES_DEFAULT: 0; + readonly CADESCOM_CADES_T: 5; + readonly CADESCOM_CADES_X_LONG_TYPE_1: 93; + } + + interface CADESCOM_CONTENT_ENCODING_TYPE { + readonly CADESCOM_BASE64_TO_BINARY: 1; + readonly CADESCOM_STRING_TO_UCS2LE: 0; + } + + interface CADESCOM_XML_SIGNATURE_TYPE { + readonly CADESCOM_XML_SIGNATURE_TYPE_ENVELOPED: 0; + readonly CADESCOM_XML_SIGNATURE_TYPE_ENVELOPING: 1; + readonly CADESCOM_XML_SIGNATURE_TYPE_TEMPLATE: 2; + } + + interface CADESCOM_ENCRYPTION_ALGORITHM { + readonly CADESCOM_ENCRYPTION_ALGORITHM_RC2: 0; + readonly CADESCOM_ENCRYPTION_ALGORITHM_RC4: 1; + readonly CADESCOM_ENCRYPTION_ALGORITHM_DES: 2; + readonly CADESCOM_ENCRYPTION_ALGORITHM_3DES: 3; + readonly CADESCOM_ENCRYPTION_ALGORITHM_AES: 4; + readonly CADESCOM_ENCRYPTION_ALGORITHM_GOST_28147_89: 25; + } + + interface CADESCOM_HASH_ALGORITHM { + readonly CADESCOM_HASH_ALGORITHM_SHA1: 0; + readonly CADESCOM_HASH_ALGORITHM_MD2: 1; + readonly CADESCOM_HASH_ALGORITHM_MD4: 2; + readonly CADESCOM_HASH_ALGORITHM_MD5: 3; + readonly CADESCOM_HASH_ALGORITHM_SHA_256: 4; + readonly CADESCOM_HASH_ALGORITHM_SHA_384: 5; + readonly CADESCOM_HASH_ALGORITHM_SHA_512: 6; + readonly CADESCOM_HASH_ALGORITHM_CP_GOST_3411: 100; + readonly CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_256: 101; + readonly CADESCOM_HASH_ALGORITHM_CP_GOST_3411_2012_512: 102; + } + + interface CADESCOM_ATTRIBUTE { + readonly CADESCOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME: 0; + readonly CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME: 1; + readonly CADESCOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION: 2; + readonly CADESCOM_ATTRIBUTE_OTHER: -1; + } + + interface CADESCOM_DISPLAY_DATA { + readonly CADESCOM_DISPLAY_DATA_NONE: 0; + readonly CADESCOM_DISPLAY_DATA_CONTENT: 1; + readonly CADESCOM_DISPLAY_DATA_ATTRIBUTE: 2; + } + + interface CADESCOM_InstallResponseRestrictionFlags { + readonly CADESCOM_AllowNone: 0; + readonly CADESCOM_AllowNoOutstandingRequest: 1; + readonly CADESCOM_AllowUntrustedCertificate: 2; + readonly CADESCOM_AllowUntrustedRoot: 4; + readonly CADESCOM_SkipInstallToStore: 0x10000000; + } +} diff --git a/types/cadesplugin/ts3.1/cadesplugin-tests.ts b/types/cadesplugin/ts3.1/cadesplugin-tests.ts new file mode 100644 index 0000000000..c9784f1671 --- /dev/null +++ b/types/cadesplugin/ts3.1/cadesplugin-tests.ts @@ -0,0 +1,12 @@ +cadesplugin.then(async () => { + if ("CreateObjectAsync" in cadesplugin) { + const pluginAsync: CADESPluginAsync = cadesplugin; + const oAbout = await pluginAsync.CreateObjectAsync("CAdESCOM.About"); + const oVersion = await oAbout.CSPVersion(); + await oVersion.toString(); + } + if ("CreateObject" in cadesplugin) { + const pluginSync: CADESPluginSync = cadesplugin; + pluginSync.CreateObject("CAdESCOM.About").CSPVersion().toString(); + } +}); diff --git a/types/cadesplugin/ts3.1/cadesplugin.d.ts b/types/cadesplugin/ts3.1/cadesplugin.d.ts new file mode 100644 index 0000000000..53bba7e1bd --- /dev/null +++ b/types/cadesplugin/ts3.1/cadesplugin.d.ts @@ -0,0 +1,80 @@ +declare namespace CADES_Plugin { + interface ObjectNames { + "CAPICOM.Store": CAPICOM.Store; + "CAdESCOM.CPSigner": CAdESCOM.CPSigner; + "CAdESCOM.About": CAdESCOM.About; + "CAdESCOM.SignedXML": CAdESCOM.SignedXML; + "CAdESCOM.HashedData": CAdESCOM.CPHashedData; + "CAdESCOM.CadesSignedData": CAdESCOM.CadesSignedData; + "CAdESCOM.CPAttribute": CAdESCOM.CPAttribute; + "CAdESCOM.RawSignature": CAdESCOM.RawSignature; + } + + interface ObjectNamesAsync { + "CAdESCOM.Store": CAPICOM.StoreAsync; + "CAdESCOM.CPSigner": CAdESCOM.CPSignerAsync; + "CAdESCOM.About": CAdESCOM.AboutAsync; + "CAdESCOM.SignedXML": CAdESCOM.SignedXMLAsync; + "CAdESCOM.HashedData": CAdESCOM.CPHashedDataAsync; + "CAdESCOM.CadesSignedData": CAdESCOM.CadesSignedDataAsync; + "CAdESCOM.CPAttribute": CAdESCOM.CPAttributeAsync; + "CAdESCOM.RawSignature": CAdESCOM.RawSignatureAsync; + } + + interface LogLevel { + readonly LOG_LEVEL_DEBUG: 4; + readonly LOG_LEVEL_INFO: 2; + readonly LOG_LEVEL_ERROR: 1; + } + + interface SignedXmlUrls { + readonly XmlDsigGost3410Url: "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411"; + readonly XmlDsigGost3410UrlObsolete: "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411"; + readonly XmlDsigGost3411Url: "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411"; + readonly XmlDsigGost3411UrlObsolete: "http://www.w3.org/2001/04/xmldsig-more#gostr3411"; + } + + interface EncodingType { + readonly CADESCOM_ENCODE_ANY: -1; + readonly CADESCOM_ENCODE_BASE64: 0; + readonly CADESCOM_ENCODE_BINARY: 1; + } +} + +interface CADESPluginBase extends Promise, + CAPICOM.StoreLocationPlugin, CAdESCOM.StoreLocationPlugin, CAPICOM.StoreNamePlugin, + CAPICOM.StoreOpenModePlugin, CAPICOM.CAPICOM_CERTIFICATE_FIND_TYPE, + CADES_Plugin.LogLevel, CAdESCOM.CADESCOM_XML_SIGNATURE_TYPE, + CADES_Plugin.SignedXmlUrls, CAdESCOM.CADESCOM_CADES_TYPE, + CADES_Plugin.EncodingType, CAPICOM.CAPICOM_CERTIFICATE_INCLUDE_OPTION, + CAPICOM.CertIntoTypePlugin, CAPICOM.KeyUsagePlugin, + CAPICOM.PropIDPlugin, CAPICOM.OIDPlugin, CAPICOM.EKUPlugin, + CAPICOM.CAPICOM_ATTRIBUTE, CAdESCOM.CADESCOM_ATTRIBUTE, + CAdESCOM.CADESCOM_CONTENT_ENCODING_TYPE, CAdESCOM.CADESCOM_DISPLAY_DATA, + CAdESCOM.CADESCOM_ENCRYPTION_ALGORITHM, CAdESCOM.CADESCOM_HASH_ALGORITHM, + CAdESCOM.CADESCOM_InstallResponseRestrictionFlags { + readonly JSModuleVersion: string; + readonly current_log_level: number; + + async_spawn(generatorFun: (...args: any[]) => Iterator): T; + + set(obj: CADESPluginBase): void; + + set_log_level(level: CADES_Common.ValuesOf): void; + + getLastError(exception: Error): string; + + is_capilite_enabled(): boolean; +} + +interface CADESPluginAsync extends CADESPluginBase { + CreateObjectAsync(objName: T): Promise; + + ReleasePluginObjects(): Promise; +} + +interface CADESPluginSync extends CADESPluginBase { + CreateObject(objName: T): CADES_Plugin.ObjectNames[T]; +} + +type CADESPlugin = CADESPluginAsync | CADESPluginSync; diff --git a/types/cadesplugin/ts3.1/capicom.d.ts b/types/cadesplugin/ts3.1/capicom.d.ts new file mode 100644 index 0000000000..02bb6f05b5 --- /dev/null +++ b/types/cadesplugin/ts3.1/capicom.d.ts @@ -0,0 +1,83 @@ +declare namespace CAPICOM { + interface EncodedData { + readonly Format: string; + + Value(EncodingType?: CAPICOM_ENCODING_TYPE): string; + } + + interface OID { + FriendlyName: string; + Name: CAPICOM_OID; + Value: string; + } + + interface PublicKey { + readonly Algorithm: OID; + readonly EncodedKey: EncodedData; + readonly EncodedParameters: EncodedData; + readonly Length: number; + } + + interface Certificate { + readonly Version: number; + readonly Thumbprint: string; + readonly SubjectName: string; + readonly SerialNumber: string; + readonly IssuerName: string; + readonly ValidFromDate: CADES_Common.VarDate; + readonly ValidToDate: CADES_Common.VarDate; + + HasPrivateKey(): boolean; + + GetInfo(infoType: CAPICOM_CERT_INFO_TYPE): string; + + IsValid(): CertificateStatus; + + Display(): void; + + PublicKey(): PublicKey; + + Export(EncodingType: CADES_Common.ValuesOf): string; + } + + interface CertificateStatus { + Result: boolean; + } + + interface Certificates { + readonly Count: number; + + Item(index: number): Certificate; + + Find(findType: CADES_Common.ValuesOf, varCriteria?: any, bFindValidOnly?: boolean): Certificates; + + Select(title?: string, displayString?: string, bMultiSelect?: boolean): Certificates; + } + + interface Store { + readonly Certificates: Certificates; + readonly Location: CADES_Common.ValuesOf; + readonly Name: string; + + Open(location?: CADES_Common.ValuesOf, name?: CADES_Common.ValuesOf, openMode?: CADES_Common.ValuesOf): void; + + Close(): void; + + Delete(): boolean; + + Import(encodedStore: string): void; + } + + interface Signers { + readonly Count: number; + + Item(index: number): Signer; + } + + interface Signer { + Certificate: Certificate; + Options: CAPICOM_CERTIFICATE_INCLUDE_OPTION; + + Load(fileName: string, password?: string): void; + } +} diff --git a/types/cadesplugin/ts3.1/capicom_async.d.ts b/types/cadesplugin/ts3.1/capicom_async.d.ts new file mode 100644 index 0000000000..5ab775aba2 --- /dev/null +++ b/types/cadesplugin/ts3.1/capicom_async.d.ts @@ -0,0 +1,19 @@ +declare namespace CAPICOM { + interface CertificateAsync extends CADES_Common.Async { + } + + interface CertificatesAsync extends CADES_Common.Async { + } + + interface StoreAsync extends CADES_Common.Async { + } + + interface EncodedDataAsync extends CADES_Common.Async { + } + + interface OIDAsync extends CADES_Common.Async { + } + + interface PublicKeyAsync extends CADES_Common.Async { + } +} diff --git a/types/cadesplugin/ts3.1/capicom_enums.d.ts b/types/cadesplugin/ts3.1/capicom_enums.d.ts new file mode 100644 index 0000000000..aada08bfe2 --- /dev/null +++ b/types/cadesplugin/ts3.1/capicom_enums.d.ts @@ -0,0 +1,226 @@ +declare namespace CAPICOM { + interface StoreLocationPlugin { + readonly CAPICOM_LOCAL_MACHINE_STORE: 1; + readonly CAPICOM_CURRENT_USER_STORE: 2; + } + + interface CAPICOM_STORE_LOCATION { + readonly CAPICOM_MEMORY_STORE: 0; + readonly CAPICOM_LOCAL_MACHINE_STORE: 1; + readonly CAPICOM_CURRENT_USER_STORE: 2; + readonly CAPICOM_ACTIVE_DIRECTORY_USER_STORE: 3; + readonly CAPICOM_SMART_CARD_USER_STORE: 4; + } + + interface StoreNamePlugin { + readonly CAPICOM_MY_STORE: "My"; + } + + interface CAPICOM_STORE_NAME extends StoreNamePlugin { + readonly CAPICOM_CA_STORE: "Ca"; + readonly CAPICOM_OTHER_STORE: "AddressBook"; + readonly CAPICOM_ROOT_STORE: "Root"; + } + + interface StoreOpenModePlugin { + readonly CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED: 2; + } + + interface CAPICOM_STORE_OPEN_MODE extends StoreOpenModePlugin { + readonly CAPICOM_STORE_OPEN_READ_ONLY: 0; + readonly CAPICOM_STORE_OPEN_READ_WRITE: 1; + readonly CAPICOM_STORE_OPEN_EXISTING_ONLY: 128; + readonly CAPICOM_STORE_OPEN_INCLUDE_ARCHIVED: 256; + } + + interface CAPICOM_CERTIFICATE_FIND_TYPE { + readonly CAPICOM_CERTIFICATE_FIND_SHA1_HASH: 0; + readonly CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME: 1; + readonly CAPICOM_CERTIFICATE_FIND_ISSUER_NAME: 2; + readonly CAPICOM_CERTIFICATE_FIND_ROOT_NAME: 3; + readonly CAPICOM_CERTIFICATE_FIND_TEMPLATE_NAME: 4; + readonly CAPICOM_CERTIFICATE_FIND_EXTENSION: 5; + readonly CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY: 6; + readonly CAPICOM_CERTIFICATE_FIND_APPLICATION_POLICY: 7; + readonly CAPICOM_CERTIFICATE_FIND_CERTIFICATE_POLICY: 8; + readonly CAPICOM_CERTIFICATE_FIND_TIME_VALID: 9; + readonly CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID: 10; + readonly CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED: 11; + readonly CAPICOM_CERTIFICATE_FIND_KEY_USAGE: 12; + } + + interface CAPICOM_CERTIFICATE_INCLUDE_OPTION { + readonly CAPICOM_CERTIFICATE_INCLUDE_CHAIN_EXCEPT_ROOT: 0; + readonly CAPICOM_CERTIFICATE_INCLUDE_END_ENTITY_ONLY: 2; + readonly CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN: 1; + } + + interface CertIntoTypePlugin { + readonly CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME: 0; + readonly CAPICOM_CERT_INFO_ISSUER_SIMPLE_NAME: 1; + } + + interface CAPICOM_CERT_INFO_TYPE extends CertIntoTypePlugin { + readonly CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME: 2; + readonly CAPICOM_CERT_INFO_ISSUER_EMAIL_NAME: 3; + readonly CAPICOM_CERT_INFO_SUBJECT_UPN: 4; + readonly CAPICOM_CERT_INFO_ISSUER_UPN: 5; + readonly CAPICOM_CERT_INFO_SUBJECT_DNS_NAME: 6; + readonly CAPICOM_CERT_INFO_ISSUER_DNS_NAME: 7; + } + + interface KeyUsagePlugin { + readonly CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE: 128; + } + + interface CAPICOM_KEY_USAGE extends KeyUsagePlugin { + readonly CAPICOM_NON_REPUDIATION_KEY_USAGE: 64; + readonly CAPICOM_KEY_ENCIPHERMENT_KEY_USAGE: 32; + readonly CAPICOM_DATA_ENCIPHERMENT_KEY_USAGE: 16; + readonly CAPICOM_KEY_AGREEMENT_KEY_USAGE: 8; + readonly CAPICOM_KEY_CERT_SIGN_KEY_USAGE: 4; + readonly CAPICOM_OFFLINE_CRL_SIGN_KEY_USAGE: 2; + readonly CAPICOM_CRL_SIGN_KEY_USAGE: 2; + readonly CAPICOM_ENCIPHER_ONLY_KEY_USAGE: 1; + readonly CAPICOM_DECIPHER_ONLY_KEY_USAGE: 32768; + } + + interface PropIDPlugin { + readonly CAPICOM_PROPID_ENHKEY_USAGE: 9; + } + + interface CAPICOM_PROPID extends PropIDPlugin { + readonly CAPICOM_PROPID_UNKNOWN: 0; + readonly CAPICOM_PROPID_KEY_PROV_HANDLE: 1; + readonly CAPICOM_PROPID_KEY_PROV_INFO: 2; + readonly CAPICOM_PROPID_SHA1_HASH: 3; + readonly CAPICOM_PROPID_HASH_PROP: 3; + readonly CAPICOM_PROPID_MD5_HASH: 4; + readonly CAPICOM_PROPID_KEY_CONTEXT: 5; + readonly CAPICOM_PROPID_KEY_SPEC: 6; + readonly CAPICOM_PROPID_IE30_RESERVED: 7; + readonly CAPICOM_PROPID_PUBKEY_HASH_RESERVED: 8; + readonly CAPICOM_PROPID_CTL_USAGE: 9; + readonly CAPICOM_PROPID_NEXT_UPDATE_LOCATION: 10; + readonly CAPICOM_PROPID_FRIENDLY_NAME: 11; + readonly CAPICOM_PROPID_PVK_FILE: 12; + readonly CAPICOM_PROPID_DESCRIPTION: 13; + readonly CAPICOM_PROPID_ACCESS_STATE: 14; + readonly CAPICOM_PROPID_SIGNATURE_HASH: 15; + readonly CAPICOM_PROPID_SMART_CARD_DATA: 16; + readonly CAPICOM_PROPID_EFS: 17; + readonly CAPICOM_PROPID_FORTEZZA_DATA: 18; + readonly CAPICOM_PROPID_ARCHIVED: 19; + readonly CAPICOM_PROPID_KEY_IDENTIFIER: 20; + readonly CAPICOM_PROPID_AUTO_ENROLL: 21; + readonly CAPICOM_PROPID_PUBKEY_ALG_PARA: 22; + readonly CAPICOM_PROPID_CROSS_CERT_DIST_POINTS: 23; + readonly CAPICOM_PROPID_ISSUER_PUBLIC_KEY_MD5_HASH: 24; + readonly CAPICOM_PROPID_SUBJECT_PUBLIC_KEY_MD5_HASH: 25; + readonly CAPICOM_PROPID_ENROLLMENT: 26; + readonly CAPICOM_PROPID_DATE_STAMP: 27; + readonly CAPICOM_PROPID_ISSUER_SERIAL_NUMBER_MD5_HASH: 28; + readonly CAPICOM_PROPID_SUBJECT_NAME_MD5_HASH: 29; + readonly CAPICOM_PROPID_EXTENDED_ERROR_INFO: 30; + readonly CAPICOM_PROPID_RENEWAL: 64; + readonly CAPICOM_PROPID_ARCHIVED_KEY_HASH: 65; + readonly CAPICOM_PROPID_FIRST_RESERVED: 66; + readonly CAPICOM_PROPID_LAST_RESERVED: 32767; + readonly CAPICOM_PROPID_FIRST_USER: 32768; + readonly CAPICOM_PROPID_LAST_USER: 65535; + } + + interface OIDPlugin { + readonly CAPICOM_OID_OTHER: 0; + readonly CAPICOM_OID_KEY_USAGE_EXTENSION: 10; + } + + interface CAPICOM_OID extends OIDPlugin { + readonly CAPICOM_OID_AUTHORITY_KEY_IDENTIFIER_EXTENSION: 1; + readonly CAPICOM_OID_KEY_ATTRIBUTES_EXTENSION: 2; + readonly CAPICOM_OID_CERT_POLICIES_95_EXTENSION: 3; + readonly CAPICOM_OID_KEY_USAGE_RESTRICTION_EXTENSION: 4; + readonly CAPICOM_OID_LEGACY_POLICY_MAPPINGS_EXTENSION: 5; + readonly CAPICOM_OID_SUBJECT_ALT_NAME_EXTENSION: 6; + readonly CAPICOM_OID_ISSUER_ALT_NAME_EXTENSION: 7; + readonly CAPICOM_OID_BASIC_CONSTRAINTS_EXTENSION: 8; + readonly CAPICOM_OID_SUBJECT_KEY_IDENTIFIER_EXTENSION: 9; + readonly CAPICOM_OID_PRIVATEKEY_USAGE_PERIOD_EXTENSION: 11; + readonly CAPICOM_OID_SUBJECT_ALT_NAME2_EXTENSION: 12; + readonly CAPICOM_OID_ISSUER_ALT_NAME2_EXTENSION: 13; + readonly CAPICOM_OID_BASIC_CONSTRAINTS2_EXTENSION: 14; + readonly CAPICOM_OID_NAME_CONSTRAINTS_EXTENSION: 15; + readonly CAPICOM_OID_CRL_DIST_POINTS_EXTENSION: 16; + readonly CAPICOM_OID_CERT_POLICIES_EXTENSION: 17; + readonly CAPICOM_OID_POLICY_MAPPINGS_EXTENSION: 18; + readonly CAPICOM_OID_AUTHORITY_KEY_IDENTIFIER2_EXTENSION: 19; + readonly CAPICOM_OID_POLICY_CONSTRAINTS_EXTENSION: 20; + readonly CAPICOM_OID_ENHANCED_KEY_USAGE_EXTENSION: 21; + readonly CAPICOM_OID_CERTIFICATE_TEMPLATE_EXTENSION: 22; + readonly CAPICOM_OID_APPLICATION_CERT_POLICIES_EXTENSION: 23; + readonly CAPICOM_OID_APPLICATION_POLICY_MAPPINGS_EXTENSION: 24; + readonly CAPICOM_OID_APPLICATION_POLICY_CONSTRAINTS_EXTENSION: 25; + readonly CAPICOM_OID_AUTHORITY_INFO_ACCESS_EXTENSION: 26; + readonly CAPICOM_OID_SERVER_AUTH_EKU: 100; + readonly CAPICOM_OID_CLIENT_AUTH_EKU: 101; + readonly CAPICOM_OID_CODE_SIGNING_EKU: 102; + readonly CAPICOM_OID_EMAIL_PROTECTION_EKU: 103; + readonly CAPICOM_OID_IPSEC_END_SYSTEM_EKU: 104; + readonly CAPICOM_OID_IPSEC_TUNNEL_EKU: 105; + readonly CAPICOM_OID_IPSEC_USER_EKU: 106; + readonly CAPICOM_OID_TIME_STAMPING_EKU: 107; + readonly CAPICOM_OID_CTL_USAGE_SIGNING_EKU: 108; + readonly CAPICOM_OID_TIME_STAMP_SIGNING_EKU: 109; + readonly CAPICOM_OID_SERVER_GATED_CRYPTO_EKU: 110; + readonly CAPICOM_OID_ENCRYPTING_FILE_SYSTEM_EKU: 111; + readonly CAPICOM_OID_EFS_RECOVERY_EKU: 112; + readonly CAPICOM_OID_WHQL_CRYPTO_EKU: 113; + readonly CAPICOM_OID_NT5_CRYPTO_EKU: 114; + readonly CAPICOM_OID_OEM_WHQL_CRYPTO_EKU: 115; + readonly CAPICOM_OID_EMBEDED_NT_CRYPTO_EKU: 116; + readonly CAPICOM_OID_ROOT_LIST_SIGNER_EKU: 117; + readonly CAPICOM_OID_QUALIFIED_SUBORDINATION_EKU: 118; + readonly CAPICOM_OID_KEY_RECOVERY_EKU: 119; + readonly CAPICOM_OID_DIGITAL_RIGHTS_EKU: 120; + readonly CAPICOM_OID_LICENSES_EKU: 121; + readonly CAPICOM_OID_LICENSE_SERVER_EKU: 122; + readonly CAPICOM_OID_SMART_CARD_LOGON_EKU: 123; + readonly CAPICOM_OID_PKIX_POLICY_QUALIFIER_CPS: 124; + readonly CAPICOM_OID_PKIX_POLICY_QUALIFIER_USERNOTICE: 125; + } + + interface EKUPlugin { + readonly CAPICOM_EKU_OTHER: 0; + readonly CAPICOM_EKU_CLIENT_AUTH: 2; + readonly CAPICOM_EKU_SMARTCARD_LOGON: 5; + } + + interface CAPICOM_EKU { + readonly CAPICOM_EKU_SERVER_AUTH: 1; + readonly CAPICOM_EKU_CODE_SIGNING: 3; + readonly CAPICOM_EKU_EMAIL_PROTECTION: 4; + readonly CAPICOM_EKU_ENCRYPTING_FILE_SYSTEM: 6; + } + + interface CAPICOM_ATTRIBUTE { + readonly CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME: 0; + readonly CAPICOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_NAME: 1; + readonly CAPICOM_AUTHENTICATED_ATTRIBUTE_DOCUMENT_DESCRIPTION: 2; + } + + interface CAPICOM_HASH_ALGORITHM { + readonly CAPICOM_HASH_ALGORITHM_SHA1: 0; + readonly CAPICOM_HASH_ALGORITHM_MD2: 1; + readonly CAPICOM_HASH_ALGORITHM_MD4: 2; + readonly CAPICOM_HASH_ALGORITHM_MD5: 3; + readonly CAPICOM_HASH_ALGORITHM_SHA_256: 4; + readonly CAPICOM_HASH_ALGORITHM_SHA_384: 5; + readonly CAPICOM_HASH_ALGORITHM_SHA_512: 6; + } + + interface CAPICOM_ENCODING_TYPE { + readonly CAPICOM_ENCODE_ANY: -1; + readonly CAPICOM_ENCODE_BASE64: 0; + readonly CAPICOM_ENCODE_BINARY: 1; + } +} diff --git a/types/cadesplugin/ts3.1/common.d.ts b/types/cadesplugin/ts3.1/common.d.ts new file mode 100644 index 0000000000..315b0490a3 --- /dev/null +++ b/types/cadesplugin/ts3.1/common.d.ts @@ -0,0 +1,25 @@ +declare namespace CADES_Common { + type ValuesOf = T[keyof T]; + type VarDate = object; + + // Extracts the type if wrapped by a Promise + type Unpacked = T extends Promise ? U : + T extends CAPICOM.Certificate ? CAPICOM.CertificateAsync : + T extends CAPICOM.Certificates ? CAPICOM.CertificatesAsync : + T extends CAdESCOM.CPSigner ? CAdESCOM.CPSignerAsync : + T extends CAdESCOM.CPHashedData ? CAdESCOM.CPHashedDataAsync : + T extends CAdESCOM.Version ? CAdESCOM.VersionAsync : + T extends CAPICOM.OID ? CAPICOM.OIDAsync : + T extends CAPICOM.EncodedData ? CAPICOM.EncodedDataAsync : + T extends CAPICOM.PublicKey ? CAPICOM.PublicKeyAsync : + T; + + type PromisifiedFunction = // tslint:disable-line ban-types + T extends (...args: infer A) => infer U ? (...args: { [K in keyof A]: Unpacked }) => Promise> : + T; + + type Async = { + readonly [K in keyof T]: T[K] extends Function ? PromisifiedFunction : // tslint:disable-line ban-types + Promise>; + }; +} diff --git a/types/cadesplugin/ts3.1/index.d.ts b/types/cadesplugin/ts3.1/index.d.ts new file mode 100644 index 0000000000..13fdba4187 --- /dev/null +++ b/types/cadesplugin/ts3.1/index.d.ts @@ -0,0 +1,13 @@ +/// + +/// +/// +/// + +/// +/// +/// + +/// + +declare const cadesplugin: CADESPlugin; diff --git a/types/cadesplugin/ts3.1/tsconfig.json b/types/cadesplugin/ts3.1/tsconfig.json new file mode 100644 index 0000000000..dbc37d117b --- /dev/null +++ b/types/cadesplugin/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "extends": "../tsconfig", + "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", + "cadesplugin-tests.ts" + ] +} diff --git a/types/cadesplugin/ts3.1/tslint.json b/types/cadesplugin/ts3.1/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/cadesplugin/ts3.1/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/cadesplugin/tsconfig.json b/types/cadesplugin/tsconfig.json new file mode 100644 index 0000000000..71e6b79545 --- /dev/null +++ b/types/cadesplugin/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" + ] +} diff --git a/types/cadesplugin/tslint.json b/types/cadesplugin/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/cadesplugin/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/cassandra-driver/cassandra-driver-tests.ts b/types/cassandra-driver/cassandra-driver-tests.ts index ad8a7426fe..3e203837b7 100644 --- a/types/cassandra-driver/cassandra-driver-tests.ts +++ b/types/cassandra-driver/cassandra-driver-tests.ts @@ -2,24 +2,103 @@ import * as cassandra from 'cassandra-driver'; import * as util from 'util'; import * as fs from 'fs'; +class CustomRequestLogger implements cassandra.metrics.ClientMetrics { + onAuthenticationError(e: Error | cassandra.errors.AuthenticationError): void { + throw new Error("Method not implemented."); + } + onClientTimeoutError(e: cassandra.errors.OperationTimedOutError): void { + throw new Error("Method not implemented."); + } + onClientTimeoutRetry(e: Error): void { + throw new Error("Method not implemented."); + } + onConnectionError(e: Error): void { + throw new Error("Method not implemented."); + } + onIgnoreError(e: Error): void { + throw new Error("Method not implemented."); + } + onOtherError(e: Error): void { + throw new Error("Method not implemented."); + } + onOtherErrorRetry(e: Error): void { + throw new Error("Method not implemented."); + } + onReadTimeoutError(e: cassandra.errors.ResponseError): void { + throw new Error("Method not implemented."); + } + onReadTimeoutRetry(e: Error): void { + throw new Error("Method not implemented."); + } + onResponse(latency: number[]): void { + throw new Error("Method not implemented."); + } + onSpeculativeExecution(): void { + throw new Error("Method not implemented."); + } + onSuccessfulResponse(latency: number[]): void { + throw new Error("Method not implemented."); + } + onUnavailableError(e: cassandra.errors.ResponseError): void { + throw new Error("Method not implemented."); + } + onUnavailableRetry(e: Error): void { + throw new Error("Method not implemented."); + } + onWriteTimeoutError(e: cassandra.errors.ResponseError): void { + throw new Error("Method not implemented."); + } + onWriteTimeoutRetry(e: Error): void { + throw new Error("Method not implemented."); + } +} + const client = new cassandra.Client({ contactPoints: ['h1', 'h2'], + localDataCenter: 'datacenter1', keyspace: 'ks1', sslOptions: { cert: fs.readFileSync('certFilePath') }, encoding: { map: Map, - set: Set - } + set: Set, + useBigIntAsLong: false, + useBigIntAsVarint: true + }, + requestTracker: new cassandra.tracker.RequestLogger({ logNormalRequests: true }), + metrics: new CustomRequestLogger() }); +console.log(client.metrics); + const query = 'SELECT email, last_name FROM user_profiles WHERE key=?'; client.execute(query, ['guy'], (err, result) => { console.log('got user profile with email ' + result.rows[0].email); }); -client.execute(query, [ 'guy' ], { prepare: true }).then( +client.execute(query, [ 'guy' ], { prepare: true, counter: false }).then( (result) => console.log(result.first().email), (error) => console.log(error) ); + +const mapper = new cassandra.mapping.Mapper( + client, + { + models: { + // example copied from library examples + // tslint:disable-next-line:object-literal-key-quotes + 'Video': { + tables: [ 'videos', 'user_videos', 'latest_videos' ], + keyspace: 'examples', + // example copied from library examples + // tslint:disable-next-line:object-literal-key-quotes + columns: { 'videoid': 'videoId', 'userid': 'userId' }, + mappings: new cassandra.mapping.UnderscoreCqlToCamelCaseMappings() + } + } + }); + +const videoMapper = mapper.forModel('Video'); +videoMapper.insert({ videoId: 'uuid', addedDate: new Date(), userId: 'uuid', name: 'My video', description: 'My desc' }); +videoMapper.find({ videoId: 'uuid' }).then(results => results.first()); diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index df95e386b6..02853c66ba 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for cassandra-driver 3.6 +// Type definitions for cassandra-driver 4.0 // Project: https://github.com/datastax/nodejs-driver // Definitions by: Marc Fisher // Christian D +// Michal Kaminski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -41,11 +42,11 @@ export namespace policies { interface LoadBalancingPolicy { init(client: Client, hosts: HostMap, callback: Callback): void; getDistance(host: Host): types.distance; - newQueryPlan(keyspace: string, queryOptions: any, callback: Callback): void; + newQueryPlan(keyspace: string, queryOptions: ExecutionOptions | null, callback: Callback): void; } interface DCAwareRoundRobinPolicyStatic { - new (localDc?: string, usedHostsPerRemoteDc?: number): DCAwareRoundRobinPolicy; + new (localDc?: string): DCAwareRoundRobinPolicy; } interface DCAwareRoundRobinPolicy extends LoadBalancingPolicy { @@ -504,6 +505,7 @@ export let Encoder: EncoderStatic; export interface ClientOptions { contactPoints: string[]; + localDataCenter?: string; keyspace?: string; refreshSchemaDelay?: number; isMetadataSyncEnabled?: boolean; @@ -541,15 +543,19 @@ export interface ClientOptions { coalescingThreshold?: number; }; authProvider?: auth.AuthProvider; + requestTracker?: tracker.RequestTracker; sslOptions?: tls.ConnectionOptions; encoding?: { map?: typeof Map | ((...args: any[]) => any); set?: typeof Set | ((...args: any[]) => any); copyBuffer?: boolean; useUndefinedAsUnset?: boolean; + useBigIntAsLong?: boolean; + useBigIntAsVarint?: boolean; }; profiles?: ExecutionProfile[]; promiseFactory?: (handler: (callback: (err?: any, result?: any) => void) => void) => Promise; + metrics?: metrics.ClientMetrics; } export interface QueryOptions { @@ -563,11 +569,11 @@ export interface QueryOptions { isIdempotent?: boolean; keyspace?: string; logged?: boolean; + counter?: boolean; pageState?: Buffer | string; prepare?: boolean; readTimeout?: number; retry?: policies.retry.RetryPolicy; - retryOnTimeout?: boolean; routingIndexes?: number[]; routingKey?: Buffer | Buffer[]; routingNames?: string[]; @@ -585,6 +591,7 @@ export interface Client extends events.EventEmitter { hosts: HostMap; keyspace: string; metadata: metadata.Metadata; + metrics: metrics.ClientMetrics; batch(queries: string[] | Array<{ query: string, params?: any }>, options: QueryOptions, callback: ResultCallback): void; batch(queries: string[] | Array<{ query: string, params?: any }>, callback: ResultCallback): void; @@ -889,3 +896,243 @@ export namespace metadata { virtual: boolean; } } + +export interface ExecutionOptionsStatic { + new (): ExecutionOptions; +} + +export interface ExecutionOptions { + getCaptureStackTrace(): boolean; + getConsistency(): types.consistencies; + getCustomPayload(): { [key: string]: any }; + getFetchSize(): number; + getFixedHost(): Host; + getHints(): string[] | string[][]; + isAutoPage(): boolean; + isBatchCounter(): boolean; + isBatchLogged(): boolean; + isIdempotent(): boolean; + isPrepared(): boolean; + isQueryTracing(): boolean; + getKeyspace(): string; + getLoadBalancingPolicy(): policies.loadBalancing.LoadBalancingPolicy; + getPageState(): Buffer; + getRawQueryOptions(): QueryOptions; + getReadTimeout(): number; + getRetryPolicy(): policies.retry.RetryPolicy; + getRoutingKey(): Buffer | Buffer[]; + getSerialConsistency(): types.consistencies; + getTimestamp(): number | Long | undefined | null; + setHints(hints: string[]): void; +} + +export let ExecutionOptions: ExecutionOptionsStatic; + +export namespace mapping { + let Mapper: MapperStatic; + let ModelBatchItem: ModelBatchItemStatic; + let ModelMappingInfo: ModelMappingInfoStatic; + let ModelMapper: ModelMapperStatic; + let MappingHandler: MappingHandlerStatic; + let Result: ResultStatic; + let DefaultTableMappings: DefaultTableMappingsStatic; + let UnderscoreCqlToCamelCaseMappings: UnderscoreCqlToCamelCaseMappingsStatic; + + interface MappingExecutionOptions { + executionProfile?: string; + isIdempotent?: boolean; + logged?: boolean; + timestamp?: number | Long; + fetchSize?: number; + pageState?: number; + } + + interface ModelTables { + name: string; + isView: boolean; + } + + interface MappingQuery { + query: string; + isIdempotent: boolean; + isCounter: boolean; + } + + interface MapperStatic { + new (client: Client, options?: MappingOptions): Mapper; + } + interface Mapper { + batch(items: ModelBatchItem[], executionOptions?: string | MappingExecutionOptions): Promise; + forModel(name: string): ModelMapper; + } + + interface MappingOptions { + models: { [key: string]: ModelOptions }; + } + + interface ModelOptions { + tables?: string[] | ModelTables[]; + mappings?: TableMappings; + columns?: { [key: string]: string }; + keyspace?: string; + } + + interface ModelMappingInfoStatic { + new (keyspace: string, tables: ModelTables[], mappings: TableMappings, columns: { [key: string]: string }): ModelMappingInfo; + parse(options: MappingOptions, currentKeyspace: string): { [key: string]: ModelMappingInfo }; + createDefault(modelName: string, currentKeyspace: string): ModelMappingInfo; + } + interface ModelMappingInfo { + keyspace: string; + tables: ModelTables[]; + + getColumnName(propName: string): string; + getPropertyName(columnName: string): string; + newInstance(): TableMappings; + } + + interface MappingDocInfo { + fields?: string[]; + ttl?: number; + ifNotExists?: boolean; + when?: { [key: string]: string }; + orderBy?: { [key: string]: string }; + limit?: number; + deleteOnlyColumns?: boolean; + } + + interface ModelBatchItemStatic { + new ( + queries: Promise, + doc: { [key: string]: any }, + docInfo: MappingDocInfo, + mappingInfo: ModelMappingInfo + ): ModelBatchItem; + } + interface ModelBatchItem {} + + interface MappingHandlerStatic { + new (client: Client, mappingInfo: ModelMappingInfo): MappingHandler; + } + interface MappingHandler {} + + interface ModelBatchMapper { + insert(doc: { [key: string]: any }, docInfo?: MappingDocInfo): ModelBatchItem; + remove(doc: { [key: string]: any }, docInfo?: MappingDocInfo): ModelBatchItem; + update(doc: { [key: string]: any }, docInfo?: MappingDocInfo): ModelBatchItem; + } + + interface ModelMapperStatic { + new (name: string, handler: MappingHandler): ModelMapper; + } + interface ModelMapper { + name: string; + batching: ModelBatchMapper; + + get(doc: { [key: string]: any }, docInfo?: MappingDocInfo, executionOptions?: string | MappingExecutionOptions): Promise; + find(doc: { [key: string]: any }, docInfo?: MappingDocInfo, executionOptions?: string | MappingExecutionOptions): Promise; + findAll(docInfo?: MappingDocInfo, executionOptions?: string | MappingExecutionOptions): Promise; + insert(doc: { [key: string]: any }, docInfo?: MappingDocInfo, executionOptions?: string | MappingExecutionOptions): Promise; + update(doc: { [key: string]: any }, docInfo?: MappingDocInfo, executionOptions?: string | MappingExecutionOptions): Promise; + remove(doc: { [key: string]: any }, docInfo?: MappingDocInfo, executionOptions?: string | MappingExecutionOptions): Promise; + mapWithQuery( + query: string, + paramsHandler: (doc: { [key: string]: any }) => any, + executionOptions?: string | MappingExecutionOptions + ): (doc: { [key: string]: any }, executionOptions?: string | MappingExecutionOptions) => Promise; + } + + interface ResultStatic { + new (rs: types.ResultSet, info: ModelMappingInfo, rowAdapter: (row: types.Row, info: ModelMappingInfo) => { [key: string]: any }): Result; + } + interface Result { + [Symbol.iterator](): Iterator<{ [key: string]: any }>; + wasApplied(): boolean; + first(): { [key: string]: any }; + toArray(): Array<{ [key: string]: any }>; + forEach(callback: (currentValue: { [key: string]: any }, index: number) => void, thisArg?: any): void; + } + + interface TableMappings { + getColumnName(propName: string): string; + getPropertyName(columnName: string): string; + newObjectInstance(): { [key: string]: any }; + } + + interface DefaultTableMappingsStatic { + new (): DefaultTableMappings; + } + interface DefaultTableMappings extends TableMappings {} + interface UnderscoreCqlToCamelCaseMappingsStatic { + new (): UnderscoreCqlToCamelCaseMappings; + } + interface UnderscoreCqlToCamelCaseMappings extends TableMappings {} +} + +export namespace tracker { + let RequestLogger: RequestLoggerStatic; + + interface RequestLoggerOptions { + slowThreshold?: number; + logNormalRequests?: boolean; + logErroredRequests?: boolean; + messageMaxQueryLength?: number; + messageMaxParameterValueLength?: number; + messageMaxErrorStackTraceLength?: number; + } + + interface RequestTracker { + onError( + host: Host, + query: string | Array<{ query: string, params?: any }>, + parameters: any[] | { [key: string]: any } | null, + executionOptions: ExecutionOptions, + requestLength: number, + err: Error, + latency: number[] + ): void; + onSuccess( + host: Host, + query: string | Array<{ query: string, params?: any }>, + parameters: any[] | { [key: string]: any } | null, + executionOptions: ExecutionOptions, + requestLength: number, + responseLength: number, + latency: number[] + ): void; + shutdown(): void; + } + + interface RequestLoggerStatic { + new (options: RequestLoggerOptions): RequestLogger; + } + interface RequestLogger extends RequestTracker {} +} + +export namespace metrics { + let DefaultMetrics: DefaultMetricsStatic; + + interface ClientMetrics { + onAuthenticationError(e: Error | errors.AuthenticationError): void; + onClientTimeoutError(e: errors.OperationTimedOutError): void; + onClientTimeoutRetry(e: Error): void; + onConnectionError(e: Error): void; + onIgnoreError(e: Error): void; + onOtherError(e: Error): void; + onOtherErrorRetry(e: Error): void; + onReadTimeoutError(e: errors.ResponseError): void; + onReadTimeoutRetry(e: Error): void; + onResponse(latency: number[]): void; + onSpeculativeExecution(): void; + onSuccessfulResponse(latency: number[]): void; + onUnavailableError(e: errors.ResponseError): void; + onUnavailableRetry(e: Error): void; + onWriteTimeoutError(e: errors.ResponseError): void; + onWriteTimeoutRetry(e: Error): void; + } + + interface DefaultMetricsStatic { + new (): DefaultMetrics; + } + interface DefaultMetrics extends ClientMetrics {} +} diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 62b99ac5b3..bd41889e07 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -231,7 +231,7 @@ export interface DecoratedPolicyOptions extends PolicyOptions { /** * @default false */ - getDecoratedValue?: boolean; + getDecoratedValue: boolean | undefined; } export interface GenerateFuncFlags { @@ -249,7 +249,7 @@ export interface GenerateFuncFlags { * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. * @see {@link https://github.com/hapijs/catbox#policy} */ -export type GenerateFunc = (id: string, flags: GenerateFuncFlags) => Promise; +export type GenerateFunc = (id: Id, flags: GenerateFuncFlags) => Promise; /** * An object with logging information about the generation operation containing the following keys (as relevant): diff --git a/types/chai-webdriverio/package.json b/types/chai-webdriverio/package.json new file mode 100644 index 0000000000..cd495fe983 --- /dev/null +++ b/types/chai-webdriverio/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "@types/webdriverio": "^4.0.0" + } +} diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index ca28a1a9f6..8e795ed77c 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -537,6 +537,7 @@ declare namespace Chart { interface LinearTickOptions extends TickOptions { maxTicksLimit?: number; stepSize?: number; + precision?: number; suggestedMin?: number; suggestedMax?: number; } diff --git a/types/chartist/chartist-tests.ts b/types/chartist/chartist-tests.ts index cb7f884264..863fdb33be 100644 --- a/types/chartist/chartist-tests.ts +++ b/types/chartist/chartist-tests.ts @@ -485,3 +485,53 @@ new Chartist.Candle('.ct-chart', { } } }); + + +// Create a simple bar chart and line chart with two dimensional arrays +new Chartist.Bar('.ct-chart', { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + {value: 1}, + {value: 2}, + {value: 3}, + {value: 4}, + {value: 5}, + {value: 6}, + {value: 7} + ], + [ + {value: 7}, + {value: 6}, + {value: 5}, + {value: 4}, + {value: 3}, + {value: 2}, + {value: 1} + ] + ] +}, {}) + +new Chartist.Line('.ct-chart', { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + {value: 1}, + {value: 2}, + {value: 3}, + {value: 4}, + {value: 5}, + {value: 6}, + {value: 7} + ], + [ + {value: 7}, + {value: 6}, + {value: 5}, + {value: 4}, + {value: 3}, + {value: 2}, + {value: 1} + ] + ] +}, {}) diff --git a/types/chartist/index.d.ts b/types/chartist/index.d.ts index 9b096839cc..8d700703c9 100644 --- a/types/chartist/index.d.ts +++ b/types/chartist/index.d.ts @@ -93,7 +93,7 @@ declare namespace Chartist { // TODO: come in and tidy this up and make it fit better interface IChartistData { labels?: Array | Array | Array; - series: Array | Array> | Array | Array>; + series: Array | Array> | Array> | Array | Array>; } interface IChartistSeriesData { diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index 06daa9b62d..9f174ecb84 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chrome extension development // Project: http://developer.chrome.com/extensions/ -// Definitions by: Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 +// Definitions by: Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 , MatCarlson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -1095,6 +1095,13 @@ declare namespace chrome.contextMenus { * The ID of the menu item that was clicked. */ menuItemId: any; + /** + * Optional. + * Since Chrome 35. + * The ID of the frame of the element where the context menu was + * clicked, if it was in a frame. + */ + frameId?: number; /** * Optional. * Since Chrome 35. @@ -1177,6 +1184,12 @@ declare namespace chrome.contextMenus { * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. */ id?: string; + /** + * Optional. + * Since Chrome 62. + * Whether the item is visible in the menu. + */ + visible?: boolean; } export interface UpdateProperties { @@ -6506,7 +6519,7 @@ declare namespace chrome.tabs { zoomSettings: ZoomSettings; } - export interface TabHighlightedEvent extends chrome.events.Event<(highlightInfo: HighlightInfo) => void> { } + export interface TabHighlightedEvent extends chrome.events.Event<(highlightInfo: TabHighlightInfo) => void> { } export interface TabRemovedEvent extends chrome.events.Event<(tabId: number, removeInfo: TabRemoveInfo) => void> { } diff --git a/types/ckeditor/ckeditor-tests.ts b/types/ckeditor/ckeditor-tests.ts index 7e224ab683..1321d5b83d 100644 --- a/types/ckeditor/ckeditor-tests.ts +++ b/types/ckeditor/ckeditor-tests.ts @@ -289,6 +289,17 @@ function test_dom_node() { strong.insertBefore(em); strong.insertBeforeMe(em); element.isReadOnly(); + var prev = node.getPreviousSourceNode(); + prev = node.getPreviousSourceNode(true); + prev = node.getPreviousSourceNode(true, CKEDITOR.NODE_TEXT); + prev = node.getPreviousSourceNode(true, CKEDITOR.NODE_COMMENT, node); + prev = node.getPreviousSourceNode(true, CKEDITOR.NODE_COMMENT, (current: CKEDITOR.dom.node) => false); + var next = node.getNextSourceNode(); + next = node.getNextSourceNode(true); + next = node.getNextSourceNode(true, CKEDITOR.NODE_ELEMENT); + next = node.getNextSourceNode(true, CKEDITOR.NODE_DOCUMENT, node); + next = node.getNextSourceNode(true, CKEDITOR.NODE_DOCUMENT_FRAGMENT, (current: CKEDITOR.dom.node) => true); + console.log(node.type); } function test_dom_nodeList() { diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 88646f67d1..910d62f2d7 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -333,6 +333,7 @@ declare namespace CKEDITOR { } class node extends domObject { + type: number; constructor(domNode: Node); appendTo(element: element): element; clone(includeChildren: boolean, cloneId: boolean): node; @@ -347,12 +348,12 @@ declare namespace CKEDITOR { getDocument(): document; getIndex(normalized?: boolean): number; getNext(evaluator?: (node: node) => boolean): node; - getNextSourceNode(startFromSibling: boolean, nodeType: number, guard: node | ((node: node) => boolean)): void; + getNextSourceNode(startFromSibling?: boolean, nodeType?: number, guard?: node | ((node: node) => boolean)): node; getParent(allowFragmentParent?: boolean): element; getParents(closerFirst?: boolean): node[]; getPosition(otherNode: node): void; getPrevious(evaluator?: (node: node) => boolean): node; - getPreviousSourceNode(startFromSibling: boolean, nodeType: number, guard: node | ((node: node) => boolean)): void; + getPreviousSourceNode(startFromSibling?: boolean, nodeType?: number, guard?: node | ((node: node) => boolean)): node; hasAscendant(name: string, includeSelf: boolean): boolean; remove(preserveChildren?: boolean): node; replace(nodeToReplace: node): void; diff --git a/types/clean-css/clean-css-tests.ts b/types/clean-css/clean-css-tests.ts index 1ba3953cfd..98049b3ef6 100644 --- a/types/clean-css/clean-css-tests.ts +++ b/types/clean-css/clean-css-tests.ts @@ -1,18 +1,20 @@ +// Original by Tanguy Krotoff +// Updated by Andrew Potter import * as CleanCSS from 'clean-css'; -var source = 'a{font-weight:bold;}'; -var minified = new CleanCSS().minify(source).styles; +let source = 'a{font-weight:bold;}'; +console.log(new CleanCSS().minify(source).styles); -var source = '@import url(http://path/to/remote/styles);'; -new CleanCSS().minify(source, function (error, minified) { +source = '@import url(http://path/to/remote/styles);'; +new CleanCSS().minify(source, (error: any, minified: CleanCSS.Output): void => { console.log(minified.styles); }); const pathToOutputDirectory = 'path'; -new CleanCSS({ sourceMap: true, target: pathToOutputDirectory }) - .minify(source, function (error, minified) { +new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }) + .minify(source, (error: any, minified: CleanCSS.Output): void => { // access minified.sourceMap for SourceMapGenerator object // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details // see https://github.com/jakubpawlowicz/clean-css/blob/master/bin/cleancss#L114 on how it's used in clean-css' CLI @@ -20,15 +22,15 @@ new CleanCSS({ sourceMap: true, target: pathToOutputDirectory }) }); const inputSourceMapAsString = 'input'; -new CleanCSS({ sourceMap: inputSourceMapAsString, target: pathToOutputDirectory }) - .minify(source, function (error, minified) { +new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }) + .minify(source, inputSourceMapAsString, (error: any, minified: CleanCSS.Output): void => { // access minified.sourceMap to access SourceMapGenerator object // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details // see https://github.com/jakubpawlowicz/clean-css/blob/master/bin/cleancss#L114 on how it's used in clean-css' CLI console.log(minified.sourceMap); }); -new CleanCSS({ sourceMap: true, target: pathToOutputDirectory }).minify({ +new CleanCSS({ sourceMap: true, rebaseTo: pathToOutputDirectory }).minify({ 'path/to/source/1': { styles: '...styles...', sourceMap: '...source-map...' @@ -37,7 +39,7 @@ new CleanCSS({ sourceMap: true, target: pathToOutputDirectory }).minify({ styles: '...styles...', sourceMap: '...source-map...' } -}, function (error, minified) { +}, (error: any, minified: CleanCSS.Output): void => { // access minified.sourceMap as above console.log(minified.sourceMap); }); @@ -52,3 +54,45 @@ new CleanCSS().minify({ styles: 'contents of file two' } }); + +// new tests - promise resolution +new CleanCSS({ returnPromise: true, rebaseTo: pathToOutputDirectory }).minify(source) + .then((minified: CleanCSS.Output): void => { + console.log(minified.styles); + }).catch((error: any): void => { + console.log(error); + } +); + +new CleanCSS({ returnPromise: true, sourceMap: true }).minify(source) + .then((minified: CleanCSS.Output): void => { + // access minified.sourceMap as above + console.log(minified.sourceMap); + }).catch((error: any): void => { + console.log(error); + } +); + +new CleanCSS({ returnPromise: true, sourceMap: true }).minify(source, inputSourceMapAsString) + .then((minified: CleanCSS.Output): void => { + // access minified.sourceMap as above + console.log(minified.sourceMap); + }).catch((error: any): void => { + console.log(error); + } +); + +// test object return when passing options as object +let CleanCssOptions: CleanCSS.Options = { returnPromise: true }; +new CleanCSS(CleanCssOptions).minify(source) + .then((minified: CleanCSS.Output): void => { + console.log(minified.styles); + }).catch((error: any): void => { + console.log(error); + } +); + +CleanCssOptions = { returnPromise: false }; +new CleanCSS(CleanCssOptions).minify(source, (error: any, minified: CleanCSS.Output): void => { + console.log(minified.styles); +}); diff --git a/types/clean-css/index.d.ts b/types/clean-css/index.d.ts index 012977f035..9f2dfe9358 100644 --- a/types/clean-css/index.d.ts +++ b/types/clean-css/index.d.ts @@ -1,108 +1,690 @@ -// Type definitions for clean-css v3.4.9 +// Type definitions for clean-css 4.2 // Project: https://github.com/jakubpawlowicz/clean-css // Definitions by: Tanguy Krotoff +// Andrew Potter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +import { RequestOptions as HttpsRequestOptions } from "https"; +import { RequestOptions as HttpRequestOptions } from "http"; + +/** + * Shared options passed when initializing a new instance of CleanCSS that returns either a promise or output + */ +interface OptionsBase { + /** + * Controls compatibility mode used; defaults to ie10+ using `'*'`. + * Compatibility hash exposes the following properties: `colors`, `properties`, `selectors`, and `units` + */ + compatibility?: "*" | "ie9" | "ie8" | "ie7" | CleanCSS.CompatibilityOptions; + + /** + * Controls a function for handling remote requests; Defaults to the build in `loadRemoteResource` function + */ + fetch?: (uri: string, inlineRequest: HttpRequestOptions | HttpsRequestOptions, inlineTimeout: number, done: (message: string | number, body: string) => void) => void; + + /** + * Controls output CSS formatting; defaults to `false`. + * Format hash exposes the following properties: `breaks`, `breakWith`, `indentBy`, `indentWith`, `spaces`, and `wrapAt`. + */ + format?: "beautify" | "keep-breaks" | CleanCSS.FormatOptions | false; + + /** + * inline option whitelists which @import rules will be processed. Defaults to `'local'` + * Accepts the following values: + * 'local': enables local inlining; + * 'remote': enables remote inlining; + * 'none': disables all inlining; + * 'all': enables all inlining, same as ['local', 'remote']; + * '[uri]': enables remote inlining from the specified uri; + * '![url]': disables remote inlining from the specified uri; + */ + inline?: ReadonlyArray | false; + + /** + * Controls extra options for inlining remote @import rules + */ + inlineRequest?: HttpRequestOptions | HttpsRequestOptions; + + /** + * Controls number of milliseconds after which inlining a remote @import fails; defaults to `5000`; + */ + inlineTimeout?: number; + + /** + * Controls optimization level used; defaults to `1`. + * Level hash exposes `1`, and `2`. + */ + level?: 0 | 1 | 2 | CleanCSS.OptimizationsOptions; + + /** + * Controls URL rebasing; defaults to `true`; + */ + rebase?: boolean; + + /** + * controls a directory to which all URLs are rebased, most likely the directory under which the output file + * will live; defaults to the current directory; + */ + rebaseTo?: string; + + /** + * Controls whether an output source map is built; defaults to `false` + */ + sourceMap?: boolean; + + /** + * Controls embedding sources inside a source map's `sourcesContent` field; defaults to `false` + */ + sourceMapInlineSources?: boolean; +} declare namespace CleanCSS { - interface Options { - // Set to false to disable advanced optimizations - selector & property merging, reduction, etc. - advanced?: boolean; - - // Set to false to disable aggressive merging of properties. - aggressiveMerging?: boolean; - - // Turns on benchmarking mode measuring time spent on cleaning up (run npm run bench to see example) - benchmark?: boolean; - - // Enables compatibility mode - compatibility?: Object; - - // Set to true to get minification statistics under stats property (see test/custom-test.js for examples) - debug?: boolean; - - // A hash of options for @import inliner, see test/protocol-imports-test.js for examples, or this comment for a proxy use case. - inliner?: Object; - - // Whether to keep line breaks (default is false) - keepBreaks?: boolean; - - // * for keeping all (default), 1 for keeping first one only, 0 for removing all - keepSpecialComments?: string | number; - - // Whether to merge @media at-rules (default is true) - mediaMerging?: boolean; - - // Whether to process @import rules - processImport?: boolean; - - // A list of @import rules, can be ['all'] (default), ['local'], ['remote'], or a blacklisted path e.g. ['!fonts.googleapis.com'] - processImportFrom?: Array; - - // Set to false to skip URL rebasing - rebase?: boolean; - - // Path to resolve relative @import rules and URLs - relativeTo?: string; - - // Set to false to disable restructuring in advanced optimizations - restructuring?: boolean; - - // Path to resolve absolute @import rules and rebase relative URLs - root?: string; - - // Rounding precision; defaults to 2; -1 disables rounding - roundingPrecision?: number; - - // Set to true to enable semantic merging mode which assumes BEM-like content (default is false as it's highly likely this will break your stylesheets - use with caution!) - semanticMerging?: boolean; - - // Set to false to skip shorthand compacting (default is true unless sourceMap is set when it's false) - shorthandCompacting?: boolean; - - // Exposes source map under sourceMap property, e.g. new CleanCSS().minify(source).sourceMap (default is false) If input styles are a product of CSS preprocessor (Less, Sass) an input source map can be passed as a string. - sourceMap?: boolean | string; - - // Set to true to inline sources inside a source map's sourcesContent field (defaults to false) It is also required to process inlined sources from input source maps. - sourceMapInlineSources?: boolean; - - // Path to a folder or an output file to which rebase all URLs - target?: string; - } - + /** + * Output returned when calling minify functions + */ interface Output { - // Optimized output CSS as a string + /** + * Optimized output CSS as a string + */ styles: string; - // Output source map (if requested with sourceMap option) + /** + * Output source map if requested with `sourceMap` option + */ sourceMap: string; - // A list of errors raised - errors: Array; + /** + * A list of errors raised + */ + errors: string[]; - // A list of warnings raised - warnings: Array; + /** + * A list of warnings raised + */ + warnings: string[]; - // A hash of statistic information (if requested with debug option) + /** + * Contains statistics on the minify process + */ stats: { - // Original content size (after import inlining) + /** + * Original content size after import inlining + */ originalSize: number; - // Optimized content size + /** + * Optimized content size + */ minifiedSize: number; - // Time spent on optimizations + /** + * Time spent on optimizations in milliseconds + */ timeSpent: number; - // A ratio of output size to input size (e.g. 25% if content was reduced from 100 bytes to 75 bytes) + /** + * `(originalSize - minifiedSize) / originalSize`, e.g. 0.25 if size is reduced from 100 bytes to 75 bytes + */ efficiency: number; }; } + + /** + * Fine grained configuration for compatibility option + */ + interface CompatibilityOptions { + /** + * A hash of compatibility options related to color + */ + colors?: { + /** + * Controls `rgba()` / `hsla()` color support; defaults to `true` + */ + opacity?: boolean; + }; + /** + * A hash of properties that can be set with compatibility + */ + properties?: { + /** + * Controls background-clip merging into shorthand; defaults to `true` + */ + backgroundClipMerging?: boolean; + + /** + * Controls background-origin merging into shorthand; defaults to `true` + */ + backgroundOriginMerging?: boolean; + + /** + * Controls background-size merging into shorthand; defaults to `true` + */ + backgroundSizeMerging?: boolean; + + /** + * controls color optimizations; defaults to `true` + */ + colors?: boolean, + + /** + * Controls keeping IE bang hack; defaults to `false` + */ + ieBangHack?: boolean; + + /** + * Controls keeping IE `filter` / `-ms-filter`; defaults to `false` + */ + ieFilters?: boolean; + + /** + * Controls keeping IE prefix hack; defaults to `false` + */ + iePrefixHack?: boolean; + + /** + * Controls keeping IE suffix hack; defaults to `false` + */ + ieSuffixHack?: boolean; + + /** + * Controls property merging based on understandably; defaults to `true` + */ + merging?: boolean; + + /** + * Controls shortening pixel units into `pc`, `pt`, or `in` units; defaults to `false` + */ + shorterLengthUnits?: false; + + /** + * Controls keeping space after closing brace - `url() no-repeat` into `url()no-repeat`; defaults to `true` + */ + spaceAfterClosingBrace?: true; + + /** + * Controls keeping quoting inside `url()`; defaults to `false` + */ + urlQuotes?: boolean; + + /** + * Controls removal of units `0` value; defaults to `true` + */ + zeroUnits?: boolean; + }; + /** + * A hash of options related to compatibility of selectors + */ + selectors?: { + /** + * Controls extra space before `nav` element; defaults to `false` + */ + adjacentSpace?: boolean; + + /** + * Controls removal of IE7 selector hacks, e.g. `*+html...`; defaults to `true` + */ + ie7Hack?: boolean; + + /** + * Controls a whitelist of mergeable pseudo classes; defaults to `[':active', ...]` + */ + mergeablePseudoClasses?: ReadonlyArray; + + /** + * Controls a whitelist of mergeable pseudo elements; defaults to `['::after', ...]` + */ + mergeablePseudoElements: ReadonlyArray; + + /** + * Controls maximum number of selectors in a single rule (since 4.1.0); defaults to `8191` + */ + mergeLimit: number; + + /** + * Controls merging of rules with multiple pseudo classes / elements (since 4.1.0); defaults to `true` + */ + multiplePseudoMerging: boolean; + }; + /** + * A hash of options related to comparability of supported units + */ + units?: { + /** + * Controls treating `ch` as a supported unit; defaults to `true` + */ + ch?: boolean; + + /** + * Controls treating `in` as a supported unit; defaults to `true` + */ + in?: boolean; + + /** + * Controls treating `pc` as a supported unit; defaults to `true` + */ + pc?: boolean; + + /** + * Controls treating `pt` as a supported unit; defaults to `true` + */ + pt?: boolean; + + /** + * Controls treating `rem` as a supported unit; defaults to `true` + */ + rem?: boolean; + + /** + * Controls treating `vh` as a supported unit; defaults to `true` + */ + vh?: boolean; + + /** + * Controls treating `vm` as a supported unit; defaults to `true` + */ + vm?: boolean; + + /** + * Controls treating `vmax` as a supported unit; defaults to `true` + */ + vmax?: boolean; + + /** + * Controls treating `vmin` as a supported unit; defaults to `true` + */ + vmin?: boolean; + }; + } + + /** + * Fine grained options for configuring the CSS formatting + */ + interface FormatOptions { + /** + * Controls where to insert breaks + */ + breaks?: { + /** + * Controls if a line break comes after an at-rule; e.g. `@charset`; defaults to `false` + */ + afterAtRule?: boolean; + + /** + * Controls if a line break comes after a block begins; e.g. `@media`; defaults to `false` + */ + afterBlockBegins?: boolean; + + /** + * Controls if a line break comes after a block ends, defaults to `false` + */ + afterBlockEnds?: boolean; + + /** + * Controls if a line break comes after a comment; defaults to `false` + */ + afterComment?: boolean; + + /** + * Controls if a line break comes after a property; defaults to `false` + */ + afterProperty?: boolean; + + /** + * Controls if a line break comes after a rule begins; defaults to `false` + */ + afterRuleBegins?: boolean; + + /** + * Controls if a line break comes after a rule ends; defaults to `false` + */ + afterRuleEnds?: boolean; + + /** + * Controls if a line break comes before a block ends; defaults to `false` + */ + beforeBlockEnds?: boolean; + + /** + * Controls if a line break comes between selectors; defaults to `false` + */ + betweenSelectors?: boolean; + }; + /** + * Controls the new line character, can be `'\r\n'` or `'\n'`(aliased as `'windows'` and `'unix'` + * or `'crlf'` and `'lf'`); defaults to system one, so former on Windows and latter on Unix + */ + breakWith?: string; + + /** + * Controls number of characters to indent with; defaults to `0` + */ + indentBy?: number; + + /** + * Controls a character to indent with, can be `'space'` or `'tab'`; defaults to `'space'` + */ + indentWith?: "space" | "tab"; + + /** + * Controls where to insert spaces + */ + spaces?: { + /** + * Controls if spaces come around selector relations; e.g. `div > a`; defaults to `false` + */ + aroundSelectorRelation?: boolean; + + /** + * Controls if a space comes before a block begins; e.g. `.block {`; defaults to `false` + */ + beforeBlockBegins?: boolean; + + /** + * Controls if a space comes before a value; e.g. `width: 1rem`; defaults to `false` + */ + beforeValue?: boolean; + }; + /** + * Controls maximum line length; defaults to `false` + */ + wrapAt?: false | number; + } + + /** + * Fine grained options for configuring optimizations + */ + interface OptimizationsOptions { + 1?: { + /** + * Sets all optimizations at this level unless otherwise specified + */ + all?: boolean; + + /** + * Controls `@charset` moving to the front of a stylesheet; defaults to `true` + */ + cleanupCharsets?: boolean; + + /** + * Controls URL normalization; defaults to `true` + */ + normalizeUrls?: boolean; + + /** + * Controls `background` property optimizations; defaults to `true` + */ + optimizeBackground?: boolean; + + /** + * Controls `border-radius` property optimizations; defaults to `true` + */ + optimizeBorderRadius?: boolean; + + /** + * Controls `filter` property optimizations; defaults to `true` + */ + optimizeFilter?: boolean; + + /** + * Controls `font` property optimizations; defaults to `true` + */ + optimizeFont?: boolean; + + /** + * Controls `font-weight` property optimizations; defaults to `true` + */ + optimizeFontWeight?: boolean; + + /** + * Controls `outline` property optimizations; defaults to `true` + */ + optimizeOutline?: boolean; + + /** + * Controls removing empty rules and nested blocks; defaults to `true` + */ + removeEmpty?: boolean; + + /** + * Controls removing negative paddings; defaults to `true` + */ + removeNegativePaddings?: boolean; + + /** + * Controls removing quotes when unnecessary; defaults to `true` + */ + removeQuotes?: boolean; + + /** + * Controls removing unused whitespace; defaults to `true` + */ + removeWhitespace?: boolean; + + /** + * Contols removing redundant zeros; defaults to `true` + */ + replaceMultipleZeros?: boolean; + + /** + * Controls replacing time units with shorter values; defaults to `true` + */ + replaceTimeUnits?: boolean; + + /** + * Controls replacing zero values with units; defaults to `true` + */ + replaceZeroUnits?: boolean; + + /** + * Rounds pixel values to `N` decimal places; `false` disables rounding; defaults to `false` + */ + roundingPrecision?: boolean; + + /** + * denotes selector sorting method; can be `'natural'` or `'standard'`, `'none'`, or false (the last two + * since 4.1.0); defaults to `'standard'` + */ + selectorsSortingMethod?: "standard" | "natural" | "none"; + + /** + * denotes a number of /*! ... * / comments preserved; defaults to `all` + */ + specialComments?: string; + + /** + * Controls at-rules (e.g. `@charset`, `@import`) optimizing; defaults to `true` + */ + tidyAtRules?: boolean; + + /** + * Controls block scopes (e.g. `@media`) optimizing; defaults to `true` + */ + tidyBlockScopes?: boolean; + + /** + * Controls selectors optimizing; defaults to `true` + */ + tidySelectors?: boolean; + + /** + * Controls removing trailing semicolons in rule; defaults to `false` - means remove + */ + semicolonAfterLastProperty?: boolean; + + /** + * Defines a callback for fine-grained property optimization; defaults to no-op + */ + transform?: (propertyName: string, propertyValue: string, selector?: string) => string; + }; + 2?: { + /** + * Sets all optimizations at this level unless otherwise specified + */ + all?: boolean; + + /** + * Controls adjacent rules merging; defaults to true + */ + mergeAdjacentRules?: boolean; + + /** + * Controls merging properties into shorthands; defaults to true + */ + mergeIntoShorthands?: boolean; + + /** + * Controls `@media` merging; defaults to true + */ + mergeMedia?: boolean; + + /** + * Controls non-adjacent rule merging; defaults to true + */ + mergeNonAdjacentRules?: boolean; + + /** + * Controls semantic merging; defaults to false + */ + mergeSemantically?: boolean; + + /** + * Controls property overriding based on understandably; defaults to true + */ + overrideProperties?: boolean; + + /** + * Controls removing empty rules and nested blocks; defaults to `true` + */ + removeEmpty?: boolean; + + /** + * Controls non-adjacent rule reducing; defaults to true + */ + reduceNonAdjacentRules?: boolean; + + /** + * Controls duplicate `@font-face` removing; defaults to true + */ + removeDuplicateFontRules?: boolean; + + /** + * Controls duplicate `@media` removing; defaults to true + */ + removeDuplicateMediaBlocks?: boolean; + + /** + * Controls duplicate rules removing; defaults to true + */ + removeDuplicateRules?: boolean; + + /** + * Controls unused at rule removing; defaults to false (available since 4.1.0) + */ + removeUnusedAtRules?: boolean; + + /** + * Controls rule restructuring; defaults to false + */ + restructureRules?: boolean; + + /** + * Controls which properties won't be optimized, defaults to `[]` which means all will be optimized (since 4.1.0) + */ + skipProperties?: ReadonlyArray; + }; + } + + /** + * Hash of input source(s). Passing an array of hashes allows you to explicitly specify the order in which the input files + * are concatenated. Whereas when you use a single hash the order is determined by the traversal order of object properties + */ + interface Source { + /** + * Path to file + */ + [path: string]: { + /** + * The contents of the file, should be css + */ + styles: string; + + /** + * The source map of the file, if needed + */ + sourceMap?: string; + }; + } + + /** + * Callback type when fetch is used + */ + type FetchCallback = (message: string | number, body: string) => void; + + /** + * Union of all types acceptable as input for the minify function + */ + type Sources = string | ReadonlyArray | Source | ReadonlyArray | Buffer; + + /** + * Union type for both types of minifier functions + */ + type Minifier = MinifierOutput | MinifierPromise; + + /** + * Interface exposed when a new CleanCSS object is created + */ + interface MinifierOutput { + minify(sources: Sources, callback?: (error: any, output: Output) => void): Output; + minify(sources: Sources, sourceMap: string, callback?: (error: any, output: Output) => void): Output; + } + /** + * Interface exposed when a new CleanCSS object is created with returnPromise set to true + */ + interface MinifierPromise { + minify(sources: Sources, sourceMap?: string): Promise; + } + + /** + * Options when returning a promise + */ + type OptionsPromise = OptionsBase & { + /** + * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` + */ + returnPromise: true + }; + + /** + * Options when returning an output + */ + type OptionsOutput = OptionsBase & { + /** + * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` + */ + returnPromise?: false + }; + + /** + * Discriminant union of both sets of options types. If you initialize without setting `returnPromise: true` + * and want to return a promise, you will need to cast to the correct options type so that TypeScript + * knows what the expected return type will be: + * `(options = options as CleanCSS.OptionsPromise).returnPromise = true` + */ + type Options = OptionsPromise | OptionsOutput; + + /** + * Constructor interface for CleanCSS + */ + interface Constructor { + new(options: OptionsPromise): MinifierPromise; + new(options?: OptionsOutput): MinifierOutput; + } } -declare class CleanCSS { - constructor(options?: CleanCSS.Options); - minify(sources: string | Array | Object, callback?: (error: any, minified: CleanCSS.Output) => void): CleanCSS.Output; -} +/** + * Creates a new CleanCSS object which can be used to minify css + */ +declare const CleanCSS: CleanCSS.Constructor; export = CleanCSS; diff --git a/types/clean-css/tslint.json b/types/clean-css/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/clean-css/tslint.json +++ b/types/clean-css/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/clean-css/v3/clean-css-tests.ts b/types/clean-css/v3/clean-css-tests.ts new file mode 100644 index 0000000000..b9b958d51b --- /dev/null +++ b/types/clean-css/v3/clean-css-tests.ts @@ -0,0 +1,54 @@ + +import * as CleanCSS from 'clean-css'; + +var source = 'a{font-weight:bold;}'; +var minified = new CleanCSS().minify(source).styles; + +var source = '@import url(http://path/to/remote/styles);'; +new CleanCSS().minify(source, function (error, minified) { + console.log(minified.styles); +}); + +const pathToOutputDirectory = 'path'; + +new CleanCSS({ sourceMap: true, target: pathToOutputDirectory }) + .minify(source, function (error, minified) { + // access minified.sourceMap for SourceMapGenerator object + // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details + // see https://github.com/jakubpawlowicz/clean-css/blob/master/bin/cleancss#L114 on how it's used in clean-css' CLI + console.log(minified.sourceMap); +}); + +const inputSourceMapAsString = 'input'; +new CleanCSS({ sourceMap: inputSourceMapAsString, target: pathToOutputDirectory }) + .minify(source, function (error, minified) { + // access minified.sourceMap to access SourceMapGenerator object + // see https://github.com/mozilla/source-map/#sourcemapgenerator for more details + // see https://github.com/jakubpawlowicz/clean-css/blob/master/bin/cleancss#L114 on how it's used in clean-css' CLI + console.log(minified.sourceMap); +}); + +new CleanCSS({ sourceMap: true, target: pathToOutputDirectory }).minify({ + 'path/to/source/1': { + styles: '...styles...', + sourceMap: '...source-map...' + }, + 'path/to/source/2': { + styles: '...styles...', + sourceMap: '...source-map...' + } +}, function (error, minified) { + // access minified.sourceMap as above + console.log(minified.sourceMap); +}); + +new CleanCSS().minify(['path/to/file/one', 'path/to/file/two']); + +new CleanCSS().minify({ + 'path/to/file/one': { + styles: 'contents of file one' + }, + 'path/to/file/two': { + styles: 'contents of file two' + } +}); \ No newline at end of file diff --git a/types/clean-css/v3/index.d.ts b/types/clean-css/v3/index.d.ts new file mode 100644 index 0000000000..87fb7e7f6c --- /dev/null +++ b/types/clean-css/v3/index.d.ts @@ -0,0 +1,108 @@ +// Type definitions for clean-css v3.4.9 +// Project: https://github.com/jakubpawlowicz/clean-css +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare namespace CleanCSS { + interface Options { + // Set to false to disable advanced optimizations - selector & property merging, reduction, etc. + advanced?: boolean; + + // Set to false to disable aggressive merging of properties. + aggressiveMerging?: boolean; + + // Turns on benchmarking mode measuring time spent on cleaning up (run npm run bench to see example) + benchmark?: boolean; + + // Enables compatibility mode + compatibility?: Object; + + // Set to true to get minification statistics under stats property (see test/custom-test.js for examples) + debug?: boolean; + + // A hash of options for @import inliner, see test/protocol-imports-test.js for examples, or this comment for a proxy use case. + inliner?: Object; + + // Whether to keep line breaks (default is false) + keepBreaks?: boolean; + + // * for keeping all (default), 1 for keeping first one only, 0 for removing all + keepSpecialComments?: string | number; + + // Whether to merge @media at-rules (default is true) + mediaMerging?: boolean; + + // Whether to process @import rules + processImport?: boolean; + + // A list of @import rules, can be ['all'] (default), ['local'], ['remote'], or a blacklisted path e.g. ['!fonts.googleapis.com'] + processImportFrom?: Array; + + // Set to false to skip URL rebasing + rebase?: boolean; + + // Path to resolve relative @import rules and URLs + relativeTo?: string; + + // Set to false to disable restructuring in advanced optimizations + restructuring?: boolean; + + // Path to resolve absolute @import rules and rebase relative URLs + root?: string; + + // Rounding precision; defaults to 2; -1 disables rounding + roundingPrecision?: number; + + // Set to true to enable semantic merging mode which assumes BEM-like content (default is false as it's highly likely this will break your stylesheets - use with caution!) + semanticMerging?: boolean; + + // Set to false to skip shorthand compacting (default is true unless sourceMap is set when it's false) + shorthandCompacting?: boolean; + + // Exposes source map under sourceMap property, e.g. new CleanCSS().minify(source).sourceMap (default is false) If input styles are a product of CSS preprocessor (Less, Sass) an input source map can be passed as a string. + sourceMap?: boolean | string; + + // Set to true to inline sources inside a source map's sourcesContent field (defaults to false) It is also required to process inlined sources from input source maps. + sourceMapInlineSources?: boolean; + + // Path to a folder or an output file to which rebase all URLs + target?: string; + } + + interface Output { + // Optimized output CSS as a string + styles: string; + + // Output source map (if requested with sourceMap option) + sourceMap: string; + + // A list of errors raised + errors: Array; + + // A list of warnings raised + warnings: Array; + + // A hash of statistic information (if requested with debug option) + stats: { + // Original content size (after import inlining) + originalSize: number; + + // Optimized content size + minifiedSize: number; + + // Time spent on optimizations + timeSpent: number; + + // A ratio of output size to input size (e.g. 25% if content was reduced from 100 bytes to 75 bytes) + efficiency: number; + }; + } +} + +declare class CleanCSS { + constructor(options?: CleanCSS.Options); + minify(sources: string | Array | Object, callback?: (error: any, minified: CleanCSS.Output) => void): CleanCSS.Output; +} + +export = CleanCSS; \ No newline at end of file diff --git a/types/clean-css/v3/tsconfig.json b/types/clean-css/v3/tsconfig.json new file mode 100644 index 0000000000..8a2c2eae67 --- /dev/null +++ b/types/clean-css/v3/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "clean-css": [ + "clean-css/v3" + ], + "clean-css/*": [ + "clean-css/v3/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clean-css-tests.ts" + ] +} \ No newline at end of file diff --git a/types/clean-css/v3/tslint.json b/types/clean-css/v3/tslint.json new file mode 100644 index 0000000000..a4c53997aa --- /dev/null +++ b/types/clean-css/v3/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} \ No newline at end of file diff --git a/types/cleave.js/cleave.js-tests.tsx b/types/cleave.js/cleave.js-tests.tsx index a826d2607a..461e4f4d05 100644 --- a/types/cleave.js/cleave.js-tests.tsx +++ b/types/cleave.js/cleave.js-tests.tsx @@ -1,7 +1,7 @@ import * as React from "react"; import Cleave = require("cleave.js"); import CleaveReact = require("cleave.js/react"); -import { Props } from "cleave.js/react/props"; +import { Props, ChangeEvent } from "cleave.js/react/props"; const ExampleSelector1 = () => { const cleave = new Cleave("#my-input", { phone: true }); @@ -41,3 +41,17 @@ const ExampleReact2 = (props: Props) => { /> ); }; + +const ExampleReact3 = (props: Props) => { + const handleChange = (e: ChangeEvent) => { + return e.target.rawValue; + }; + return ( + + ); +}; diff --git a/types/cleave.js/index.d.ts b/types/cleave.js/index.d.ts index 77d2e818ca..11067195ea 100644 --- a/types/cleave.js/index.d.ts +++ b/types/cleave.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cleave.js 1.3 +// Type definitions for cleave.js 1.4 // Project: https://github.com/nosir/cleave.js // Definitions by: C Lentfort , // J Giancono , diff --git a/types/cleave.js/react/props.d.ts b/types/cleave.js/react/props.d.ts index 6ce47db62c..d881e1b319 100644 --- a/types/cleave.js/react/props.d.ts +++ b/types/cleave.js/react/props.d.ts @@ -3,8 +3,15 @@ import { CleaveOptions } from "../options"; export type InitHandler = (owner: React.ReactInstance) => void; +export interface ChangeEvent extends React.ChangeEvent { + target: { rawValue: string } & EventTarget & T; +} + +export type ChangeEventHandler = React.EventHandler>; + export interface Props extends React.InputHTMLAttributes { onInit?: InitHandler; options: CleaveOptions; htmlRef?: (i: any) => void; + onChange?: ChangeEventHandler; } diff --git a/types/cli-spinners/cli-spinners-tests.ts b/types/cli-spinners/cli-spinners-tests.ts new file mode 100644 index 0000000000..45acb25db7 --- /dev/null +++ b/types/cli-spinners/cli-spinners-tests.ts @@ -0,0 +1,3 @@ +import cliSpinners = require('cli-spinners'); + +cliSpinners.dots; // $ExpectType Spinner diff --git a/types/cli-spinners/index.d.ts b/types/cli-spinners/index.d.ts new file mode 100644 index 0000000000..db04ab5cc1 --- /dev/null +++ b/types/cli-spinners/index.d.ts @@ -0,0 +1,87 @@ +// Type definitions for cli-spinners 1.3 +// Project: https://github.com/sindresorhus/cli-spinners#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = cliSpinners; + +declare const cliSpinners: Record; + +declare namespace cliSpinners { + type SpinnerName = + | 'dots' + | 'dots2' + | 'dots3' + | 'dots4' + | 'dots5' + | 'dots6' + | 'dots7' + | 'dots8' + | 'dots9' + | 'dots10' + | 'dots11' + | 'dots12' + | 'line' + | 'line2' + | 'pipe' + | 'simpleDots' + | 'simpleDotsScrolling' + | 'star' + | 'star2' + | 'flip' + | 'hamburger' + | 'growVertical' + | 'growHorizontal' + | 'balloon' + | 'balloon2' + | 'noise' + | 'bounce' + | 'boxBounce' + | 'boxBounce2' + | 'triangle' + | 'arc' + | 'circle' + | 'squareCorners' + | 'circleQuarters' + | 'circleHalves' + | 'squish' + | 'toggle' + | 'toggle2' + | 'toggle3' + | 'toggle4' + | 'toggle5' + | 'toggle6' + | 'toggle7' + | 'toggle8' + | 'toggle9' + | 'toggle10' + | 'toggle11' + | 'toggle12' + | 'toggle13' + | 'arrow' + | 'arrow2' + | 'arrow3' + | 'bouncingBar' + | 'bouncingBall' + | 'smiley' + | 'monkey' + | 'hearts' + | 'clock' + | 'earth' + | 'moon' + | 'runner' + | 'pong' + | 'shark' + | 'dqpb' + | 'weather' + | 'christmas' + | 'grenade' + | 'point' + | 'layer'; + + interface Spinner { + interval: number; + frames: string[]; + } +} diff --git a/types/cli-spinners/tsconfig.json b/types/cli-spinners/tsconfig.json new file mode 100644 index 0000000000..8b4a54bd83 --- /dev/null +++ b/types/cli-spinners/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", + "cli-spinners-tests.ts" + ] +} diff --git a/types/cli-spinners/tslint.json b/types/cli-spinners/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cli-spinners/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/clovelced-plugin-audiomanagement/clovelced-plugin-audiomanagement-tests.ts b/types/clovelced-plugin-audiomanagement/clovelced-plugin-audiomanagement-tests.ts new file mode 100644 index 0000000000..ed544553b9 --- /dev/null +++ b/types/clovelced-plugin-audiomanagement/clovelced-plugin-audiomanagement-tests.ts @@ -0,0 +1,29 @@ +import * as AudioManagement from 'clovelced-plugin-audiomanagement'; + +AudioManagement.setAudioMode(AudioManagement.AudioMode.NORMAL, () => { +}, (error: any) => { +}); + +AudioManagement.getAudioMode((results) => { + results.audioMode; + results.label; +}, (error: any) => { +}); + +AudioManagement.setVolume(AudioManagement.VolumeType.MUSIC, 5, () => { +}, (error: any) => { +}); + +AudioManagement.getVolume(AudioManagement.VolumeType.NOTIFICATION, (results) => { + results.volume; +}, (error: any) => { +}); + +AudioManagement.getMaxVolume(AudioManagement.VolumeType.RING, (results) => { + results.maxVolume; +}, (error: any) => { +}); + +AudioManagement.AudioMode.SILENT; +AudioManagement.AudioMode.VIBRATE; +AudioManagement.VolumeType.SYSTEM; diff --git a/types/clovelced-plugin-audiomanagement/index.d.ts b/types/clovelced-plugin-audiomanagement/index.d.ts new file mode 100644 index 0000000000..efd51a941a --- /dev/null +++ b/types/clovelced-plugin-audiomanagement/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for clovelced-plugin-audiomanagement 1.0 +// Project: https://github.com/clovelCed/cordova-plugin-audiomanagement#readme +// Definitions by: Marc Kassay +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export enum AudioMode { + SILENT = 0, + VIBRATE, + NORMAL +} + +export enum VolumeType { + RING = 0, + MUSIC, + NOTIFICATION, + SYSTEM +} + +/** + * Sets the `AudioManagement.AudioMode` for the device. + * + * @param mode the device can be set to: Silent, Normal, Vibrate + * @param onSuccess a callback when setting succeeds. + * @param onError a callback when setting fails. + * @returns void + */ +export function setAudioMode(mode: AudioMode, onSuccess: () => void, onError: (error: any) => void): void; + +/** + * Gets the current `AudioManagement.AudioMode` of the device. + * + * @param onSuccess a callback when succeeds with an object with `label` and `audioMode` properties. + * @param onError a callback when getting fails. + * @returns void + */ +export function getAudioMode(onSuccess: (results: { audioMode: AudioMode, label: string }) => void, onError: (error: any) => void): void; + +/** + * Sets the specified `AudioManagement.VolumeType` for the device with the value from `volume`. + * + * @param type the `AudioManagement.VolumeType` to set + * @param volume the volume value + * @param onSuccess a callback when setting succeeds. + * @param onError a callback when setting fails. + * @returns void + */ +export function setVolume(type: VolumeType, volume: number, onSuccess: () => void, onError: (error: any) => void): void; + +/** + * Gets the specified `AudioManagement.VolumeType`'s `volume`. + * + * @param type the `AudioManagement.VolumeType` to get + * @param onSuccess a callback when getting succeeds with an object with numeric `volume` property. + * @param onError a callback when getting fails. + * @returns void + */ +export function getVolume(type: VolumeType, onSuccess: (results: { volume: number }) => void, onError: (error: any) => void): void; + +/** + * Gets the specified `AudioManagement.VolumeType`'s maximum `volume` that the device is currently set to. + * + * @param type the `AudioManagement.VolumeType` to get + * @param onSuccess a callback when getting succeeds with an object with numeric `maxVolume` property. + * @param onError a callback when getting fails. + * @returns void + */ +export function getMaxVolume(type: VolumeType, onSuccess: (results: { maxVolume: number }) => void, onError: (error: any) => void): void; diff --git a/types/clovelced-plugin-audiomanagement/tsconfig.json b/types/clovelced-plugin-audiomanagement/tsconfig.json new file mode 100644 index 0000000000..5798a1f280 --- /dev/null +++ b/types/clovelced-plugin-audiomanagement/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", + "clovelced-plugin-audiomanagement-tests.ts" + ] +} diff --git a/types/clovelced-plugin-audiomanagement/tslint.json b/types/clovelced-plugin-audiomanagement/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/clovelced-plugin-audiomanagement/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/clusterize.js/index.d.ts b/types/clusterize.js/index.d.ts index 7c549761d6..47da5a2140 100644 --- a/types/clusterize.js/index.d.ts +++ b/types/clusterize.js/index.d.ts @@ -32,9 +32,9 @@ declare namespace Clusterize { } interface Callbacks { - clusterWillChange?(cb: () => void): void; - clusterChanged?(cb: () => void): void; - scrollingProgress?(cb: (progress: number) => void): void; + clusterWillChange?: () => void; + clusterChanged?: () => void; + scrollingProgress?: (progress: number) => void; } } diff --git a/types/coinbase/coinbase-tests.ts b/types/coinbase/coinbase-tests.ts index fb804ac566..65ec9693bd 100644 --- a/types/coinbase/coinbase-tests.ts +++ b/types/coinbase/coinbase-tests.ts @@ -25,7 +25,7 @@ client.getAccount("abcdef", (error: Error, account: coinbase.Account): void => { account.getBuy("abcdef", (error: Error, buy: coinbase.Buy): void => undefined); - account.getBuys((error: Error, buy: coinbase.Buy[]): void => undefined); + account.getBuys(null, (error: Error, buy: coinbase.Buy[]): void => undefined); account.getDeposit("abcdef", (error: Error, deposit: coinbase.Deposit): void => undefined); @@ -33,7 +33,7 @@ client.getAccount("abcdef", (error: Error, account: coinbase.Account): void => { account.getSell("abcdef", (error: Error, deposit: coinbase.Sell): void => undefined); - account.getSells((error: Error, deposit: coinbase.Sell[]): void => undefined); + account.getSells(null, (error: Error, deposit: coinbase.Sell[]): void => undefined); account.getTransaction("abcdef", (error: Error, deposit: coinbase.Transaction): void => undefined); diff --git a/types/coinbase/index.d.ts b/types/coinbase/index.d.ts index 6057f58142..82fc32a7d3 100644 --- a/types/coinbase/index.d.ts +++ b/types/coinbase/index.d.ts @@ -536,6 +536,21 @@ export class Account implements Resource { */ balance: MoneyHash; + /** + * Allow deposits + */ + allow_deposits: boolean; + + /** + * Allow withdrawls + */ + allow_withdrawals: boolean; + + /** + * Account worth in fiat. + */ + native_balance: MoneyHash; + /** * Promote an account as primary account. * Scope: wallet:accounts:update @@ -630,7 +645,7 @@ export class Account implements Resource { * Lists buys for an account. * Scope: wallet:buys:read */ - getBuys(cb: (error: Error, result: Buy[]) => void): void; + getBuys(opts: null, cb: (error: Error, result: Buy[]) => void): void; /** * Show an individual buy. @@ -663,7 +678,7 @@ export class Account implements Resource { * Lists sells for an account. * Scope: wallet:sells:read */ - getSells(cb: (error: Error, result: Sell[]) => void): void; + getSells(opts: null, cb: (error: Error, result: Sell[]) => void): void; /** * Show an individual sell. @@ -883,7 +898,7 @@ export class Buy implements Resource { /** * Fee associated to this buy */ - fee: MoneyHash; + fees: Fee[]; /** * Has this buy been committed? @@ -900,6 +915,26 @@ export class Buy implements Resource { */ payout_at?: string; + /** + * Unit price of the base currency. + */ + unit_price: UnitPrice; + + /** + * Hold period for transfer. + */ + hold_business_days: number; + + /** + * Is it the first buy for this symbol? + */ + is_first_buy: boolean; + + /** + * Is there another action required to make the transfer pass? + */ + requires_completion_step: boolean; + /** * Completes a buy that is created in commit: false state. * If the exchange rate has changed since the buy was created, this call will fail with the error “The exchange rate updated while you @@ -910,6 +945,32 @@ export class Buy implements Resource { commit(cb: (error: Error, transaction: Buy) => void): void; } +export interface Fee { + /** + * Amount associated to this fee + */ + amount: MoneyHash; + /** + * Fee beneficiary ("bank", "coinbase", ...) + */ + type: string; +} + +export interface UnitPrice { + /** + * Amount as floating-point in a string + */ + amount: string; + /** + * Currency e.g. "BTC" (see Client#getCurrencies() for available strings) + */ + currency: string; + /** + * Type of price + */ + scale: number; +} + export type SellStatus = "created" | "completed" | "canceled"; /** diff --git a/types/color-diff/color-diff-tests.ts b/types/color-diff/color-diff-tests.ts new file mode 100644 index 0000000000..684858c203 --- /dev/null +++ b/types/color-diff/color-diff-tests.ts @@ -0,0 +1,17 @@ +import diff from "color-diff"; + +const color = { R: 255, G: 1, B: 30 }; +// red, green, blue +const palette = [ + { R: 255, G: 0, B: 0 }, + { R: 0, G: 255, B: 0 }, + { R: 0, G: 0, B: 255 } +]; + +diff.closest(color, palette); // {R: 255, G: 0, B: 0 }, red + +const color1 = { R: 255, G: 255, B: 255 }; +// black, white +const palette1 = [{ R: 0, G: 0, B: 0 }, { R: 255, G: 255, B: 255 }]; + +diff.furthest(color1, palette1); // {R: 0, G: 0, B: 0 }, black diff --git a/types/color-diff/index.d.ts b/types/color-diff/index.d.ts new file mode 100644 index 0000000000..f331b7203c --- /dev/null +++ b/types/color-diff/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for color-diff 1.1 +// Project: https://github.com/markusn/color-diff#readme +// Definitions by: katsanva +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +export interface RGBColor { + R: number; + G: number; + B: number; + A?: number; +} + +export interface LabColor { + L: number; + a: number; + b: number; +} + +export function diff(c1: LabColor, c2: LabColor): number; + +export function rgb_to_lab(c: RGBColor): LabColor; +export function rgba_to_lab(c: RGBColor, bc?: RGBColor): LabColor; + +export function closest( + color: RGBColor, + palette: ReadonlyArray, + backgroundColor?: RGBColor +): RGBColor; + +export function furthest( + color: RGBColor, + palette: ReadonlyArray, + backgroundColor?: RGBColor +): RGBColor; + +export function map_palette( + a: ReadonlyArray, + b: ReadonlyArray, + type?: "closest" | "furthest", + backgroundColor?: RGBColor +): { [key: string]: RGBColor }; + +export function palette_map_key(c: RGBColor): string; + +export function closest_lab( + color: LabColor, + palette: ReadonlyArray +): LabColor; + +export function furthest_lab( + color: LabColor, + palette: ReadonlyArray +): LabColor; + +export function map_palette_lab( + p1: ReadonlyArray, + p2: ReadonlyArray +): { [key: string]: LabColor }; + +export function lab_palette_map_key(c: LabColor): string; + +export function match_palette_lab( + target_color: LabColor, + palette: ReadonlyArray, + find_furthest: boolean +): LabColor; diff --git a/types/color-diff/tsconfig.json b/types/color-diff/tsconfig.json new file mode 100644 index 0000000000..b8a60d5c99 --- /dev/null +++ b/types/color-diff/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "color-diff-tests.ts"] +} diff --git a/types/color-diff/tslint.json b/types/color-diff/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-diff/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/commonmark/index.d.ts b/types/commonmark/index.d.ts index 96bb2774c5..2f2899b44a 100644 --- a/types/commonmark/index.d.ts +++ b/types/commonmark/index.d.ts @@ -4,15 +4,18 @@ // Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export type NodeType = + 'text' |'softbreak' | 'linebreak' | 'emph' | 'strong' | 'html_inline' | 'link' | 'image' | 'code' | 'document' | 'paragraph' | + 'block_quote' | 'item' | 'list' | 'heading' | 'code_block' | 'html_block' | 'thematic_break' | 'custom_inline' | 'custom_block'; + export class Node { - constructor(nodeType: string, sourcepos?: Position); + constructor(nodeType: NodeType, sourcepos?: Position); /** * (read-only): a String, one of text, softbreak, linebreak, emph, strong, html_inline, link, image, code, document, paragraph, * block_quote, item, list, heading, code_block, html_block, thematic_break. */ - readonly type: 'text' | 'softbreak' | 'linebreak' | 'emph' | 'strong' | 'html_inline' | 'link' | 'image' | 'code' | 'document' | 'paragraph' | - 'block_quote' | 'item' | 'list' | 'heading' | 'code_block' | 'html_block' | 'thematic_break' | 'custom_inline' | 'custom_block'; + readonly type: NodeType; /** * (read-only): a Node or null. */ diff --git a/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-exclusions-tests.ts b/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-exclusions-tests.ts new file mode 100644 index 0000000000..291622b349 --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-exclusions-tests.ts @@ -0,0 +1,70 @@ +import historyApiFallback = require('connect-history-api-fallback-exclusions'); +import express = require('express'); + +const app = express(); +app.use(historyApiFallback()); + +historyApiFallback({ + verbose: true +}); + +historyApiFallback({ + logger: console.log.bind(console) +}); + +historyApiFallback({ + exclusions: [ + '/api/*', + '/health', + ], +}); + +historyApiFallback({ + rewrites: [ + { from: /\/soccer/, to: '/soccer.html' } + ] +}); + +historyApiFallback({ + index: 'default.html' +}); + +historyApiFallback({ + htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] +}); + +historyApiFallback({ + rewrites: [ + { + from: /^\/libs\/(.*)$/, + to(context) { + return './bower_components' + context.parsedUrl.pathname; + } + } + ] +}); + +historyApiFallback({ + rewrites: [ + { + from: /\/app\/login/, + to: function onMatch(ctx) { + if (ctx.parsedUrl.path && ctx.parsedUrl.path.indexOf('.js')) { + return ctx.parsedUrl.href || ''; + } + return '/app/login/index.html'; + } + } + ] +}); + +historyApiFallback({ + rewrites: [ + { + from: /^\/libs\/(.*)$/, + to(context) { + return `/${context.match[2]}/${context.match[3]}`; + } + } + ] +}); diff --git a/types/connect-history-api-fallback-exclusions/index.d.ts b/types/connect-history-api-fallback-exclusions/index.d.ts new file mode 100644 index 0000000000..c83335203a --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for connect-history-api-fallback-exclusions 1.5 +// Project: https://github.com/Wirewheel/connect-history-api-fallback#readme +// Definitions by: Tony Stone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import { Url } from 'url'; + +import * as core from "express-serve-static-core"; + +declare function historyApiFallback(options?: historyApiFallback.Options): core.RequestHandler; + +declare namespace historyApiFallback { + interface Options { + exclusions?: string[]; + disableDotRule?: true; + htmlAcceptHeaders?: string[]; + index?: string; + logger?: typeof console.log; + rewrites?: Rewrite[]; + verbose?: boolean; + } + + interface Context { + match: RegExpMatchArray; + parsedUrl: Url; + } + type RewriteTo = (context: Context) => string; + + interface Rewrite { + from: RegExp; + to: string | RegExp | RewriteTo; + } +} +export = historyApiFallback; diff --git a/types/connect-history-api-fallback-exclusions/tsconfig.json b/types/connect-history-api-fallback-exclusions/tsconfig.json new file mode 100644 index 0000000000..1fc7fec2ca --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/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", + "connect-history-api-fallback-exclusions-tests.ts" + ] +} \ No newline at end of file diff --git a/types/connect-history-api-fallback-exclusions/tslint.json b/types/connect-history-api-fallback-exclusions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/content-range/content-range-tests.ts b/types/content-range/content-range-tests.ts new file mode 100644 index 0000000000..c482d6f072 --- /dev/null +++ b/types/content-range/content-range-tests.ts @@ -0,0 +1,23 @@ +import { format, parse } from 'content-range'; + +format({ + first: 10, + last: 100, + length: 100, + limit: 20, + unit: 'items', +}); + +format({ + length: null, + unit: 'bytes', +}); + +const parts = parse('items 10-29/100'); + +if (parts) { + parts.first; + parts.last; + parts.length; + parts.unit; +} diff --git a/types/content-range/index.d.ts b/types/content-range/index.d.ts new file mode 100644 index 0000000000..b8ee780541 --- /dev/null +++ b/types/content-range/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for content-range 1.1 +// Project: https://github.com/neoziro/content-range +// Definitions by: Alex Brick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ContentRangeFormatOptions { + first?: number; + last?: number; + length: number | null; + limit?: number; + unit: string; +} + +export interface ContentRangeParts { + first: number | null; + last: number | null; + length: number | null; + unit: string; +} + +export function format(options: ContentRangeFormatOptions): string; +export function parse(str: string): ContentRangeParts | null; diff --git a/types/content-range/tsconfig.json b/types/content-range/tsconfig.json new file mode 100644 index 0000000000..a2649416e0 --- /dev/null +++ b/types/content-range/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "content-range-tests.ts" + ] +} diff --git a/types/content-range/tslint.json b/types/content-range/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/content-range/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cookiejar/index.d.ts b/types/cookiejar/index.d.ts index ba50b63ea2..b976a0e1dc 100644 --- a/types/cookiejar/index.d.ts +++ b/types/cookiejar/index.d.ts @@ -112,5 +112,5 @@ export class CookieJar { * grab all cookies matching this access_info * @param accessInfo CookieAccessInfo */ - getCookies(accessInfo: CookieAccessInfo): ReadonlyArray; + getCookies(accessInfo: CookieAccessInfo): ReadonlyArray & { toValueString(): string }; } diff --git a/types/copy/copy-tests.ts b/types/copy/copy-tests.ts new file mode 100644 index 0000000000..c72ad3532a --- /dev/null +++ b/types/copy/copy-tests.ts @@ -0,0 +1,35 @@ +import copy = require('copy'); +import File = require('vinyl'); + +copy.each(['a', 'b'], '.', { cwd: '..' }, () => {}); +copy.each(['a', 'b'], '.', { cwd: '..' }, (error, files) => { + error; // $ExpectType Error | null + files; // $ExpectType File[] | undefined +}); +copy.each(['a', 'b'], '.', () => {}); +copy.each(['a', 'b'], '.', (error, files) => { + error; // $ExpectType Error | null + files; // $ExpectType File[] | undefined +}); + +copy.one('a', '.', { cwd: '..' }, () => {}); +copy.one('a', '.', { cwd: '..' }, (error, files) => { + error; // $ExpectType Error | null + files; // $ExpectType File[] | undefined +}); +copy.one('a', '.', () => {}); +copy.one('a', '.', (error, files) => { + error; // $ExpectType Error | null + files; // $ExpectType File[] | undefined +}); + +copy(['a', 'b'], '.', { cwd: '..' }, () => {}); +copy(['a', 'b'], '.', { cwd: '..' }, (error, files) => { + error; // $ExpectType Error | null + files; // $ExpectType File[] | undefined +}); +copy(['a', 'b'], '.', () => {}); +copy(['a', 'b'], '.', (error, files) => { + error; // $ExpectType Error | null + files; // $ExpectType File[] | undefined +}); diff --git a/types/copy/index.d.ts b/types/copy/index.d.ts new file mode 100644 index 0000000000..567d6594d3 --- /dev/null +++ b/types/copy/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for copy 0.3 +// Project: https://github.com/jonschlinkert/copy +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import File = require('vinyl'); + +declare namespace copy { + /** + * Copy an array of files to the given destination `directory`, with + * `options` and callback function that exposes `err` and the array of + * vinyl files that are created by the copy operation. + * + * ```js + * copy.each(['foo.txt', 'bar.txt', 'baz.txt'], 'dist', function(err, files) { + * // exposes the vinyl `files` created when the files are copied + * }); + * ``` + * @param `files` Filepaths or vinyl files. + * @param `dir` Destination directory + * @param `options` or callback function + * @param `cb` Callback function if no options are specified + */ + function each(files: string[] | File[], dir: string, options: Options, cb: Callback): void; + function each(files: string[] | File[], dir: string, cb: Callback): void; + + /** + * Copy a single `file` to the given `dest` directory, using + * the specified options and callback function. + * + * ```js + * copy.one('foo.txt', 'dist', function(err, file) { + * if (err) throw err; + * // exposes the vinyl `file` that is created when the file is copied + * }); + * ``` + * @param `file` Filepath or vinyl file + * @param `dir` Destination directory + * @param `options` or callback function + * @param `cb` Callback function if no options are specified + */ + function one(pattern: string | File, dir: string, options: Options, cb: Callback): void; + function one(pattern: string | File, dir: string, cb: Callback): void; + + type Callback = (error: Error | null, files?: File[]) => void; + + interface Options { + cwd?: string; + srcBase?: string; + } +} + +/** + * Copy a filepath, vinyl file, array of files, or glob of files to the + * given destination `directory`, with `options` and callback function that + * exposes `err` and the array of vinyl files that are created by the copy + * operation. + * + * ```js + * copy('*.js', 'dist', function(err, file) { + * // exposes the vinyl `file` created when the file is copied + * }); + * ``` + * @param `patterns` Filepath(s), vinyl file(s) or glob of files. + * @param `dir` Destination directory + * @param `options` or callback function + * @param `cb` Callback function if no options are specified + */ +declare function copy( + patterns: string | File | string[] | File[], + dir: string, + options: copy.Options, + callback: copy.Callback, +): void; +declare function copy(patterns: string | File | string[] | File[], dir: string, callback: copy.Callback): void; + +export = copy; diff --git a/types/copy/tsconfig.json b/types/copy/tsconfig.json new file mode 100644 index 0000000000..0b3e1bd3d3 --- /dev/null +++ b/types/copy/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", + "copy-tests.ts" + ] +} diff --git a/types/copy/tslint.json b/types/copy/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/copy/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/copyfiles/copyfiles-tests.ts b/types/copyfiles/copyfiles-tests.ts new file mode 100644 index 0000000000..e1549c3c82 --- /dev/null +++ b/types/copyfiles/copyfiles-tests.ts @@ -0,0 +1,6 @@ +import copyfiles = require('copyfiles'); + +copyfiles(['file'], () => {}); +copyfiles(['file'], error => {}); +copyfiles(['file'], {all: true}, error => {}); +copyfiles(['file'], 10, error => {}); diff --git a/types/copyfiles/index.d.ts b/types/copyfiles/index.d.ts new file mode 100644 index 0000000000..9fc6ecde87 --- /dev/null +++ b/types/copyfiles/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for copyfiles 2.1 +// Project: https://github.com/calvinmetcalf/copyfiles#readme +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace copyfiles { + interface Options { + /** include files & directories begining with a dot (.) */ + all?: boolean; + /** throw error if nothing is copied */ + error?: boolean; + /** pattern or glob to exclude */ + exclude?: string; + /** flatten the output */ + flat?: boolean; + /** do not overwrite destination files if they exist */ + soft?: boolean; + /** slice a path off the bottom of the paths */ + up?: number; + /** print more information to console */ + verbose?: boolean; + } + + type Callback = (error?: Error) => void; +} + +declare function copyfiles(paths: string[], options: copyfiles.Options | number, callback: copyfiles.Callback): void; +declare function copyfiles(paths: string[], callback: copyfiles.Callback): void; + +export = copyfiles; diff --git a/types/copyfiles/tsconfig.json b/types/copyfiles/tsconfig.json new file mode 100644 index 0000000000..83672e27b7 --- /dev/null +++ b/types/copyfiles/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", + "copyfiles-tests.ts" + ] +} diff --git a/types/copyfiles/tslint.json b/types/copyfiles/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/copyfiles/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts b/types/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts index 6e4317ac9d..f7830c18b2 100644 --- a/types/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts +++ b/types/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts @@ -61,59 +61,89 @@ var demoExtendedData : BLECentralPlugin.PeripheralDataExtended = { //get updates about the bluethooth states ble.startStateNotifications((state) => log(`BLE state ${state}`)); +ble.startStateNotifications((state) => log(`BLE state ${state}`), (err: string) => log(`things when wrong ${err}`)); -ble.isEnabled(()=> log(`bluetooth is enabled`), ()=>log(`bluetooth is not enabled`)); +ble.isEnabled(()=> log(`bluetooth is enabled`), err =>log(`bluetooth is not enabled: ${err}`)); //here we try to enable bluetooth -ble.enable(() => log(`yes it worked, or it was already enabled `), () => log(`nope it didn't work, the user pressed cancel, or we are in iOS`)); +ble.enable(() => log(`yes it worked, or it was already enabled `), err => log(`nope it didn't work, the user pressed cancel, or we are in iOS: ${err}`)); ble.showBluetoothSettings(() => log(`yes it worked`), () => log(`nope it didn't work`)) //stop getting updates about the bluethooth states ble.stopStateNotifications() +ble.stopStateNotifications(() => log(`yes it worked`)) +ble.stopStateNotifications(() => log(`yes it worked`), () => log(`nope it didn't work`)) //scan 5 seconds -ble.scan([], 5000, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ); +ble.scan([], 5000, (data) => { devices.push(data); }); +ble.scan([], 5000, (data) => { devices.push(data); }, () => log(`couldn't connect`) ); +ble.scan([], 5000, (data) => { devices.push(data); }, err => log(`couldn't connect: ${err}`) ); //scan continously -ble.startScan([], (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ) +ble.startScan([], (data) => { devices.push(data); }) +ble.startScan([], (data) => { devices.push(data); }, () => log('couldn\'t connect') ) +ble.startScan([], (data) => { devices.push(data); }, err => log(`couldn't connect: ${err}`) ); ////scan continously -ble.startScanWithOptions([], {reportDuplicates:false }, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ) +ble.startScanWithOptions([], {reportDuplicates:false }, (data) => { devices.push(data); }); +ble.startScanWithOptions([], {reportDuplicates:false }, (data) => { devices.push(data); }, err => log(`couldn't connect: ${err}`)); //stop scanning ble.stopScan(()=> log('all good'), ()=> log('couldn\'t stop scanning')); //are we conenected to that device? +ble.isConnected(demoDevice.id, () => log(`already connected to this device`)); ble.isConnected(demoDevice.id, () => log(`already connected to this device`), ()=> log(`not yet connected to that device`)); //connect to a specific device var extendedData : BLECentralPlugin.PeripheralDataExtended; -ble.connect(demoDevice.id, (data)=> extendedData = data, () => log(`couldn't connect to the device`) ); +ble.connect(demoDevice.id, (data)=> extendedData = data, err => log(`couldn't connect to the device: ${err}`) ); //read some data from a characteristic var charsOfOneOfItsServices = demoExtendedData.characteristics.filter((value) => value.service == demoExtendedData.services[0]); +ble.read(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic); ble.read(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data) => log(`we've received some data`), ()=> log(`couldn't read any data`)); //read the rssi ble.readRSSI(demoDevice.id, (rssi)=>log(`Device ${demoDevice.name} has an RSSI of ${rssi}`)); +ble.readRSSI(demoDevice.id, (rssi)=>log(`Device ${demoDevice.name} has an RSSI of ${rssi}`), err => log(`Unable to read RSSI: ${err}`)); + + +// request mtu +ble.requestMtu(demoDevice.id, 10); +ble.requestMtu(demoDevice.id, 10, () => log('it worked')); +ble.requestMtu(demoDevice.id, 10, () => log('it worked'), () => log('it failed')); + +// refreshDeviceCache +ble.refreshDeviceCache(demoDevice.id, 10); +ble.refreshDeviceCache(demoDevice.id, 10, () => log('it worked')); +ble.refreshDeviceCache(demoDevice.id, 10, () => log('it worked'), () => log('it failed')); var notificationsReceived : number = 0; //get notified of changes for that characteristic -ble.startNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data)=> notificationsReceived++, ()=> log(`darn`)); +ble.startNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, + (data)=> notificationsReceived++); +ble.startNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, + (data)=> notificationsReceived++, err => log(`darn: ${err}`)); //write some data +ble.write(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40)); +ble.write(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`)); ble.write(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`)); //write some data without getting notified +ble.writeWithoutResponse(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40)); +ble.writeWithoutResponse(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`)); ble.writeWithoutResponse(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`)); //stop getting notified of changes. ble.stopNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic); +ble.stopNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, () => log('it worked')); +ble.stopNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, () => log('it worked'), () => log('it failed')); //notificationsReceived == 1 //just disconnect ble.disconnect(demoDevice.id); - - - +ble.disconnect(demoDevice.id, () => log('it worked')); +ble.disconnect(demoDevice.id, () => log('it worked'), () => log('it failed')); diff --git a/types/cordova-plugin-ble-central/index.d.ts b/types/cordova-plugin-ble-central/index.d.ts index ccf2396833..070b62ff9e 100644 --- a/types/cordova-plugin-ble-central/index.d.ts +++ b/types/cordova-plugin-ble-central/index.d.ts @@ -1,12 +1,13 @@ -// Type definitions for cordova-plugin-ble-central 1.1.2 +// Type definitions for cordova-plugin-ble-central 1.2.2 // Project: https://github.com/don/cordova-plugin-ble-central // Definitions by: Gidon Junge +// Philip Peitsch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace BLECentralPlugin { - interface PeripheralCharacteristic { + interface PeripheralCharacteristic { service: string; characteristic: string; properties: string[]; @@ -26,7 +27,12 @@ declare namespace BLECentralPlugin { characteristics: PeripheralCharacteristic[] } - + + interface BLEError { + name: string; + id: string; + errorMessage: string; + } interface StartScanOptions { @@ -34,75 +40,80 @@ declare namespace BLECentralPlugin { } export interface BLECentralPluginStatic { - scan(services: string[], seconds: number, success : (data: PeripheralData) => any): void; - scan(services: string[], seconds: number, success : (data: PeripheralData) => any, failure : () => any): void; - - startScan(services: string[], success: (data: PeripheralData) => any): void; - startScan(services: string[], success: (data: PeripheralData) => any, failure: () => any): void; + scan(services: string[], seconds: number, success : (data: PeripheralData) => any, failure? : (error: string) => any): void; - startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any): void; - startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any, failure: () => any): void; + startScan(services: string[], success: (data: PeripheralData) => any, failure?: (error: string|BLEError) => any): void; + + startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any, failure?: (error: string) => any): void; stopScan(): void; - stopScan(success: () => any): void; - stopScan(success: () => any, failure: () => any): void; - - connect(device_id:string, success: (data: PeripheralDataExtended) => any, failure: () => any): void; + stopScan(success: () => any, failure?: () => any): void; - disconnect(device_id:string): void; - disconnect(device_id:string, success: () => any): void; - disconnect(device_id:string, success: () => any, failure: () => any): void; + connect(device_id:string, success: (data: PeripheralDataExtended) => any, failure: (error: string|BLEError) => any): void; - read(device_id: string, service_uuid:string, characteristic_uuid:string): void; - read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void; - read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void; + /* Automatically connect to a device when it is in range of the phone + [iOS] background notifications on ios must be enabled if you want to run in the background + [Android] this relies on the autoConnect argument of BluetoothDevice.connectGatt(). Not all Android devices implement this feature correctly. */ + autoConnect(device_id:string, success: (data: PeripheralDataExtended) => any, failure: (error: string|BLEError) => any): void; - write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void; - write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void; - write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void; + disconnect(device_id:string, success?: () => any, failure?: (error: string|BLEError) => any): void; - /* Writes data to a characteristic without a response from the peripheral. You are not notified if the write fails in the BLE stack. + read(device_id: string, service_uuid:string, characteristic_uuid:string, success?: (rawData: ArrayBuffer) => any, failure?: (error: string|BLEError) => any): void; + + write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success?: () => any, failure?: (error: string|BLEError) => any): void; + + /* Writes data to a characteristic without a response from the peripheral. You are not notified if the write fails in the BLE stack. The success callback is be called when the characteristic is written.*/ - writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void; - writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void; - writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void; + writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success?: () => any, failure?: (error: string) => any): void; /* Register to be notified when the value of a characteristic changes. */ - startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void; - startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void; - - stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string): void; - stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any): void; - stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any, failure: () => any): void; + startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure?: (error: string|BLEError) => any): void; + + stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success?: () => any, failure?: (error: string|BLEError) => any): void; /* Reports if bluetooth is enabled. */ - isEnabled(success: () => any , failure: () => any): void; + isEnabled(success: () => any , failure: (error: string) => any): void; /* Calls the success callback when the peripheral is connected and the failure callback when not connected. */ - isConnected(device_id: string, success: () => any): void; - isConnected(device_id: string, success: () => any, failure: () => any): void; + isConnected(device_id: string, success: () => any, failure?: (error: string) => any): void; - startStateNotifications(success: (state: string) => any): void; - startStateNotifications(success: (state: string) => any, failure: () => any): void; + /* May be used to request (on Android) a larger MTU size to be able to send more data at once + [iOS] requestMtu is not supported on iOS. */ + requestMtu(device_id: string, mtu: number, success?: () => any, failure?: () => any): void; + + /* Clears cached services and characteristics info for some poorly behaved devices. Uses an undocumented API, + so it is not guaranteed to work. + [iOS] refreshDeviceCache is not supported on iOS. */ + refreshDeviceCache(device_id: string, timeout_millis: number, success?: (data: PeripheralDataExtended) => any, failure?: (error: string|BLEError) => any): void; + + startStateNotifications(success: (state: string) => any, failure?: (error: string) => any): void; + + stopStateNotifications(success?: () => any, failure?: () => any): void; - stopStateNotifications(): void; - stopStateNotifications(success: () => any): void; - stopStateNotifications(success: () => any, failure: () => any): void; - /* Opens the Bluetooth settings for the operating systems. [iOS] showBluetoothSettings is not supported on iOS. */ - showBluetoothSettings(): void; - showBluetoothSettings(success: () => any): void; showBluetoothSettings(success: () => any, failure: () => any): void; - + /* Enable Bluetooth on the device. [iOS] enable is not supported on iOS. */ - enable(success: () => any, failure: () => any): void; - + enable(success: () => any, failure: (error: string) => any): void; - readRSSI(device_id:string, success: (rssi: number) => any): void; - readRSSI(device_id:string, success: (rssi: number) => any, failure: () => any): void; + readRSSI(device_id:string, success: (rssi: number) => any, failure?: (error: string) => any): void; + + /* Find connected peripherals offering the listed service UUIDs. + This function wraps CBCentralManager.retrieveConnectedPeripheralsWithServices. + [Android] peripheralsWithIdentifiers is not supported on Android. */ + connectedPeripheralsWithServices(services: string[], success: (data: PeripheralData[]) => any, failure: () => any): void; + + /* Find known (but not necessarily connected) peripherals offering the listed service UUIDs. + This function wraps CBCentralManager.retrievePeripheralsWithIdentifiers + [Android] peripheralsWithIdentifiers is not supported on Android. */ + peripheralsWithIdentifiers(services: string[], success: (data: PeripheralData[]) => any, failure: () => any): void; + + /* Find the bonded devices. + [iOS] bondedDevices is not supported on iOS. */ + bondedDevices(success: (data: PeripheralData[]) => any, failure: () => any): void; } } -declare var ble: BLECentralPlugin.BLECentralPluginStatic; \ No newline at end of file +declare var ble: BLECentralPlugin.BLECentralPluginStatic; diff --git a/types/country-data/country-data-tests.ts b/types/country-data/country-data-tests.ts new file mode 100644 index 0000000000..850116dc63 --- /dev/null +++ b/types/country-data/country-data-tests.ts @@ -0,0 +1,14 @@ +import * as lib from 'country-data'; + +lib.callingCodes.all; // $ExpectType ReadonlyArray +lib.callingCountries.all; // $ExpectType ReadonlyArray +lib.continents.africa; // $ExpectType Continent +lib.continents.africa.countries; // $ExpectType ReadonlyArray +lib.countries.all; // $ExpectType ReadonlyArray +lib.currencies.all; // $ExpectType ReadonlyArray +lib.languages.all; // $ExpectType ReadonlyArray +lib.regions.antarctica; // $ExpectType Region +lib.regions.antarctica.countries; // $ExpectType ReadonlyArray +lib.lookup.countries(""); // $ExpectType ReadonlyArray +lib.lookup.currencies(""); // $ExpectType ReadonlyArray +lib.lookup.languages(""); // $ExpectType ReadonlyArray diff --git a/types/country-data/index.d.ts b/types/country-data/index.d.ts new file mode 100644 index 0000000000..80acbbcbba --- /dev/null +++ b/types/country-data/index.d.ts @@ -0,0 +1,103 @@ +// Type definitions for country-data 0.0 +// Project: https://github.com/OpenBookPrices/country-data +// Definitions by: Logan Dam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Country { + readonly alpha2: string; + readonly alpha3: string; + readonly countryCallingCodes: ReadonlyArray; + readonly currencies: ReadonlyArray; + readonly emoji: string; + readonly ioc: string; + readonly languages: ReadonlyArray; + readonly name: string; + readonly status: string; +} + +export interface Currency { + readonly code: string; + readonly decimals: number; + readonly name: string; + readonly number: number; +} + +export interface Language { + readonly alpha2: string; + readonly alpha3: string; + readonly bibliographic: string; + readonly name: string; +} + +export interface Continent { + readonly name: string; + readonly regions: ReadonlyArray; + readonly countries: ReadonlyArray; +} + +export interface Region { + readonly name: string; + readonly countries: ReadonlyArray; +} + +export const countries: { + readonly all: ReadonlyArray; +}; + +export const continents: { + readonly africa: Continent; + readonly antarctica: Continent; + readonly asia: Continent; + readonly europe: Continent; + readonly northAmerica: Continent; + readonly oceania: Continent; + readonly southAmerica: Continent; +}; + +export const callingCodes: { + readonly all: ReadonlyArray; +}; + +export const callingCountries: { + readonly all: ReadonlyArray; +}; + +export const currencies: { + readonly all: ReadonlyArray; +}; + +export const languages: { + readonly all: ReadonlyArray; +}; + +export const regions: { + readonly centralAsia: Region; + readonly southernAsia: Region; + readonly southeastAsia: Region; + readonly eastAsia: Region; + readonly westernAsia: Region; + readonly centralAfrica: Region; + readonly northAfrica: Region; + readonly southernAfrica: Region; + readonly eastAfrica: Region; + readonly westAfrica: Region; + readonly centralAmerica: Region; + readonly northernAmerica: Region; + readonly caribbean: Region; + readonly southAmerica: Region; + readonly antarctica: Region; + readonly northernEurope: Region; + readonly southernEurope: Region; + readonly easternEurope: Region; + readonly westernEurope: Region; + readonly australia: Region; + readonly melanesia: Region; + readonly micronesia: Region; + readonly polynesia: Region; +}; + +export const lookup: { + readonly countries: (query: any) => ReadonlyArray; + readonly currencies: (query: any) => ReadonlyArray; + readonly languages: (query: any) => ReadonlyArray; +}; diff --git a/types/country-data/tsconfig.json b/types/country-data/tsconfig.json new file mode 100644 index 0000000000..ccbbf6ecd6 --- /dev/null +++ b/types/country-data/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", + "country-data-tests.ts" + ] +} diff --git a/types/country-data/tslint.json b/types/country-data/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/country-data/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/create-xpub/create-xpub-tests.ts b/types/create-xpub/create-xpub-tests.ts new file mode 100644 index 0000000000..c202d819d8 --- /dev/null +++ b/types/create-xpub/create-xpub-tests.ts @@ -0,0 +1,23 @@ +import createXpub = require('create-xpub'); + +// $ExpectType string +createXpub({ + depth: 3, + childNumber: 2147483648, + chainCode: '84cf7d9029cdd9fcadbb3717fd92ec0db7d7d9787c57c13c08fc887c389b566b', + publicKey: + '048bcdcf59f046b13f1eb35b608d1211265fde8cc44fc7a5a7f7107c5cf238095328a0e0d7be17c7d3e48490e8c6433af6d2c3dacc687f3fecaa98a3d05f17de97', +}); + +// $ExpectType string +createXpub({ + networkVersion: createXpub.testnet, + depth: 3, + childNumber: 2147483648, + chainCode: '84cf7d9029cdd9fcadbb3717fd92ec0db7d7d9787c57c13c08fc887c389b566b', + publicKey: + '048bcdcf59f046b13f1eb35b608d1211265fde8cc44fc7a5a7f7107c5cf238095328a0e0d7be17c7d3e48490e8c6433af6d2c3dacc687f3fecaa98a3d05f17de97', +}); + +createXpub.mainnet; // $ExpectType 76067358 +createXpub.testnet; // $ExpectType 70617039 diff --git a/types/create-xpub/index.d.ts b/types/create-xpub/index.d.ts new file mode 100644 index 0000000000..13057396eb --- /dev/null +++ b/types/create-xpub/index.d.ts @@ -0,0 +1,52 @@ +// Type definitions for create-xpub 2.1 +// Project: https://github.com/lukechilds/create-xpub#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = createXpub; + +/** + * Creates a Base58 encoded extended public key (xpub) for use in a + * [BIP32 hierarchical deterministic wallet](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki). + * + * Tip: If you're working with ledgerjs you can pass the output of + * [`getWalletPublicKey()`](http://ledgerhq.github.io/ledgerjs/docs/#btcgetwalletpublickey) almost directly in. + * + * @returns A Base58 encoded extended public key. + */ +declare function createXpub(options: createXpub.Options): string; + +declare namespace createXpub { + /** + * Mainnet (xpub) version bytes. + */ + const mainnet: 0x0488B21E; + /** + * Testnet (tpub) version bytes. + */ + const testnet: 0x043587CF; + + interface Options { + /** + * Network version bytes. + * @default 0x0488B21E + */ + networkVersion?: number; + /** + * The depth of the derived key. + */ + depth: number; + /** + * The child number. + */ + childNumber: number; + /** + * The chain code. + */ + chainCode: string; + /** + * The public key in compressed or uncompressed form. + */ + publicKey: string; + } +} diff --git a/types/create-xpub/tsconfig.json b/types/create-xpub/tsconfig.json new file mode 100644 index 0000000000..53e9b64c11 --- /dev/null +++ b/types/create-xpub/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "create-xpub-tests.ts" + ] +} diff --git a/types/create-xpub/tslint.json b/types/create-xpub/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-xpub/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cron/index.d.ts b/types/cron/index.d.ts index b27bfdf90c..596a9536ca 100644 --- a/types/cron/index.d.ts +++ b/types/cron/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cron 1.3 +// Type definitions for cron 1.6 // Project: https://www.npmjs.com/package/cron // Definitions by: Hiroki Horiuchi // Lundarl Gholoi @@ -9,8 +9,9 @@ export declare class CronTime { * Create a new ```CronTime```. * @param source The time to fire off your job. This can be in the form of cron syntax or a JS ```Date``` object. * @param zone Timezone name. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). + * @param utcOffset UTC offset. Don't use both ```zone``` and ```utcOffset``` together or weird things may happen. */ - constructor(source: string | Date, zone?: string); + constructor(source: string | Date, zone?: string, utcOffset?: string | number); /** * Tells you when ```CronTime``` will be run. @@ -29,19 +30,19 @@ export declare interface CronJobParameters { */ cronTime: string | Date; /** - * The function to fire at the specified time. + * The function to fire at the specified time. If an ```onComplete``` callback was provided, ```onTick``` will receive it as an argument. ```onTick``` may call ```onComplete``` when it has finished its work. */ onTick: () => void; /** - * A function that will fire when the job is complete, when it is stopped. + * A function that will fire when the job is stopped with ```job.stop()```, and may also be called by ```onTick``` at the end of each run. */ onComplete?: () => void; /** - * Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call ```job.start()``` in order to start the job (assuming ```job``` is the variable you set the cronjob to). This does not immediately fire your onTick function, it just gives you more control over the behavior of your jobs. + * Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call ```job.start()``` in order to start the job (assuming ```job``` is the variable you set the cronjob to). This does not immediately fire your ```onTick``` function, it just gives you more control over the behavior of your jobs. */ start?: boolean; /** - * Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). + * Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. */ timeZone?: string; /** @@ -52,6 +53,14 @@ export declare interface CronJobParameters { * This will immediately fire your ```onTick``` function as soon as the requisit initialization has happened. This option is set to ```false``` by default for backwards compatibility. */ runOnInit?: boolean; + /** + * This allows you to specify the offset of your timezone rather than using the ```timeZone``` param. Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. + */ + utcOffset?: string | number; + /** + * If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs. + */ + unrefTimeout?: boolean; } export declare class CronJob { @@ -73,8 +82,10 @@ export declare class CronJob { * @param timeZone Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at [Moment Timezone Website](http://momentjs.com/timezone/). * @param context The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call ```this.stop()```. However, if you change this you'll have access to the functions and values within your context object. * @param runOnInit This will immediately fire your ```onTick``` function as soon as the requisit initialization has happened. This option is set to ```false``` by default for backwards compatibility. + * @param utcOffset This allows you to specify the offset of your timezone rather than using the ```timeZone``` param. Probably don't use both ```timeZone``` and ```utcOffset``` together or weird things may happen. + * @param unrefTimeout If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs. */ - constructor(cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean); + constructor(cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean); /** * Create a new ```CronJob```. * @param options Job parameters. @@ -111,7 +122,7 @@ export declare class CronJob { } export declare var job: - ((cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean) => CronJob) + ((cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean, utcOffset?: string | number, unrefTimeout?: boolean) => CronJob) | ((options: CronJobParameters) => CronJob); export declare var time: (source: string | Date, zone?: string) => CronTime; export declare var sendAt: (cronTime: CronTime) => Date; diff --git a/types/custom-functions-runtime/custom-functions-runtime-tests.ts b/types/custom-functions-runtime/custom-functions-runtime-tests.ts index 0a3c482505..3b773e95b1 100644 --- a/types/custom-functions-runtime/custom-functions-runtime-tests.ts +++ b/types/custom-functions-runtime/custom-functions-runtime-tests.ts @@ -5,17 +5,25 @@ function add10(n: number) { CustomFunctions.associate('ADD10', add10); +CustomFunctions.associate({ + ADD10: add10, + RANDOM: (n: number) => n * Math.random() +}); + +function callerAddress(invocation: CustomFunctions.Invocation) { + return invocation.address; +} + async function getStockValues(ticker: string): Promise { const response = await fetch(`myService.com/prices/${ticker}`); return (await response.json())["price"]; } -async function getStockValuesCancellable( - ticker: string, - handler: CustomFunctions.CancelableHandler -): Promise { +async function getStockValuesCancellable(ticker: string, + invocation: CustomFunctions.CancelableInvocation): Promise { + const address = invocation.address; let shouldStop = false; - handler.onCanceled = () => (shouldStop = true); + invocation.onCanceled = () => (shouldStop = true); await pause(1000); if (shouldStop) { @@ -26,10 +34,9 @@ async function getStockValuesCancellable( return (await response.json())["price"]; } -function stockPriceStream( - ticker: string, - handler: CustomFunctions.StreamingHandler -) { +function stockPriceStream(ticker: string, + invocation: CustomFunctions.StreamingInvocation) { + const address = invocation.address; const updateFrequency = 10 /* milliseconds*/; let isPending = false; @@ -44,14 +51,14 @@ function stockPriceStream( try { const response = await fetch(url); const data = await response.json(); - handler.setResult(data.price); + invocation.setResult(data.price); } catch (error) { - handler.setResult(error); + invocation.setResult(error); } isPending = false; }, updateFrequency); - handler.onCanceled = () => { + invocation.onCanceled = () => { clearInterval(timer); }; } diff --git a/types/custom-functions-runtime/index.d.ts b/types/custom-functions-runtime/index.d.ts index f78f6a45c4..c907fe327e 100644 --- a/types/custom-functions-runtime/index.d.ts +++ b/types/custom-functions-runtime/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for Custom Functions 1.4 // Project: https://github.com/OfficeDev/office-js -// Definitions by: OfficeDev , Michael Zlatkovsky , Michelle Scharlock +// Definitions by: OfficeDev , +// Adam Krantz , +// Michael Zlatkovsky , +// Michelle Scharlock // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -10,41 +13,83 @@ Copyright (c) Microsoft Corporation */ /** - * CustomFunctions namespace, used by Excel Custom Functions * @beta + * CustomFunctions namespace, used by Excel Custom Functions */ declare namespace CustomFunctions { /** * @beta - * Ties together the function's JavaScript name with the JSON id property + * Associates the JavaScript function to the name given by the "id" property in the metadata JSON file. */ function associate(id: string, functionObject: Function): void; + /** + * @beta + * Associates the JavaScript functions to the names given by the "id" properties in the metadata JSON file. + */ + function associate(mappings: { [key: string]: Function }): void; /** - * A handler passed automatically as the last parameter - * to a streaming function. With this parameter, a - * function can use handler.setResult to set a cell value - * or hook into the handler.onCanceled event to - * to handle what happens when the function stops streaming. * @beta + * Provides information about the invocation of a custom function. */ - - interface StreamingHandler extends CancelableHandler { + interface Invocation { /** - * Sets the returned result for a streaming custom function. * @beta + * The cell address where the function is being called, if requested, otherwise undefined. + * + * To request the address for the function, in the metadata JSON file, the function options should specify: + * `{ "requiresAddress": true }` + * + * If the metadata JSON file is being generated from JSDoc comments, include the tag `@requiresAddress`. */ - setResult: (value: T | Error) => void; + address?: string; } + /** * @beta - * CancelableHandler interface + * Provides information about the invocation of a cancelable custom function. + * A cancelable custom function can provide a handler for the onCanceled event. + * + * To indicate that a function is cancelable, in the metadata JSON file, the function options should specify: + * `{ "cancelable": true }` + * + * If the metadata JSON file is being generated from JSDoc comments, include the tag `@cancelable`. */ - interface CancelableHandler { + interface CancelableInvocation extends Invocation { /** - * Handles what should occur when a custom function is canceled. * @beta + * Event handler called when the custom function is canceled. */ onCanceled: () => void; } + + /** + * @beta + * @deprecated Use `CancelableInvocation` instead. + */ + interface CancelableHandler extends CancelableInvocation { + } + + /** + * @beta + * Provides information about the invocation of a streaming custom function. + * A streaming custom function can provide results which can change over time. + * + * Call `setResult()` one or more times to provide the result instead of returning + * a result from the function. + */ + interface StreamingInvocation extends CancelableInvocation { + /** + * @beta + * Set the result for the custom function. May be called more than once. + */ + setResult: (value: ResultType | Error) => void; + } + + /** + * @beta + * @deprecated Use `StreamingInvocation` instead. + */ + interface StreamingHandler extends StreamingInvocation { + } } diff --git a/types/custom-functions-runtime/tslint.json b/types/custom-functions-runtime/tslint.json index ad17c76132..bb858f4682 100644 --- a/types/custom-functions-runtime/tslint.json +++ b/types/custom-functions-runtime/tslint.json @@ -2,6 +2,7 @@ "extends": "dtslint/dt.json", "rules": { "ban-types": false, - "file-name-casing": false + "file-name-casing": false, + "no-empty-interface": false } } diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 391e2786be..11b9e0de35 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -181,7 +181,7 @@ export function ascending(a: Primitive | undefined, b: Primitive | undefined): n // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. /** - * Compares two primitive values for sorting (in ascending order). + * Compares two primitive values for sorting (in descending order). */ export function descending(a: Primitive | undefined, b: Primitive | undefined): number; diff --git a/types/d3-geo/d3-geo-tests.ts b/types/d3-geo/d3-geo-tests.ts index 6e824e8e69..36c4debbe3 100644 --- a/types/d3-geo/d3-geo-tests.ts +++ b/types/d3-geo/d3-geo-tests.ts @@ -371,6 +371,7 @@ const gnomonicRaw: d3Geo.GeoRawProjection = d3Geo.geoGnomonicRaw(); const mercatorRaw: d3Geo.GeoRawProjection = d3Geo.geoMercatorRaw(); const orthographicRaw: d3Geo.GeoRawProjection = d3Geo.geoOrthographicRaw(); const stereographicRaw: d3Geo.GeoRawProjection = d3Geo.geoStereographicRaw(); +const equalEarthRaw: d3Geo.GeoRawProjection = d3Geo.geoEqualEarthRaw(); const transverseMercatorRaw: d3Geo.GeoRawProjection = d3Geo.geoTransverseMercatorRaw(); const naturalEarth1Raw: d3Geo.GeoRawProjection = d3Geo.geoNaturalEarth1Raw(); @@ -398,6 +399,7 @@ const gnomonic: d3Geo.GeoProjection = d3Geo.geoGnomonic(); const mercator: d3Geo.GeoProjection = d3Geo.geoMercator(); const orthographic: d3Geo.GeoProjection = d3Geo.geoOrthographic(); const stereographic: d3Geo.GeoProjection = d3Geo.geoStereographic(); +const equalEarth: d3Geo.GeoProjection = d3Geo.geoEqualEarth(); const transverseMercator: d3Geo.GeoProjection = d3Geo.geoTransverseMercator(); const naturalEarth1: d3Geo.GeoProjection = d3Geo.geoNaturalEarth1(); diff --git a/types/d3-geo/index.d.ts b/types/d3-geo/index.d.ts index 8f22503d71..16c51dfae6 100644 --- a/types/d3-geo/index.d.ts +++ b/types/d3-geo/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for D3JS d3-geo module 1.10 +// Type definitions for D3JS d3-geo module 1.11 // Project: https://github.com/d3/d3-geo/ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Last module patch version validated against: 1.10.0 +// Last module patch version validated against: 1.11.3 import * as GeoJSON from 'geojson'; @@ -1345,11 +1345,22 @@ export function geoOrthographicRaw(): GeoRawProjection; * The stereographic projection. */ export function geoStereographic(): GeoProjection; + /** * The raw stereographic projection. */ export function geoStereographicRaw(): GeoRawProjection; +/** + * The Equal Eartch projection, by Bojan Šavrič et al., 2018. + */ +export function geoEqualEarth(): GeoProjection; + +/** + * The raw Equal Earth projection, by Bojan Šavrič et al., 2018. + */ +export function geoEqualEarthRaw(): GeoRawProjection; + // Composite Projections --------------------------------------------------- /** diff --git a/types/d3-shape/d3-shape-tests.ts b/types/d3-shape/d3-shape-tests.ts index 8ad3e4809a..1ce464093f 100644 --- a/types/d3-shape/d3-shape-tests.ts +++ b/types/d3-shape/d3-shape-tests.ts @@ -161,8 +161,9 @@ accessorArcDatumNumberOrNull = svgArc.padRadius(); // centroid(...) --------------------------------------------------------------------- -const centroid: [number, number] = svgArc.centroid(arcDatum); -// centroid = svgArc.centroid(arcDefaultDatum); // fails, wrong datum type +let centroid: [number, number] = svgArc.centroid(arcDatum); +// $ExpectError +centroid = svgArc.centroid(arcDefaultDatum); // fails, wrong datum type // generate arc ---------------------------------------------------------------------- @@ -176,10 +177,13 @@ const wrongArc1: Selection = select = select('.arc-paths'); // mock pArc.attr('d', svgArc); -// wrongArc1.attr('d', svgArc); // fails, incompatible this contexts -// wrongArc2.attr('d', svgArc); // fails, incompatible datum types +// $ExpectError +wrongArc1.attr('d', svgArc); // fails, incompatible this contexts +// $ExpectError +wrongArc2.attr('d', svgArc); // fails, incompatible datum types -// pathStringMaybe = svgArc(arcDatum); // fails, wrong this type for invocation +// $ExpectError +pathStringMaybe = svgArc(arcDatum); // fails, wrong this type for invocation // Use with custom object @@ -270,13 +274,13 @@ let pie: d3Shape.Pie = d3Shape.pie(); // value(...) ------------------------------------------------------------------------- -let defaultPieValueAccessor: (d: number | { valueOf(): number }, i?: number, data?: Array) => number; +let defaultPieValueAccessor: (d: number | { valueOf(): number }, i: number, data: Array) => number; defaultPie = defaultPie.value(10); defaultPieValueAccessor = defaultPie.value(); -let pieValueAccessor: (d: PieDatum, i?: number, data?: PieDatum[]) => number; +let pieValueAccessor: (d: PieDatum, i: number, data: PieDatum[]) => number; pie = pie.value((d, i, data) => { console.log(data.length > 0 ? data[0].val : 'no data'); // data type is Array @@ -364,8 +368,8 @@ interface LineDatum { missing: boolean; } -let lineXYAccessorFn: (d: LineDatum, index?: number, data?: LineDatum[]) => number; -let lineDefAccessorFn: (d: LineDatum, index?: number, data?: LineDatum[]) => boolean; +let lineXYAccessorFn: (d: LineDatum, index: number, data: LineDatum[]) => number; +let lineDefAccessorFn: (d: LineDatum, index: number, data: LineDatum[]) => boolean; interface LineRadialDatum { angle: number; @@ -373,8 +377,8 @@ interface LineRadialDatum { missing: boolean; } -let lineRadialAngRAccessorFn: (d: LineRadialDatum, index?: number, data?: LineRadialDatum[]) => number; -let lineRadialDefAccessorFn: (d: LineRadialDatum, index?: number, data?: LineRadialDatum[]) => boolean; +let lineRadialAngRAccessorFn: (d: LineRadialDatum, index: number, data: LineRadialDatum[]) => number; +let lineRadialDefAccessorFn: (d: LineRadialDatum, index: number, data: LineRadialDatum[]) => boolean; // line(...) create Line generator ===================================================== @@ -541,9 +545,9 @@ interface AreaDatum { missing: boolean; } -let areaXYAccessorFn: (d: AreaDatum, index?: number, data?: AreaDatum[]) => number; -let areaXYAccessorFnMaybe: null | ((d: AreaDatum, index?: number, data?: AreaDatum[]) => number); -let areaDefAccessorFn: (d: AreaDatum, index?: number, data?: AreaDatum[]) => boolean; +let areaXYAccessorFn: (d: AreaDatum, index: number, data: AreaDatum[]) => number; +let areaXYAccessorFnMaybe: null | ((d: AreaDatum, index: number, data: AreaDatum[]) => number); +let areaDefAccessorFn: (d: AreaDatum, index: number, data: AreaDatum[]) => boolean; interface AreaRadialDatum { startAngle: number; @@ -553,9 +557,9 @@ interface AreaRadialDatum { missing: boolean; } -let areaRadialAngRAccessorFn: (d: AreaRadialDatum, index?: number, data?: AreaRadialDatum[]) => number; -let areaRadialAngRAccessorFnMaybe: null | ((d: AreaRadialDatum, index?: number, data?: AreaRadialDatum[]) => number); -let areaRadialDefAccessorFn: (d: AreaRadialDatum, index?: number, data?: AreaRadialDatum[]) => boolean; +let areaRadialAngRAccessorFn: (d: AreaRadialDatum, index: number, data: AreaRadialDatum[]) => number; +let areaRadialAngRAccessorFnMaybe: null | ((d: AreaRadialDatum, index: number, data: AreaRadialDatum[]) => number); +let areaRadialDefAccessorFn: (d: AreaRadialDatum, index: number, data: AreaRadialDatum[]) => boolean; // area(...) create Area generator ===================================================== @@ -662,7 +666,8 @@ areaDefAccessorFn = area.defined(); defaultArea = defaultArea.curve(d3Shape.curveLinear); area = area.curve(d3Shape.curveCardinal.tension(0.5)); -// area = area.curve(d3Shape.curveBundle.beta(0.5)); // fails, as curveBundle-based line generator does not support area-related methods +// $ExpectError +area = area.curve(d3Shape.curveBundle.beta(0.5)); // fails, as curveBundle-based line generator does not support area-related methods currentCurveFactory = area.curve(); @@ -800,7 +805,8 @@ areaRadialDefAccessorFn = areaRadial.defined(); defaultAreaRadial = defaultAreaRadial.curve(d3Shape.curveLinear); areaRadial = areaRadial.curve(d3Shape.curveCardinal.tension(0.5)); -// areaRadial = areaRadial.curve(d3Shape.curveBundle.beta(0.5)); // fails, as curveBundle-based line generator does not support area-related methods +// $ExpectError +areaRadial = areaRadial.curve(d3Shape.curveBundle.beta(0.5)); // fails, as curveBundle-based line generator does not support area-related methods currentCurveFactory = areaRadial.curve(); @@ -868,7 +874,8 @@ curveBundleFactory = d3Shape.curveBundle.beta(0.5); lineOnlyGenerator = d3Shape.curveBundle.beta(0.5)(context!); // force context to be non-null with post-fix for mock lineOnlyGenerator = d3Shape.curveBundle.beta(0.5)(path()); -// curveGenerator = d3Shape.curveBundle.beta(0.5)(context); // fails, no area related methods +// $ExpectError +curveGenerator = d3Shape.curveBundle.beta(0.5)(context); // fails, no area related methods let curveCardinalFactory: d3Shape.CurveCardinalFactory; @@ -1153,22 +1160,28 @@ defaultLinkRadial(defaultLinkDatum); // vertical/horizontal pLink.attr('d', svgLink); -// wrongLink1.attr('d', svgLink); // fails, incompatible this contexts -// wrongLink2.attr('d', svgLink); // fails, incompatible datum types +// $ExpectError +wrongLink1.attr('d', svgLink); // fails, incompatible this contexts +// $ExpectError +wrongLink2.attr('d', svgLink); // fails, incompatible datum types pathStringMaybe = link(linkDatum); -// pathStringMaybe = svgLink(linkDatum); // fails, wrong this type for invocation +// $ExpectError +pathStringMaybe = svgLink(linkDatum); // fails, wrong this type for invocation // radial pLink.attr('d', svgLinkRadial); -// wrongLink1.attr('d', svgLinkRadial); // fails, incompatible this contexts -// wrongLink2.attr('d', svgLinkRadial); // fails, incompatible datum types +// $ExpectError +wrongLink1.attr('d', svgLinkRadial); // fails, incompatible this contexts +// $ExpectError +wrongLink2.attr('d', svgLinkRadial); // fails, incompatible datum types pathStringMaybe = radialLink(linkDatum); -// pathStringMaybe = svgLinkRadial(linkDatum); // fails, wrong this type for invocation +// $ExpectError +pathStringMaybe = svgLinkRadial(linkDatum); // fails, wrong this type for invocation // ----------------------------------------------------------------------------------- // Test Symbols @@ -1259,10 +1272,13 @@ const wrongSymbol1: Selection = select< const wrongSymbol2: Selection = select('.symbol-path'); // mock pSymbol.attr('d', svgSymbol); -// wrongSymbol1.attr('d', svgSymbol); // fails, incompatible this contexts -// wrongSymbol2.attr('d', svgSymbol); // fails, incompatible datum types +// $ExpectError +wrongSymbol1.attr('d', svgSymbol); // fails, incompatible this contexts +// $ExpectError +wrongSymbol2.attr('d', svgSymbol); // fails, incompatible datum types -// pathStringMaybe = svgSymbol(symbolDatum); // fails, wrong this type for invocation +// $ExpectError +pathStringMaybe = svgSymbol(symbolDatum); // fails, wrong this type for invocation // Use with custom object @@ -1390,11 +1406,11 @@ keysAccessor = overlyComplicatedStack.keys(); defaultStack = defaultStack.value(30); -overlyComplicatedStack = overlyComplicatedStack.value((d, key, j, data) => { +overlyComplicatedStack = overlyComplicatedStack.value((d, key, i, data) => { return d.values[key.name]; }); -let valueAccessorFn: (this: any, d: StackDatum, key: StackKey, j?: number, data?: StackDatum[]) => number; +let valueAccessorFn: (d: StackDatum, key: StackKey, i: number, data: StackDatum[]) => number; valueAccessorFn = overlyComplicatedStack.value(); // order(...) ---------------------------------------------------------------------- @@ -1448,6 +1464,7 @@ seriesDatum = seriesPoint.data; let order: number[]; const seriesAnyAny: d3Shape.Series = seriesArray[0]; +order = d3Shape.stackOrderAppearance(seriesAnyAny); order = d3Shape.stackOrderAscending(seriesAnyAny); order = d3Shape.stackOrderDescending(seriesAnyAny); order = d3Shape.stackOrderInsideOut(seriesAnyAny); diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index 0c0e27cbd7..350df78487 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -1,10 +1,13 @@ -// Type definitions for D3JS d3-shape module 1.2 +// Type definitions for D3JS d3-shape module 1.3 // Project: https://github.com/d3/d3-shape/ -// 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.2.0 +// Last module patch version validated against: 1.3.3 import { Path } from 'd3-path'; @@ -38,7 +41,7 @@ export interface CanvasPath_D3Shape { // ----------------------------------------------------------------------------------- /** - * Interface corresponding to the minimum data type assumed by the accessor functions of the Arc generator + * Interface corresponding to the minimum data type assumed by the accessor functions of the Arc generator. */ export interface DefaultArcObject { /** @@ -385,7 +388,7 @@ export function arc(): Arc; */ export interface PieArcDatum { /** - * The input datum; the corresponding element in the input data array of the Pie generator + * The input datum; the corresponding element in the input data array of the Pie generator. */ data: T; /** @@ -439,7 +442,6 @@ export interface Pie { /** * Returns the current value accessor, which defaults to a function returning the first argument passed into it. * The default value accessor assumes that the input data are numbers, or that they are coercible to numbers using valueOf. - * */ value(): (d: Datum, i: number, data: Datum[]) => number; /** @@ -455,7 +457,6 @@ export interface Pie { * The default value accessor assumes that the input data are numbers, or that they are coercible to numbers using valueOf. * If your data are not simply numbers, then you should specify an accessor that returns the corresponding numeric value for a given datum. * - * * @param value A value accessor function, which is invoked for each element in the input data array, being passed the element d, the index i, and the array data as three arguments. * It returns a numeric value. */ @@ -506,7 +507,6 @@ export interface Pie { * @param comparator The value comparator takes two arguments a and b which are values derived from the input data array using the value accessor, not the data elements. * If the arc for a should be before the arc for b, then the comparator must return a number less than zero; * if the arc for a should be after the arc for b, then the comparator must return a number greater than zero; returning zero means that the relative order of a and b is unspecified. - * */ sortValues(comparator: (a: number, b: number) => number): this; /** @@ -737,7 +737,7 @@ export interface Line { * Note that if a line segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * - * @param defined A boolean constant + * @param defined A boolean constant. */ defined(defined: boolean): this; /** @@ -912,7 +912,7 @@ export interface LineRadial { * Note that if a radial line segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * - * @param defined A boolean constant + * @param defined A boolean constant. */ defined(defined: boolean): this; /** @@ -1166,7 +1166,6 @@ export interface Area { * two-element array of numbers. * * If the y1 accessor is null, the previously-computed y0 value is reused for the y1 value. - * */ y1(): ((d: Datum, index: number, data: Datum[]) => number) | null; /** @@ -1209,9 +1208,9 @@ export interface Area { * As a result, the generated area may have several discrete segments. * * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. - * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * - * @param defined A boolean constant + * @param defined A boolean constant. */ defined(defined: boolean): this; /** @@ -1228,7 +1227,7 @@ export interface Area { * As a result, the generated area may have several discrete segments. * * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. - * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * * @param defined An accessor function which returns a boolean value. The accessor will be invoked for each defined element in the input data array, * being passed the element d, the index i, and the array data as three arguments. @@ -1248,7 +1247,6 @@ export interface Area { /** * Sets the curve factory and returns this area generator. * - * * @param curve A valid curve factory. */ curve(curve: CurveFactory): this; @@ -1470,7 +1468,6 @@ export interface AreaRadial { * two-element array of numbers. * * If the outerRadius accessor is null, the previously-computed innerRadius value is reused for the outerRadius value. - * */ outerRadius(): ((d: Datum, index: number, data: Datum[]) => number) | null; /** @@ -1515,9 +1512,9 @@ export interface AreaRadial { * As a result, the generated area may have several discrete segments. * * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. - * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * - * @param defined A boolean constant + * @param defined A boolean constant. */ defined(defined: boolean): this; /** @@ -1533,7 +1530,7 @@ export interface AreaRadial { * As a result, the generated area may have several discrete segments. * * Note that if an area segment consists of only a single point, it may appear invisible unless rendered with rounded or square line caps. - * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points + * In addition, some curves such as curveCardinalOpen only render a visible segment if it contains multiple points. * * @param defined An accessor function which returns a boolean value. The accessor will be invoked for each defined element in the input data array, * being passed the element d, the index i, and the array data as three arguments. @@ -1668,16 +1665,13 @@ export interface CurveGeneratorLineOnly { /** * A factory for curve generators addressing only lines, but not areas. */ -// This is a base interface to be extended, hence the suppression of the warning -// tslint:disable-next-line:callable-types -export interface CurveFactoryLineOnly { +export type CurveFactoryLineOnly = /** * Returns a "lines only" curve generator which renders to the specified context. * - * @param context A rendering context + * @param context A rendering context. */ - (context: CanvasRenderingContext2D | Path): CurveGeneratorLineOnly; -} + (context: CanvasRenderingContext2D | Path) => CurveGeneratorLineOnly; /** * A minimal interface for a curve generator which supports the rendering of lines and areas. @@ -1704,16 +1698,13 @@ export interface CurveGenerator extends CurveGeneratorLineOnly { /** * A factory for curve generators addressing both lines and areas. */ -// This is a base interface to be extended, hence the suppression of the warning -// tslint:disable-next-line:callable-types -export interface CurveFactory { +export type CurveFactory = /** * Returns a curve generator which renders to the specified context. * - * @param context A rendering context + * @param context A rendering context. */ - (context: CanvasRenderingContext2D | Path): CurveGenerator; -} + (context: CanvasRenderingContext2D | Path) => CurveGenerator; /** * A curve factory for cubic basis spline generators. @@ -1924,7 +1915,7 @@ export const curveStepBefore: CurveFactory; /** * An interface describing the default Link Data structure expected - * by the Link and LinkRadial generators + * by the Link and LinkRadial generators. */ export interface DefaultLinkObject { /** @@ -2077,7 +2068,7 @@ export function linkHorizontal(): Link * * The first generic corresponds to the datum type of the link object for which the link is to be generated. * - * The second generic corresponds to the datum type of the source/target node contained in the link object + * The second generic corresponds to the datum type of the source/target node contained in the link object. */ export function linkHorizontal(): Link; /** @@ -2091,7 +2082,7 @@ export function linkHorizontal(): Link(): Link; @@ -2111,7 +2102,7 @@ export function linkVertical(): Link; * * The first generic corresponds to the datum type of the link object for which the link is to be generated. * - * The second generic corresponds to the datum type of the source/target node contained in the link object + * The second generic corresponds to the datum type of the source/target node contained in the link object. */ export function linkVertical(): Link; /** @@ -2125,7 +2116,7 @@ export function linkVertical(): Link(): Link; @@ -2262,7 +2253,7 @@ export function linkRadial(): LinkRadial(): LinkRadial; /** @@ -2276,7 +2267,7 @@ export function linkRadial(): LinkRadial(): LinkRadial; @@ -2289,7 +2280,7 @@ export function linkRadial(): LinkRadial { /** * Sets the symbol type to the specified symbol type and returns this symbol generator. * - * * @param type A constant symbol type. */ type(type: SymbolType): this; @@ -2485,7 +2475,7 @@ export function pointRadial(angle: number, radius: number): [number, number]; * the difference between y0 and y1 corresponds to the computed value for this point. * * SeriesPoint is a [number, number] two-element Array with added data and index properties - * related to the data element which formed the basis for theSeriesPoint + * related to the data element which formed the basis for theSeriesPoint. */ export interface SeriesPoint extends Array { /** @@ -2510,11 +2500,11 @@ export interface SeriesPoint extends Array { */ export interface Series extends Array> { /** - * Key of the series + * Key of the series. */ key: Key; /** - * Index of the series in the series array returned by stack generator + * Index of the series in the series array returned by stack generator. */ index: number; } @@ -2578,7 +2568,7 @@ export interface Stack { * * Thus, by default the stack generator assumes that the input data is an array of objects, with each object exposing named properties with numeric values; see stack for an example. */ - value(): (d: Datum, key: Key, j: number, data: Datum[]) => number; + value(): (d: Datum, key: Key, i: number, data: Datum[]) => number; /** * Sets the value accessor to the specified number and returns this stack generator. * @@ -2591,7 +2581,7 @@ export interface Stack { * @param value A value accessor function which returns the numeric value for a given data element and key combination. The accessor function is invoked for each data element and key being passed * the datum, the key, index of the data element in the input data array, and the complete data array. */ - value(value: (d: Datum, key: Key, j: number, data: Datum[]) => number): this; + value(value: (d: Datum, key: Key, i: number, data: Datum[]) => number): this; /** * Returns the current order accessor, which defaults to stackOrderNone; this uses the order given by the key accessor. @@ -2680,17 +2670,24 @@ export function stack(): Stack; */ export function stack(): Stack; +/** + * Returns a series order such that the earliest series (according to the maximum value) is at the bottom. + * + * @param series A series generated by a stack generator. + */ +export function stackOrderAppearance(series: Series): number[]; + /** * Returns a series order such that the smallest series (according to the sum of values) is at the bottom. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderAscending(series: Series): number[]; /** * Returns a series order such that the largest series (according to the sum of values) is at the bottom. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderDescending(series: Series): number[]; @@ -2698,28 +2695,28 @@ export function stackOrderDescending(series: Series): number[]; * Returns a series order such that the larger series (according to the sum of values) are on the inside and the smaller series are on the outside. * This order is recommended for streamgraphs in conjunction with the wiggle offset. See Stacked Graphs—Geometry & Aesthetics by Byron & Wattenberg for more information. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderInsideOut(series: Series): number[]; /** * Returns the given series order [0, 1, … n - 1] where n is the number of elements in series. Thus, the stack order is given by the key accessor. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderNone(series: Series): number[]; /** * Returns the reverse of the given series order [n - 1, n - 2, … 0] where n is the number of elements in series. Thus, the stack order is given by the reverse of the key accessor. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. */ export function stackOrderReverse(series: Series): number[]; /** * Applies a zero baseline and normalizes the values for each point such that the topline is always one. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetExpand(series: Series, order: number[]): void; @@ -2727,7 +2724,7 @@ export function stackOffsetExpand(series: Series, order: number[]): vo /** * Positive values are stacked above zero, while negative values are stacked below zero. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetDiverging(series: Series, order: number[]): void; @@ -2735,7 +2732,7 @@ export function stackOffsetDiverging(series: Series, order: number[]): /** * Applies a zero baseline. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetNone(series: Series, order: number[]): void; @@ -2743,7 +2740,7 @@ export function stackOffsetNone(series: Series, order: number[]): void /** * Shifts the baseline down such that the center of the streamgraph is always at zero. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetSilhouette(series: Series, order: number[]): void; @@ -2752,7 +2749,7 @@ export function stackOffsetSilhouette(series: Series, order: number[]) * Shifts the baseline so as to minimize the weighted wiggle of layers. This offset is recommended for streamgraphs in conjunction with the inside-out order. * See Stacked Graphs—Geometry & Aesthetics by Bryon & Wattenberg for more information. * - * @param series A series generated by a stack generator + * @param series A series generated by a stack generator. * @param order An array of numeric indexes representing the stack order. */ export function stackOffsetWiggle(series: Series, order: number[]): void; diff --git a/types/d3-shape/tsconfig.json b/types/d3-shape/tsconfig.json index 0436aafd66..093e9b98c3 100644 --- a/types/d3-shape/tsconfig.json +++ b/types/d3-shape/tsconfig.json @@ -8,7 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/d3-shape/tslint.json b/types/d3-shape/tslint.json index b1ba182ba6..54efb0b84e 100644 --- a/types/d3-shape/tslint.json +++ b/types/d3-shape/tslint.json @@ -1,10 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - // TODO - "no-this-assignment": false, "unified-signatures": false, - "callable-types": false, "no-unnecessary-generics": false } } diff --git a/types/d3/index.d.ts b/types/d3/index.d.ts index 43c264f280..9b62c1e025 100644 --- a/types/d3/index.d.ts +++ b/types/d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3 standard bundle 5.5 +// Type definitions for D3JS d3 standard bundle 5.7 // Project: https://github.com/d3/d3 // Definitions by: Tom Wanzek // Alex Ford @@ -7,7 +7,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Last module patch version validated against: 5.5.0 +// Last module patch version validated against: 5.7.0 // NOTE TO MAINTAINERS: Review D3 v4.x module dependencies (see v4 sub-folder) and update its path-mappings in tsconfig (v4 folder), // if new MAJOR version of D3 v4 modules are released!!! diff --git a/types/debounce-fn/debounce-fn-tests.ts b/types/debounce-fn/debounce-fn-tests.ts new file mode 100644 index 0000000000..9f9d3881e9 --- /dev/null +++ b/types/debounce-fn/debounce-fn-tests.ts @@ -0,0 +1,10 @@ +import debounceFn = require('debounce-fn'); + +const debounced = debounceFn((s: string) => true); +debounced; // $ExpectType ((s: string) => boolean | undefined) & { cancel(): void; } + +debounceFn((s: string) => true); +debounceFn((s: string) => true, { wait: 100 }); +debounceFn((s: string) => true, { immediate: true }); + +debounced.cancel(); diff --git a/types/debounce-fn/index.d.ts b/types/debounce-fn/index.d.ts new file mode 100644 index 0000000000..01e147a14a --- /dev/null +++ b/types/debounce-fn/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for debounce-fn 1.0 +// Project: https://github.com/sindresorhus/debounce-fn#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +export = debounce; + +/** + * Returns a debounced function that delays calling the `input` function until after `wait` milliseconds + * have elapsed since the last time the debounced function was called. + * + * It comes with a `.cancel()` method to cancel any scheduled `input` function calls. + */ +declare function debounce( + input: (...args: TArgs) => TResult, + options?: debounce.Options +): ((...args: TArgs) => TResult | undefined) & { cancel(): void }; + +declare namespace debounce { + interface Options { + /** + * Time to wait until the `input` function is called. + * @default 0 + */ + wait?: number; + /** + * Trigger the function on the leading edge instead of the trailing edge of the `wait` interval. + * For example, can be useful for preventing accidental double-clicks on a "submit" button + * from firing a second time. + */ + immediate?: boolean; + } +} diff --git a/types/debounce-fn/tsconfig.json b/types/debounce-fn/tsconfig.json new file mode 100644 index 0000000000..f2d90018fb --- /dev/null +++ b/types/debounce-fn/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", + "debounce-fn-tests.ts" + ] +} diff --git a/types/debounce-fn/tslint.json b/types/debounce-fn/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/debounce-fn/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/defaults-deep/defaults-deep-tests.ts b/types/defaults-deep/defaults-deep-tests.ts new file mode 100644 index 0000000000..daabc46d7d --- /dev/null +++ b/types/defaults-deep/defaults-deep-tests.ts @@ -0,0 +1,7 @@ +import defaults = require('defaults-deep'); + +defaults(); +defaults({a: 'foo'}); +defaults({a: 'foo'}, {a: 'bar'}); +defaults({a: 'foo'}, {a: 'bar'}, {a: 'foobar'}); +defaults({a: {b: 'foo'}}, {a: {b: 'bar'}}); diff --git a/types/defaults-deep/index.d.ts b/types/defaults-deep/index.d.ts new file mode 100644 index 0000000000..749257eb88 --- /dev/null +++ b/types/defaults-deep/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for defaults-deep 0.2 +// Project: https://github.com/jonschlinkert/defaults-deep +// Definitions by: Hugo Alliaume +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Obj { + [k: string]: any; +} + +declare function defaultsDeep(...objs: Obj[]): Obj; + +export = defaultsDeep; diff --git a/types/defaults-deep/tsconfig.json b/types/defaults-deep/tsconfig.json new file mode 100644 index 0000000000..9b7c12bf2b --- /dev/null +++ b/types/defaults-deep/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", + "defaults-deep-tests.ts" + ] +} diff --git a/types/defaults-deep/tslint.json b/types/defaults-deep/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/defaults-deep/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/detox/index.d.ts b/types/detox/index.d.ts index de74163bf1..977f32e249 100644 --- a/types/detox/index.d.ts +++ b/types/detox/index.d.ts @@ -434,4 +434,10 @@ declare global { } } -export { by, detox, device, element, expect, waitFor }; +export { by, detox, device, element, waitFor }; + +// Not exporting the global `expect` from the top of the file here +// because `expect` conflicts with the global `expect` of jest and +// therefore exporting it doesn't work. The global `expect` is kept +// for backwards compatibility though. +export const expect: Detox.Expect>; diff --git a/types/dhtmlxgantt/index.d.ts b/types/dhtmlxgantt/index.d.ts index f2e322b0e3..5502cdcaf2 100644 --- a/types/dhtmlxgantt/index.d.ts +++ b/types/dhtmlxgantt/index.d.ts @@ -1455,13 +1455,13 @@ interface GanttStatic { * exports a Gantt chart into the PDF format * @param _export_ an object with export settings (see the details) */ - exportToPDF(_export_: any): void; + exportToPDF(_export_?: any): void; /** * exports a Gantt chart into the PNG format * @param _export_ an object with export settings (see the details) */ - exportToPNG(_export_: any): void; + exportToPNG(_export_?: any): void; /** * returns all dependency loops in the chart @@ -2242,4 +2242,4 @@ declare module "gantt" { declare module "Gantt" { export = Gantt; -} \ No newline at end of file +} diff --git a/types/diff/diff-tests.ts b/types/diff/diff-tests.ts index 2f640da490..ca00b1f458 100644 --- a/types/diff/diff-tests.ts +++ b/types/diff/diff-tests.ts @@ -1,47 +1,55 @@ -import jsdiff = require('diff'); +import * as diff from 'diff'; + const one = 'beep boop'; const other = 'beep boob blah'; -let diff = jsdiff.diffChars(one, other); -printDiff(diff); +let changes = diff.diffChars(one, other); +examineChanges(changes); -const diffArraysResult = jsdiff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); +// $ExpectType void +diff.diffChars(one, other, { + callback: (err, value) => { + err; // $ExpectType undefined + value; // $ExpectType Change[] | undefined + }, +}); +// $ExpectType void +diff.diffChars(one, other, (err, value) => { + err; // $ExpectType undefined + value; // $ExpectType Change[] | undefined +}); + +const diffArraysResult = diff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); diffArraysResult.forEach(result => { - if (result.added) { - console.log(`added ${result.value.length} line(s):`, ...result.value); - } else if (result.removed) { - console.log(`removed ${result.value.length} line(s):`, ...result.value); - } else { - console.log(`no changes`); - } + result.added; // $ExpectType boolean | undefined + result.removed; // $ExpectType boolean | undefined + result.value; // $ExpectType string[] + result.count; // $ExpectType number | undefined }); interface DiffObj { value: number; } -const a: DiffObj = {value: 0}; -const b: DiffObj = {value: 1}; -const c: DiffObj = {value: 2}; -const d: DiffObj = {value: 3}; -const arrayOptions: jsdiff.IArrayOptions = { - comparator: (left: DiffObj, right: DiffObj) => { - return left.value === right.value; - } +const a: DiffObj = { value: 0 }; +const b: DiffObj = { value: 1 }; +const c: DiffObj = { value: 2 }; +const d: DiffObj = { value: 3 }; +const arrayOptions: diff.ArrayOptions = { + comparator: (left, right) => { + return left.value === right.value; + }, }; -const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions); -diffResult.forEach(result => { - if (result.added) { - console.log(`added ${result.value.length} line(s):`, ...result.value); - } else if (result.removed) { - console.log(`removed ${result.value.length} line(s):`, ...result.value); - } else { - console.log(`no changes`); - } +const arrayChanges = diff.diffArrays([a, b, c], [a, b, d], arrayOptions); +arrayChanges.forEach(result => { + result.added; // $ExpectType boolean | undefined + result.removed; // $ExpectType boolean | undefined + result.value; // $ExpectType DiffObj[] + result.count; // $ExpectType number | undefined }); // -------------------------- -class LineDiffWithoutWhitespace extends jsdiff.Diff { +class LineDiffWithoutWhitespace extends diff.Diff { tokenize(value: string): any { return value.split(/^/m); } @@ -52,71 +60,71 @@ class LineDiffWithoutWhitespace extends jsdiff.Diff { } const obj = new LineDiffWithoutWhitespace(); -diff = obj.diff(one, other); -printDiff(diff); +changes = obj.diff(one, other); +examineChanges(changes); -function printDiff(diff: jsdiff.IDiffResult[]) { - function addLineHeader(decorator: string, str: string | string[]) { - return (typeof str === 'string' ? str.split("\n") : str).map((line, index, array) => { - if (index === array.length - 1 && line === "") { - return line; - } else { - return decorator + line; - } - }).join("\n"); - } - - diff.forEach((part) => { - if (part.added) { - console.log(addLineHeader("+", part.value)); - } else if (part.removed) { - console.log(addLineHeader("-", part.value)); - } else { - console.log(addLineHeader(" ", part.value)); - } +function examineChanges(diff: diff.Change[]) { + diff.forEach(part => { + part.added; // $ExpectType boolean | undefined + part.removed; // $ExpectType boolean | undefined + part.value; // $ExpectType string + part.count; // $ExpectType number | undefined }); } -function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { - const verifyPatch = jsdiff.parsePatch( - jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr, - "old", "new", { context: 1 })); +function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: diff.ParsedDiff) { + const verifyPatch = diff.parsePatch( + diff.createTwoFilesPatch('oldFile.ts', 'newFile.ts', oldStr, newStr, 'old', 'new', { + context: 1, + }) + ); - if (JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== JSON.stringify(uniDiff, Object.keys(uniDiff).sort())) { - console.error("Patch did not match uniDiff"); + if ( + JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== + JSON.stringify(uniDiff, Object.keys(uniDiff).sort()) + ) { + throw new Error('Patch did not match uniDiff'); } } -function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { - const verifyApply = [ - jsdiff.applyPatch(oldStr, uniDiff), - jsdiff.applyPatch(oldStr, [uniDiff]) - ]; - jsdiff.applyPatches([uniDiff], { - loadFile: (index: number, callback: (err: Error, data: string) => void) => { +function verifyApplyMethods(oldStr: string, newStr: string, uniDiffStr: string) { + const uniDiff = diff.parsePatch(uniDiffStr)[0]; + const verifyApply = [diff.applyPatch(oldStr, uniDiff), diff.applyPatch(oldStr, [uniDiff])]; + const options: diff.ApplyPatchesOptions = { + loadFile(index, callback) { + index; // $ExpectType ParsedDiff callback(undefined, one); }, - patched: (index: number, content: string) => { + patched(index, content) { + index; // $ExpectType ParsedDiff verifyApply.push(content); }, - complete: (err?: Error) => { + complete(err) { if (err) { - console.error(err); + throw err; } verifyApply.forEach(result => { if (result !== newStr) { - console.error("Result did not match newStr"); + throw new Error('Result did not match newStr'); } }); - } - }); + }, + compareLine(_, line, operator, patchContent) { + if (operator === ' ') { + return true; + } + return line === patchContent; + }, + fuzzFactor: 0 + }; + diff.applyPatches([uniDiff], options); + diff.applyPatches(uniDiffStr, options); } -const uniDiffPatch = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, - "old", "new", { context: 1 }); +const uniDiffPatch = diff.structuredPatch('oldFile.ts', 'newFile.ts', one, other, 'old', 'new', { + context: 1, +}); verifyPatchMethods(one, other, uniDiffPatch); -const uniDiffStr = jsdiff.createPatch("file.ts", one, other, "old", "new", - { context: 1 }); -const uniDiffApply = jsdiff.parsePatch(uniDiffStr)[0]; -verifyApplyMethods(one, other, uniDiffApply); +const uniDiffStr = diff.createPatch('file.ts', one, other, 'old', 'new', { context: 1 }); +verifyApplyMethods(one, other, uniDiffStr); diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts index 760aee4e61..5afb72192e 100644 --- a/types/diff/index.d.ts +++ b/types/diff/index.d.ts @@ -1,121 +1,402 @@ -// Type definitions for diff 3.5 +// Type definitions for diff 4.0 // Project: https://github.com/kpdecker/jsdiff // Definitions by: vvakame // szdc // moc-yuto +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -export = JsDiff; -export as namespace JsDiff; +export as namespace Diff; -declare namespace JsDiff { - interface IOptions { - ignoreCase: boolean; - } +export type Callback = (err: undefined, value?: Change[]) => void; - interface ILinesOptions extends IOptions { - ignoreWhitespace?: boolean; - newlineIsToken?: boolean; - } - - interface IArrayOptions { - comparator?: (left: any, right: any) => boolean; - } - - interface IDiffResult { - value: string; - count?: number; - added?: boolean; - removed?: boolean; - } - - interface IDiffArraysResult { - value: T[]; - count?: number; - added?: boolean; - removed?: boolean; - } - - interface IBestPath { - newPos: number; - componenets: IDiffResult[]; - } - - interface IHunk { - oldStart: number; - oldLines: number; - newStart: number; - newLines: number; - lines: string[]; - } - - interface IUniDiff { - oldFileName: string; - newFileName: string; - oldHeader: string; - newHeader: string; - index: string; - hunks: IHunk[]; - } - - class Diff { - diff(oldString: string, newString: string, options?: IOptions): IDiffResult[]; - - pushComponent(components: IDiffResult[], added: boolean, removed: boolean): void; - - extractCommon(basePath: IBestPath, newString: string, oldString: string, diagonalPath: number): number; - - equals(left: string, right: string): boolean; - - removeEmpty(array: any[]): any[]; - - castInput(value: any): any; - - join(chars: string[]): string; - - tokenize(value: string): any; // return types are string or string[] - } - - function diffChars(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffWords(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffWordsWithSpace(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffJson(oldObj: object, newObj: object, options?: IOptions): IDiffResult[]; - - function diffLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; - - function diffCss(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffTrimmedLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; - - function diffSentences(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; - - function diffArrays(oldArr: T[], newArr: T[], options?: IArrayOptions): Array>; - - function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; - - function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; - - function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff; - - function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string; - - function applyPatches(uniDiff: IUniDiff[], options: { - loadFile(index: number, callback: (err: Error, data: string) => void): void, - patched(index: number, content: string): void, - complete(err?: Error): void - }): void; - - function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[]; - - function convertChangesToXML(changes: IDiffResult[]): string; - - function convertChangesToDMP(changes: IDiffResult[]): Array<{0: number; 1: string; }>; - - function merge(mine: string, theirs: string, base: string): IUniDiff; - - function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; +export interface CallbackOptions { + /** + * Callback to call with the result instead of returning the result directly. + */ + callback: Callback; } + +export interface BaseOptions { + /** + * `true` to ignore casing difference. + * @default false + */ + ignoreCase?: boolean; +} + +export interface WordsOptions extends BaseOptions { + /** + * `true` to ignore leading and trailing whitespace. This is the same as `diffWords()`. + */ + ignoreWhitespace?: boolean; +} + +export interface LinesOptions extends BaseOptions { + /** + * `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines()`. + */ + ignoreWhitespace?: boolean; + + /** + * `true` to treat newline characters as separate tokens. This allows for changes to the newline structure + * to occur independently of the line content and to be treated as such. In general this is the more + * human friendly form of `diffLines()` and `diffLines()` is better suited for patches and other computer + * friendly output. + */ + newlineIsToken?: boolean; +} + +export interface JsonOptions extends LinesOptions { + /** + * Replacer used to stringify the properties of the passed objects. + */ + stringifyReplacer?: (key: string, value: any) => any; + + /** + * The value to use when `undefined` values in the passed objects are encountered during stringification. + * Will only be used if `stringifyReplacer` option wasn't specified. + * @default undefined + */ + undefinedReplacement?: any; +} + +export interface ArrayOptions extends BaseOptions { + /** + * Comparator for custom equality checks. + */ + comparator?: (left: TLeft, right: TRight) => boolean; +} + +export interface PatchOptions extends LinesOptions { + /** + * Describes how many lines of context should be included. + * @default 4 + */ + context?: number; +} + +export interface ApplyPatchOptions { + /** + * Number of lines that are allowed to differ before rejecting a patch. + * @default 0 + */ + fuzzFactor?: number; + + /** + * Callback used to compare to given lines to determine if they should be considered equal when patching. + * Should return `false` if the lines should be rejected. + * + * @default strict equality + */ + compareLine?: ( + lineNumber: number, + line: string, + operation: '-' | ' ', + patchContent: string + ) => boolean; +} + +export interface ApplyPatchesOptions extends ApplyPatchOptions { + loadFile(index: ParsedDiff, callback: (err: any, data: string) => void): void; + patched(index: ParsedDiff, content: string, callback: (err: any) => void): void; + complete(err: any): void; +} + +export interface Change { + count?: number; + /** + * Text content. + */ + value: string; + /** + * `true` if the value was inserted into the new string. + */ + added?: boolean; + /** + * `true` if the value was removed from the old string. + */ + removed?: boolean; +} + +export interface ArrayChange { + value: T[]; + count?: number; + added?: boolean; + removed?: boolean; +} + +export interface ParsedDiff { + index?: string; + oldFileName?: string; + newFileName?: string; + oldHeader?: string; + newHeader?: string; + hunks: Hunk[]; +} + +export interface Hunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: string[]; +} + +export interface BestPath { + newPos: number; + componenets: Change[]; +} + +export class Diff { + diff( + oldString: string, + newString: string, + options?: Callback | (ArrayOptions & Partial) + ): Change[]; + + pushComponent(components: Change[], added: boolean, removed: boolean): void; + + extractCommon( + basePath: BestPath, + newString: string, + oldString: string, + diagonalPath: number + ): number; + + equals(left: any, right: any): boolean; + + removeEmpty(array: any[]): any[]; + + castInput(value: any): any; + + join(chars: string[]): string; + + tokenize(value: string): any; // return types are string or string[] +} + +/** + * Diffs two blocks of text, comparing character by character. + * + * @returns A list of change objects. + */ +export function diffChars(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffChars( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing word by word, ignoring whitespace. + * + * @returns A list of change objects. + */ +export function diffWords(oldStr: string, newStr: string, options?: WordsOptions): Change[]; +export function diffWords( + oldStr: string, + newStr: string, + options: Callback | (WordsOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing word by word, treating whitespace as significant. + * + * @returns A list of change objects. + */ +export function diffWordsWithSpace( + oldStr: string, + newStr: string, + options?: WordsOptions +): Change[]; +export function diffWordsWithSpace( + oldStr: string, + newStr: string, + options: Callback | (WordsOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing line by line. + * + * @returns A list of change objects. + */ +export function diffLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; +export function diffLines( + oldStr: string, + newStr: string, + options: Callback | (LinesOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. + * + * @returns A list of change objects. + */ +export function diffTrimmedLines(oldStr: string, newStr: string, options?: LinesOptions): Change[]; +export function diffTrimmedLines( + oldStr: string, + newStr: string, + options: Callback | (LinesOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing sentence by sentence. + * + * @returns A list of change objects. + */ +export function diffSentences(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffSentences( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two blocks of text, comparing CSS tokens. + * + * @returns A list of change objects. + */ +export function diffCss(oldStr: string, newStr: string, options?: BaseOptions): Change[]; +export function diffCss( + oldStr: string, + newStr: string, + options: Callback | (BaseOptions & CallbackOptions) +): void; + +/** + * Diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter + * in this comparison. + * + * @returns A list of change objects. + */ +export function diffJson( + oldObj: string | object, + newObj: string | object, + options?: JsonOptions +): Change[]; +export function diffJson( + oldObj: string | object, + newObj: string | object, + options: Callback | (JsonOptions & CallbackOptions) +): void; + +/** + * Diffs two arrays, comparing each item for strict equality (`===`). + * + * @returns A list of change objects. + */ +export function diffArrays( + oldArr: TOld[], + newArr: TNew[], + options?: ArrayOptions +): Array>; + +/** + * Creates a unified diff patch. + * + * @param oldFileName String to be output in the filename section of the patch for the removals. + * @param newFileName String to be output in the filename section of the patch for the additions. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the old file header. + * @param newHeader Additional information to include in the new file header. + */ +export function createTwoFilesPatch( + oldFileName: string, + newFileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): string; + +/** + * Creates a unified diff patch. + * Just like `createTwoFilesPatch()`, but with `oldFileName` being equal to `newFileName`. + * + * @param fileName String to be output in the filename section. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the old file header. + * @param newHeader Additional information to include in the new file header. + */ +export function createPatch( + fileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): string; + +/** + * This method is similar to `createTwoFilesPatch()`, but returns a data structure suitable for further processing. + * Parameters are the same as `createTwoFilesPatch()`. + * + * @param oldFileName String to be output in the `oldFileName` hunk property. + * @param newFileName String to be output in the `newFileName` hunk property. + * @param oldStr Original string value. + * @param newStr New string value. + * @param oldHeader Additional information to include in the `oldHeader` hunk property. + * @param newHeader Additional information to include in the `newHeader` hunk property. + * @returns An object with an array of hunk objects. + */ +export function structuredPatch( + oldFileName: string, + newFileName: string, + oldStr: string, + newStr: string, + oldHeader?: string, + newHeader?: string, + options?: PatchOptions +): ParsedDiff; + +/** + * Applies a unified diff patch. + * + * @param patch May be a string diff or the output from the `parsePatch()` or `structuredPatch()` methods. + * @returns A string containing new version of provided data. + */ +export function applyPatch( + source: string, + patch: string | ParsedDiff | [ParsedDiff], + options?: ApplyPatchOptions +): string; + +/** + * Applies one or more patches. + * This method will iterate over the contents of the patch and apply to data provided through callbacks. + * + * The general flow for each patch index is: + * + * 1. `options.loadFile(index, callback)` is called. The caller should then load the contents of the file + * and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. + * 2. `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be + * the return value from `applyPatch()`. When it's ready, the caller should call `callback(err)` callback. + * Passing an `err` will terminate further patch execution. + * 3. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. + */ +export function applyPatches(patch: string | ParsedDiff[], options: ApplyPatchesOptions): void; + +/** + * Parses a patch into structured data. + * + * @returns A JSON object representation of the a patch, suitable for use with the `applyPatch()` method. + */ +export function parsePatch(diffStr: string, options?: { strict?: boolean }): ParsedDiff[]; + +/** + * Converts a list of changes to a serialized XML format. + */ +export function convertChangesToXML(changes: Change[]): string; + +/** + * Converts a list of changes to [DMP](http://code.google.com/p/google-diff-match-patch/wiki/API) format. + */ +export function convertChangesToDMP(changes: Change[]): Array<[1 | 0 | -1, string]>; + +export function merge(mine: string, theirs: string, base: string): ParsedDiff; + +export function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; diff --git a/types/diff/tsconfig.json b/types/diff/tsconfig.json index 9a1fdba840..b32089d091 100644 --- a/types/diff/tsconfig.json +++ b/types/diff/tsconfig.json @@ -2,12 +2,11 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +20,4 @@ "index.d.ts", "diff-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/diff/tslint.json b/types/diff/tslint.json index 1b7b2672e6..3db14f85ea 100644 --- a/types/diff/tslint.json +++ b/types/diff/tslint.json @@ -1,7 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "interface-name": false, - "export-just-namespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/diff/v3/diff-tests.ts b/types/diff/v3/diff-tests.ts new file mode 100644 index 0000000000..2f640da490 --- /dev/null +++ b/types/diff/v3/diff-tests.ts @@ -0,0 +1,122 @@ +import jsdiff = require('diff'); +const one = 'beep boop'; +const other = 'beep boob blah'; + +let diff = jsdiff.diffChars(one, other); +printDiff(diff); + +const diffArraysResult = jsdiff.diffArrays(['a', 'b', 'c'], ['a', 'c', 'd']); +diffArraysResult.forEach(result => { + if (result.added) { + console.log(`added ${result.value.length} line(s):`, ...result.value); + } else if (result.removed) { + console.log(`removed ${result.value.length} line(s):`, ...result.value); + } else { + console.log(`no changes`); + } +}); + +interface DiffObj { + value: number; +} +const a: DiffObj = {value: 0}; +const b: DiffObj = {value: 1}; +const c: DiffObj = {value: 2}; +const d: DiffObj = {value: 3}; +const arrayOptions: jsdiff.IArrayOptions = { + comparator: (left: DiffObj, right: DiffObj) => { + return left.value === right.value; + } +}; +const diffResult = jsdiff.diffArrays([a, b, c], [a, b, d], arrayOptions); +diffResult.forEach(result => { + if (result.added) { + console.log(`added ${result.value.length} line(s):`, ...result.value); + } else if (result.removed) { + console.log(`removed ${result.value.length} line(s):`, ...result.value); + } else { + console.log(`no changes`); + } +}); + +// -------------------------- + +class LineDiffWithoutWhitespace extends jsdiff.Diff { + tokenize(value: string): any { + return value.split(/^/m); + } + + equals(left: string, right: string): boolean { + return left.trim() === right.trim(); + } +} + +const obj = new LineDiffWithoutWhitespace(); +diff = obj.diff(one, other); +printDiff(diff); + +function printDiff(diff: jsdiff.IDiffResult[]) { + function addLineHeader(decorator: string, str: string | string[]) { + return (typeof str === 'string' ? str.split("\n") : str).map((line, index, array) => { + if (index === array.length - 1 && line === "") { + return line; + } else { + return decorator + line; + } + }).join("\n"); + } + + diff.forEach((part) => { + if (part.added) { + console.log(addLineHeader("+", part.value)); + } else if (part.removed) { + console.log(addLineHeader("-", part.value)); + } else { + console.log(addLineHeader(" ", part.value)); + } + }); +} + +function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + const verifyPatch = jsdiff.parsePatch( + jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr, + "old", "new", { context: 1 })); + + if (JSON.stringify(verifyPatch[0], Object.keys(verifyPatch[0]).sort()) !== JSON.stringify(uniDiff, Object.keys(uniDiff).sort())) { + console.error("Patch did not match uniDiff"); + } +} +function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + const verifyApply = [ + jsdiff.applyPatch(oldStr, uniDiff), + jsdiff.applyPatch(oldStr, [uniDiff]) + ]; + jsdiff.applyPatches([uniDiff], { + loadFile: (index: number, callback: (err: Error, data: string) => void) => { + callback(undefined, one); + }, + patched: (index: number, content: string) => { + verifyApply.push(content); + }, + complete: (err?: Error) => { + if (err) { + console.error(err); + } + + verifyApply.forEach(result => { + if (result !== newStr) { + console.error("Result did not match newStr"); + } + }); + } + }); +} + +const uniDiffPatch = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, + "old", "new", { context: 1 }); +verifyPatchMethods(one, other, uniDiffPatch); + +const uniDiffStr = jsdiff.createPatch("file.ts", one, other, "old", "new", + { context: 1 }); +const uniDiffApply = jsdiff.parsePatch(uniDiffStr)[0]; +verifyApplyMethods(one, other, uniDiffApply); diff --git a/types/diff/v3/index.d.ts b/types/diff/v3/index.d.ts new file mode 100644 index 0000000000..760aee4e61 --- /dev/null +++ b/types/diff/v3/index.d.ts @@ -0,0 +1,121 @@ +// Type definitions for diff 3.5 +// Project: https://github.com/kpdecker/jsdiff +// Definitions by: vvakame +// szdc +// moc-yuto +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = JsDiff; +export as namespace JsDiff; + +declare namespace JsDiff { + interface IOptions { + ignoreCase: boolean; + } + + interface ILinesOptions extends IOptions { + ignoreWhitespace?: boolean; + newlineIsToken?: boolean; + } + + interface IArrayOptions { + comparator?: (left: any, right: any) => boolean; + } + + interface IDiffResult { + value: string; + count?: number; + added?: boolean; + removed?: boolean; + } + + interface IDiffArraysResult { + value: T[]; + count?: number; + added?: boolean; + removed?: boolean; + } + + interface IBestPath { + newPos: number; + componenets: IDiffResult[]; + } + + interface IHunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: string[]; + } + + interface IUniDiff { + oldFileName: string; + newFileName: string; + oldHeader: string; + newHeader: string; + index: string; + hunks: IHunk[]; + } + + class Diff { + diff(oldString: string, newString: string, options?: IOptions): IDiffResult[]; + + pushComponent(components: IDiffResult[], added: boolean, removed: boolean): void; + + extractCommon(basePath: IBestPath, newString: string, oldString: string, diagonalPath: number): number; + + equals(left: string, right: string): boolean; + + removeEmpty(array: any[]): any[]; + + castInput(value: any): any; + + join(chars: string[]): string; + + tokenize(value: string): any; // return types are string or string[] + } + + function diffChars(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffWords(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffWordsWithSpace(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffJson(oldObj: object, newObj: object, options?: IOptions): IDiffResult[]; + + function diffLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; + + function diffCss(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffTrimmedLines(oldStr: string, newStr: string, options?: ILinesOptions): IDiffResult[]; + + function diffSentences(oldStr: string, newStr: string, options?: IOptions): IDiffResult[]; + + function diffArrays(oldArr: T[], newArr: T[], options?: IArrayOptions): Array>; + + function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; + + function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; + + function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff; + + function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string; + + function applyPatches(uniDiff: IUniDiff[], options: { + loadFile(index: number, callback: (err: Error, data: string) => void): void, + patched(index: number, content: string): void, + complete(err?: Error): void + }): void; + + function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[]; + + function convertChangesToXML(changes: IDiffResult[]): string; + + function convertChangesToDMP(changes: IDiffResult[]): Array<{0: number; 1: string; }>; + + function merge(mine: string, theirs: string, base: string): IUniDiff; + + function canonicalize(obj: any, stack: any[], replacementStack: any[]): any; +} diff --git a/types/dwt/v12/tsconfig.json b/types/diff/v3/tsconfig.json similarity index 81% rename from types/dwt/v12/tsconfig.json rename to types/diff/v3/tsconfig.json index f856dd2657..92e1861ec8 100644 --- a/types/dwt/v12/tsconfig.json +++ b/types/diff/v3/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -13,8 +14,8 @@ "../../" ], "paths": { - "dwt": [ - "dwt/v12" + "diff": [ + "diff/v3" ] }, "types": [], @@ -23,6 +24,6 @@ }, "files": [ "index.d.ts", - "dwt-tests.ts" + "diff-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/diff/v3/tslint.json b/types/diff/v3/tslint.json new file mode 100644 index 0000000000..1b7b2672e6 --- /dev/null +++ b/types/diff/v3/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "interface-name": false, + "export-just-namespace": false + } +} diff --git a/types/dlv/dlv-tests.ts b/types/dlv/dlv-tests.ts new file mode 100644 index 0000000000..abe4b259c3 --- /dev/null +++ b/types/dlv/dlv-tests.ts @@ -0,0 +1,44 @@ +import dlv from 'dlv'; + +const obj = { + undef: undefined, + zero: 0, + one: 1, + n: null, + f: false, + a: { + two: 2, + b: { + three: 3, + c: { + four: 4 + } + } + } +}; + +// Test without defaults +dlv(obj, ''); +dlv(obj, 'one'); +dlv(obj, 'one.two'); +dlv(obj, 'a'); +dlv(obj, 'a.two'); +dlv(obj, 'a.b'); +dlv(obj, 'a.b.three'); +dlv(obj, 'a.b.c'); +dlv(obj, 'a.b.c.four'); +dlv(obj, 'n'); +dlv(obj, 'n.badkey'); +dlv(obj, 'f'); +dlv(obj, 'f.badkey'); + +// Test defaults +dlv(obj, '', 'foo'); +dlv(obj, 'undef', 'foo'); +dlv(obj, 'n', null); +dlv(obj, 'n.badkey', 'foo'); +dlv(obj, 'zero', 0); +dlv(obj, 'a.badkey', 'foo'); +dlv(obj, 'a.badkey.anotherbadkey', 'foo'); +dlv(obj, 'f', false); +dlv(obj, 'f.badkey', 'foo'); diff --git a/types/dlv/index.d.ts b/types/dlv/index.d.ts new file mode 100644 index 0000000000..5813ec0595 --- /dev/null +++ b/types/dlv/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for dlv 1.1 +// Project: https://github.com/developit/dlv#readme +// Definitions by: Ryan Sonshine +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Safely get a dot-notated path within a nested object, with ability to + * return a default if the full key path does not exist or the value is + * undefined + */ +export default function dlv(object: object, key: string | string[], defaultValue?: any): any; diff --git a/types/dlv/tsconfig.json b/types/dlv/tsconfig.json new file mode 100644 index 0000000000..222ce070e7 --- /dev/null +++ b/types/dlv/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", + "dlv-tests.ts" + ] +} diff --git a/types/dlv/tslint.json b/types/dlv/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dlv/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index cd06bc7ebb..0581057dea 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -151,8 +151,8 @@ declare namespace Dockerode { modem: any; name: string; - inspect(callback: Callback): void; - inspect(): Promise; + inspect(callback: Callback): void; + inspect(): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; @@ -174,6 +174,10 @@ declare namespace Dockerode { update(options: {}, callback: Callback): void; update(options: {}): Promise; + + logs(options: ContainerLogsOptions, callback: Callback): void; + logs(callback: Callback): void; + logs(options?: ContainerLogsOptions): Promise; } class Task { @@ -367,6 +371,22 @@ declare namespace Dockerode { Ingress: boolean; } + interface VolumeInspectInfo { + Name: string; + Driver: string; + Mountpoint: string; + Status?: { [key: string]: string }; + Labels: { [key: string]: string }; + Scope: 'local' | 'global'; + // Field is always present, but sometimes is null + Options: { [key: string]: string } | null; + // Field is sometimes present, and sometimes null + UsageData?: { + Size: number; + RefCount: number; + } | null; + } + interface ContainerInspectInfo { Id: string; Created: string; @@ -1140,9 +1160,18 @@ declare class Dockerode { listPlugins(callback: Callback): void; listPlugins(options?: {}): Promise; - listVolumes(options: {}, callback: Callback): void; - listVolumes(callback: Callback): void; - listVolumes(options?: {}): Promise; + listVolumes(options: {}, callback: Callback<{ + Volumes: Dockerode.VolumeInspectInfo[]; + Warnings: string[]; + }>): void; + listVolumes(callback: Callback<{ + Volumes: Dockerode.VolumeInspectInfo[]; + Warnings: string[]; + }>): void; + listVolumes(options?: {}): Promise<{ + Volumes: Dockerode.VolumeInspectInfo[]; + Warnings: string[]; + }>; listNetworks(options: {}, callback: Callback): void; listNetworks(callback: Callback): void; diff --git a/types/doge-seed/doge-seed-tests.ts b/types/doge-seed/doge-seed-tests.ts new file mode 100644 index 0000000000..fa47414d65 --- /dev/null +++ b/types/doge-seed/doge-seed-tests.ts @@ -0,0 +1,4 @@ +import dogeSeed = require('doge-seed'); + +dogeSeed(); // $ExpectType string +dogeSeed(128); // $ExpectType string diff --git a/types/doge-seed/index.d.ts b/types/doge-seed/index.d.ts new file mode 100644 index 0000000000..8670f36332 --- /dev/null +++ b/types/doge-seed/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for doge-seed 1.0 +// Project: https://github.com/lukechilds/doge-seed#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = dogeSeed; + +/** + * Generates a cryptographically secure mnemonic seed phrase with added dankness. + * The first four words will be a randomly generated Doge-like sentence. + * + * The seed phrases are fully valid checksummed BIP39 seeds. They can be used with any cryptocurrency + * and can be imported into any BIP39 compliant wallet. + * + * @param bits The number of bits to derive a BIP39 mnemonic from. Default: `128`. + * @returns A BIP39 mnemonic seed phrase. + */ +declare function dogeSeed(bits?: 128 | 160 | 192 | 224 | 256): string; diff --git a/types/doge-seed/tsconfig.json b/types/doge-seed/tsconfig.json new file mode 100644 index 0000000000..cd46d1ee9c --- /dev/null +++ b/types/doge-seed/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", + "doge-seed-tests.ts" + ] +} diff --git a/types/doge-seed/tslint.json b/types/doge-seed/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/doge-seed/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dot-object/dot-object-tests.ts b/types/dot-object/dot-object-tests.ts index a553c6c68d..c87c6f5a80 100644 --- a/types/dot-object/dot-object-tests.ts +++ b/types/dot-object/dot-object-tests.ts @@ -47,12 +47,21 @@ var newObj = { nested: { value: 'Hi there!' } + }, + breath: { + value: 'Hello' } }; var val = dot.pick('some.nested.value', newObj); console.log(val); +// Set a new value +val = dot.str('breath.value', 'World', newObj); + +// Replacing with a new object +val = dot.set('breath', { value: 'Goodbye' }, newObj); + // Pick & Remove the value val = dot.pick('some.nested.value', newObj, true); diff --git a/types/dot-object/index.d.ts b/types/dot-object/index.d.ts index 8bb7d0657c..ef119a3424 100644 --- a/types/dot-object/index.d.ts +++ b/types/dot-object/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for Dot-Object v1.5 +// Type definitions for Dot-Object 1.7 // Project: https://github.com/rhalff/dot-object // Definitions by: Niko Kovačič // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 declare namespace DotObject { @@ -120,12 +121,25 @@ declare namespace DotObject { */ remove(path: string, obj: any): any; /** + * + * Replace/create with a string + * * @param {String} path dotted path * @param {String} v value to be set * @param {Object} obj object to be modified * @param {Function|Array} mods optional modifier */ - str(path: string, v: any, obj: Object, mods?: ModifierFunctionWrapper | Array): void; + str(path: string, v: any, obj: object, mods?: ModifierFunctionWrapper | Array): void; + /** + * + * Replace/merge an object to an existing object property + * + * @param {String} path dotted path + * @param {Object} v object to be set + * @param {Object} obj object to be modified + * @param {Boolean} merge optional merge + */ + set(path: string, v: any, obj: object, merge?: boolean): void; /** * * Transfer a property from one object to another object. diff --git a/types/dot-object/tslint.json b/types/dot-object/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/dot-object/tslint.json +++ b/types/dot-object/tslint.json @@ -7,7 +7,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, diff --git a/types/dotenv-flow/dotenv-flow-tests.ts b/types/dotenv-flow/dotenv-flow-tests.ts new file mode 100644 index 0000000000..c1d12834db --- /dev/null +++ b/types/dotenv-flow/dotenv-flow-tests.ts @@ -0,0 +1,18 @@ +import dotenv = require("dotenv-flow"); + +const env = dotenv.config(); +const dbUrl: string | null = env.error || !env.parsed ? null : env.parsed["BASIC"]; + +dotenv.load({ + cwd: "someDir", + encoding: "utf8", + purge_dotenv: true +}); + +const parsed = dotenv.parse("NODE_ENV=production\nDB_HOST=a.b.c"); +const dbHost: string = parsed["DB_HOST"]; + +const parsedFromBuffer = dotenv.parse(new Buffer("JUSTICE=league\n"), { + debug: true +}); +const justice: string = parsedFromBuffer["JUSTICE"]; diff --git a/types/dotenv-flow/index.d.ts b/types/dotenv-flow/index.d.ts new file mode 100644 index 0000000000..33a494c4a8 --- /dev/null +++ b/types/dotenv-flow/index.d.ts @@ -0,0 +1,62 @@ +// Type definitions for dotenv-flow 0.2 +// Project: https://github.com/motdotla/dotenv +// Definitions by: Vincent Langlet +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export interface DotenvParseOptions { + /** + * You may turn on logging to help debug why certain keys or values are not being set as you expect. + */ + debug?: boolean; +} + +export interface DotenvParseOutput { + [name: string]: string; +} + +/** + * Parses a string or buffer in the .env file format into an object. + * + * @param src - contents to be parsed + * @param options - additional options + * @returns an object with keys and values based on `src` + */ +export function parse( + src: string | Buffer, + options?: DotenvParseOptions +): DotenvParseOutput; + +export interface DotenvConfigOptions { + /** + * You may specify a custom path if your file containing environment variables is located elsewhere. + */ + cwd?: string; + + /** + * You may specify the encoding of your file containing environment variables. + */ + encoding?: string; + + /** + * In some cases the original "dotenv" library can be used by one of the dependent npm modules. Use to fix this. + */ + purge_dotenv?: boolean; +} + +export interface DotenvConfigOutput { + error?: Error; + parsed?: DotenvParseOutput; +} + +/** + * Loads `.env` file contents into {@link https://nodejs.org/api/process.html#process_process_env | `process.env`}. + * Example: 'KEY=value' becomes { parsed: { KEY: 'value' } } + * + * @param options - controls behavior + * @returns an object with a `parsed` key if successful or `error` key if an error occurred + * + */ +export function config(options?: DotenvConfigOptions): DotenvConfigOutput; +export const load: typeof config; diff --git a/types/dotenv-flow/tsconfig.json b/types/dotenv-flow/tsconfig.json new file mode 100644 index 0000000000..376a2532ce --- /dev/null +++ b/types/dotenv-flow/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", + "dotenv-flow-tests.ts" + ] +} diff --git a/types/dotenv-flow/tslint.json b/types/dotenv-flow/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dotenv-flow/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dotenv-webpack/dotenv-webpack-tests.ts b/types/dotenv-webpack/dotenv-webpack-tests.ts index 6605550529..b4d7e849d8 100644 --- a/types/dotenv-webpack/dotenv-webpack-tests.ts +++ b/types/dotenv-webpack/dotenv-webpack-tests.ts @@ -3,19 +3,27 @@ import DotenvWebpackPlugin = require('dotenv-webpack'); new DotenvWebpackPlugin(); // $ExpectType DotenvWebpackPlugin -const options: DotenvWebpackPlugin.Options = { +const optionsEmpty: DotenvWebpackPlugin.Options = {}; + +const optionsFull: DotenvWebpackPlugin.Options = { path: './some.other.env', safe: true, systemvars: true, - silent: true + silent: true, + expand: true, + defaults: true +}; + +const optionsStrings: DotenvWebpackPlugin.Options = { + safe: './some.other.env.example', + defaults: './some.other.env.defaults' }; const config: webpack.Configuration = { plugins: [ new DotenvWebpackPlugin(), - new DotenvWebpackPlugin({ - path: './some.other.env', - }), - new DotenvWebpackPlugin(options), + new DotenvWebpackPlugin(optionsEmpty), + new DotenvWebpackPlugin(optionsFull), + new DotenvWebpackPlugin(optionsStrings) ] }; diff --git a/types/dotenv-webpack/index.d.ts b/types/dotenv-webpack/index.d.ts index 2d330ace45..25c64b7905 100644 --- a/types/dotenv-webpack/index.d.ts +++ b/types/dotenv-webpack/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for dotenv-webpack 1.5 +// Type definitions for dotenv-webpack 1.7 // Project: https://github.com/mrsteele/dotenv-webpack // Definitions by: Karol Majewski +// Dave Cardwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 @@ -20,7 +21,7 @@ declare namespace DotenvWebpackPlugin { /** * If `false` ignore safe-mode, if `true` load `'./.env.example'`, if a `string` load that file as the sample. Default: `false`. */ - safe?: boolean; + safe?: boolean | string; /** * Set to `true` if you would rather load all system variables as well (useful for CI purposes). Default: `false`. @@ -31,6 +32,17 @@ declare namespace DotenvWebpackPlugin { * If `true`, all warnings will be surpressed. Default: `false`. */ silent?: boolean; + + /** + * Allows your variables to be "expanded" for reusability within your .env file. Default: `false`. + */ + expand?: boolean; + + /** + * Adds support for dotenv-defaults. If set to `true`, uses `./.env.defaults`. If a `string`, uses that location for a defaults file. + * Read more at https://www.npmjs.com/package/dotenv-defaults. Default: `false`. + */ + defaults?: boolean | string; } } diff --git a/types/drivelist/drivelist-tests.ts b/types/drivelist/drivelist-tests.ts new file mode 100644 index 0000000000..9e1f04bf35 --- /dev/null +++ b/types/drivelist/drivelist-tests.ts @@ -0,0 +1,59 @@ +import * as drivelist from "drivelist"; + +drivelist.list((error, drives) => { + if (!error) { + drives.forEach(drive => { + const { + enumerator, + busType, + busVersion, + device, + devicePath, + raw, + description, + error, + size, + blockSize, + logicalBlockSize, + mountpoints, + isReadOnly, + isSystem, + isVirtual, + isRemovable, + isCard, + isSCSI, + isUSB, + isUAS + } = drive; + + enumerator; // $ExpectType string + busType; // $ExpectType BusType + busVersion; // $ExpectType string | null + device; // $ExpectType string + devicePath; // $ExpectType string | null + raw; // $ExpectType string + description; // $ExpectType string + error; // $ExpectType any + size; // $ExpectType number | null + blockSize; // $ExpectType number | null + logicalBlockSize; // $ExpectType number | null + + mountpoints; // $ExpectType MountPoint[] + mountpoints.forEach(mountpoint => { + const { path, label } = mountpoint; + + path; // $ExpectType string + label; // $ExpectType string | undefined + }); + + isReadOnly; // $ExpectType boolean + isSystem; // $ExpectType boolean + isVirtual; // $ExpectType boolean | null + isRemovable; // $ExpectType boolean | null + isCard; // $ExpectType boolean | null + isSCSI; // $ExpectType boolean | null + isUSB; // $ExpectType boolean | null + isUAS; // $ExpectType boolean | null + }); + } +}); diff --git a/types/drivelist/index.d.ts b/types/drivelist/index.d.ts new file mode 100644 index 0000000000..d2acd039df --- /dev/null +++ b/types/drivelist/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for drivelist 6.4 +// Project: https://github.com/resin-io-modules/drivelist +// Definitions by: Xiao Deng +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type BusType = "SATA" | "SCSI" | "ATA" | "IDE" | "PCI" | "UNKNOWN"; + +export interface MountPoint { + path: string; + label?: string; +} + +export interface Drive { + enumerator: string; + busType: BusType; + busVersion: string | null; + device: string; + devicePath: string | null; + raw: string; + description: string; + error: any; // can be null + size: number | null; + blockSize: number | null; + logicalBlockSize: number | null; + mountpoints: MountPoint[]; + isReadOnly: boolean; + isSystem: boolean; + isVirtual: boolean | null; + isRemovable: boolean | null; + isCard: boolean | null; + isSCSI: boolean | null; + isUSB: boolean | null; + isUAS: boolean | null; +} + +export function list(callback: (error: any, drives: Drive[]) => void): void; diff --git a/types/drivelist/tsconfig.json b/types/drivelist/tsconfig.json new file mode 100644 index 0000000000..0dd1a9ecdd --- /dev/null +++ b/types/drivelist/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", + "drivelist-tests.ts" + ] +} diff --git a/types/drivelist/tslint.json b/types/drivelist/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/drivelist/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dwt/Dynamsoft.d.ts b/types/dwt/Dynamsoft.d.ts new file mode 100644 index 0000000000..65569f61b3 --- /dev/null +++ b/types/dwt/Dynamsoft.d.ts @@ -0,0 +1,113 @@ +declare namespace Dynamsoft { + let Lib: DynamsoftLib; + let WebTwainEnv: dwtEnv; + namespace WebTwain { + namespace Addon { + let OCRPro: OCRProAddon; + } + } + namespace DWT { + let defaultEnv: dwtEnv; + } +} + +declare const dwt: WebTwain; + +interface dwtEnv { + ActiveXInstallWithCAB: boolean; + ActiveXVersion: string; + AutoLoad: boolean; + CloseDialog(): void; + ContainerMap: {}; + Containers: Container[]; + CreateDWTObject(newObjID: string, successFn: (dwtObject: WebTwain) => void, failurefn: (...args: any[]) => void): void; + CreateDWTObject(newObjID: string, ip: number | string, port: number | string, portSSL: number | string, successFn: (dwtObject: WebTwain) => void, failurefn: (...args: any[]) => void): void; + Debug: boolean; + DeleteDWTObject(objID: string): void; + DynamicContainers: string[]; + DynamicDWTMap: {}; + GetWebTwain(cid: string): WebTwain; + IfUpdateService: boolean; + IfUseActiveXForIE10Plus: boolean; + JSVersion: string; + Load(): void; + + /*ignored + OnWebTwainInitMessage OnWebTwainNeedUpgrade OnWebTwainNeedUpgradeWebJavascript OnWebTwainNotFound OnWebTwainOldPluginNotAllowed + */ + + OnWebTwainPostExecute(): void; + OnWebTwainPreExecute(): void; + + /*ignored + OnWebTwainReady + */ + + PluginVersion: string; + ProductKey: string; + RegisterEvent(event: string, fn: (...args: any[]) => void): void; + RemoveAllAuthorizations(): void; + ResourcesPath: string; + ServerVersionInfo: string; + ShowDialog(_dialogWidth: number, _dialogHeight: number, _strDialogMessageWithHtmlFormat: string, _bChangeImage: boolean, bHideCloseButton: boolean): void; + Trial: boolean; + Unload(): void; + UseDefaultInstallUI: boolean; + initQueue: any[]; + inited: boolean; +} + +interface DynamsoftLib { + /*ignored + Addon_Events Addon_Sendback_Events AttachAndShowImage BIO DOM DynamicLoadAddonFuns DynamicWebTwain EnumMouseButton + Errors Events IntToColorStr LS OnGetImageByURL OnGetImageFromServer Path ProgressBar UI Uri + addEventListener ajax all appendMessage appendRichMessage aryControlLoadImage attachAddon attachProperty + base64 bio cancelFrome clearMessage closeAll closeProgress colorStrToInt config css currentStyle + debug*/ + + detect: { + /*ignored + OnCreatWS OnDetectNext OnWebTwainPostExecute OnWebTwainPreExecute StartWSByIPTimeoutId StartWSTimeoutId + aryReconnectSTwains arySTwains arySTwainsByIP bFirst bNeedUpgradeEvent bNoControlEvent bOK bPromptJSOrServerOutdated + cUrlIndex dcpCallbackType dcpStatus detectType getVersionArray global_dlg hideMask isDWTVersionLatest onNoControl + onNotAllowedForChrome ports scriptLoaded showMask starting tryTimes*/ + ssl: boolean; + }; + + /*ignored + detectButton dialog dialogShowStatus dlgProgress dlgRef drawBoxBorder drawImageWithHermite + each empty endsWith + */ + + env: { + WSSession: number, WSVersion: string, + bChrome: boolean, bEdge: boolean, bFileSystem: boolean, bFirefox: boolean, + bIE: boolean, bLinux: boolean, bMac: boolean, bSafari: boolean, bWin: boolean, bWin64: boolean, + basePath: string, iPluginLength: number, isX64: boolean, pathType: number, + strChromeVersion: string, strFirefoxVersion: string, strIEVersion: string + }; + + /*ignored + error escapeHtml escapeRegExp extend filter fireEvent fromUnicode get getColor getCss + getElDimensions getHex getHexColor getHttpUrl getLogger getOffset getRandom getRealPath getScript + getWS getWSUrl getWheelDelta globalEval guid hide html5 imageControlCount indexOf install + io isArray isBoolean isDef isFunction isLocalIP isNaN isNull isNumber isObject + isPlainObject isString isUndef isUndefined isWindow keys log main makeArray mix + needShowTwiceShowDialog nil noop now obj one page param parse parseHTML parser + product progressMessage ready removeEventListener replaceAll replaceControl show showProgress startWS + startWSByIP startsWith stopPropagation stringify style support switchEvent tmp toggle trim + type unEscapeHtml unparam upperCaseFirst urlDecode urlEncode utf8 win + ...other internal ones + */ + hideMask(): void; + showMask(): void; +} + +/** + * interface for a DWT container which basically defines a DIV on the page + */ +interface Container { + ContainerId: string; + Width: string | number; + Height: string | number; +} diff --git a/types/dwt/addon.ocr.d.ts b/types/dwt/addon.ocr.d.ts new file mode 100644 index 0000000000..5020d5eec3 --- /dev/null +++ b/types/dwt/addon.ocr.d.ts @@ -0,0 +1,192 @@ +declare enum EnumDWT_OCRLanguage { + OCRL_ENG = "eng", + OCRL_ARA = "ara", + OCRL_CHI_SIM = "chi_sim", + OCRL_CHI_TRA = "chi_tra", + OCRL_HIN = "hin", + OCRL_URD = "urd", + OCRL_SPA = "spa", + OCRL_FRA = "fra", + OCRL_MSA = "msa", + OCRL_IND = "ind", + OCRL_RUS = "rus", + OCRL_BEN = "ben", + OCRL_POR = "por", + OCRL_PAN = "pan", + OCRL_DEU = "deu", + OCRL_JPN = "jpn", + OCRL_FAS = "fas", + OCRL_SWA = "swa", + OCRL_JAV = "jav", + OCRL_TEL = "tel", + OCRL_TUR = "tur", + OCRL_KOR = "kor", + OCRL_MAR = "mar", + OCRL_TAM = "tam", + OCRL_VIE = "vie", + OCRL_ITA = "ita", + OCRL_THA = "tha" +} + +declare enum EnumDWT_OCRPageSetMode { + OCRPSM_OSD_ONLY = 0, + PSM_AUTO_OSD = 1, + PSM_AUTO_ONLY = 2, + PSM_AUTO = 3, + PSM_SINGLE_COLUMN = 4, + PSM_SINGLE_BLOCK_VERT_TEXT = 5, + PSM_SINGLE_BLOCK = 6, + PSM_SINGLE_LINE = 7, + PSM_SINGLE_WORD = 8, + PSM_CIRCLE_WORD = 9, + PSM_SINGLE_CHAR = 10 +} + +declare enum EnumDWT_OCROutputFormat { + OCROF_TEXT = 0, + OCROF_PDFPLAINTEXT = 1, + OCROF_PDFIMAGEOVERTEXT = 2, + OCROF_PDFPLAINTEXT_PDFX = 3, + OCROF_PDFIMAGEOVERTEXT_PDFX = 4 +} + +/** + * @class + */ +interface OCR { + /** + * Downloads and installs the ocr add-on on the local system. + * @method Dynamsoft.WebTwain#Download + * @param {string} remoteFile specifies the value of which frame to get. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + Download(remoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Downloads and deploys the OCR language package on the local system. + * @method Dynamsoft.WebTwain#DownloadLangData + * @param {string} remoteFile specifies the value of which frame to get. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + DownloadLangData(remoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Performs OCR on a given image. + * @method Dynamsoft.WebTwain#Read + * @param {number} sImageIndex Specifies the index of the image. + * @param {function} AsyncSuccessFunc The function to call when OCR operation succeeds. Please refer to the function prototype OnOCRSuccess. + * @param {function} AsyncFailureFunc The function to call when OCR operation fails. Please refer to the function prototype OnOCRFailure. + * @return {boolean} + */ + Recognize(sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Peforms OCR on the given rectangle on a specified image. + * @method Dynamsoft.WebTwain#ReadRect + * @param {number} sImageIndex Specifies the index of the image. + * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @param {function} AsyncSuccessFunc The function to call when OCR operation succeeds. Please refer to the function prototype OnOCRSuccess. + * @param {function} AsyncFailureFunc The function to call when OCR operation fails. Please refer to the function prototype OnOCRFailure. + * @return {boolean} + */ + RecognizeRect(sImageIndex: number, left: number, top: number, right: number, bottom: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Performs OCR on one or multiple specified local file(s) directly. + * @method Dynamsoft.WebTwain#Read + * @param {string} fileNames Specifies the local paths of the target files. If multiple files are given, they should be separated by the '|' character. + * @param {function} AsyncSuccessFunc The function to call when OCR operation succeeds. Please refer to the function prototype OnOCRSuccess. + * @param {function} AsyncFailureFunc The function to call when OCR operation fails. Please refer to the function prototype OnOCRFailure. + * @return {boolean} + */ + RecognizeFile(fileNames: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Performs OCR on the currently selected images in the buffer. + * @method Dynamsoft.WebTwain#Read + * @param {function} AsyncSuccessFunc The function to call when OCR operation succeeds. Please refer to the function prototype OnOCRSuccess. + * @param {function} AsyncFailureFunc The function to call when OCR operation fails. Please refer to the function prototype OnOCRFailure. + * @return {boolean} + */ + RecognizeSelectedImages(optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Specifies a font to be used by OCR when Addon.OCR.SetIfUseDetectedFont is set to false. + * @method Dynamsoft.WebTwain#SetUnicodeFontName + * @param {string} name Specifies a font to be used by + * @return {boolean} + */ + SetUnicodeFontName(name: string): void; + + /** + * Returns the detected OCR font name. + * @method Dynamsoft.WebTwain#GetUnicodeFontName + * @return {string} Returns the detected OCR font name. + */ + GetUnicodeFontName(): void; + + /** + * Determines whether PDF output should use the fonts detected by the OCR system, or the default/provided fonts instead. + * @method Dynamsoft.WebTwain#SetIfUseDetectedFont + * @param {boolean} bValue By default this is true, indicating detected fonts should be used. The detected fonts must exist on the user's system for this to be successful. + * @return {boolean} + */ + SetIfUseDetectedFont(bValue: boolean): void; + + /** + * Returns whether PDF output should use the fonts detected by the OCR system, or the default/provided fonts instead. + * @method Dynamsoft.WebTwain#GetIfUseDetectedFont + * @return {boolean} Returns whether PDF output should use the fonts detected by the OCR system, or the default/provided fonts instead. + */ + GetIfUseDetectedFont(): void; + + /** + * Applies higher-level accuracy of OCR to the area of the image where the font size is bigger than the value set here. + * @method Dynamsoft.WebTwain#SetIfUseDetectedFont + * @param {number} nValue Specifies the font size base to apply the higher-level accracy OCR. The default value is 0 which means no regional accurate OCR is performed. + * @return {boolean} + */ + SetMinFontSizeforMoreAccurateResult(nValue: number): void; + + /** + * Returns the font size base to apply higher-level regional accarate OCR which is set through Addon.OCR.SetMinFontSizeforMoreAccurateResult. + * @method Dynamsoft.WebTwain#GetMinFontSizeforMoreAccurateResult + * @return {boolean} Returns the font size base to apply higher-level regional accarate OCR. If the return value is 0, it indicates no regional accurate OCR is performed. + */ + GetMinFontSizeforMoreAccurateResult(): void; + + /** + * Sets the target language for OCR operations. + * @method Dynamsoft.WebTwain#SetLanguage + * @param {string} value Specifies the target language for OCR operation. + * @return {boolean} + */ + SetLanguage(value: string): void; + + /** + * Sets the mode for OCR page layout analysis. Determines how pages are determined when processing OCR. + * @method Dynamsoft.WebTwain#SetPageSetMode + * @param {EnumDWT_OCRPageSetMode} value Specifies the OCR Page layout analysis mode. + * @return {boolean} + */ + SetPageSetMode(value: EnumDWT_OCRPageSetMode): void; + + /** + * Sets the OCR result format. Determines whether the OCR output is in text or PDF format. + * @method Dynamsoft.WebTwain#SetOutputFormat + * @param {EnumDWT_OCROutputFormat} value Specifies the OCR result format. + * @return {boolean} + */ + SetOutputFormat(value: EnumDWT_OCROutputFormat): void; +} + +interface WebTwainAddon { + OCR: OCR; +} diff --git a/types/dwt/addon.ocrp.d.ts b/types/dwt/addon.ocrp.d.ts new file mode 100644 index 0000000000..48931bea9d --- /dev/null +++ b/types/dwt/addon.ocrp.d.ts @@ -0,0 +1,164 @@ +interface Redaction { + FindText: string; + FindTextFlags: EnumDWT_OCRFindTextFlags.OCRFT_WHOLEWORD; + FindTextAction: EnumDWT_OCRFindTextAction.OCRFT_MARKFORREDACT; +} + +interface OCRZone { + left: number; + top: number; + right: number; + bottom: number; +} + +interface OCRReadPara { + STWAIN: WebTwain; + AjaxFunctionUrl: string; + FunctionName: string; + ImageIndex: number; + FileNames: string; + Type: string; + AryZone: number[]; + JsonString: string; + OnSuccess(): void; + OnFailure(): void; +} + +interface OCRError { + responseText: string; + errorString: string; +} + +interface Settings { + RecognitionModule: string; + Languages: string; + OutputFormat: EnumDWT_OCRProOutputFormat; + PDFVersion: EnumDWT_OCRProPDFVersion; + PDFAVersion: EnumDWT_OCRProPDFAVersion; + LicenseChecker: string; + Redaction: Redaction; +} + +interface DynamsoftLib { + NewRedaction(): Redaction; + NewOCRReadPara(): OCRReadPara; + NewOCRZone(): OCRZone; +} + +interface OCRProAddon { + NewOCRError(): OCRError; + NewOCRReadPara(): OCRReadPara; + NewOCRZone(): OCRZone; + NewSettings(): Settings; +} + +declare enum EnumDWT_OCRFindTextFlags { + OCRFT_WHOLEWORD = 1, + OCRFT_MATCHCASE = 2, + OCRFT_FUZZYMATCH = 4 +} +declare enum EnumDWT_OCRFindTextAction { + OCRFT_HIGHLIGHT = 0, + OCRFT_STRIKEOUT = 1, + OCRFT_MARKFORREDACT = 2 +} + +declare enum EnumDWT_OCRProOutputFormat { + OCRPFT_IOTPDF = "IOTPDF", + OCRPFT_IOTPDF_MRC = "IOTPDF_MRC", + OCRPFT_TXTCSV = "TXTCSV", + OCRPFT_TXTF = "TXTF", + OCRPFT_TXTS = "TXTS", + OCRPFT_XML = "XML" +} + +declare enum EnumDWT_OCRProPDFAVersion { + OCRPPDFAV_1A = "pdf/a-1a", + OCRPPDFAV_1B = "pdf/a-1b", + OCRPPDFAV_2A = "pdf/a-2a", + OCRPPDFAV_2B = "pdf/a-2b", + OCRPPDFAV_2U = "pdf/a-2u", + OCRPPDFAV_3A = "pdf/a-3a", + OCRPPDFAV_3B = "pdf/a-3b", + OCRPPDFAV_3U = "pdf/a-3u" +} + +declare enum EnumDWT_OCRProPDFVersion { + OCRPPDFV_0 = "1.0", + OCRPPDFV_1 = "1.1", + OCRPPDFV_2 = "1.2", + OCRPPDFV_3 = "1.3", + OCRPPDFV_4 = "1.4", + OCRPPDFV_5 = "1.5", + OCRPPDFV_6 = "1.6", + OCRPPDFV_7 = "1.7" +} + +declare enum EnumDWT_OCRProRecognitionModule { + OCRPM_AUTO = "AUTO", + OCRPM_MOSTACCURATE = "MOSTACCURATE", + OCRPM_BALANCED = "BALANCED", + OCRPM_FASTEST = "FASTEST" +} + +declare enum EnumDWT_OCRProType { + OCRDT_File = 0, + OCRDT_Index = 1 +} + +interface OCRPro { + /** + * Returns whether OCR Pro addon is installed + * @return {boolean} + */ + IsModuleInstalled(): boolean; + + /** + * Downloads and installs the ocr add-on on the local system. + * @param {string} remoteFile specifies the URL to download a ZIP which contains the OCR Pro addon + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {void} + */ + Download(remoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Performs OCR on a given image. + * @param {number} sImageIndex Specifies the index of the image. + * @param {function} AsyncSuccessFunc The function to call when OCR operation succeeds. Please refer to the function prototype OnOCRSuccess. + * @param {function} AsyncFailureFunc The function to call when OCR operation fails. Please refer to the function prototype OnOCRFailure. + * @return {void} + */ + Recognize(sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Performs OCR on one or multiple specified local file(s) directly. + * @param {string} fileNames Specifies the local paths of the target files. If multiple files are given, they should be separated by the '|' character. + * @param {function} AsyncSuccessFunc The function to call when OCR operation succeeds. Please refer to the function prototype OnOCRSuccess. + * @param {function} AsyncFailureFunc The function to call when OCR operation fails. Please refer to the function prototype OnOCRFailure. + * @return {void} + */ + RecognizeFile(fileNames: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Peforms OCR on the given rectangle on a specified image. + * @param {number} sImageIndex Specifies the index of the image. + * @param {number[]} aryZone specifies the coordinates of the rectangle. + * @param {function} AsyncSuccessFunc The function to call when OCR operation succeeds. Please refer to the function prototype OnOCRSuccess. + * @param {function} AsyncFailureFunc The function to call when OCR operation fails. Please refer to the function prototype OnOCRFailure. + * @return {void} + */ + RecognizeRect(sImageIndex: number, aryZone: number[], optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Performs OCR on the currently selected images in the buffer. + * @param {function} AsyncSuccessFunc The function to call when OCR operation succeeds. Please refer to the function prototype OnOCRSuccess. + * @param {function} AsyncFailureFunc The function to call when OCR operation fails. Please refer to the function prototype OnOCRFailure. + * @return {void} + */ + RecognizeSelectedImages(optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; +} + +interface WebTwainAddon { + OCRPro: OCRPro; +} diff --git a/types/dwt/addon.pdf.d.ts b/types/dwt/addon.pdf.d.ts index 6a2a8636ee..6f9ad5cec1 100644 --- a/types/dwt/addon.pdf.d.ts +++ b/types/dwt/addon.pdf.d.ts @@ -1,14 +1,3 @@ -/*! -* Dynamsoft WebTwain PDF Addon -* Based on Dynamsoft WebTwain JavaScript Intellisense -* Product: Dynamsoft Web Twain -* Web Site: http://www.dynamsoft.com -* -* Copyright 2018, Dynamsoft Corporation -* Author: Dynamsoft Support Team -* Version: 14.2 -*/ - declare enum EnumDWT_ConvertMode { CM_DEFAULT = 0, CM_RENDERALL = 1 @@ -73,7 +62,3 @@ interface PDF { interface WebTwainAddon { PDF: PDF; } - -interface WebTwain { - Addon: WebTwainAddon; -} diff --git a/types/dwt/addon.webcam.d.ts b/types/dwt/addon.webcam.d.ts new file mode 100644 index 0000000000..efb31cda3e --- /dev/null +++ b/types/dwt/addon.webcam.d.ts @@ -0,0 +1,334 @@ +/** -2400 to -2499 is webcam error code */ +declare enum EnumDWT_ErrorCode { + /** All error from directshow sdk */ + WCERR_SYSTEM = -2400, + /** Create ICreateDevEnum interface failed. */ + WCERR_FAIL_ICREATEDEVENUM = -2401, + /** Create IEnumMoniker interface failed. */ + WCERR_FAIL_IENUMMONIKER = -2402, + /** The camera doesn't support IAMVideoProcAmp interface. */ + WCERR_NOT_IAMVIDEOPROPERTY = -2403, + /** The camera doesn't support IAMCameraControl interface. */ + WCERR_NOT_IAMCAMERACONTROL = -2404, + /** The property doesn't support auto capability. */ + WCERR_NOT_AUTOPROPERTY = -2405, + /** No webcam device is found. */ + WCERR_NO_DEVICE = -2406, + /** Could not get video window interface */ + WCERR_FAIL_VIDEOWINDOW = -2407, + /** Could not create filter graph. */ + WCERR_FAIL_FILTERGRAPH = -2408, + /** Could not create SampleGrabber (isqedit.all registered?). */ + WCERR_FAIL_SAMPLEGRABBER = -2409, + /** Unable to make NULL renderer */ + WCERR_NULLRENDER = -2410, + /** Can't add the filter to graph */ + WCERR_FAIL_ADDFILTER = -2411, + /** Can't build the graph */ + WCERR_FAIL_BUILDGRAPH = -2412, + /** Failed to register filter graph with ROT. */ + WCERR_FAIL_REGFILTERGRAPH = -2413, + /** Time out */ + WCERR_GRAB_TIMEOUT = -2414 +} + +/** Specifies the video rotate mode on a video capture device. */ +declare enum EnumDWT_VideoRotateMode { + /** Don't rotate */ + VRM_NONE = 0, + /** 90 deg Clockwise */ + VRM_90_DEGREES_CLOCKWISE = 1, + /** 180 deg Clockwise */ + VRM_180_DEGREES_CLOCKWISE = 2, + /** 270 deg Clockwise */ + VRM_270_DEGREES_CLOCKWISE = 3, + /** Flip */ + VRM_FLIP_VERTICAL = 4, + /** Mirror */ + VRM_FLIP_HORIZONTAL = 5 +} + +/** Specifies video properties on a video capture device. */ +declare enum EnumDWT_VideoProperty { + /** Specifies the brightness, also called the black level. For NTSC, the value is expressed in IRE units * 100. + * For non-NTSC sources, the units are arbitrary, with zero representing blanking and 10,000 representing pure white. + * Values range from -10,000 to 10,000. + */ + VP_BRIGHTNESS = 0, + /** Specifies the contrast, expressed as gain factor * 100. Values range from zero to 10,000. */ + VP_CONTRAST = 1, + /** Specifies the hue, in degrees * 100. Values range from -180,000 to 180,000 (-180 to +180 degrees). */ + VP_HUE = 2, + /** Specifies the saturation. Values range from 0 to 10,000. */ + VP_SATURATION = 3, + /** Specifies the sharpness. Values range from 0 to 100. */ + VP_SHARPNESS = 4, + /** Specifies the gamma, as gamma * 100. Values range from 1 to 500. */ + VP_GAMMA = 5, + /** Specifies the color enable setting. The possible values are 0 (off) and 1 (on). */ + VP_COLORENABLE = 6, + /** Specifies the white balance, as a color temperature in degrees Kelvin. The range of values depends on the device. */ + VP_WHITEBALANCE = 7, + /** Specifies the backlight compensation setting. Possible values are 0 (off) and 1 (on). */ + VP_BACKLIGHTCOMPENSATION = 8, + /** Specifies the gain adjustment. Zero is normal. Positive values are brighter and negative values are darker. + * The range of values depends on the device. + */ + VP_GAIN = 9 +} + +/** Specifies a setting on a camera. */ +declare enum EnumDWT_CameraControlProperty { + /** Specifies the camera's pan setting, in degrees. Values range from -180 to +180, with the default set to zero. + * Positive values are clockwise from the origin (the camera rotates clockwise when viewed from above), + * and negative values are counterclockwise from the origin. + */ + CCP_PAN = 0, + /** Specifies the camera's tilt setting, in degrees. Values range from -180 to +180, with the default set to zero. + * Positive values point the imaging plane up, and negative values point the imaging plane down. + */ + CCP_TILT = 1, + /** Specifies the camera's roll setting, in degrees. Values range from -180 to +180, with the default set to zero. + * Positive values cause a clockwise rotation of the camera along the image-viewing axis, and negative values cause a counterclockwise rotation of the camera. + */ + CCP_ROLL = 2, + /** Specifies the camera's zoom setting, in millimeters. Values range from 10 to 600, and the default is specific to the device. */ + CCP_ZOOM = 3, + /** Specifies the exposure setting, in log base 2 seconds. In other words, for values less than zero, the exposure time is 1/2^n seconds, + * and for values zero or above, the exposure time is 2^n seconds. For example: + * Value Seconds + * -3 1/8 + * -2 1/4 + * -1 1/2 + * 0 1 + * 1 2 + * 2 4 + */ + CCP_EXPOSURE = 4, + /** Specifies the camera's iris setting, in units of fstop* 10. */ + CCP_IRIS = 5, + /** Specifies the camera's focus setting, as the distance to the optimally focused target, in millimeters. + * The range and default value are specific to the device. + */ + CCP_FOCUS = 6 +} + +interface WebcamMediaType { + GetCount(): number; + Get(index: number): string; + GetCurrent(): string; +} + +interface WebcamResolution { + GetCount(): number; + Get(index: number): string; + GetCurrent(): string; +} + +interface WebcamFrameRate { + GetCount(): number; + Get(index: number): string; + GetCurrent(): string; +} + +interface CameraControlMoreSetting { + GetMinValue(): number; + GetMaxValue(): number; + GetSteppingDelta(): number; + GetDefaultValue(): number; + GetIfAuto(): boolean; +} + +interface CameraControlSetting { + GetValue(): number; + GetIfAuto(): boolean; +} + +interface VideoPropertyMoreSetting { + GetMinValue(): number; + GetMaxValue(): number; + GetSteppingDelta(): number; + GetDefaultValue(): number; + GetIfAuto(): boolean; +} + +interface VideoPropertySetting { + GetValue(): number; + GetIfAuto(): boolean; +} + +/** + * @class + */ +interface Webcam { + IsModuleInstalled(): boolean; + GetFramePartURL(): string; + GetFrameURL(): string; + + /** + * Download and install webcam add-on on the local system. + * @method Dynamsoft.WebTwain#Download + * @param {string} remoteFile:string specifies the value of which frame to get. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + Download(remoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: () => void): void; + + /** + * Return supported webcam source names. + * @method Dynamsoft.WebTwain#GetSourceList + * @return {string array} + */ + GetSourceList(): string[]; + + /** + * Select the source with the specified name. + * @method Dynamsoft.WebTwain#SelectSource + * @param {string} strSourceName The source name. + * @return {boolean} + */ + SelectSource(strSourceName: string): boolean; + + /** + * Close the selected source and release the webcam. + * @method Dynamsoft.WebTwain#CloseSource + * @return {boolean} + */ + CloseSource(): boolean; + + /** + * Show video stream in a specified container + * @method Dynamsoft.WebTwain#StopVideo + * @param {WebTwain} DWObject Specifies the WebTwain Object. + * @param {number} quality Specifies the quality of each frame in the video stream. Only valid for the HTML5 edition. + * @param {function} onFrameCaptured callback of the operation to capture + * @return {void} + */ + PlayVideo(DWObject: WebTwain, quality: number, onFrameCaptured: () => void): void; + + /** + * Stop the video stream in the specified container + * @method Dynamsoft.WebTwain#StopVideo + * @return {boolean} + */ + StopVideo(): boolean; + + /** + * Capture image from the specified webcam. + * @method Dynamsoft.WebTwain#CaptureImage + * @param {function} OnCaptureSuccess he function to call when the capture succeeds. Please refer to the function prototype OnCaptureSuccess. + * @param {function} OnCaptureError The function to call when the capture fails. Please refer to the function prototype OnCaptureError. + * @return {void} + */ + CaptureImage(OnCaptureSuccess: () => void, OnCaptureError: () => void): void; + + /** + * Returns the media type for a camera. + * @method Dynamsoft.WebTwain#GetMediaType + * @return {class MediaType} + */ + GetMediaType(): WebcamMediaType; + + /** + * Returns the count in the media type list. + * @method Dynamsoft.WebTwain#GetResolution + * @return {class Resolution} + */ + GetResolution(): WebcamResolution; + + /** + * Returns the frame rate for a camera. + * @method Dynamsoft.WebTwain#GetFrameRate + * @return {class FrameRate} + */ + GetFrameRate(): WebcamFrameRate; + + /** + * Set the media type of the current selected source by the value. + * @method Dynamsoft.WebTwain#SetMediaType + * @param {string} value The new media type value. + * @return {boolean} + */ + SetMediaType(value: string): boolean; + + /** + * Set the resolution of the current camera source. + * @method Dynamsoft.WebTwain#SetResolution + * @param {string} value The new resolution value. + * @return {boolean} + */ + SetResolution(value: string): boolean; + + /** + * Set current frame rate. + * @method Dynamsoft.WebTwain#SetFrameRate + * @param {number} value The new frame rate value. + * @return {boolean} + */ + SetFrameRate(value: number): boolean; + + /** + * Gets the current setting of a video property. + * @method Dynamsoft.WebTwain#GetVideoPropertySetting + * @param {EnumDWT_VideoProperty} property The property. + * @return {class VideoPropertySetting} + */ + GetVideoPropertySetting(property: EnumDWT_VideoProperty): VideoPropertySetting; + + /** + * Gets the range and default value of a specified video property. + * @method Dynamsoft.WebTwain#GetVideoPropertyMoreSetting + * @param {EnumDWT_VideoProperty} property The property. + * @return {class VideoPropertyMoreSetting} + */ + GetVideoPropertyMoreSetting(property: EnumDWT_VideoProperty): VideoPropertyMoreSetting; + + /** + * Gets the current setting of a camera property. + * @method Dynamsoft.WebTwain#GetCameraControlPropertySetting + * @param {EnumDWT_CameraControlProperty} property The property. + * @return {class CameraControlPropertySetting} + */ + GetCameraControlPropertySetting(property: EnumDWT_CameraControlProperty): CameraControlSetting; + + /** + * Gets the range and default value of a specified camera property. + * @method Dynamsoft.WebTwain#GetVideoPropertyMoreSetting + * @param {EnumDWT_CameraControlProperty} property The property. + * @return {class CameraControlPropertyMoreSetting} + */ + GetCameraControlPropertyMoreSetting(property: EnumDWT_CameraControlProperty): CameraControlMoreSetting; + + /** + * Sets video quality for a specified property. + * @method Dynamsoft.WebTwain#SetVideoPropertySetting + * @param {EnumDWT_VideoProperty} property The property. + * @param {number} value The new value of the property. + * @param {boolean} auto The desired control setting, whether the setting is controlled manually or automatically. + * @return {boolean} + */ + SetVideoPropertySetting(property: EnumDWT_VideoProperty, value: number, auto: boolean): boolean; + + /** + * Sets video rotate mode. + * @method Dynamsoft.WebTwain#SetVideoRotateMode + * @param {EnumDWT_VideoRotateMode} enumAngle The rotate angle. + * @return {boolean} + */ + SetVideoRotateMode(enumAngle: EnumDWT_VideoRotateMode): boolean; + + /** + * Sets a specified property on the camera. + * @method Dynamsoft.WebTwain#SetCameraControlPropertySetting + * @param {EnumDWT_CameraControlProperty} property The property. + * @param {number} value The new value of the property. + * @param {boolean} auto The desired control setting, whether the setting is controlled manually or automatically. + * @return {boolean} + */ + SetCameraControlPropertySetting(property: EnumDWT_CameraControlProperty, value: number, auto: boolean): boolean; +} + +interface WebTwainAddon { + Webcam: Webcam; +} diff --git a/types/dwt/dbr.d.ts b/types/dwt/dbr.d.ts new file mode 100644 index 0000000000..e8d8f6addc --- /dev/null +++ b/types/dwt/dbr.d.ts @@ -0,0 +1,192 @@ +interface RunTimeSetting { + mAntiDamageLevel: number; + mBarcodeFormatIds: number; + mBarcodeInvertMode: number; + mBinarizationBlockSize: number; + mColourImageConvertMode: number; + mDeblurLevel: number; + mEnableFillBinaryVacancy: number; + mExpectedBarcodesCount: number; + mGrayEqualizationSensitivity: number; + mLocalizationAlgorithmPriority: string; + mMaxAlgorithmThreadCount: number; + mMaxBarcodesCount: number; + mMaxDimOfFullImageAsBarcodeZone: number; + mPDFRasterDPI: number; + mRegionPredetectionMode: number; + mReserved: string; + mScaleDownThreshold: number; + mTextFilterMode: number; + mTextureDetectionSensitivity: number; + mTimeout: number; +} + +interface dbrEnv { + bAutoConnectService: boolean; + logLevel: number; + productKey: string; + resourcesPath: string; + onAutoConnectServiceSuccess(): void; + onAutoConnectServiceError(status: any): void; +} + +declare namespace dynamsoft { + let TaskQueue: TaskQueue; + let dbrEnv: dbrEnv; + /**dbrMasterPage20170526 */ + let dcp: { + ifCheck64bitServiceFirst: boolean; + }; + /**dwtDbrDemo20170613 */ + let initOrder: any; + let lib: any; + let managerEnv: any; + let navInfo: any; + namespace BarcodeReader { + /** Barcode Formats */ + enum EnumBarcodeFormat { + All = 503317503, + OneD = 0x3FF, + CODE_39 = 0x1, + CODE_128 = 0x2, + CODE_93 = 0x4, + CODABAR = 0x8, + ITF = 0x10, + EAN_13 = 0x20, + EAN_8 = 0x40, + UPC_A = 0x80, + UPC_E = 0x100, + INDUSTRIAL_25 = 0x200, + PDF417 = 0x2000000, + QR_CODE = 0x4000000, + DATAMATRIX = 0x8000000, + AZTEC = 0x10000000 + } + + enum EnumErrorCode { + DBR_SYSTEM_EXCEPTION = 1, + DBR_SUCCESS = 0, + DBR_UNKNOWN = -10000, + DBR_NO_MEMORY = -10001, + DBR_NULL_REFERENCE = -10002, + DBR_LICENSE_INVALID = -10003, + DBR_LICENSE_EXPIRED = -10004, + DBR_FILE_NOT_FOUND = -10005, + DBR_FILETYPE_NOT_SUPPORTED = -10006, + DBR_BPP_NOT_SUPPORTED = -10007, + DBR_INDEX_INVALID = -10008, + DBR_BARCODE_FORMAT_INVALID = -10009, + DBR_CUSTOM_REGION_INVALID = -10010, + DBR_MAX_BARCODE_NUMBER_INVALID = -10011, + DBR_IMAGE_READ_FAILED = -10012, + DBR_TIFF_READ_FAILED = -10013, + DBR_QR_LICENSE_INVALID = -10016, + DBR_1D_LICENSE_INVALID = -10017, + DBR_DIB_BUFFER_INVALID = -10018, + DBR_PDF417_LICENSE_INVALID = 10019, + DBR_DATAMATRIX_LICENSE_INVALID = -10020, + DBR_PDF_READ_FAILED = -10021, + DBR_PDF_DLL_MISSING = -10022, + DBR_PAGE_NUMBER_INVALID = -10023, + DBR_CUSTOM_SIZE_INVALID = -10024, + DBR_CUSTOM_MODULESIZE_INVALID = -10025, + DBR_RECOGNITION_TIMEOUT = -10026, + DBR_JSON_PARSE_FAILED = -10030, + DBR_JSON_TYPE_INVALID = -10031, + DBR_JSON_KEY_INVALID = -10032, + DBR_JSON_VALUE_INVALID = -10033, + DBR_JSON_NAME_KEY_MISSING = -10034, + DBR_JSON_NAME_VALUE_DUPLICATED = -10035, + DBR_TEMPLATE_NAME_INVALID = -10036, + DBR_JSON_NAME_REFERENCE_INVALID = -10037, + DBR_PARAMETER_VALUE_INVALID = 10038, + DBR_DOMAIN_NOT_MATCHED = -10039, + DBR_RESERVEDINFO_NOT_MATCHED = -10040, + DBR_DBRERR_AZTEC_LICENSE_INVALID = -10041 + } + enum EnumConflictMode { + ECM_Ignore = 1, + ECM_Overwrite = 2 + } + enum EnumImagePixelFormat { + IPF_Binary = 0, + IPF_BinaryInverted = 1, + IPF_GrayScaled = 2, + IPF_NV21 = 3, + IPF_RGB_565 = 4, + IPF_RGB_555 = 5, + IPF_RGB_888 = 6, + IPF_ARGB_8888 = 7 + } + enum EnumResultType { + EDT_CandidateText = 2, + EDT_PartialText = 3, + EDT_RawText = 1, + EDT_StandardText = 0 + } + enum EnumTerminateStage { + ETS_Localized = 1, + ETS_Prelocalized = 0, + ETS_Recognized = 2 + } + } + + class BarcodeReader { + static BarcodeReaderException(): any; + static initServiceConnection(): Promise; + static name: string; + static length: number; + static version: string; + // appendTplStringToRuntimeSettings(b, d): + /** + * Read barcode from the source image. + * @method BarcodeReader#decode + * @param {string} source specifies the image to read on + * @return {Promise} + * @example + ```javascript + // dwtUrl: HTML5 Edition only + reader.decode('dwt://dwt_trial_13000404/img?id=306159652&index=0&t=1502184632022').then( + results=>{ + for(var i = 0; i < results.length; ++i){ + console.log(results[i].BarcodeText); + // Confidence >= 30 is reliable + console.log(results[i].LocalizationResult.ExtendedResultArray[0].Confidence); + } + }); + // dcsUrl + reader.decode('dcs://dcs_trial_6110531/img?id=306159652&index=0&t=1502184632022').then( + function(results){ + // ie6-7 does not support console.log + var messageArr = []; + for(var i = 0; i < results.length; ++i){ + messageArr.push(results[i].BarcodeText); + // Confidence >= 30 is reliable + messageArr.push(results[i].LocalizationResult.ExtendedResultArray[0].Confidence); + } + alert(messageArr.join('')); + })['catch'](function(ex){ + // ie6-9 does not support '.catch(function(ex){...})' + if(ex){alert(ex.message||ex);} + }); + ``` + */ + decode(source: string): Promise; + + /** + * Read barcode from base64 string + */ + decodeBase64String(base64String: string): Promise; + getAllLocalizationResults(): any; + getAllParameterTemplateNames(): any; + getRuntimeSettings(): RunTimeSetting; + initRuntimeSettingsWithString(): any; + outputSettingsToString(): any; + resetRuntimeSettings(): void; + updateRuntimeSettings(setting: RunTimeSetting): void; + /** + * Constructs a new barcode reader + */ + constructor(dbrKey?: string); + } +} diff --git a/types/dwt/v12/index.d.ts b/types/dwt/dwt.d.ts similarity index 77% rename from types/dwt/v12/index.d.ts rename to types/dwt/dwt.d.ts index cc0d1f8079..28f7bf567e 100644 --- a/types/dwt/v12/index.d.ts +++ b/types/dwt/dwt.d.ts @@ -1,64 +1,2397 @@ -// Type definitions for dwt 12.3 -// Project: http://www.dynamsoft.com/Products/WebTWAIN_Overview.aspx -// Definitions by: Xiao Ling -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// properties (get/set) / sync functions +interface WebTwain { + Addon: WebTwainAddon; -/*! -* Dynamsoft WebTwain JavaScript Intellisense -* Product: Dynamsoft Web Twain -* Web Site: http://www.dynamsoft.com -* -* Copyright 2017, Dynamsoft Corporation -* Author: Dynamsoft Support Team -* Version: 12.3 -*/ + /** + * Returns whether the instance of a DWT is initialized + * @type {boolean} + */ + bReady: boolean; -/** - * @namespace Dynamsoft - */ -declare namespace Dynamsoft { - namespace WebTwainEnv { - function GetWebTwain (cid: string): WebTwain; - function RegisterEvent(event: string, fn: () => void): void; - } -} - -/** ICAP_PIXELTYPE values (PT_ means Pixel Type) */ -declare enum EnumDWT_PixelType { - TWPT_BW = 0, - TWPT_GRAY = 1, - TWPT_RGB = 2, - TWPT_PALLETE = 3, - TWPT_CMY = 4, - TWPT_CMYK = 5, - TWPT_YUV = 6, - TWPT_YUVK = 7, - TWPT_CIEXYZ = 8, - TWPT_LAB = 9, - TWPT_SRGB = 10, - TWPT_SCRGB = 11, - TWPT_INFRARED = 16 + /** + * Returns the runtime id of the dwt object + * @type {string} + */ + readonly clientId: string; + + /** + * Returns the runtime class for the dwt container DIV + * @type {string} + */ + containerClass: string; + + /*ignored + httpUrl + objectName + + ...other internal ones + */ + + /* + * Properties + */ + + /** + * Returns or sets whether multi-page selection is supported. + * @type {boolean} + */ + AllowMultiSelect: boolean; + + /** + * [Deprecated.] Returns or sets whether allowing the plugin to send authentication request. The default value of this property is TRUE. + * @type {boolean} + */ + AllowPluginAuthentication: boolean; + + /** + * [Deprecated.] Returns or sets whether the async mode is activated. With this mode, Dynamic Web TWAIN is able to upload/download files via HTTP/FTP asynchronously. The default value is false. + * @type {boolean} + */ + AsyncMode: boolean; + + /** + * Returns or sets the background color of the main control. It is a value specifying the 24-bit RGB value. + * @type {number} + */ + BackgroundColor: number; + + /** + * Returns or sets the fill color of the selected area of an image when it is cut, erased or rotated. It is a value specifying the 24-bit RGB value. + * @type {number} + */ + BackgroundFillColor: number; + + /** + * Returns or sets the pixel bit depths for the current value of PixelType property. This is a runtime property. + * @type {number} + */ + BitDepth: number; + + /** + * Returns the current deviation of the pixels in the image. + * @type {number} + */ + readonly BlankImageCurrentStdDev: number; + + /** + * Returns or sets the standard deviation of the pixels in the image. + * @type {number} + */ + BlankImageMaxStdDev: number; + + /** + * Returns or sets the dividing line between black and white. The default value is 128. + * @type {number} + */ + BlankImageThreshold: number; + + /** + * [Deprecated.] Returns or sets the border style. + * @type {EnumDWT_BorderStyle} + */ + BorderStyle: EnumDWT_BorderStyle; + + /** + * Returns or sets the brightness values available within the Source. This is a runtime property. + * @type {number} + */ + Brightness: number; + + /** + * [Deprecated.] Sets or returns whether brokerprocess is enabled for scanning. + * @type {number} + */ + BrokerProcessType: number; + + /** + * Sets or returns how much physical memory is allowed for storing images currently loaded in Dynamic Web TWAIN. Once the limit is reached, images will be cached on the hard disk. + * @type {number} + */ + BufferMemoryLimit: number; + + /** + * Sets or returns the index (0-based) of a list to indicate the Current Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. + * @type {number} + */ + CapCurrentIndex: number; + + /** + * Sets or returns the current value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {number} + */ + CapCurrentValue: number; + + /** + * Returns the index (0-based) of a list to indicate the Default Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime, read-only property. + * @type {number} + */ + readonly CapDefaultIndex: number; + + /** + * Returns the default value in a range when the value of the CapType property is TWON_RANGE. This is a runtime, read-only property. + * @type {number} + */ + CapDefaultValue: number; + + /** + * Retruns the description for a capability + * @type {string} + */ + CapDescription: string; + + /** + * Sets or returns the maximum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {number} + */ + CapMaxValue: number; + + /** + * Sets or returns the minimum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {number} + */ + CapMinValue: number; + + /** + * [Deprecated.] Sets or returns how many items are in the list when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. For String data type, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. + * @type {number} + */ + CapNumItems: number; + + /** + * Sets or returns the step size in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {number} + */ + CapStepSize: number; + + /** + * Sets or returns the type of capability container used to exchange capability information between application and source. This is a runtime property. + * @type {EnumDWT_CapType} + */ + CapType: EnumDWT_CapType; + + /** + * Returns or sets the value of the capability specified by Capability property when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. + * @type {number} + */ + CapValue: number; + + /** + * Sets or returns the string value for a capability when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. + * @type {string} + */ + CapValueString: string; + + /** + * Sets or returns the value type for reading the value of a capability. This is a runtime property. + * @type {number} + */ + CapValueType: number; + + /** + * Specifies the capabiltiy to be negotiated. This is a runtime property. + * @type {EnumDWT_Cap} + */ + Capability: EnumDWT_Cap; + + /** + * Returns or sets the contrast values available within the Source. This is a runtime property. + * @type {number} + */ + Contrast: number; + + /** + * Returns or sets current index of image in buffer. This is a runtime property. + * @type {number} + */ + CurrentImageIndexInBuffer: number; + + /** + * Returns the device name of current source. This is a runtime, read-only property. + * @type {string} + */ + readonly CurrentSourceName: string; + + /** + * Returns the value indicating the data source status. This is a runtime, read-only property. + * @type {number} + */ + readonly DataSourceStatus: number; + + /** + * Returns the device name of default source. This is a runtime, read-only property. + * @type {string} + */ + readonly DefaultSourceName: string; + + /** + * Returns whether the source supports duplex. If so, it further returns the level of duplex the Source supports (one pass or two pass duplex). This is a runtime, read-only property. + * @type {EnumDWT_DUPLEX} + */ + readonly Duplex: EnumDWT_DUPLEX; + + /** + * [Deprecated.] Returns or sets whether the user can zoom image using hot key. + * @type {boolean} + */ + EnableInteractiveZoom: boolean; + + /** + * Returns the error code. This is a runtime, read-only property. + * @type {number} + */ + readonly ErrorCode: number; + + /** + * Returns the error string. This is a runtime, read-only property. + * @type {string} + */ + readonly ErrorString: string; + + /** + * Returns or sets the password used to log into the FTP server. + * @type {string} + */ + FTPPassword: string; + + /** + * Returns or sets the port number of the FTP server. + * @type {number} + */ + FTPPort: number; + + /** + * Returns or sets the user name used to log into the FTP server. + * @type {string} + */ + FTPUserName: string; + + /** + * Returns or sets whether to resize the image to fit the image to the width or height of the window. To use the property, the view mode should be set to -1 by -1. You can use SetViewMode method to set the view mode. + * @type {EnumDWT_FitWindowType} + */ + FitWindowType: EnumDWT_FitWindowType; + + /** + * Returns the response string from the HTTP server if an error occurs for HTTPUploadThroughPost() method. This is a runtime, read-only property. + * @type {string} + */ + readonly HTTPPostResponseString: string; + + /** + * Returns whether a HTTP request has credentials + * @type {boolean} + */ + HTTPRequestswithCredentials: boolean; + + /** + * Returns or sets the height of the dwt viewer object + * @type {string|number} + */ + Height: string | number; + + /** + * Returns how many images are in buffer. This is a runtime, read-only property. + * @type {number} + */ + readonly HowManyImagesInBuffer: number; + + /** + * Specifies the content type of a http upload. + * @type {string} + */ + HttpContentTypeFieldValue: string; + + /** + * Specifies the field name of uploaded image through POST. + * @type {string} + */ + HttpFieldNameOfUploadedImage: string; + + /** + * [Deprecated.] Sets or returns the password used to log into the HTTP server. + * @type {string} + */ + HTTPPassword: string; + + /** + * Returns or sets the port number of the HTTP server. + * @type {number|string} + */ + HTTPPort: number | string; + + /** + * [Deprecated.] Returns or sets the user name used to log into the HTTP server. + * @type {string} + */ + HTTPUserName: string; + + /** + * Returns or sets whether the feature of disk caching is enabled. + * @type {boolean} + */ + IfAllowLocalCache: boolean; + + /** + * Returns or sets whether insert or append new scanned images. + * @type {boolean} + */ + IfAppendImage: boolean; + + /** + * Returns or sets whether the Source's Auto-brightness function is enabled. This is a runtime property. + * @type {boolean} + */ + IfAutoBright: boolean; + + /** + * Returns or sets whether the data source (scanner) will discard blank images during scanning. The property works only if the device and its driver support discarding blank pages. You can find whether your device supports this capbility from its user manual. Or, you can use the built-in methods of Dynamic Web TWAIN to detect blank images: IsBlankImage, IsBlankImageEx. + * @type {boolean} + */ + IfAutoDiscardBlankpages: boolean; + + /** + * Returns or sets whether the Source enable automatic document feeding process. This is a runtime property. + * @type {boolean} + */ + IfAutoFeed: boolean; + + /** + * Returns or sets whether the Source enables the automatic document scanning process. This is a runtime property. + * @type {boolean} + */ + IfAutoScan: boolean; + + /** + * Specifies whether or not to automatically scroll to the last image or stay on the current image when loading or acquiring images + * @type {boolean} + */ + IfAutoScroll: boolean; + + /** + * Turns automatic border detection on and off. The property works only if the device and its driver support detecting the border automatically. You can find whether your device supports this capbility from its user manual. + * @type {boolean} + */ + IfAutomaticBorderDetection: boolean; + + /** + * Turns automatic skew correction on and off. + * @type {boolean} + */ + IfAutomaticDeskew: boolean; + + /** + * Returns or sets whether close the Data Source User Interface after acquire all images. Default value of this property is FALSE. + * @type {boolean} + */ + IfDisableSourceAfterAcquire: boolean; + + /** + * Returns or sets whether the Source supports duplex. If TRUE, the scanner scans both sides of a paper; otherwise, the scanner will scan only one side of the image. This is a runtime property. + * @type {boolean} + */ + IfDuplexEnabled: boolean; + + /** + * Returns or sets whether the Automatic Document Feeder (ADF) is enabled. This is a runtime property. + * @type {boolean} + */ + IfFeederEnabled: boolean; + + /** + * Returns whether or not there are documents loaded in the Source's feeder when IfFeederEnabled and IfPaperDetectable are TRUE. This is a runtime, read-only property. + * @type {boolean} + */ + readonly IfFeederLoaded: boolean; + + /** + * Returns or sets whether to resize the image to fit the size of window when the view mode is set to -1 by -1. You can use SetViewMode method to set the view mode. + * @type {boolean} + */ + IfFitWindow: boolean; + + /** + * [Deprecated.] Returns or sets whether the UI (User Interface) of Source runs in modal state. Default value of this property is TRUE. + * @type {boolean} + */ + IfModalUI: boolean; + + /** + * Sets or returns whether Dynamic Web TWAIN uses Graphics Device Interface (GDI) when decoding images. + * @type {boolean} + */ + IfOpenImageWithGDIPlus: boolean; + + /** + * Returns or sets whether FTP passive mode is enabled. + * @type {boolean} + */ + IfPASVMode: boolean; + + /** + * Returns the value whether the Source has a paper sensor that can detect documents on the ADF or Flatbed. This is a runtime, read-only property. + * @type {boolean} + */ + readonly IfPaperDetectable: boolean; + + /** + * Returns or sets whether SSL is used when uploading or downloading images. + * @type {boolean} + */ + IfSSL: boolean; + + /** + * [Deprecated.] Returns or sets whether communicate with device in a separate thread. Default value of this property is FALSE. + * @type {boolean} + */ + IfScanInNewThread: boolean; + + /** + * Sets or returns whether to show the cancel dialog when uploading images to server. + * @type {boolean} + */ + IfShowCancelDialogWhenImageTransfer: boolean; + + /** + * Returns or sets whether to show the file dialog box when saving scanned images or loading images from local folder. + * @type {boolean} + */ + IfShowFileDialog: boolean; + + /** + * Returns or sets whether the Source displays a progress indicator during acquisition and transfer, regardless of whether the Source's user interface is active. This is a runtime property. + * @type {boolean} + */ + IfShowIndicator: boolean; + + /** + * [Deprecated.] Returns or sets whether the driver of the printer displays the User Interface. + * @type {boolean} + */ + IfShowPrintUI: boolean; + + /** + * Returns or sets whether the progress bar will be displayed during the transaction. This is a runtime property. + * @type {boolean} + */ + IfShowProgressBar: boolean; + + /** + * Returns or sets whether the Source displays the User Interface. + * @type {boolean} + */ + IfShowUI: boolean; + + /** + * Returns or sets whether to throw exceptions + * @type {boolean} + */ + IfThrowException: boolean; + + /** + * Return or sets whether the Source allows to save many images in one TIFF file. The default value is FALSE. + * @type {boolean} + */ + IfTiffMultiPage: boolean; + + /** + * Returns whether the Source supports acquisition with the UI (User Interface) disabled. If FALSE, indicates that this Source can only support acquisition with the UI enabled. This is a runtime, read-only property. + * @type {boolean} + */ + readonly IfUIControllable: boolean; + + /** + * Sets or returns whether Dynamic Web TWAIN uses the new TWAIN Data Source Manager (TWAINDSM.dll) when acquiring images from TWAIN devices. + * @type {boolean} + */ + IfUseTwainDSM: boolean; + + /** + * [Deprecated.] The number of bits in each image pixel (or bit depth). This is a runtime, read-only property. + * @type {number} + */ + ImageBitsPerPixel: number; + + /** + * Returns or sets whether a TWAIN driver or Native Scan of Mac OS X is used for document scanning. This property works for Mac edition only. + * @type {number} + */ + ImageCaptureDriverType: number; + + /** + * [Deprecated.] Returns or sets whether the image enumerator is enabled in Image Editor. + * @type {boolean} + */ + ImageEditorIfEnableEnumerator: boolean; + + /** + * [Deprecated.] Returns or sets whether the Image Editor is a modal window. + * @type {boolean} + */ + ImageEditorIfModal: boolean; + + /** + * [Deprecated.] Returns or sets whether the Image Editor is read-only. + * @type {boolean} + */ + ImageEditorIfReadonly: boolean; + + /** + * [Deprecated.] Returns or sets the title of Image Editor window. + * @type {string} + */ + ImageEditorWindowTitle: string; + + /** + * Returns the document number of the current image. This is a runtime, read-only property. + * @type {number} + */ + readonly ImageLayoutDocumentNumber: number; + + /** + * Returns the value of the bottom-most edge of the current image frame (in Unit). This is a read-only runtime property. + * @type {number} + */ + readonly ImageLayoutFrameBottom: number; + + /** + * Returns the value of the left-most edge of the current image frame (in Unit). This is a runtime, read-only property. + * @type {number} + */ + readonly ImageLayoutFrameLeft: number; + + /** + * Returns the frame number of the current image. This is a runtime, read-only property. + * @type {number} + */ + readonly ImageLayoutFrameNumber: number; + + /** + * Returns the value of the right-most edge of the current image frame (in Unit). This is a runtime, read-only property. + * @type {number} + */ + readonly ImageLayoutFrameRight: number; + + /** + * Returns the value of the top-most edge of the current image frame (in Unit). This is a runtime, read-only property. + * @type {number} + */ + readonly ImageLayoutFrameTop: number; + + /** + * Returns the page number of the current image. This is a runtime, read-only property. + * @type {Long} + */ + readonly ImageLayoutPageNumber: number; + + /** + * [Deprecated.] Returns how tall/long, in pixels, the image is. This is a runtime, read-only property. + * @type {number} + */ + ImageLength: number; + + /** + * Returns or sets the margin between images when multiple images are displayed in Dynamic Web TWAIN. + * @type {number} + */ + ImageMargin: number; + + /** + * Returns the pixel type of the current image. This is a runtime, read-only property. Please note the property is only valid in OnPreTransfer and OnPostTransfer event. + * @type {EnumDWT_PixelType} + */ + readonly ImagePixelType: EnumDWT_PixelType; + + /** + * [Deprecated.] Returns how width, in pixels, the image is. This is a runtime, read-only property. + * @type {number} + */ + ImageWidth: number; + + /** + * [Deprecated.] Returns the X resolution of the current image. X resolution is the number of pixels per Unit in the horizontal direction. This is a runtime, read-only property. + * @type {number} + */ + ImageXResolution: number; + + /** + * [Deprecated.] Returns the Y resolution of the current image. Y resolution is the number of pixels per Unit in the vertical direction. This is a runtime, read-only property. + * @type {number} + */ + ImageYResolution: number; + + /** + * Returns or sets the quality of JPEG files and PDF files using JPEG compression. + * @type {number} + */ + JPEGQuality: number; + + /** + * Returns or sets the log level for debugging. + * @type {number} + */ + LogLevel: number; + + /** + * Return the magnetic data if the scanner support magnetic data recognition. + * @type {string} + */ + readonly MagData: string; + + /** + * Return the magnetic type if the scanner support magnetic data recognition. + * @type {number} + */ + readonly MagType: number; + + /** + * Sets or returns the manufacture string for the application identity. + * @type {string} + */ + Manufacturer: string; + + /** + * Returns or sets the maximum number of images can be held in buffer. + * @type {number} + */ + MaxImagesInBuffer: number; + + /** + * [Deprecated.] Returns or sets how many threads can be used when you upload files through POST. + * @type {number} + */ + MaxInternetTransferThreads: number; + + /** + * Sets or returns the maximum allowed size when Dynamic Web TWAIN uploads a document. + * @type {number} + */ + MaxUploadImageSize: number; + + /** + * Returns or sets the shape of the mouse. + * @type {boolean} + */ + MouseShape: boolean; + + /** + * Returns the X co-ordinate of the mouse. This is a runtime property. + * @type {number} + */ + readonly MouseX: number; + + /** + * Returns the Y co-ordinate of the mouse. This is a runtime property. + * @type {number} + */ + readonly MouseY: number; + + /** + * Returns or sets the name of the person who creates the PDF document. + * @type {string} + */ + PDFAuthor: string; + + /** + * Returns or sets the compression type of PDF files. This is a runtime property. + * @type {EnumDWT_PDFCompressionType} + */ + PDFCompressionType: EnumDWT_PDFCompressionType; + + /** + * Returns or sets the date when the PDF document is created. + * @type {string} + */ + PDFCreationDate: string; + + /** + * Returns or sets the name of the application that created the original document, if the PDF document is converted from another form. + * @type {string} + */ + PDFCreator: string; + + /** + * Returns or sets the keywords associated with the PDF document. + * @type {string} + */ + PDFKeywords: string; + + /** + * Returns or sets the date when the PDF document is last modified. + * @type {string} + */ + PDFModifiedDate: string; + + /** + * Returns or sets the name of the application that converted the PDF document from its native. + * @type {string} + */ + PDFProducer: string; + + /** + * Returns or sets the subject of the PDF document. + * @type {string} + */ + PDFSubject: string; + + /** + * Returns or sets the title of the PDF document. + * @type {string} + */ + PDFTitle: string; + + /** + * Returns or sets the value of the PDF version. + * @type {string} + */ + PDFVersion: string; + + /** + * Returns or sets the page size(s) the Source can/should use to acquire image data. This is a runtime property. + * @type {EnumDWT_CapSupportedSizes} + */ + PageSize: EnumDWT_CapSupportedSizes; + + /** + * Returns the number of transfers the Source is ready to supply, upon demand. This is a runtime, read-only property. + * @type {number} + */ + readonly PendingXfers: number; + + /** + * Returns or sets the pixel flavor for acquired images. This is a runtime property. + * @type {number} + */ + PixelFlavor: number; + + /** + * Returns or sets the pixel type of current data source. This is a runtime property. Using this property after calling OpenSource() method and before calling AcquireImage(). + * @type {EnumDWT_PixelType} + */ + PixelType: EnumDWT_PixelType; + + /** + * Sets or returns the product family string for the application identity. + * @type {string} + */ + ProductFamily: string; + + /** + * Sets the product key. A product key is generated in Licensing Tool which is intalled with Dynamic Web TWAIN. Each product key corresponds with a license. + * @type {string} + */ + ProductKey: string; + + /** + * Sets or returns the product name string for the application identity. + * @type {string} + */ + ProductName: string; + + /** + * [Deprecated.] Returns or sets the name of the proxy server. + * @type {string} + */ + ProxyServer: string; + + /** + * Returns or sets the current resolution for acquired images. This is a runtime property. + * @type {number} + */ + Resolution: number; + + /** + * Returns or sets how many scanned images are selected. + * @type {number} + */ + SelectedImagesCount: number; + + /** + * Returns or sets the border color of the selected image. It is a value specifying the 24-bit RGB value. + * @type {number} + */ + SelectionImageBorderColor: number; + + /** + * Specifies a fixed aspect ratio to be used for selecting an area. + * @type {number} + */ + SelectionRectAspectRatio: number; + + /** + * Specifies whether to show the page number + * @type {boolean} + */ + ShowPageNumber: boolean; + + /** + * Returns how many sources are installed in the system. This is a runtime, read-only property. + * @type {number} + */ + readonly SourceCount: number; + + /** + * Returns or sets the compression type of TIFF files. This is a runtime property. + * @type {EnumDWT_TIFFCompressionType} + */ + TIFFCompressionType: EnumDWT_TIFFCompressionType; + + /** + * Sets or returns the transfer mode. + * @type {EnumDWT_TransferMode} + */ + TransferMode: EnumDWT_TransferMode; + + /** + * Returns or sets the unit of measure. This is a runtime property. + * @type {EnumDWT_UnitType} + */ + Unit: EnumDWT_UnitType; + + /** + * Specifies whether to show the vertical scroll bar + * @type {boolean} + */ + VScrollBar: boolean; + + /** + * Sets or returns the version info string for the application identity. + * @type {string} + */ + readonly VersionInfo: string; + + /** + * Returns or sets the width of the dwt object viewer + * @type {string|number} + */ + Width: string | number; + + /** + * Returns and sets the number of images you are willing to transfer per session. This is a runtime property. + * @type {number} + */ + XferCount: number; + + /** + * Returns or sets zoom factor for the image, only valid When the view mode is set to -1 by -1. + * @type {number} + */ + Zoom: number; + + /* ignored + style + _AutoCropMethod + */ + + /* + *Methods + */ + + /** + * Displays the source's built-in interface to acquire image. + * @method WebTwain#AcquireImage + * @param {object} optionalDeviceConfig a JS object used to set up the device for image acquisition. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + AcquireImage(optionalDeviceConfig?: object, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Add text on an image. + * @method WebTwain#AddText + * @param {number} sImageIndex the index of the image that you want to add text to. + * @param {number} x the x coordinate for the text. + * @param {number} y the y coordinate for the text. + * @param {string} text the content of the text that you want to add. + * @param {number} txtColor the color for the text. + * @param {number} backgroundColor the background color. + * @param {number} backgroundRoundRadius ranging from 0 to 0.5. Please NOTE that MAC version does not support this parameter. + * @param {number} backgroundOpacity specifies the opacity of the background of the added text, it ranges from 0 to 1.0. Please NOTE that Mac version only supports value 0 and 1 + * @return {boolean} + */ + AddText(sImageIndex: number, x: number, y: number, text: string, txtColor: number, backgroundColor: number, backgroundRoundRadius: number, backgroundOpacity: number): boolean; + + /** + * Cancels all pending transfers. + * @method WebTwain#CancelAllPendingTransfers + * @return {boolean} + */ + CancelAllPendingTransfers(): boolean; + + /** + * Gets information of the capability specified by the Capability property. + * @method WebTwain#CapGet + * @return {boolean} + */ + CapGet(): boolean; + + /** + * Returns the Source's current Value for the specified capability. + * @method WebTwain#CapGetCurrent + * @return {boolean} + */ + CapGetCurrent(): boolean; + + /** + * Returns the Source's Default Value for the specified capability. This is the Source's preferred default value. + * @method WebTwain#CapGetDefault + * @return {boolean} + */ + CapGetDefault(): boolean; + + /** + * Returns the value of the bottom-most edge of the specified frame. + * @method WebTwain#CapGetFrameBottom + * @param {number} index specifies the value of which frame to get. The index is 0-based. + * @return {number} + */ + CapGetFrameBottom(index: number): number; + + /** + * Returns the value (in Unit) of the left-most edge of the specified frame. + * @method WebTwain#CapGetFrameLeft + * @param {number} index specifies the value of which frame to get. The index is 0-based. + * @return {number} + */ + CapGetFrameLeft(index: number): number; + + /** + * Returns the value (in Unit) of the left-most edge of the specified frame. + * @method WebTwain#CapGetFrameRight + * @param {number} index specifies the value of which frame to get. The index is 0-based. + * @return {number} + */ + CapGetFrameRight(index: number): number; + + /** + * Returns the value (in Unit) of the top-most edge of the specified frame. + * @method WebTwain#CapGetFrameTop + * @param {number} index specifies the value of which frame to get. The index is 0-based. + * @return {number} + */ + CapGetFrameTop(index: number): number; + + /* ignored + * CapGetHelp + * CapGetLabel + * CapGetLabels + */ + + /** + * Queries whether the Source supports a particular operation on the capability. + * @method WebTwain#CapIfSupported + * @param {EnumDWT_MessageType} messageType specifies the type of capability operation. + * @return {boolean} + */ + CapIfSupported(messageType: EnumDWT_MessageType): boolean; + + /** + * Changes the Current Value of the capability specified by Capability property back to its power-on value. + * @method WebTwain#CapReset + * @return {boolean} + */ + CapReset(): boolean; + + /** + * Sets the current capability using the container type specified by CapType property. The current capability is specified by Capability property. + * @method WebTwain#CapSet + * @return {boolean} + */ + CapSet(): boolean; + + /** + * Sets the values of the specified frame. + * @method WebTwain#CapSetFrame + * @param {number} index specifies the values of which frame to set. The index is 0-based. + * @param {number} left the value (in Unit) of the left-most edge of the specified frame. + * @param {number} top the value (in Unit) of the top-most edge of the specified frame. + * @param {number} right the value (in Unit) of the right-most edge of the specified frame. + * @param {number} bottom the value (in Unit) of the bottom-most edge of the specified frame. + * @return {boolean} + */ + CapSetFrame(index: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Changes the bitdepth of a specified image. + * @method WebTwain#ChangeBitDepth + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} sBitDepth specifies the target bit depth. + * @param {boolean} bHighQuality specifies whether or not to keep high quality while changing the bit depth. When it's true, it takes more time. + * @return {boolean} + */ + ChangeBitDepth(sImageIndex: number, sBitDepth: number, bHighQuality: boolean): boolean; + + /** + * Changes width and height of the image of a specified index in the buffer. Please note the file size of the image will be changed proportionately. + * @method WebTwain#ChangeImageSize + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} iNewWidth specifies the pixel width of the new image. + * @param {number} iNewHeight specifies the pixel height of the new image. + * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. + * @return {boolean} + */ + ChangeImageSize(sImageIndex: number, iNewWidth: number, iNewHeight: number, newVal: EnumDWT_InterpolationMethod): boolean; + + /** + * Clears all the web forms which are used for image uploading. + * @method WebTwain#ClearAllHTTPFormField + * @return {boolean} + */ + ClearAllHTTPFormField(): boolean; + + /** + * Clears the content of all custom tiff tags. + * @method WebTwain#ClearTiffCustomTag + * @return {void} + */ + ClearTiffCustomTag(): void; + + /** + * Closes Data Source. + * @method WebTwain#CloseSource + * @return {boolean} + */ + CloseSource(): boolean; + + /** + * Closes and unloads Data Source Manager. + * @method WebTwain#CloseSourceManager + * @return {boolean} + */ + CloseSourceManager(): boolean; + + /** + * Closes the current process used to scan + * @method WebTwain#CloseWorkingProcess + * @return {boolean} + */ + CloseWorkingProcess(): boolean; + + /** + * Converts the images specified by the indices to base64 synchronously. + * @method WebTwain#ConvertToBase64 + * @param {Array} indices indices specifies which images are to be converted to base64. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. + * @return {Base64Result} + + ConvertToBase64(indices: number[], enumImageType: EnumDWT_ImageType): Base64Result; + */ + + /** + * Converts the images specified by the indices to base64 asynchronously. + * @method WebTwain#ConvertToBase64 + * @param {Array} indices indices specifies which images are to be converted to base64. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + ConvertToBase64(indices: number[], enumImageType: EnumDWT_ImageType, asyncSuccessFunc: (result: Base64Result) => void, asyncFailureFunc: (errorCode: number, errorString: string) => void): boolean; + + /** + * Converts the images specified by the indices to blob synchronously. + * @method WebTwain#ConvertToBlob + * @param {Array} indices indices specifies which images are to be converted to base64. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. + * @return {Blob} + */ + ConvertToBlob(indices: number[], enumImageType: EnumDWT_ImageType): Blob; + + /** + * Converts the images specified by the indices to blob asynchronously. + * @method WebTwain#ConvertToBlob + * @param {Array} indices indices specifies which images are to be converted to base64. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + ConvertToBlob(indices: number[], enumImageType: EnumDWT_ImageType, asyncSuccessFunc: (result: any) => void, asyncFailureFunc: (errorCode: number, errorString: string) => void): boolean; + + /** + * Changes a specified image to gray scale. + * @method WebTwain#ConvertToGrayScale + * @param {number} sIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + ConvertToGrayScale(sIndex: number): boolean; + + /** + * Copies the image of a specified index in buffer to clipboard in DIB format. + * @method WebTwain#CopyToClipboard + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + CopyToClipboard(sImageIndex: number): boolean; + + /** + * Create the font for adding text using the method AddText. + * @method WebTwain#CreateTextFont + * @param {number} height Specifies the desired height (in logical units) of the font.The absolute value of nHeight must not exceed 16,384 device units after it is converted.For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size or the smallest font if all the fonts exceed the requested size. + * @param {number} width Specifies the average width (in logical units) of characters in the font. If Width is 0, the aspect ratio of the device will be matched against the digitization aspect ratio of the available fonts to find the closest match, which is determined by the absolute value of the difference. + * @param {number} escapement Specifies the angle (in 0.1-degree units) between the escapement vector and the x-axis of the display surface. The escapement vector is the line through the origins of the first and last characters on a line. The angle is measured counterclockwise from the x-axis. + * @param {number} orientation Specifies the angle (in 0.1-degree units) between the baseline of a character and the x-axis.The angle is measured counterclockwise from the x-axis for coordinate systems in which the y-direction is down and clockwise from the x-axis for coordinate systems in which the y-direction is up. + * @param {number} weight Specifies the font weight (in inked pixels per 1000). The described valuesare approximate; the actual appearance depends on the typeface. Some fonts haveonly FW_NORMAL, FW_REGULAR, and FW_BOLD weights. If FW_DONTCARE is specified, a default weight is used. + * @param {number} italic Specifies an italic font if set to TRUE. + * @param {number} underline Specifies an underlined font if set to TRUE. + * @param {number} strikeOut A strikeout font if set to TRUE. + * @param {number} charSet Specifies the font's character set. The OEM character set is system-dependent. Fonts with other character sets may exist in the system. An application that uses a font with an unknown character set must not attempt to translate or interpret strings that are to be rendered with that font. + * @param {number} outputPrecision Specifies the desired output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, and pitch. + * @param {number} clipPrecision Specifies the desired clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. + * @param {number} quality Specifies the font's output quality, which defines how carefully the GDI must attempt to match the logical-font attributes to those of an actual physical font. + * @param {number} pitchAndFamily The pitch and family of the font. + * @param {string} faceName the typeface name, the length of this string must not exceed 32 characters, including the terminating null character. + * @return {boolean} + */ + CreateTextFont(height: number, width: number, escapement: number, orientation: number, weight: number, italic: number, underline: number, strikeOut: number, charSet: number, outputPrecision: number, clipPrecision: number, quality: number, pitchAndFamily: number, faceName: string): boolean; + + /** + * Crops the image of a specified index in buffer. + * @method WebTwain#Crop + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {boolean} + */ + Crop(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Crops the image of a specified index in buffer to clipboard in DIB format. + * @method WebTwain#CropToClipboard + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {boolean} + */ + CropToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Cuts the image data in the specified area to the system clipboard in DIB format. + * @method WebTwain#CutFrameToClipboard + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {boolean} + */ + CutFrameToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Cuts the image of a specified index in buffer to clipboard in DIB format. + * @method WebTwain#CutToClipboard + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + CutToClipboard(sImageIndex: number): boolean; + + /** + * Disable the source. If the source's user interface is displayed when the source is enabled, it will be closed. + * @method WebTwain#DisableSource + * @return {boolean} + */ + DisableSource(): boolean; + + /** + * Enables the source to accept image. + * @method WebTwain#EnableSource + * @return {boolean} + */ + EnableSource(): boolean; + + /** + * Clears the specified area of a specified image, and fill the area with the fill color. + * @method WebTwain#Erase + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {boolean} + */ + Erase(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Downloads an image from the FTP server. + * @method WebTwain#FTPDownload + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPDownload(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly download a file from the FTP server to local disk without loading it into Dynamic Web TWAIN. + * @method WebTwain#FTPDownloadDirectly + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. + * @param {string} localFile specify a full path to store the file. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPDownloadDirectly(FTPServer: string, FTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Downloads an image from the FTP server. + * @method WebTwain#FTPDownloadEx + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. + * @param {EnumDWT_ImageType} lImageType simage format of the file to be downloaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPDownloadEx(FTPServer: string, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the FTP server. + * @method WebTwain#FTPUpload + * @param {string} FTPServer the name of the FTP server. + * @param {number} sImageIndex specifies the index of the image in the buffer. The index is 0-based. + * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPUpload(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly upload a specific file to the FTP server without loading it into Dynamic Web TWAIN. + * @method WebTwain#FTPUploadDirectly + * @param {string} FTPServer the name of the FTP server. + * @param {string} localFile specify the the full path of a local file. + * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPUploadDirectly(FTPServer: string, localFile: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the FTP server as a specified image format. + * @method WebTwain#FTPUploadEx + * @param {string} FTPServer the name of the FTP server. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPUploadEx(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in buffer to the FTP server as Multi-Page TIFF. + * @method WebTwain#FTPUploadAllAsMultiPageTIFF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPUploadAllAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in buffer to the FTP server as Multi-Page PDF. + * @method WebTwain#FTPUploadAllAsPDF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPUploadAllAsPDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in buffer to the FTP server as Multi-Page PDF. + * @method WebTwain#FTPUploadAsMultiPagePDF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPUploadAsMultiPagePDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in buffer to the FTP server as Multi-Page TIFF. + * @method WebTwain#FTPUploadAsMultiPageTIFF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + FTPUploadAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Sets the Source to eject the current page and advance the next page in the document feeder into the feeder acquire area when IfFeederEnabled is TRUE. + * @method WebTwain#FeedPage + * @return {boolean} + */ + FeedPage(): boolean; + + /** + * Check whether a certain file exists on the local disk. + * @method WebTwain#FileExists + * @param {string} localFile specifies the absolute path of the local file. + * @return {boolean} + */ + FileExists(localFile: string): boolean; + + /** + * Flips the image of a specified index in buffer. + * @method WebTwain#Flip + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + Flip(sImageIndex: number): boolean; + + /** + * Get the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. + * @method WebTwain#GetCapItems + * @param {number} index Index is 0-based. It is the index of the cap item. + * @return {number} + */ + GetCapItems(index: number): number; + + /** + * Returns the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. + * @method WebTwain#GetCapItemsString + * @param {number} index Index is 0-based. It is the index of the cap item. + * @return {string} + */ + GetCapItemsString(index: number): string; + + // Get custom DS data, and returned string is encoded with base64 + /** + * Gets custom DS data, the returned string is base64 encoded. + * @method WebTwain#GetCustomDSDataEx + * @return {string | boolean} + */ + GetCustomDSDataEx(): string | boolean; + + // Get custom DS data, and save the data to the specified file + /** + * Gets custom DS data and save the data in a specified file. + * @method WebTwain#GetCustomDSData + * @param {string} fileName the path of the file used for storing custom DS data. + * @return {boolean} + */ + GetCustomDSData(fileName: string): boolean; + + /** + * Retrieve the device type of the currently selected data source, it might be a scanner, a web camera, etc. + * @method WebTwain#GetDeviceType + * @return {number | boolean} + */ + GetDeviceType(): number | boolean; + + /** + * Returns the pixel bit depth of the selected image. + * @method WebTwain#GetImageBitDepth + * @param {number} sImageIndex specifies the index of image. The index is 0-based. + * @return {number} + */ + GetImageBitDepth(sImageIndex: number): number; + + /** + * Returns the height (pixels) of the selected image. This is a read-only property. + * @method WebTwain#GetImageHeight + * @param {number} sImageIndex specifies the index of image. The index is 0-based. + * @return {number} + */ + GetImageHeight(sImageIndex: number): number; + + /** + * Returns the direct URL of an image specified by index, if iWidth and iHeight are not specified, you get the original image, otherwise you get the image with specified iWidth or iHeight while keeping the same aspect ratio. The returned string is like this 'dwt://dwt_trial_13000404/img?id=306159652&index=0&t=1502184632022' + * @method WebTwain#GetImagePartURL + * @param {number} index the index of the image. + * @param {number} iWidth the width of the image, it must be 150 or bigger + * @param {number} iHeight the height of the image, it must be 150 or bigger + * @return {string} + */ + GetImagePartURL(index: number, iWidth?: number, iHeight?: number): string; + + /** + * Returns the file size of the new image resized from the image of a specified index in buffer. + * @method WebTwain#GetImageSize + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} iWidth specifies the pixel width of the new image. + * @param {number} iHeight specifies the pixel height of the new image. + * @return {number} + */ + GetImageSize(sImageIndex: number, iWidth: number, iHeight: number): number; + + /** + * Pre-calculate the file size of the local image file that is saved from an image of a specified index in buffer. + * @method WebTwain#GetImageSizeWithSpecifiedType + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {EnumDWT_ImageType} sImageType specifies the type of an image file.. + * @return {number} + */ + GetImageSizeWithSpecifiedType(sImageIndex: number, sImageType: EnumDWT_ImageType): number; + + /** + * Returns the direct URL of an image specified by index, if iWidth or iHeight is set to -1, you get the original image, otherwise you get the image with specified iWidth or iHeight while keeping the same aspect ratio. + * @method WebTwain#GetImageURL + * @param {number} index the index of the image. + * @param {number} iWidth the width of the image. + * @param {number} iHeight the height of the image. + * @return {string} + */ + GetImageURL(index: number, iWidth: number, iHeight: number): string; + + /** + * Returns the width (pixels) of the selected image. This is a read-only property. + * @method WebTwain#GetImageWidth + * @param {number} sImageIndex specifies the index of image. The index is 0-based. + * @return {number} + */ + GetImageWidth(sImageIndex: number): number; + + /** + * Return the horizontal resolution of the specified image. + * @method WebTwain#GetImageXResolution + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {number} + */ + GetImageXResolution(sImageIndex: number): number; + + /** + * Return the vertical resolution of the specified image. + * @method WebTwain#GetImageYResolution + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {number} + */ + GetImageYResolution(sImageIndex: number): number; + + /** + * Return the runtime license info. + * @method WebTwain#GetLicenseInfo + */ + GetLicenseInfo(optionalAsyncSuccessFunc?: (result: any) => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Returns the index of the selected image. + * @method WebTwain#GetSelectedImageIndex + * @param {number} sSelectedIndex specifies the index of the selected image. + * @return {number} + */ + GetSelectedImageIndex(sSelectedIndex: number): number; + + /** + * Pre-calculate the file size of the local image file that is saved from the selected images in buffer. + * @method WebTwain#GetSelectedImagesSize + * @param {EnumDWT_ImageType} iImageType specifies the type of an image file. + * @return {number} + */ + GetSelectedImagesSize(iImageType: EnumDWT_ImageType): number; + + /** + * Check the skew angle of an image by its index in buffer. + * @method WebTwain#GetSkewAngle + * @param {number} sImageIndex the index of the image in the buffer. + * @return {number} + */ + GetSkewAngle(sImageIndex: number): number; + + /** + * Check the skew angle of a rectangular part of an image by its index in buffer. + * @method WebTwain#GetSkewAngleEx + * @param {number} sImageIndex the index of the image in the buffer. + * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {number} + */ + GetSkewAngleEx(sImageIndex: number, left: number, top: number, right: number, bottom: number): number; + + /** + * Get the source name according to the source index. + * @method WebTwain#GetSourceNameItems + * @param {number} index number index. Index is 0-based and can not be greater than SourceCount property. + * @return {string} + */ + GetSourceNameItems(index: number): string; + + /*ignored + GetSourceNames + GetSourceType + GetVersionInfoAsync + */ + + /** + * Downloads an image from the HTTP server. + * @method WebTwain#HTTPDownload + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile the name of the image to be downloaded. It should be the relative path of the file on the HTTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPDownload(HTTPServer: string, HTTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly downloads a file from the HTTP server to a local disk without loading it into Dynamic Web TWAIN. + * @method WebTwain#HTTPDownloadDirectly + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile The relative path of the file on the HTTP server. + * @param {string} localFile specify the location to store the downloaded file. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPDownloadDirectly(HTTPServer: string, HTTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Downloads an image from the HTTP server. + * @method WebTwain#HTTPDownloadEx + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) + * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPDownloadEx(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /*ignored + HTTPDownloadStreamThroughPost + HTTPDownloadThroughGet + */ + + /** + * Download an image from the server using a HTTP Post call. + * @method WebTwain#HTTPDownloadThroughPost + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) + * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPDownloadThroughPost(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * Uploads just a form created by SetHTTPFormField and SetHTTPHeader + * @method WebTwain#HTTPUpload + * @param {string} url the url where the images are sent in a POST request. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUpload(url: string, asyncSuccessFunc: (httppostresponsestring: string) => void, asyncFailureFunc: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * Uploads the images specified by the indices to the HTTP server. + * @method WebTwain#HTTPUpload + * @param {string} url the url where the images are sent in a POST request. + * @param {Array} indices indices specifies which images are to be uploaded. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be uploaded. + * @param {EnumDWT_UploadDataFormat} dataFormat whether to upload the images as binary or a base64-based string. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUpload(url: string, indices: number[], enumImageType: EnumDWT_ImageType, dataFormat: EnumDWT_UploadDataFormat, asyncSuccessFunc: (httppostresponsestring: string) => void, asyncFailureFunc: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * Uploads the images specified by the indices to the HTTP server. + * @method WebTwain#HTTPUpload + * @param {string} url the url where the images are sent in a POST request. + * @param {Array} indices indices specifies which images are to be uploaded. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be uploaded. + * @param {EnumDWT_UploadDataFormat} dataFormat whether to upload the images as binary or a base64-based string. + * @param {string} fileName the file name + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUpload(url: string, indices: number[], enumImageType: EnumDWT_ImageType, dataFormat: EnumDWT_UploadDataFormat, fileName: string, asyncSuccessFunc: (httppostresponsestring: string) => void, asyncFailureFunc: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * Uploads all images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadAllThroughPostAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {boolean} + */ + HTTPUploadAllThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * Uploads all images in the buffer to the HTTP server through HTTP Post method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadAllThroughPostAsPDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {boolean} + */ + HTTPUploadAllThroughPostAsPDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadAllThroughPutAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUploadAllThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadAllThroughPutAsPDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUploadAllThroughPutAsPDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /*ignored + HTTPUploadStreamThroughPost + */ + + /** + * Uploads the image of a specified index in the buffer to the HTTP server through the HTTP POST method. + * @method WebTwain#HTTPUploadThroughPost + * @param {string} HTTPServer the name of the HTTP server. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {boolean} + */ + HTTPUploadThroughPost(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadThroughPostAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {boolean} + */ + HTTPUploadThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadThroughPostAsMultiPagePDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {boolean} + */ + HTTPUploadThroughPostAsMultiPagePDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * Directly upload a specific local file to the HTTP server through the HTTP POST method without loading it into Dynamic Web TWAIN. + * @method WebTwain#HTTPUploadThroughPostDirectly + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} localFile specifies the path of a local file . + * @param {string} ActionPage the specified page for posting files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the file to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {boolean} + */ + HTTPUploadThroughPostDirectly(HTTPServer: string, localFile: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP POST method. + * @method WebTwain#HTTPUploadThroughPostEx + * @param {string} HTTPServer the name of the HTTP server. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server.s + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadFailure. + * @return {boolean} + */ + HTTPUploadThroughPostEx(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; + + /** + * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server through the HTTP PUT method. + * @method WebTwain#HTTPUploadThroughPut + * @param {string} HTTPServer the name of the HTTP server. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} RemoteFileName the name of the image to be created on the HTTP server. It should a relative path on the web server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUploadThroughPut(HTTPServer: string, sImageIndex: number, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadThroughPutAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUploadThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadThroughPutAsMultiPagePDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUploadThroughPutAsMultiPagePDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Directly uploads a specific local file to the HTTP server through the HTTP PUT method without loading it into Dynamic Web TWAIN. + * @method WebTwain#HTTPUploadThroughPutDirectly + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} localFile specifies the path of a local file. + * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUploadThroughPutDirectly(HTTPServer: string, localFile: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP PUT method. + * @method WebTwain#HTTPUploadThroughPutEx + * @param {string} HTTPServer the name of the HTTP server. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + HTTPUploadThroughPutEx(HTTPServer: string, sImageIndex: number, RemoteFileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Detects whether an image is blank. + * @method WebTwain#IsBlankImage + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + IsBlankImage(sImageIndex: number): boolean; + + /** + * [Deprecated.] Detects whether a certain area on an image is blank. + * @method WebTwain#IsBlankImageEx + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @param {boolean} bFuzzyMatch specifies whether use fuzzy matching when detecting. + * @return {boolean} + */ + IsBlankImageEx(sImageIndex: number, left: number, top: number, right: number, bottom: number, bFuzzyMatch: boolean): boolean; + + /** + * Detects whether a specific image is blank. + * @method WebTwain#IsBlankImageExpress + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + IsBlankImageExpress(sImageIndex: number): boolean; + + /** + * Loads a DIB format image from Clipboard into the Dynamic Web TWAIN. + * @method WebTwain#LoadDibFromClipboard + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + LoadDibFromClipboard(optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads an image into the Dynamic Web TWAIN. + * @method WebTwain#LoadImage + * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + LoadImage(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads an image into the Dynamic Web TWAIN. + * @method WebTwain#LoadImageEx + * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be loaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + LoadImageEx(localFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads image from a base64 byte array with the specified file format. + * @method WebTwain#LoadImageFromBase64Binary + * @param {string} bry specifies the base64 string data. + * @param {EnumDWT_ImageType} lImageType specifies the file format. + * @return {boolean} + */ + LoadImageFromBase64Binary(bry: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Loads image from a byte array with the specified file format. + * @method WebTwain#LoadImageFromBytes + * @param {number} lBufferSize Specifies the buffer size. + * @param {Array} buffer A byte array of the image data. + * @param {EnumDWT_ImageType} lImageType Specifies the file format. + * @return {boolean} + */ + LoadImageFromBytes(lBufferSize: number, buffer: number[], lImageType: EnumDWT_ImageType): boolean; + + /** + * Mirrors the image of a specified index in buffer. + * @method WebTwain#Mirror + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + Mirror(sImageIndex: number): boolean; + + /** + * Moves a specified image. + * @method WebTwain#MoveImage + * @param {number} sSourceImageIndex Specifies the source index of image in buffer. The index is 0-based. + * @param {number} sTargetImageIndex Specifies the target index of image in buffer. The index is 0-based. + * @return {boolean} + */ + MoveImage(sSourceImageIndex: number, sTargetImageIndex: number): boolean; + + /*ignored + OnRefreshUI + */ + + /** + * Loads the specified Source into main memory and causes its initialization, + * placing Dynamic Web TWAIN into Capability Negotiation state. If no source is + * specified (no SelectSource() or SelectSourceByIndex() is called), opens the default source. + * @method WebTwain#OpenSource + * @return {boolean} + */ + OpenSource(): boolean; + + /** + * Loads and opens Data Source Manager. + * @method WebTwain#OpenSourceManager + * @return {boolean} + */ + OpenSourceManager(): boolean; + + /** + * Decorates image of a specified index in buffer with rectangles of transparent color. + * @method WebTwain#OverlayRectangle + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @param {number} color Specifies the fill color of the rectangle. The byte-ordering of the RGB value is 0xBBGGRR. BB represents blue, GG represents green, RR represents red. + * @param {number} fOpacity Specifies the opacity of the rectangle. The value represents opacity. 1.0 is 100% opaque and 0.0 is totally transparent. + * @return {boolean} + */ + OverlayRectangle(sImageIndex: number, left: number, top: number, right: number, bottom: number, color: number, fOpacity: number): boolean; + + /** + * Shows the GUI of Image Printer. + * @method WebTwain#Print + * @param {boolean} bUseSystemDefaultPrintUI specifies whether to use the system Print UI or not. + * @return {boolean} + */ + Print(bUseSystemDefaultPrintUI: boolean): boolean; + + /** + * Binds a specified function to an event, so that the function gets called whenever the event fires. + * @method WebTwain#RegisterEvent + * @param {string} name the name of the event that the function is bound to. + * @param {any} evt specifies the function to call when event fires. + * @return {boolean} + */ + RegisterEvent(name: string, evt: any): boolean; + + /** + * Removes all images in buffer. + * @method WebTwain#RemoveAllImages + * @return {boolean} + */ + RemoveAllImages(): boolean; + + /** + * Removes selected images in buffer. + * @method WebTwain#RemoveAllSelectedImages + * @return {boolean} + */ + RemoveAllSelectedImages(): boolean; + + /** + * Removes the image of a specified index in buffer. + * @method WebTwain#RemoveImage + * @param {number} sImageIndexToBeDeleted specifies the index of the image to be deleted in buffer. The index is 0-based. + * @return {boolean} + */ + RemoveImage(sImageIndexToBeDeleted: number): boolean; + + /** + * Reverts the current image layout to the Data Source's default. + * @method WebTwain#ResetImageLayout + * @return {boolean} + */ + ResetImageLayout(): boolean; + + /** + * Sets the Source to return the current page to the input side of the document feeder and + * feed the last page from the outside of the feeder back into the acquisition area if IfFeederEnabled is TRUE. + * @method WebTwain#RewindPage + * @return {boolean} + */ + RewindPage(): boolean; + + /** + * Rotates the image of a specified index in buffer by specified angle. + * @method WebTwain#Rotate + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} fAngle Specifies the rotation angle. + * @param {boolean} bKeepSize Keep size or not. + * @return {boolean} + */ + Rotate(sImageIndex: number, fAngle: number, bKeepSize: boolean): boolean; + + /** + * Rotates the image of a specified index in buffer by specified angle. + * @method WebTwain#RotateEx + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} fAngle Specifies the rotation angle. + * @param {boolean} bKeepSize Keep size or not. + * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. + * @return {boolean} + */ + RotateEx(sImageIndex: number, fAngle: number, bKeepSize: boolean, newVal: EnumDWT_InterpolationMethod): boolean; + + /** + * Rotates the image of a specified index in buffer by 90 degrees counter-clockwise. + * @method WebTwain#RotateLeft + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + RotateLeft(sImageIndex: number): boolean; + + /** + * Rotates the image of a specified index in buffer by 90 degrees clockwise. + * @method WebTwain#RotateRight + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + RotateRight(sImageIndex: number): boolean; + + /** + * Saves all images in buffer as a MultiPage TIFF file. + * @method WebTwain#SaveAllAsMultiPageTIFF + * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + SaveAllAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves all images in buffer as a Multi-Page PDF file. + * @method WebTwain#SaveAllAsPDF + * @param {string} localFile the name of the Multi-Page PDF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + SaveAllAsPDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the image of a specified index in buffer as a BMP file. + * @method WebTwain#SaveAsBMP + * @param {string} localFile the name of the BMP file to be saved. It should be an absolute path on the local disk. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + SaveAsBMP(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /*ignored + SaveAsGIF + */ + + /** + * Saves the image of a specified index in buffer as a JPEG file. + * @method WebTwain#SaveAsJPEG + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + SaveAsJPEG(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the image of a specified index in buffer as a PDF file. + * @method WebTwain#SaveAsPDF + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + SaveAsPDF(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the image of a specified index in buffer as a PNG file. + * @method WebTwain#SaveAsPNG + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + SaveAsPNG(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the image of a specified index in buffer as a TIFF file. + * @method WebTwain#SaveAsTIFF + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + SaveAsTIFF(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the selected images in buffer as a Multipage PDF file. + * @method WebTwain#SaveSelectedImagesAsMultiPagePDF + * @param {string} localFile the name of the MultiPage PDF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + SaveSelectedImagesAsMultiPagePDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the selected images in buffer as a Multipage TIFF file. + * @method WebTwain#SaveSelectedImagesAsMultiPageTIFF + * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {boolean} + */ + SaveSelectedImagesAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the selected images in buffer to base64 string. + * @method WebTwain#SaveSelectedImagesToBase64Binary + * @return {string|boolean} + */ + SaveSelectedImagesToBase64Binary(optionalAsyncSuccessFunc?: (result: string[]) => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): string | boolean; + + /** + * [Deprecated.] Saves the selected images in buffer to a byte array in the specified file format. + * @method WebTwain#SaveSelectedImagesToBytes + * @param {number} bufferSize specified the buffer size. + * @param {Array} buffer A byte array of the image data. + * @return {number} + */ + SaveSelectedImagesToBytes(bufferSize: number, buffer: number[]): number; + + /** + * Brings up the TWAIN Data Source Manager's Source Selection User Interface (UI) + * so that user can choose which Data Source to be the current Source. + * @method WebTwain#SelectSource + * @return {boolean} + */ + SelectSource(): boolean; + + /** + * Selects the index-the source in SourceNameItems property as the current source. + * @method WebTwain#SelectSourceByIndex + * @param {number} index It is the index of SourceNameItems property. + * @return {boolean} + */ + SelectSourceByIndex(index: number): boolean; + + /*ignored + SetCancel + */ + + /** + * Set the value of the specified cap item. + * @method WebTwain#SetCapItems + * @param {number} index Index is 0-based. It is the index of the cap item. + * @param {number} newVal For string type, please use CapItemsstring property. + * @return {void} + */ + SetCapItems(index: number, newVal: number): void; + + /** + * Set the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. + * @method WebTwain#SetCapItemsString + * @param {number} index Index is 0-based. It is the index of the cap item. + * @param {string} newVal The new value to be set. + * @return {void} + */ + SetCapItemsString(index: number, newVal: string): void; + + /** + * [Deprecated.] Sets current cookie into the Http Header to be used when uploading scanned images through POST. + * @method WebTwain#SetCookie + * @param {string} cookie the cookie on current page. + * @return {void} + */ + SetCookie(cookie: string): void; + + // Set custom DS data (DAT_CUSTOMDSDATA), the input string is encoded with base64 + /** + * Sets custom DS data to be used for scanning, the input string is encoded with base64. Custom DS data means a specific scanning profile. + * @method WebTwain#SetCustomDSDataEx + * @param {string} value the input string which is encoded with base64. + * @return {boolean} + */ + SetCustomDSDataEx(value: string): boolean; + + // Set custom DS data, load data from the specified file + /** + * Sets custom DS data to be used for scanning, the data is stored in a file. Custom DS data means a specific scanning profile. + * @method WebTwain#SetCustomDSData + * @param {string} fileName the absolute path of the file where the custom data source data is stored. + * @return {boolean} + */ + SetCustomDSData(fileName: string): boolean; + + /** + * Change the DPI (dots per inch) for the specified image. + * @method WebTwain#SetDPI + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} xResolution The horizontal resolution. + * @param {number} yResolution The vertical resolution. + * @param {boolean} bResampleImage Whether to resample the image. (The image size will be changed if this is set to true). + * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. + * @return {boolean} + */ + SetDPI(sImageIndex: number, xResolution: number, yResolution: number, bResampleImage: boolean, newVal: EnumDWT_InterpolationMethod): boolean; + + /** + * Sets file name and file format information used in File Transfer Mode. + * @method WebTwain#SetFileXferInfo + * @param {string} fileName the name of the file to be used in transfer. + * @param {EnumDWT_FileFormat} fileFormat an enumerated value indicates the format of the image. + * @return {boolean} + */ + SetFileXferInfo(fileName: string, fileFormat: EnumDWT_FileFormat): boolean; + + /** + * Sets a text parameter as a filed in a web form. This form is maintained by the component itself (meaning it's not on the page). All fields in this form will be passed to the server when uploading images. + * @method WebTwain#SetHTTPFormField + * @param {string} FieldName specifies the name of a text field in web form. + * @param {string} FieldValue specifies the value of a text field in web form. + * @return {boolean} + */ + SetHTTPFormField(FieldName: string, FieldValue: string): boolean; + + /** + * Sets a text parameter as a filed in a web form. This form is maintained by the component itself (meaning it's not on the page). All fields in this form will be passed to the server when uploading images. + * @method WebTwain#SetHTTPFormField + * @param {string} FieldName specifies the name of the field which could later be used to retrieve the blob + * @param {Blob} blobValue specifies the blob to be put in the form. + * @param {string} optionalFileName specifies the file name for the blob + * @return {boolean} + */ + SetHTTPFormField(FieldName: string, blobValue: Blob, optionalFileName?: string): boolean; + + /** + * Sets a header for the current HTTP Post request. + * @method WebTwain#SetHTTPHeader + * @param {string} key the key of the header. + * @param {string} value the value of the header. + * @return {boolean} + */ + SetHTTPHeader(key: string, value: string): boolean; + + /** + * Sets the left, top, right, and bottom sides of the image layout rectangle for the current Data Source. + * @method WebTwain#SetImageLayout + * @param {number} left specifies the floating point number for the left side of the image layout rectangle. + * @param {number} top specifies the floating point number for the top side of the image layout rectangle. + * @param {number} right specifies the floating point number for the right side of the image layout rectangle. + * @param {number} bottom specifies the floating point number for the bottom side of the image layout rectangle. + * @return {boolean} + */ + SetImageLayout(left: number, top: number, right: number, bottom: number): boolean; + + /** + * Change the width of an image in buffer. + * @method WebTwain#SetImageWidth + * @param {number} sImageIndex specifies which image you'd like to change. + * @param {number} iNewWidth specifies how wide you'd like to change the image. + * @return {boolean} + */ + SetImageWidth(sImageIndex: number, iNewWidth: number): boolean; + + /** + * Set the language for the authorization dialogs. + * @method WebTwain#SetLanguage + * @param {EnumDWT_Language} language specify the language + * @return {boolean} + */ + SetLanguage(language: EnumDWT_Language): boolean; + + /** + * Sets the time-out used to open a specified Data Source. + * @method WebTwain#SetOpenSourceTimeout + * @param {number} iMilliseconds specifies the number of milliseconds. + * @return {boolean} + */ + SetOpenSourceTimeout(iMilliseconds: number): boolean; + + /** + * Draws a rectangle on the viewer which represents the selected area. + * @method WebTwain#SetSelectedImageArea + * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {number} left The X axis of the left border. + * @param {number} top The Y axis of the top border. + * @param {number} right The X axis of the right border. + * @param {number} bottom The Y axis of the bottom border. + * @return {boolean} + */ + SetSelectedImageArea(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * You can use the method to select images programatically which is ususally done by mouse clicking. + * @method WebTwain#SetSelectedImageIndex + * @param {number} sSelectedIndex this is the index of an array that holds the indices of selected images. + * @param {number} newVal specifies the index of an image that you want to select. + * @return {boolean} + */ + SetSelectedImageIndex(selectedIndex: number, newVal: number): boolean; + + /** + * Sets a custom tiff tag. Currently you can set up to 32 tags. The string to be set in a tag can be encoded with base64. + * @method WebTwain#SetTiffCustomTag + * @param {number} tag specifies the tag identifier. The value should be between 600 and 700. + * @param {string} content the string to be set for this tag. The string will be written to the .tiff file when you save/upload it. If the string is base64 encoded, we'll decode it before writing it. + * @param {boolean} base64Str if you'd like to encode the string with base64, set this to true. Otherwise, the string will be plin text. + * @return {boolean} + */ + SetTiffCustomTag(tag: number, content: string, base64Str: boolean): boolean; + + /** + * Configures how segmented upload is done. + * @method WebTwain#SetUploadSegment + * @param {number} segmentUploadThreshold specifies the threshold (in MB) over which segmented upload will be invoked. + * @param {number} moduleSize specifies the size of each segment (in KB). + * @return {boolean} + */ + SetUploadSegment(segmentUploadThreshold: number, moduleSize: number): boolean; + + /** + * Sets the view mode that images are displayed in Dynamic Web TWAIN. You can use this method to display multiple images in Dynamic Web TWAIN. + * @method WebTwain#SetViewMode + * @param {number} sHorizontalImageCount specifies how many columns can be displayed in Dynamic Web TWAIN. + * @param {number} sVerticalImageCount specifies how many rows can be displayed in Dynamic Web TWAIN.. + * @return {void} + */ + SetViewMode(sHorizontalImageCount: number, sVerticalImageCount: number): void; + + /** + * Show save file dialog or show open file dialog. + * @method WebTwain#ShowFileDialog + * @param {boolean} SaveDialog True -- show save file dialog, False -- show open file dialog. + * @param {string} Filter The filter name specifies the filter pattern (for example, "*.TXT"). To specify multiple filter patterns for a single display string, use a semicolon to separate the patterns (for example, "*.TXT;*.DOC;*.BAK"). A pattern string can be a combination of valid file name characters and the asterisk (*) wildcard character. Do not include spaces in the pattern string. To retrieve a shortcut's target without filtering, use the string "All Files\0*.*\0\0", but the program will replace "\0" with "|" automatically. + * @param {number} FilterIndex The index of the currently selected filter in the File Types control. The buffer pointed to by Filter contains pairs of strings that define the filters. The index is 0-based. + * @param {string} DefExtension Define the default extension. GetOpenFileName and GetSaveFileName append this extension to the file name only if the user fails to type an extension. If this member is NULL and the user fails to type an extension, no extension is appended. + * @param {string} InitialDir The initial directory. The algorithm for selecting the initial directory varies on different platforms. + * @param {boolean} AllowMultiSelect True -- allows users to select more than one file, False -- only allows to select one file. + * @param {boolean} OverwritePrompt True -- If a file already exists with the same name, the old file will be simply overwritten, False -- not allows to save and overwrite a same name file. + * @param {number} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and parameters "AllowMultiSelect" and "OverwritePrompt" will be useless. + * @return {boolean} + */ + ShowFileDialog(SaveDialog: boolean, Filter: string, FilterIndex: number, DefExtension: string, InitialDir: string, AllowMultiSelect: boolean, OverwritePrompt: boolean, Flags: number): boolean; + + /** + * Shows the GUI of Image Editor. + * @method WebTwain#ShowImageEditor + * @return {boolean} + */ + ShowImageEditor(divID?: string, divWidth?: number, divHeight?: number): boolean; + + /** + * [Deprecated.] Shows the GUI of Image Editor with custom settings. + * @method WebTwain#ShowImageEditorEx + * @param {number} x specifies the new position of the left top corner of the window. + * @param {number} y specifies the new position of the left top corner of the window. + * @param {number} cx specifies the width of the window. + * @param {number} cy specifies the height of the window. + * @param {number} nCmdShow specifices how the window should be shown. + * @return {boolean} + */ + ShowImageEditorEx(x: number, y: number, cx: number, cy: number, nCmdShow: number): boolean; + + /*ingored + SourceNameItems + */ + + /** + * Switchs two images of specified indices in buffer. + * @method WebTwain#SwitchImage + * @param {number} sImageIndex1 specifies the index of image in buffer. The index is 0-based. + * @param {number} sImageIndex2 specifies the index of image in buffer. The index is 0-based. + * @return {boolean} + */ + SwitchImage(sImageIndex1: number, sImageIndex2: number): boolean; + + /** + * Unbinds an event from the specified function, so that the function stops receiving notifications when the event fires. + * @method WebTwain#UnregisterEvent + * @param {string} name the name of the event. + * @param {object} evt specified the function to be unbound. + * @return {boolean} + */ + UnregisterEvent(name: string, evt: object): boolean; + + /*ignored + checkErrorString + first + getInstance + last + next + on + onEvent + previous + + ...other internal ones + */ } +/** Border Styles */ declare enum EnumDWT_BorderStyle { - /** No border. */ - TWBS_NONE = 0, - /** Flat border. */ - TWBS_SINGLEFLAT = 1, - /** 3D border. */ - TWBS_SINGLE3D = 2 -} - -/** For query the operation that are supported by the data source on a capability . - * Application gets these through DG_CONTROL/DAT_CAPABILITY/MSG_QUERYSUPPORT - */ -declare enum EnumDWT_MessageType { - TWQC_GET = 1, - TWQC_SET = 2, - TWQC_GETDEFAULT = 4, - TWQC_GETCURRENT = 8, - TWQC_RESET = 16 + /** No border. */ + TWBS_NONE = 0, + /** Flat border. */ + TWBS_SINGLEFLAT = 1, + /** 3D border. */ + TWBS_SINGLE3D = 2 } /** Capabilities */ @@ -266,45 +2599,45 @@ declare enum EnumDWT_Cap { * any frames with a left offset of zero. * TWFA_RIGHT: The alignment is to the right. */ - CAP_FEEDERALIGNMENT = 4141, + CAP_FEEDERALIGNMENT = 4141, /** TWFO_FIRSTPAGEFIRST if the feeder starts with the top of the first page. * TWFO_LASTPAGEFIRST is the feeder starts with the top of the last page. */ - CAP_FEEDERORDER = 4142, + CAP_FEEDERORDER = 4142, /** Indicates whether the physical hardware (e.g. scanner, digital camera) is capable of acquiring * multiple images of the same page without changes to the physical registration of that page. */ - CAP_REACQUIREALLOWED = 4144, + CAP_REACQUIREALLOWED = 4144, /** The minutes of battery power remaining to the device. */ - CAP_BATTERYMINUTES = 4146, + CAP_BATTERYMINUTES = 4146, /** When used with CapGet(), return the percentage of battery power level on camera. If -1 is returned, it indicates that the battery is not present. */ - CAP_BATTERYPERCENTAGE = 4147, + CAP_BATTERYPERCENTAGE = 4147, /** Added 1.91 */ - CAP_CAMERASIDE = 4148, + CAP_CAMERASIDE = 4148, /** Added 1.91 */ - CAP_SEGMENTED = 4149, + CAP_SEGMENTED = 4149, /** Added 2.0 */ - CAP_CAMERAENABLED = 4150, + CAP_CAMERAENABLED = 4150, /** Added 2.0 */ - CAP_CAMERAORDER = 4151, + CAP_CAMERAORDER = 4151, /** Added 2.0 */ - CAP_MICRENABLED = 4152, + CAP_MICRENABLED = 4152, /** Added 2.0 */ - CAP_FEEDERPREP = 4153, + CAP_FEEDERPREP = 4153, /** Added 2.0 */ - CAP_FEEDERPOCKET = 4154, + CAP_FEEDERPOCKET = 4154, /** Added 2.1 */ - CAP_AUTOMATICSENSEMEDIUM = 4155, + CAP_AUTOMATICSENSEMEDIUM = 4155, /** Added 2.1 */ - CAP_CUSTOMINTERFACEGUID = 4156, + CAP_CUSTOMINTERFACEGUID = 4156, /** TRUE enables and FALSE disables the Source's Auto-brightness function (if any). */ - ICAP_AUTOBRIGHT = 4352, + ICAP_AUTOBRIGHT = 4352, /** The brightness values available within the Source. */ - ICAP_BRIGHTNESS = 4353, + ICAP_BRIGHTNESS = 4353, /** The contrast values available within the Source. */ - ICAP_CONTRAST = 4355, + ICAP_CONTRAST = 4355, /** Specifies the square-cell halftone (dithering) matrix the Source should use to halftone the image. */ - ICAP_CUSTHALFTONE = 4356, + ICAP_CUSTHALFTONE = 4356, /** Specifies the exposure time used to capture the image, in seconds. */ ICAP_EXPOSURETIME = 4357, /** Describes the color characteristic of the subtractive filter applied to the image data. Multiple @@ -561,204 +2894,85 @@ declare enum EnumDWT_Cap { ICAP_SUPPORTEDEXTIMAGEINFO = 4446 } -/** Capabilities exist in many varieties but all have a Default Value, Current Value, and may have other values available that can be supported if selected. - * To help categorize the supported values into clear structures, TWAIN defines four types of containers for capabilities = - * TW_ONEVALUE, TW_ARRAY, TW_RANGE and TW_ENUMERATION. - */ -declare enum EnumDWT_CapType { - /** Nothing. */ - TWON_NONE = 0, - /** A rectangular array of values that describe a logical item. It is similar to the TW_ONEVALUE because the current and default values are the same and - * there are no other values to select from. For example, a list of the names, such as the supported capabilities list returned by the CAP_SUPPORTEDCAPS - * capability, would use this type of container. +/** ICAP_BITORDER values. */ +declare enum EnumDWT_CapBitOrder { + TWBO_LSBFIRST = 0, + /** Indicates that the leftmost bit in the byte (usually bit 7) is the byte's Most Significant Bit. */ + TWBO_MSBFIRST = 1 +} + +/** ICAP_BITDEPTHREDUCTION values. */ +declare enum EnumDWT_CapBitdepthReduction { + TWBR_THRESHOLD = 0, + TWBR_HALFTONE = 1, + TWBR_CUSTHALFTONE = 2, + TWBR_DIFFUSION = 3 +} + +/** CAP_FEEDERALIGNMENT values. */ +declare enum EnumDWT_CapFeederAlignment { + /** The alignment is free-floating. Applications should assume that the origin for frames is on the left. */ + TWFA_NONE = 0, + /** The alignment is to the left. */ + TWFA_LEFT = 1, + /** The alignment is centered. This means that the paper will be fed in the middle of the ICAP_PHYSICALWIDTH of the + * device. If this is set, then the Application should calculate any frames with a left offset of zero. */ - TWON_ARRAY = 3, - /** This is the most general type because it defines a list of values from which the Current Value can be chosen. - * The values do not progress uniformly through a range and there is not a consistent step size between the values. - * For example, if a Source's resolution options do not occur in even step sizes then an enumeration would be used (for example, 150, 400, and 600). - */ - TWON_ENUMERATION = 4, - /** A single value whose current and default values are coincident. The range of available values for this type of capability is simply this single value. - * For example, a capability that indicates the presence of a document feeder could be of this type. - */ - TWON_ONEVALUE = 5, - /** Many capabilities allow users to select their current value from a range of regularly spaced values. - * The capability can specify the minimum and maximum acceptable values and the incremental step size between the values. - * For example, resolution might be supported from 100 to 600 in steps of 50 (100, 150, 200, ..., 550, 600). - */ - TWON_RANGE = 6 + TWFA_CENTER = 2, + /** The alignment is to the right. */ + TWFA_RIGHT = 3 } -/** ICAP_XFERMECH values. */ -declare enum EnumDWT_TransferMode { - /** Native transfers require the data to be transferred to a single large block of RAM. Therefore, - * they always face the risk of having an inadequate amount of RAM available to perform the transfer successfully. - */ - TWSX_NATIVE = 0, - /** Disk File Mode Transfers. */ - TWSX_FILE = 1, - /** Buffered Memory Mode Transfers. */ - TWSX_MEMORY = 2, - /** added 1.91 */ - TWSX_MEMFILE = 4 +/** CAP_FEEDERORDER values. */ +declare enum EnumDWT_CapFeederOrder { + /** The feeder starts with the top of the first page. */ + TWFO_FIRSTPAGEFIRST = 0, + /** The feeder starts with the top of the last page. */ + TWFO_LASTPAGEFIRST = 1 } -/** ICAP_IMAGEFILEFORMAT values. */ -declare enum EnumDWT_FileFormat { - /** Used for document imaging. Tagged Image File Format */ - TWFF_TIFF = 0, - /** Native Macintosh format. Macintosh PICT */ - TWFF_PICT = 1, - /** Native Microsoft format. Windows Bitmap */ - TWFF_BMP = 2, - /** Used for document imaging. X-Windows Bitmap */ - TWFF_XBM = 3, - /** Wrapper for JPEG images. JPEG File Interchange Format */ - TWFF_JFIF = 4, - /** FlashPix, used with digital cameras. Flash Pix */ - TWFF_FPX = 5, - /** Multi-page TIFF files. Multi-page tiff file */ - TWFF_TIFFMULTI = 6, - /** An image format standard intended for use on the web, replaces GIF. */ - TWFF_PNG = 7, - /** A standard from JPEG, intended to replace JFIF, also supports JBIG. */ - TWFF_SPIFF = 8, - /** File format for use with digital cameras. */ - TWFF_EXIF = 9, - /** A file format from Adobe. 1.91 NB: this is not PDF/A */ - TWFF_PDF = 10, - /** A file format from the Joint Photographic Experts Group. 1.91 */ - TWFF_JP2 = 11, - /** 1.91 */ - TWFF_JPN = 12, - /** 1.91 */ - TWFF_JPX = 13, - /** A file format from LizardTech. 1.91 */ - TWFF_DEJAVU = 14, - /** A file format from Adobe. 2.0 */ - TWFF_PDFA = 15, - /** 2.1 Adobe PDF/A, Version 2 */ - TWFF_PDFA2 = 16 +/** ICAP_FILTER values. */ +declare enum EnumDWT_CapFilterType { + TWFT_RED = 0, + TWFT_GREEN = 1, + TWFT_BLUE = 2, + TWFT_NONE = 3, + TWFT_WHITE = 4, + TWFT_CYAN = 5, + TWFT_MAGENTA = 6, + TWFT_YELLOW = 7, + TWFT_BLACK = 8 } -/** TIFF file compression type. */ -declare enum EnumDWT_TIFFCompressionType { - /** Auto mode. */ - TIFF_AUTO = 0, - /** Dump mode. */ - TIFF_NONE = 1, - /** CCITT modified Huffman RLE. */ - TIFF_RLE = 2, - /** CCITT Group 3 fax encoding. */ - TIFF_FAX3 = 3, - /** CCITT T.4 (TIFF 6 name). */ - TIFF_T4 = 3, - /** CCITT Group 4 fax encoding */ - TIFF_FAX4 = 4, - /** CCITT T.6 (TIFF 6 name). */ - TIFF_T6 = 4, - /** Lempel Ziv and Welch */ - TIFF_LZW = 5, - TIFF_JPEG = 7, - TIFF_PACKBITS = 32773 +/** ICAP_FLASHUSED2 values. */ +declare enum EnumDWT_CapFlash { + TWFL_NONE = 0, + TWFL_OFF = 1, + TWFL_ON = 2, + TWFL_AUTO = 3, + TWFL_REDEYE = 4 } -/** The method to do interpolation. */ -declare enum EnumDWT_InterpolationMethod { - IM_NEARESTNEIGHBOUR = 1, - IM_BILINEAR = 2, - IM_BICUBIC = 3, - IM_BESTQUALITY = 5 +/** ICAP_FLIPROTATION values. */ +declare enum EnumDWT_CapFlipRotation { + /** The images to be scanned are viewed in book form, flipping each page from left to right or right to left. */ + TWFR_BOOK = 0, + /** The images to be scanned are viewed in fanfold paper style, flipping each page up or down. */ + TWFR_FANFOLD = 1 } -/** Image type */ -declare enum EnumDWT_ImageType { - /** Native Microsoft format. */ - IT_BMP = 0, - /** JPEG format. */ - IT_JPG = 1, - /** Tagged Image File Format. */ - IT_TIF = 2, - /** An image format standard intended for use on the web, replaces GIF. */ - IT_PNG = 3, - /** A file format from Adobe. */ - IT_PDF = 4, - IT_ALL = 5 -} - -/** PDF file compression type. */ -declare enum EnumDWT_PDFCompressionType { - /** Auto mode. */ - PDF_AUTO = 0, - /** CCITT Group 3 fax encoding. */ - PDF_FAX3 = 1, - /** CCITT Group 4 fax encoding */ - PDF_FAX4 = 2, - /** Lempel Ziv and Welch */ - PDF_LZW = 3, - /** CCITT modified Huffman RLE. */ - PDF_RLE = 4, - PDF_JPEG = 5 -} - -declare enum EnumDWT_ShowMode { - /** Activates the window and displays it in its current size and position. */ - SW_ACTIVE = 0, - /** Maximizes the window */ - SW_MAX = 1, - /** Minimize the window */ - SW_MIN = 2, - /** Close the latest opened editor window */ - SW_CLOSE = 3, - /** Check whether a window exists */ - SW_IFLIVE = 4 -} - -/** The kind of data stored in the container. */ -declare enum EnumDWT_CapValueType { - TWTY_INT8 = 0, - /** Means Item is a TW_INT16 */ - TWTY_INT16 = 1, - /** Means Item is a TW_INT32 */ - TWTY_INT32 = 2, - /** Means Item is a TW_UINT8 */ - TWTY_UINT8 = 3, - /** Means Item is a TW_UINT16 */ - TWTY_UINT16 = 4, - /** Means Item is a TW_int */ - TWTY_int = 5, - /** Means Item is a TW_BOOL */ - TWTY_BOOL = 6, - /** Means Item is a TW_FIX32 */ - TWTY_FIX32 = 7, - /** Means Item is a TW_FRAME */ - TWTY_FRAME = 8, - /** Means Item is a TW_STR32 */ - TWTY_STR32 = 9, - /** Means Item is a TW_STR64 */ - TWTY_STR64 = 10, - /** Means Item is a TW_STR128 */ - TWTY_STR128 = 11, - /** Means Item is a TW_STR255 */ - TWTY_STR255 = 12 -} - -/** ICAP_UNITS values. */ -declare enum EnumDWT_UnitType { - TWUN_INCHES = 0, - TWUN_CENTIMETERS = 1, - TWUN_PICAS = 2, - TWUN_POINTS = 3, - TWUN_TWIPS = 4, - TWUN_PIXELS = 5, - TWUN_MILLIMETERS = 6 -} - -/** ICAP_DUPLEX values. */ -declare enum EnumDWT_DUPLEX { - TWDX_NONE = 0, - TWDX_1PASSDUPLEX = 1, - TWDX_2PASSDUPLEX = 2 +/** ICAP_IMAGEFILTER values. */ +declare enum EnumDWT_CapImageFilter { + TWIF_NONE = 0, + TWIF_AUTO = 1, + /** Good for halftone images. */ + TWIF_LOWPASS = 2, + /** Good for improving text. */ + TWIF_BANDPASS = 3, + /** Good for improving fine lines. */ + TWIF_HIGHPASS = 4, + TWIF_TEXT = 3, + TWIF_FINELINE = 4 } /** CAP_LANGUAGE values. */ @@ -912,6 +3126,92 @@ declare enum EnumDWT_CapLanguage { TWLG_VIETNAMESE = 113 } +/** ICAP_LIGHTPATH values. */ +declare enum EnumDWT_CapLightPath { + TWLP_REFLECTIVE = 0, + TWLP_TRANSMISSIVE = 1 +} + +/** ICAP_LIGHTSOURCE values. */ +declare enum EnumDWT_CapLightSource { + TWLS_RED = 0, + TWLS_GREEN = 1, + TWLS_BLUE = 2, + TWLS_NONE = 3, + TWLS_WHITE = 4, + TWLS_UV = 5, + TWLS_IR = 6 +} + +/** ICAP_NOISEFILTER values. */ +declare enum EnumDWT_CapNoiseFilter { + TWNF_NONE = 0, + TWNF_AUTO = 1, + TWNF_LONEPIXEL = 2, + TWNF_MAJORITYRULE = 3 +} + +/** ICAP_ORIENTATION values. */ +declare enum EnumDWT_CapORientation { + TWOR_ROT0 = 0, + TWOR_ROT90 = 1, + TWOR_ROT180 = 2, + TWOR_ROT270 = 3, + TWOR_PORTRAIT = 0, + TWOR_LANDSCAPE = 3, + /** 2.0 */ + TWOR_AUTO = 4, + /** 2.0 */ + TWOR_AUTOTEXT = 5, + /** 2.0 */ + TWOR_AUTOPICTURE = 6 +} + +/** ICAP_OVERSCAN values. */ +declare enum EnumDWT_CapOverscan { + TWOV_NONE = 0, + TWOV_AUTO = 1, + TWOV_TOPBOTTOM = 2, + TWOV_LEFTRIGHT = 3, + TWOV_ALL = 4 +} + +/** ICAP_PIXELFLAVOR values. */ +declare enum EnumDWT_CapPixelFlavor { + /** Zero pixel represents darkest shade. zero pixel represents darkest shade */ + TWPF_CHOCOLATE = 0, + /** Zero pixel represents lightest shade. zero pixel represents lightest shade */ + TWPF_VANILLA = 1 +} + +/** ICAP_PLANARCHUNKY values. */ +declare enum EnumDWT_CapPlanarChunky { + TWPC_CHUNKY = 0, + TWPC_PLANAR = 1 +} + +/** CAP_PRINTER values. */ +declare enum EnumDWT_CapPrinter { + TWPR_IMPRINTERTOPBEFORE = 0, + TWPR_IMPRINTERTOPAFTER = 1, + TWPR_IMPRINTERBOTTOMBEFORE = 2, + TWPR_IMPRINTERBOTTOMAFTER = 3, + TWPR_ENDORSERTOPBEFORE = 4, + TWPR_ENDORSERTOPAFTER = 5, + TWPR_ENDORSERBOTTOMBEFORE = 6, + TWPR_ENDORSERBOTTOMAFTER = 7 +} + +/** CAP_PRINTERMODE values. */ +declare enum EnumDWT_CapPrinterMode { + /** Specifies that the printed text will consist of a single string. */ + TWPM_SINGLESTRING = 0, + /** Specifies that the printed text will consist of an enumerated list of strings to be printed in order. */ + TWPM_MULTISTRING = 1, + /** Specifies that the printed string will consist of a compound of a String followed by a value followed by a suffix string. */ + TWPM_COMPOUNDSTRING = 2 +} + /** TWAIN Supported sizes. */ declare enum EnumDWT_CapSupportedSizes { /** 0 */ @@ -1040,180 +3340,68 @@ declare enum EnumDWT_CapSupportedSizes { TWSS_MAXSIZE = 54 } -/** CAP_FEEDERALIGNMENT values. */ -declare enum EnumDWT_CapFeederAlignment { - /** The alignment is free-floating. Applications should assume that the origin for frames is on the left. */ - TWFA_NONE = 0, - /** The alignment is to the left. */ - TWFA_LEFT = 1, - /** The alignment is centered. This means that the paper will be fed in the middle of the ICAP_PHYSICALWIDTH of the - * device. If this is set, then the Application should calculate any frames with a left offset of zero. +/** Capabilities exist in many varieties but all have a Default Value, Current Value, and may have other values available that can be supported if selected. + * To help categorize the supported values into clear structures, TWAIN defines four types of containers for capabilities = + * TW_ONEVALUE, TW_ARRAY, TW_RANGE and TW_ENUMERATION. + */ +declare enum EnumDWT_CapType { + /** Nothing. */ + TWON_NONE = 0, + /** A rectangular array of values that describe a logical item. It is similar to the TW_ONEVALUE because the current and default values are the same and + * there are no other values to select from. For example, a list of the names, such as the supported capabilities list returned by the CAP_SUPPORTEDCAPS + * capability, would use this type of container. */ - TWFA_CENTER = 2, - /** The alignment is to the right. */ - TWFA_RIGHT = 3 -} -/** CAP_FEEDERORDER values. */ -declare enum EnumDWT_CapFeederOrder { - /** The feeder starts with the top of the first page. */ - TWFO_FIRSTPAGEFIRST = 0, - /** The feeder starts with the top of the last page. */ - TWFO_LASTPAGEFIRST = 1 + TWON_ARRAY = 3, + /** This is the most general type because it defines a list of values from which the Current Value can be chosen. + * The values do not progress uniformly through a range and there is not a consistent step size between the values. + * For example, if a Source's resolution options do not occur in even step sizes then an enumeration would be used (for example, 150, 400, and 600). + */ + TWON_ENUMERATION = 4, + /** A single value whose current and default values are coincident. The range of available values for this type of capability is simply this single value. + * For example, a capability that indicates the presence of a document feeder could be of this type. + */ + TWON_ONEVALUE = 5, + /** Many capabilities allow users to select their current value from a range of regularly spaced values. + * The capability can specify the minimum and maximum acceptable values and the incremental step size between the values. + * For example, resolution might be supported from 100 to 600 in steps of 50 (100, 150, 200, ..., 550, 600). + */ + TWON_RANGE = 6 } -/** CAP_PRINTER values. */ -declare enum EnumDWT_CapPrinter { - TWPR_IMPRINTERTOPBEFORE = 0, - TWPR_IMPRINTERTOPAFTER = 1, - TWPR_IMPRINTERBOTTOMBEFORE = 2, - TWPR_IMPRINTERBOTTOMAFTER = 3, - TWPR_ENDORSERTOPBEFORE = 4, - TWPR_ENDORSERTOPAFTER = 5, - TWPR_ENDORSERBOTTOMBEFORE = 6, - TWPR_ENDORSERBOTTOMAFTER = 7 +/** The kind of data stored in the container. */ +declare enum EnumDWT_CapValueType { + TWTY_INT8 = 0, + /** Means Item is a TW_INT16 */ + TWTY_INT16 = 1, + /** Means Item is a TW_INT32 */ + TWTY_INT32 = 2, + /** Means Item is a TW_UINT8 */ + TWTY_UINT8 = 3, + /** Means Item is a TW_UINT16 */ + TWTY_UINT16 = 4, + /** Means Item is a TW_int */ + TWTY_int = 5, + /** Means Item is a TW_BOOL */ + TWTY_BOOL = 6, + /** Means Item is a TW_FIX32 */ + TWTY_FIX32 = 7, + /** Means Item is a TW_FRAME */ + TWTY_FRAME = 8, + /** Means Item is a TW_STR32 */ + TWTY_STR32 = 9, + /** Means Item is a TW_STR64 */ + TWTY_STR64 = 10, + /** Means Item is a TW_STR128 */ + TWTY_STR128 = 11, + /** Means Item is a TW_STR255 */ + TWTY_STR255 = 12 } -/** CAP_PRINTERMODE values. */ -declare enum EnumDWT_CapPrinterMode { - /** Specifies that the printed text will consist of a single string. */ - TWPM_SINGLESTRING = 0, - /** Specifies that the printed text will consist of an enumerated list of strings to be printed in order. */ - TWPM_MULTISTRING = 1, - /** Specifies that the printed string will consist of a compound of a String followed by a value followed by a suffix string. */ - TWPM_COMPOUNDSTRING = 2 -} - -/** ICAP_BITDEPTHREDUCTION values. */ -declare enum EnumDWT_CapBitdepthReduction { - TWBR_THRESHOLD = 0, - TWBR_HALFTONE = 1, - TWBR_CUSTHALFTONE = 2, - TWBR_DIFFUSION = 3 -} - -/** ICAP_BITORDER values. */ -declare enum EnumDWT_CapBitOrder { - TWBO_LSBFIRST = 0, - /** Indicates that the leftmost bit in the byte (usually bit 7) is the byte's Most Significant Bit. */ - TWBO_MSBFIRST = 1 -} - -/** ICAP_FILTER values. */ -declare enum EnumDWT_CapFilterType { - TWFT_RED = 0, - TWFT_GREEN = 1, - TWFT_BLUE = 2, - TWFT_NONE = 3, - TWFT_WHITE = 4, - TWFT_CYAN = 5, - TWFT_MAGENTA = 6, - TWFT_YELLOW = 7, - TWFT_BLACK = 8 -} - -/** ICAP_FLASHUSED2 values. */ -declare enum EnumDWT_CapFlash { - TWFL_NONE = 0, - TWFL_OFF = 1, - TWFL_ON = 2, - TWFL_AUTO = 3, - TWFL_REDEYE = 4 -} - -/** ICAP_FLIPROTATION values. */ -declare enum EnumDWT_CapFlipRotation { - /** The images to be scanned are viewed in book form, flipping each page from left to right or right to left. */ - TWFR_BOOK = 0, - /** The images to be scanned are viewed in fanfold paper style, flipping each page up or down. */ - TWFR_FANFOLD = 1 -} - -/** ICAP_IMAGEFILTER values. */ -declare enum EnumDWT_CapImageFilter { - TWIF_NONE = 0, - TWIF_AUTO = 1, - /** Good for halftone images. */ - TWIF_LOWPASS = 2, - /** Good for improving text. */ - TWIF_BANDPASS = 3, - /** Good for improving fine lines. */ - TWIF_HIGHPASS = 4, - TWIF_TEXT = 3, - TWIF_FINELINE = 4 -} - -/** ICAP_LIGHTPATH values. */ -declare enum EnumDWT_CapLightPath { - TWLP_REFLECTIVE = 0, - TWLP_TRANSMISSIVE = 1 -} - -/** ICAP_LIGHTSOURCE values. */ -declare enum EnumDWT_CapLightSource { - TWLS_RED = 0, - TWLS_GREEN = 1, - TWLS_BLUE = 2, - TWLS_NONE = 3, - TWLS_WHITE = 4, - TWLS_UV = 5, - TWLS_IR = 6 -} - -/** TWEI_MAGTYPE values. (MD_ means Mag Type) Added 2.0 */ -declare enum EnumDWT_MagType { - /** Added 2.0 */ - TWMD_MICR = 0, - /** added 2.1 */ - TWMD_RAW = 1, - /** added 2.1 */ - TWMD_INVALID = 2 -} - -/** ICAP_NOISEFILTER values. */ -declare enum EnumDWT_CapNoiseFilter { - TWNF_NONE = 0, - TWNF_AUTO = 1, - TWNF_LONEPIXEL = 2, - TWNF_MAJORITYRULE = 3 -} - -/** ICAP_ORIENTATION values. */ -declare enum EnumDWT_CapORientation { - TWOR_ROT0 = 0, - TWOR_ROT90 = 1, - TWOR_ROT180 = 2, - TWOR_ROT270 = 3, - TWOR_PORTRAIT = 0, - TWOR_LANDSCAPE = 3, - /** 2.0 */ - TWOR_AUTO = 4, - /** 2.0 */ - TWOR_AUTOTEXT = 5, - /** 2.0 */ - TWOR_AUTOPICTURE = 6 -} - -/** ICAP_OVERSCAN values. */ -declare enum EnumDWT_CapOverscan { - TWOV_NONE = 0, - TWOV_AUTO = 1, - TWOV_TOPBOTTOM = 2, - TWOV_LEFTRIGHT = 3, - TWOV_ALL = 4 -} - -/** ICAP_PIXELFLAVOR values. */ -declare enum EnumDWT_CapPixelFlavor { - /** Zero pixel represents darkest shade. zero pixel represents darkest shade */ - TWPF_CHOCOLATE = 0, - /** Zero pixel represents lightest shade. zero pixel represents lightest shade */ - TWPF_VANILLA = 1 -} - -/** ICAP_PLANARCHUNKY values. */ -declare enum EnumDWT_CapPlanarChunky { - TWPC_CHUNKY = 0, - TWPC_PLANAR = 1 +/** ICAP_DUPLEX values. */ +declare enum EnumDWT_DUPLEX { + TWDX_NONE = 0, + TWDX_1PASSDUPLEX = 1, + TWDX_2PASSDUPLEX = 2 } /** Data source status. */ @@ -1228,6 +3416,48 @@ declare enum EnumDWT_DataSourceStatus { TWDSS_ACQUIRING = 3 } +declare enum EnumDWT_Error { + ModuleNotExists = -2371 +} + +/** ICAP_IMAGEFILEFORMAT values. */ +declare enum EnumDWT_FileFormat { + /** Used for document imaging. Tagged Image File Format */ + TWFF_TIFF = 0, + /** Native Macintosh format. Macintosh PICT */ + TWFF_PICT = 1, + /** Native Microsoft format. Windows Bitmap */ + TWFF_BMP = 2, + /** Used for document imaging. X-Windows Bitmap */ + TWFF_XBM = 3, + /** Wrapper for JPEG images. JPEG File Interchange Format */ + TWFF_JFIF = 4, + /** FlashPix, used with digital cameras. Flash Pix */ + TWFF_FPX = 5, + /** Multi-page TIFF files. Multi-page tiff file */ + TWFF_TIFFMULTI = 6, + /** An image format standard intended for use on the web, replaces GIF. */ + TWFF_PNG = 7, + /** A standard from JPEG, intended to replace JFIF, also supports JBIG. */ + TWFF_SPIFF = 8, + /** File format for use with digital cameras. */ + TWFF_EXIF = 9, + /** A file format from Adobe. 1.91 NB: this is not PDF/A */ + TWFF_PDF = 10, + /** A file format from the Joint Photographic Experts Group. 1.91 */ + TWFF_JP2 = 11, + /** 1.91 */ + TWFF_JPN = 12, + /** 1.91 */ + TWFF_JPX = 13, + /** A file format from LizardTech. 1.91 */ + TWFF_DEJAVU = 14, + /** A file format from Adobe. 2.0 */ + TWFF_PDFA = 15, + /** 2.1 Adobe PDF/A, Version 2 */ + TWFF_PDFA2 = 16 +} + /** Fit window type */ declare enum EnumDWT_FitWindowType { /** Fit the image to the width and height of the window */ @@ -1238,2222 +3468,214 @@ declare enum EnumDWT_FitWindowType { enumFitWindowWidth = 2 } -declare enum EnumDWT_UploadDataFormat { - Binary = 0, - Base64 = 1 +/** Image type */ +declare enum EnumDWT_ImageType { + /** Native Microsoft format. */ + IT_BMP = 0, + /** JPEG format. */ + IT_JPG = 1, + /** Tagged Image File Format. */ + IT_TIF = 2, + /** An image format standard intended for use on the web, replaces GIF. */ + IT_PNG = 3, + /** A file format from Adobe. */ + IT_PDF = 4, + /** All supported formats which are bmp, jpg, tif, png and pdf */ + IT_ALL = 5 +} + +declare enum EnumDWT_InitMsg { + Info = 1, + Error = 2, + NotInstalledError = 3, + DownloadError = 4, + DownloadNotRestartError = 5 +} + +/** The method to do interpolation. */ +declare enum EnumDWT_InterpolationMethod { + IM_NEARESTNEIGHBOUR = 1, + IM_BILINEAR = 2, + IM_BICUBIC = 3, + IM_BESTQUALITY = 5 +} + +declare enum EnumDWT_Language { + English = 0, + French = 1, + Arabic = 2, + Spanish = 3, + Portuguese = 4, + German = 5, + Italian = 6, + Russian = 7, + Chinese = 8 +} + +/** TWEI_MAGTYPE values. (MD_ means Mag Type) Added 2.0 */ +declare enum EnumDWT_MagType { + /** Added 2.0 */ + TWMD_MICR = 0, + /** added 2.1 */ + TWMD_RAW = 1, + /** added 2.1 */ + TWMD_INVALID = 2 +} + +/** For query the operation that are supported by the data source on a capability . + * Application gets these through DG_CONTROL/DAT_CAPABILITY/MSG_QUERYSUPPORT + */ +declare enum EnumDWT_MessageType { + TWQC_GET = 1, + TWQC_SET = 2, + TWQC_GETDEFAULT = 4, + TWQC_GETCURRENT = 8, + TWQC_RESET = 16 } declare enum EnumDWT_MouseShape { - Default = 0, - Hand = 1, - Crosshair = 2, - Zoom = 3 + Default = 0, + Hand = 1, + Crosshair = 2, + Zoom = 3 +} + +/** PDF file compression type. */ +declare enum EnumDWT_PDFCompressionType { + /** Auto mode. */ + PDF_AUTO = 0, + /** CCITT Group 3 fax encoding. */ + PDF_FAX3 = 1, + /** CCITT Group 4 fax encoding */ + PDF_FAX4 = 2, + /** Lempel Ziv and Welch */ + PDF_LZW = 3, + /** CCITT modified Huffman RLE. */ + PDF_RLE = 4, + /** JPEG compression. */ + PDF_JPEG = 5 +} + +/** ICAP_PIXELTYPE values (PT_ means Pixel Type) */ +declare enum EnumDWT_PixelType { + TWPT_BW = 0, + TWPT_GRAY = 1, + TWPT_RGB = 2, + TWPT_PALLETE = 3, + TWPT_CMY = 4, + TWPT_CMYK = 5, + TWPT_YUV = 6, + TWPT_YUVK = 7, + TWPT_CIEXYZ = 8, + TWPT_LAB = 9, + TWPT_SRGB = 10, + TWPT_SCRGB = 11, + TWPT_INFRARED = 16 +} + +declare enum EnumDWT_PlatformType { + /// Fit the image to the width and height of the window + enumWindow = 0, + /// Fit the image to the height of the window + enumMac = 1, + /// Fit the image to the width of the window + enumLinux = 2 +} + +declare enum EnumDWT_ShowMode { + /** Activates the window and displays it in its current size and position. */ + SW_ACTIVE = 0, + /** Maximizes the window */ + SW_MAX = 1, + /** Minimize the window */ + SW_MIN = 2, + /** Close the latest opened editor window */ + SW_CLOSE = 3, + /** Check whether a window exists */ + SW_IFLIVE = 4 +} + +/** TIFF file compression type. */ +declare enum EnumDWT_TIFFCompressionType { + /** Auto mode. */ + TIFF_AUTO = 0, + /** Dump mode. */ + TIFF_NONE = 1, + /** CCITT modified Huffman RLE. */ + TIFF_RLE = 2, + /** CCITT Group 3 fax encoding. */ + TIFF_FAX3 = 3, + /** CCITT T.4 (TIFF 6 name). */ + TIFF_T4 = 3, + /** CCITT Group 4 fax encoding */ + TIFF_FAX4 = 4, + /** CCITT T.6 (TIFF 6 name). */ + TIFF_T6 = 4, + /** Lempel Ziv and Welch */ + TIFF_LZW = 5, + TIFF_JPEG = 7, + TIFF_PACKBITS = 32773 +} + +/** ICAP_XFERMECH values. */ +declare enum EnumDWT_TransferMode { + /** Native transfers require the data to be transferred to a single large block of RAM. Therefore, + * they always face the risk of having an inadequate amount of RAM available to perform the transfer successfully. + */ + TWSX_NATIVE = 0, + /** Disk File Mode Transfers. */ + TWSX_FILE = 1, + /** Buffered Memory Mode Transfers. */ + TWSX_MEMORY = 2/*,*/ + /** added 1.91 , not supported in DWT yet*/ + /** TWSX_MEMFILE = 4*/ +} + +/** ICAP_UNITS values. */ +declare enum EnumDWT_UnitType { + TWUN_INCHES = 0, + TWUN_CENTIMETERS = 1, + TWUN_PICAS = 2, + TWUN_POINTS = 3, + TWUN_TWIPS = 4, + TWUN_PIXELS = 5, + TWUN_MILLIMETERS = 6 +} + +declare enum EnumDWT_UploadDataFormat { + Binary = 0, + Base64 = 1 } /** - * @class + * interface for a base64 result */ -// properties (get/set) / sync functions -interface WebTwain { - /** - * Returns or sets whether multi-page selection is supported. - * @type {bool} - */ - AllowMultiSelect: boolean; - - /** - * [Deprecated.] Returns or sets whether allowing the plugin to send authentication request. The default value of this property is TRUE. - * @type {bool} - */ - AllowPluginAuthentication: boolean; - - /** - * [Deprecated.] Returns or sets whether the async mode is activated. With this mode, Dynamic Web TWAIN is able to upload/download files via HTTP/FTP asynchronously. The default value is false. - * @type {bool} - */ - AsyncMode: boolean; - - /** - * Returns or sets the background color of the main control. It is a value specifying the 24-bit RGB value. - * @type {int} - */ - BackgroundColor: number; - - /** - * Returns or sets the fill color of the selected area of an image when it is cut, erased or rotated. It is a value specifying the 24-bit RGB value. - * @type {int} - */ - BackgroundFillColor: number; - - /** - * [Deprecated.] Returns the number of barcode detected in an image. - * @type {int} - */ - BarcodeCount: number; - - /** - * Returns or sets the pixel bit depths for the current value of PixelType property. This is a runtime property. - * @type {short} - */ - BitDepth: number; - - /** - * Returns the current deviation of the pixels in the image. - * @type {float} - */ - BlankImageCurrentStdDev: number; - - /** - * Returns or sets the standard deviation of the pixels in the image. - * @type {float} - */ - BlankImageMaxStdDev: number; - - /** - * Returns or sets the dividing line between black and white. The default value is 128. - * @type {int} - */ - BlankImageThreshold: number; - - /** - * [Deprecated.] Returns or sets the border style. - * @type {EnumDWT_BorderStyle} - */ - BorderStyle: EnumDWT_BorderStyle; - - /** - * Returns or sets the brightness values available within the Source. This is a runtime property. - * @type {float} - */ - Brightness: number; - - /** - * [Deprecated.] Sets or returns whether brokerprocess is enabled for scanning. - * @type {int} - */ - BrokerProcessType: number; - - /** - * Sets or returns how much physical memory is allowed for storing images currently loaded in Dynamic Web TWAIN. Once the limit is reached, images will be cached on the hard disk. - * @type {int} - */ - BufferMemoryLimit: number; - - /** - * Specifies the capabiltiy to be negotiated. This is a runtime property. - * @type {EnumDWT_Cap} - */ - Capability: EnumDWT_Cap; - - /** - * Sets or returns the index (0-based) of a list to indicate the Current Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. - * @type {int} - */ - CapCurrentIndex: number; - - /** - * Sets or returns the current value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. - * @type {double} - */ - CapCurrentValue: number; - - /** - * Returns the index (0-based) of a list to indicate the Default Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime, read-only property. - * @type {int} - */ - CapDefaultIndex: number; - - /** - * Returns the default value in a range when the value of the CapType property is TWON_RANGE. This is a runtime, read-only property. - * @type {double} - */ - CapDefaultValue: number; - - /** - * Sets or returns the maximum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. - * @type {double} - */ - CapMaxValue: number; - - /** - * Sets or returns the minimum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. - * @type {double} - */ - CapMinValue: number; - - /** - * [Deprecated.] Sets or returns how many items are in the list when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. For String data type, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. - * @type {int} - */ - CapNumItems: number; - - /** - * [Deprecated.] Replaced by GetCapItemsString method and SetCapItemsString method. - * @type {string} - */ - CapItemsString: string; - - /** - * Sets or returns the step size in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. - * @type {double} - */ - CapStepSize: number; - - /** - * Sets or returns the type of capability container used to exchange capability information between application and source. This is a runtime property. - * @type {EnumDWT_CapType} - */ - CapType: EnumDWT_CapType; - - /** - * Returns or sets the value of the capability specified by Capability property when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. - * @type {double} - */ - CapValue: number; - - /** - * Sets or returns the string value for a capability when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. - * @type {string} - */ - CapValueString: string; - - /** - * Sets or returns the value type for reading the value of a capability. This is a runtime property. - * @type {short} - */ - CapValueType: number; - - /** - * Returns or sets the contrast values available within the Source. This is a runtime property. - * @type {float} - */ - Contrast: number; - - /** - * Sets or returns the product name string for the application identity. - * @type {string} - */ - ProductName: string; - - /** - * Returns or sets current index of image in buffer. This is a runtime property. - * @type {short} - */ - CurrentImageIndexInBuffer: number; - - /** - * Returns the device name of current source. This is a runtime, read-only property. - * @type {string} - */ - CurrentSourceName: string; - - /** - * Returns the value indicating the data source status. This is a runtime, read-only property. - * @type {int} - */ - DataSourceStatus: number; - - /** - * Returns the device name of default source. This is a runtime, read-only property. - * @type {string} - */ - DefaultSourceName: string; - - /** - * Returns whether the source supports duplex. If so, it further returns the level of duplex the Source supports (one pass or two pass duplex). This is a runtime, read-only property. - * @type {int} - */ - Duplex: number; - - /** - * [Deprecated.] Returns or sets whether the user can zoom image using hot key. - * @type {bool} - */ - EnableInteractiveZoom: boolean; - - /** - * Returns the error code. This is a runtime, read-only property. - * @type {int} - */ - ErrorCode: number; - - /** - * Returns the error string. This is a runtime, read-only property. - * @type {string} - */ - ErrorString: string; - - /** - * Returns or sets whether to resize the image to fit the image to the width or height of the window. To use the property, the view mode should be set to -1 by -1. You can use SetViewMode method to set the view mode. - * @type {EnumDWT_FitWindowType} - */ - FitWindowType: EnumDWT_FitWindowType; - - /** - * Returns or sets the password used to log into the FTP server. - * @type {string} - */ - FTPPassword: string; - - /** - * Returns or sets the port number of the FTP server. - * @type {int} - */ - FTPPort: number; - - /** - * Returns or sets the user name used to log into the FTP server. - * @type {string} - */ - FTPUserName: string; - - /** - * Returns how many images are in buffer. This is a runtime, read-only property. - * @type {short} - */ - HowManyImagesInBuffer: number; - - /** - * Specifies the field name of uploaded image through POST. - * @type {string} - */ - HttpFieldNameOfUploadedImage: string; - - /** - * [Deprecated.] Sets or returns the password used to log into the HTTP server. - * @type {string} - */ - HTTPPassword: string; - - /** - * Returns or sets the port number of the HTTP server. - * @type {int} - */ - HTTPPort: number; - - /** - * Returns the response string from the HTTP server if an error occurs for HTTPUploadThroughPost() method. This is a runtime, read-only property. - * @type {string} - */ - HTTPPostResponseString: string; - - /** - * [Deprecated.] Returns or sets the user name used to log into the HTTP server. - * @type {string} - */ - HTTPUserName: string; - - /** - * Returns or sets whether the feature of disk caching is enabled. - * @type {bool} - */ - IfAllowLocalCache: boolean; - - /** - * Returns or sets whether insert or append new scanned images. - * @type {bool} - */ - IfAppendImage: boolean; - - /** - * Returns or sets whether the Source's Auto-brightness function is enabled. This is a runtime property. - * @type {bool} - */ - IfAutoBright: boolean; - - /** - * Returns or sets whether the data source (scanner) will discard blank images during scanning. The property works only if the device and its driver support discarding blank pages. You can find whether your device supports this capbility from its user manual. Or, you can use the built-in methods of Dynamic Web TWAIN to detect blank images: IsBlankImage, IsBlankImageEx. - * @type {bool} - */ - IfAutoDiscardBlankpages: boolean; - - /** - * Returns or sets whether the Source enable automatic document feeding process. This is a runtime property. - * @type {bool} - */ - IfAutoFeed: boolean; - - /** - * Turns automatic border detection on and off. The property works only if the device and its driver support detecting the border automatically. You can find whether your device supports this capbility from its user manual. - * @type {bool} - */ - IfAutomaticBorderDetection: boolean; - - /** - * Turns automatic skew correction on and off. - * @type {bool} - */ - IfAutomaticDeskew: boolean; - - /** - * Returns or sets whether the Source enables the automatic document scanning process. This is a runtime property. - * @type {bool} - */ - IfAutoScan: boolean; - - /** - * Returns or sets whether close the Data Source User Interface after acquire all images. Default value of this property is FALSE. - * @type {bool} - */ - IfDisableSourceAfterAcquire: boolean; - - /** - * Returns or sets whether the Source supports duplex. If TRUE, the scanner scans both sides of a paper; otherwise, the scanner will scan only one side of the image. This is a runtime property. - * @type {bool} - */ - IfDuplexEnabled: boolean; - - /** - * Returns or sets whether the Automatic Document Feeder (ADF) is enabled. This is a runtime property. - * @type {bool} - */ - IfFeederEnabled: boolean; - - /** - * Returns whether or not there are documents loaded in the Source's feeder when IfFeederEnabled and IfPaperDetectable are TRUE. This is a runtime, read-only property. - * @type {bool} - */ - IfFeederLoaded: boolean; - - /** - * Returns or sets whether to resize the image to fit the size of window when the view mode is set to -1 by -1. You can use SetViewMode method to set the view mode. - * @type {bool} - */ - IfFitWindow: boolean; - - /** - * [Deprecated.] Returns or sets whether the UI (User Interface) of Source runs in modal state. Default value of this property is TRUE. - * @type {bool} - */ - IfModalUI: boolean; - - /** - * Sets or returns whether Dynamic Web TWAIN uses Graphics Device Interface (GDI) when decoding images. - * @type {bool} - */ - IfOpenImageWithGDIPlus: boolean; - - /** - * Returns the value whether the Source has a paper sensor that can detect documents on the ADF or Flatbed. This is a runtime, read-only property. - * @type {bool} - */ - IfPaperDetectable: boolean; - - /** - * Returns or sets whether FTP passive mode is enabled. - * @type {bool} - */ - IfPASVMode: boolean; - - /** - * [Deprecated.] Returns or sets whether communicate with device in a separate thread. Default value of this property is FALSE. - * @type {bool} - */ - IfScanInNewThread: boolean; - - /** - * Sets or returns whether to show the cancel dialog when uploading images to server. - * @type {bool} - */ - IfShowCancelDialogWhenImageTransfer: boolean; - - /** - * Returns or sets whether to show the file dialog box when saving scanned images or loading images from local folder. - * @type {bool} - */ - IfShowFileDialog: boolean; - - /** - * Returns or sets whether the Source displays a progress indicator during acquisition and transfer, regardless of whether the Source's user interface is active. This is a runtime property. - * @type {bool} - */ - IfShowIndicator: boolean; - - /** - * [Deprecated.] Returns or sets whether the driver of the printer displays the User Interface. - * @type {bool} - */ - IfShowPrintUI: boolean; - - /** - * Returns or sets whether the progress bar will be displayed during the transaction. This is a runtime property. - * @type {bool} - */ - IfShowProgressBar: boolean; - - /** - * Returns or sets whether the Source displays the User Interface. - * @type {bool} - */ - IfShowUI: boolean; - - /** - * Returns or sets whether SSL is used when uploading or downloading images. - * @type {bool} - */ - IfSSL: boolean; - - /** - * Return or sets whether the Source allows to save many images in one TIFF file. The default value is FALSE. - * @type {bool} - */ - IfTiffMultiPage: boolean; - - /** - * Returns whether the Source supports acquisition with the UI (User Interface) disabled. If FALSE, indicates that this Source can only support acquisition with the UI enabled. This is a runtime, read-only property. - * @type {bool} - */ - IfUIControllable: boolean; - - /** - * Sets or returns whether Dynamic Web TWAIN uses the new TWAIN Data Source Manager (TWAINDSM.dll) when acquiring images from TWAIN devices. - * @type {bool} - */ - IfUseTwainDSM: boolean; - - /** - * Specifies whether or not to automatically scroll to the last image or stay on the current image when loading or acquiring images - * @type {bool} - */ - IfAutoScroll: boolean; - - /** - * [Deprecated.] The number of bits in each image pixel (or bit depth). This is a runtime, read-only property. - * @type {short} - */ - ImageBitsPerPixel: number; - - /** - * Returns or sets whether a TWAIN driver or Native Scan of Mac OS X is used for document scanning. This property works for Mac edition only. - * @type {int} - */ - ImageCaptureDriverType: number; - - /** - * [Deprecated.] Returns or sets whether the image enumerator is enabled in Image Editor. - * @type {bool} - */ - ImageEditorIfEnableEnumerator: boolean; - - /** - * [Deprecated.] Returns or sets whether the Image Editor is a modal window. - * @type {bool} - */ - ImageEditorIfModal: boolean; - - /** - * [Deprecated.] Returns or sets whether the Image Editor is read-only. - * @type {bool} - */ - ImageEditorIfReadonly: boolean; - - /** - * [Deprecated.] Returns or sets the title of Image Editor window. - * @type {string} - */ - ImageEditorWindowTitle: string; - - /** - * Returns the document number of the current image. This is a runtime, read-only property. - * @type {int} - */ - ImageLayoutDocumentNumber: number; - - /** - * Returns the value of the bottom-most edge of the current image frame (in Unit). This is a read-only runtime property. - * @type {float} - */ - ImageLayoutFrameBottom: number; - - /** - * Returns the value of the left-most edge of the current image frame (in Unit). This is a runtime, read-only property. - * @type {float} - */ - ImageLayoutFrameLeft: number; - - /** - * Returns the frame number of the current image. This is a runtime, read-only property. - * @type {int} - */ - ImageLayoutFrameNumber: number; - - /** - * Returns the value of the right-most edge of the current image frame (in Unit). This is a runtime, read-only property. - * @type {float} - */ - ImageLayoutFrameRight: number; - - /** - * Returns the value of the top-most edge of the current image frame (in Unit). This is a runtime, read-only property. - * @type {float} - */ - ImageLayoutFrameTop: number; - - /** - * Returns the page number of the current image. This is a runtime, read-only property. - * @type {Long} - */ - ImageLayoutPageNumber: number; - - /** - * [Deprecated.] Returns how tall/long, in pixels, the image is. This is a runtime, read-only property. - * @type {int} - */ - ImageLength: number; - - /** - * Returns or sets the margin between images when multiple images are displayed in Dynamic Web TWAIN. - * @type {short} - */ - ImageMargin: number; - - /** - * Returns the pixel type of the current image. This is a runtime, read-only property. Please note the property is only valid in OnPreTransfer and OnPostTransfer event. - * @type {EnumDWT_PixelType} - */ - ImagePixelType: EnumDWT_PixelType; - - /** - * [Deprecated.] Returns how width, in pixels, the image is. This is a runtime, read-only property. - * @type {int} - */ - ImageWidth: number; - - /** - * [Deprecated.] Returns the X resolution of the current image. X resolution is the number of pixels per Unit in the horizontal direction. This is a runtime, read-only property. - * @type {float} - */ - ImageXResolution: number; - - /** - * [Deprecated.] Returns the Y resolution of the current image. Y resolution is the number of pixels per Unit in the vertical direction. This is a runtime, read-only property. - * @type {float} - */ - ImageYResolution: number; - - /** - * Returns or sets the quality of JPEG files and PDF files using JPEG compression. - * @type {short} - */ - JPEGQuality: number; - - /** - * Returns or sets the log level for debugging. - * @type {short} - */ - LogLevel: number; - - /** - * Return the magnetic data if the scanner support magnetic data recognition. - * @type {string} - */ - MagData: string; - - /** - * Return the magnetic type if the scanner support magnetic data recognition. - * @type {short} - */ - MagType: number; - - /** - * Sets or returns the manufacture string for the application identity. - * @type {string} - */ - Manufacturer: string; - - /** - * Returns or sets the maximum number of images can be held in buffer. - * @type {short} - */ - MaxImagesInBuffer: number; - - /** - * [Deprecated.] Returns or sets how many threads can be used when you upload files through POST. - * @type {int} - */ - MaxInternetTransferThreads: number; - - /** - * Sets or returns the maximum allowed size when Dynamic Web TWAIN uploads a document. - * @type {int} - */ - MaxUploadImageSize: number; - - /** - * Returns or sets the shape of the mouse. - * @type {bool} - */ - MouseShape: boolean; - - /** - * Returns the X co-ordinate of the mouse. This is a runtime property. - * @type {int} - */ - MouseX: number; - - /** - * Returns the Y co-ordinate of the mouse. This is a runtime property. - * @type {int} - */ - MouseY: number; - - /** - * Returns or sets the page size(s) the Source can/should use to acquire image data. This is a runtime property. - * @type {short} - */ - PageSize: number; - - /** - * Returns or sets the name of the person who creates the PDF document. - * @type {string} - */ - PDFAuthor: string; - - /** - * Returns or sets the compression type of PDF files. This is a runtime property. - * @type {EnumDWT_PDFCompressionType} - */ - PDFCompressionType: EnumDWT_PDFCompressionType; - - /** - * Returns or sets the date when the PDF document is created. - * @type {string} - */ - PDFCreationDate: string; - - /** - * Returns or sets the name of the application that created the original document, if the PDF document is converted from another form. - * @type {string} - */ - PDFCreator: string; - - /** - * Returns or sets the keywords associated with the PDF document. - * @type {string} - */ - PDFKeywords: string; - - /** - * Returns or sets the date when the PDF document is last modified. - * @type {string} - */ - PDFModifiedDate: string; - - /** - * Returns or sets the name of the application that converted the PDF document from its native. - * @type {string} - */ - PDFProducer: string; - - /** - * Returns or sets the subject of the PDF document. - * @type {string} - */ - PDFSubject: string; - - /** - * Returns or sets the title of the PDF document. - * @type {string} - */ - PDFTitle: string; - - /** - * Returns or sets the value of the PDF version. - * @type {string} - */ - PDFVersion: string; - - /** - * Returns the number of transfers the Source is ready to supply, upon demand. This is a runtime, read-only property. - * @type {short} - */ - PendingXfers: number; - - /** - * Returns or sets the pixel flavor for acquired images. This is a runtime property. - * @type {short} - */ - PixelFlavor: number; - - /** - * Returns or sets the pixel type of current data source. This is a runtime property. Using this property after calling OpenSource() method and before calling AcquireImage(). - * @type {EnumDWT_PixelType} - */ - PixelType: EnumDWT_PixelType; - - /** - * Sets or returns the product family string for the application identity. - * @type {string} - */ - ProductFamily: string; - - /** - * Sets the product key. A product key is generated in Licensing Tool which is intalled with Dynamic Web TWAIN. Each product key corresponds with a license. - * @type {string} - */ - ProductKey: string; - - /** - * [Deprecated.] Returns or sets the name of the proxy server. - * @type {string} - */ - ProxyServer: string; - - /** - * Returns or sets the current resolution for acquired images. This is a runtime property. - * @type {float} - */ - Resolution: number; - - /** - * Returns or sets how many scanned images are selected. - * @type {short} - */ - SelectedImagesCount: number; - - /** - * Returns or sets the border color of the selected image. It is a value specifying the 24-bit RGB value. - * @type {int} - */ - SelectionImageBorderColor: number; - - /** - * Specifies a fixed aspect ratio to be used for selecting an area. - * @type {float} - */ - SelectionRectAspectRatio: number; - - /** - * Returns how many sources are installed in the system. This is a runtime, read-only property. - * @type {int} - */ - SourceCount: number; - - /** - * [Deprecated.] Replaced by GetSourceNameItems method. - * @type {string} - */ - SourceNameItems: string; - - /** - * [Deprecated.] - * @type {string} - */ - GetSourceNames: string; - - /** - * Returns or sets the compression type of TIFF files. This is a runtime property. - * @type {EnumDWT_TIFFCompressionType} - */ - TIFFCompressionType: EnumDWT_TIFFCompressionType; - - /** - * Sets or returns the transfer mode. - * @type {EnumDWT_TransferMode} - */ - TransferMode: EnumDWT_TransferMode; - - /** - * Returns or sets the unit of measure. This is a runtime property. - * @type {short} - */ - Unit: number; - - /** - * Sets or returns the version info string for the application identity. - * @type {string} - */ - VersionInfo: string; - - /** - * Returns and sets the number of images you are willing to transfer per session. This is a runtime property. - * @type {short} - */ - XferCount: number; - - /** - * Returns or sets zoom factor for the image, only valid When the view mode is set to -1 by -1. - * @type {float} - */ - Zoom: number; - - /** - * Binds a specified function to an event, so that the function gets called whenever the event fires. - * @method WebTwain#RegisterEvent - * @param {string} name the name of the event that the function is bound to. - * @param {object} evt specifies the function to call when event fires. - * @return {bool} - */ - RegisterEvent(name: string, evt: object): boolean; - - // --- SCAN start -- - - /** - * Cancels all pending transfers. - * @method WebTwain#CancelAllPendingTransfers - * @return {bool} - */ - CancelAllPendingTransfers(): boolean; - - /** - * Closes Data Source. - * @method WebTwain#CloseSource - * @return {bool} - */ - CloseSource(): boolean; - - /** - * Closes and unloads Data Source Manager. - * @method WebTwain#CloseSourceManager - * @return {bool} - */ - CloseSourceManager(): boolean; - - /** - * Disable the source. If the source's user interface is displayed when the source is enabled, it will be closed. - * @method WebTwain#DisableSource - * @return {bool} - */ - DisableSource(): boolean; - - /** - * Sets the Source to eject the current page and advance the next page in the document feeder into the feeder acquire area when IfFeederEnabled is TRUE. - * @method WebTwain#FeedPage - * @return {bool} - */ - FeedPage(): boolean; - - /** - * Retrieve the device type of the currently selected data source, it might be a scanner, a web camera, etc. - * @method WebTwain#GetDeviceType - * @return {int} - */ - GetDeviceType(): number; - - /** - * Get the source name according to the source index. - * @method WebTwain#GetSourceNameItems - * @param {short} index int index. Index is 0-based and can not be greater than SourceCount property. - * @return {string} - */ - GetSourceNameItems(index: number): string; - - /** - * Loads the specified Source into main memory and causes its initialization, - * placing Dynamic Web TWAIN into Capability Negotiation state. If no source is - * specified (no SelectSource() or SelectSourceByIndex() is called), opens the default source. - * @method WebTwain#OpenSource - * @return {bool} - */ - OpenSource(): boolean; - - /** - * Loads and opens Data Source Manager. - * @method WebTwain#OpenSourceManager - * @return {bool} - */ - OpenSourceManager(): boolean; - - /** - * Reverts the current image layout to the Data Source's default. - * @method WebTwain#ResetImageLayout - * @return {bool} - */ - ResetImageLayout(): boolean; - - /** - * Sets the Source to return the current page to the input side of the document feeder and - * feed the last page from the outside of the feeder back into the acquisition area if IfFeederEnabled is TRUE. - * @method WebTwain#RewindPage - * @return {bool} - */ - RewindPage(): boolean; - - /** - * Brings up the TWAIN Data Source Manager's Source Selection User Interface (UI) - * so that user can choose which Data Source to be the current Source. - * @method WebTwain#SelectSource - * @return {bool} - */ - SelectSource(): boolean; - - /** - * Selects the index-the source in SourceNameItems property as the current source. - * @method WebTwain#SelectSourceByIndex - * @param {short} index It is the index of SourceNameItems property. - * @return {bool} - */ - SelectSourceByIndex(index: number): boolean; - - /** - * Sets file name and file format information used in File Transfer Mode. - * @method WebTwain#SetFileXferInfo - * @param {string} fileName the name of the file to be used in transfer. - * @param {EnumDWT_FileFormat} fileFormat an enumerated value indicates the format of the image. - * @return {bool} - */ - SetFileXferInfo(fileName: string, fileFormat: EnumDWT_FileFormat): boolean; - - /** - * Sets the left, top, right, and bottom sides of the image layout rectangle for the current Data Source. - * @method WebTwain#SetImageLayout - * @param {float} left specifies the floating point number for the left side of the image layout rectangle. - * @param {float} top specifies the floating point number for the top side of the image layout rectangle. - * @param {float} right specifies the floating point number for the right side of the image layout rectangle. - * @param {float} bottom specifies the floating point number for the bottom side of the image layout rectangle. - * @return {bool} - */ - SetImageLayout(left: number, top: number, right: number, bottom: number): boolean; - - /** - * Clears all the web forms which are used for image uploading. - * @method WebTwain#ClearAllHTTPFormField - * @return {bool} - */ - ClearAllHTTPFormField(): boolean; - - /** - * Clears the content of all custom tiff tags. - * @method WebTwain#ClearTiffCustomTag - * @return {void} - */ - ClearTiffCustomTag(): void; - - /** - * Check whether a certain file exists on the local disk. - * @method WebTwain#FileExists - * @param {string} localFile specifies the absolute path of the local file. - * @return {bool} - */ - FileExists(localFile: string): boolean; - - /** - * Downloads an image from the FTP server. - * @method WebTwain#FTPDownload - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPDownload(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Directly download a file from the FTP server to local disk without loading it into Dynamic Web TWAIN. - * @method WebTwain#FTPDownloadDirectly - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. - * @param {string} localFile specify a full path to store the file. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPDownloadDirectly(FTPServer: string, FTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Downloads an image from the FTP server. - * @method WebTwain#FTPDownloadEx - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. - * @param {EnumDWT_ImageType} lImageType simage format of the file to be downloaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPDownloadEx(FTPServer: string, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the image of a specified index in the buffer to the FTP server. - * @method WebTwain#FTPUpload - * @param {string} FTPServer the name of the FTP server. - * @param {short} sImageIndex specifies the index of the image in the buffer. The index is 0-based. - * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPUpload(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Directly upload a specific file to the FTP server without loading it into Dynamic Web TWAIN. - * @method WebTwain#FTPUploadDirectly - * @param {string} FTPServer the name of the FTP server. - * @param {string} localFile specify the the full path of a local file. - * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPUploadDirectly(FTPServer: string, localFile: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the image of a specified index in the buffer to the FTP server as a specified image format. - * @method WebTwain#FTPUploadEx - * @param {string} FTPServer the name of the FTP server. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. - * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPUploadEx(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads all images in buffer to the FTP server as Multi-Page TIFF. - * @method WebTwain#FTPUploadAllAsMultiPageTIFF - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPUploadAllAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads all images in buffer to the FTP server as Multi-Page PDF. - * @method WebTwain#FTPUploadAllAsPDF - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPUploadAllAsPDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the selected images in buffer to the FTP server as Multi-Page PDF. - * @method WebTwain#FTPUploadAsMultiPagePDF - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPUploadAsMultiPagePDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the selected images in buffer to the FTP server as Multi-Page TIFF. - * @method WebTwain#FTPUploadAsMultiPageTIFF - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - FTPUploadAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Downloads an image from the HTTP server. - * @method WebTwain#HTTPDownload - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} HTTPRemoteFile the name of the image to be downloaded. It should be the relative path of the file on the HTTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPDownload(HTTPServer: string, HTTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Directly downloads a file from the HTTP server to a local disk without loading it into Dynamic Web TWAIN. - * @method WebTwain#HTTPDownloadDirectly - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} HTTPRemoteFile The relative path of the file on the HTTP server. - * @param {string} localFile specify the location to store the downloaded file. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPDownloadDirectly(HTTPServer: string, HTTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Downloads an image from the HTTP server. - * @method WebTwain#HTTPDownloadEx - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) - * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPDownloadEx(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Download an image from the server using a HTTP Post call. - * @method WebTwain#HTTPDownloadThroughPost - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) - * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPDownloadThroughPost(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the image of a specified index in the buffer to the HTTP server through the HTTP POST method. - * @method WebTwain#HTTPUploadThroughPost - * @param {string} HTTPServer the name of the HTTP server. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {bool} - */ - HTTPUploadThroughPost(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Directly upload a specific local file to the HTTP server through the HTTP POST method without loading it into Dynamic Web TWAIN. - * @method WebTwain#HTTPUploadThroughPostDirectly - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} localFile specifies the path of a local file . - * @param {string} ActionPage the specified page for posting files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the file to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {bool} - */ - HTTPUploadThroughPostDirectly(HTTPServer: string, localFile: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP POST method. - * @method WebTwain#HTTPUploadThroughPostEx - * @param {string} HTTPServer the name of the HTTP server. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server.s - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadFailure. - * @return {bool} - */ - HTTPUploadThroughPostEx(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads all images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. - * @method WebTwain#HTTPUploadAllThroughPostAsMultiPageTIFF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {bool} - */ - HTTPUploadAllThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. - * @method WebTwain#HTTPUploadThroughPostAsMultiPageTIFF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {bool} - */ - HTTPUploadThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads all images in the buffer to the HTTP server through HTTP Post method as a Multi-Page PDF. - * @method WebTwain#HTTPUploadAllThroughPostAsPDF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {bool} - */ - HTTPUploadAllThroughPostAsPDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page PDF. - * @method WebTwain#HTTPUploadThroughPostAsMultiPagePDF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {bool} - */ - HTTPUploadThroughPostAsMultiPagePDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Directly uploads a specific local file to the HTTP server through the HTTP PUT method without loading it into Dynamic Web TWAIN. - * @method WebTwain#HTTPUploadThroughPutDirectly - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} localFile specifies the path of a local file. - * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPUploadThroughPutDirectly(HTTPServer: string, localFile: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server through the HTTP PUT method. - * @method WebTwain#HTTPUploadThroughPut - * @param {string} HTTPServer the name of the HTTP server. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} RemoteFileName the name of the image to be created on the HTTP server. It should a relative path on the web server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPUploadThroughPut(HTTPServer: string, sImageIndex: number, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP PUT method. - * @method WebTwain#HTTPUploadThroughPutEx - * @param {string} HTTPServer the name of the HTTP server. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. - * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPUploadThroughPutEx(HTTPServer: string, sImageIndex: number, RemoteFileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. - * @method WebTwain#HTTPUploadAllThroughPutAsMultiPageTIFF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} RemoteFileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPUploadAllThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. - * @method WebTwain#HTTPUploadThroughPutAsMultiPageTIFF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} RemoteFileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPUploadThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. - * @method WebTwain#HTTPUploadAllThroughPutAsPDF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} RemoteFileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPUploadAllThroughPutAsPDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. - * @method WebTwain#HTTPUploadThroughPutAsMultiPagePDF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} RemoteFileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPUploadThroughPutAsMultiPagePDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Configures how segmented upload is done. - * @method WebTwain#SetUploadSegment - * @param {int} segmentUploadThreshold specifies the threshold (in MB) over which segmented upload will be invoked. - * @param {int} moduleSize specifies the size of each segment (in KB). - * @return {bool} - */ - SetUploadSegment (segmentUploadThreshold: number, moduleSize: number): boolean; - - /** - * Uploads the images specified by the indices to the HTTP server. - * @method WebTwain#HTTPUpload - * @param {string} url the url where the images are sent in a POST request. - * @param {Array} indices indices specifies which images are to be uploaded. - * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be uploaded. - * @param {EnumDWT_UploadDataFormat} dataFormat whether to upload the images as binary or a base64-based string. - * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - HTTPUpload (url: string, indices: number[], enumImageType: EnumDWT_ImageType, dataFormat: EnumDWT_UploadDataFormat, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Loads a DIB format image from Clipboard into the Dynamic Web TWAIN. - * @method WebTwain#LoadDibFromClipboard - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - LoadDibFromClipboard(optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Loads an image into the Dynamic Web TWAIN. - * @method WebTwain#LoadImage - * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - LoadImage(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Loads an image into the Dynamic Web TWAIN. - * @method WebTwain#LoadImageEx - * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. - * @param {EnumDWT_ImageType} lImageType the image format of the file to be loaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - LoadImageEx(localFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Loads image from a base64 byte array with the specified file format. - * @method WebTwain#LoadImageFromBase64Binary - * @param {string} bry specifies the base64 string data. - * @param {EnumDWT_ImageType} lImageType specifies the file format. - * @return {bool} - */ - LoadImageFromBase64Binary(bry: string, lImageType: EnumDWT_ImageType): boolean; - - /** - * [Deprecated.] Loads image from a byte array with the specified file format. - * @method WebTwain#LoadImageFromBytes - * @param {int} lBufferSize Specifies the buffer size. - * @param {Array} buffer A byte array of the image data. - * @param {EnumDWT_ImageType} lImageType Specifies the file format. - * @return {bool} - */ - LoadImageFromBytes(lBufferSize: number, buffer: number[], lImageType: EnumDWT_ImageType): boolean; - - /** - * Saves all images in buffer as a MultiPage TIFF file. - * @method WebTwain#SaveAllAsMultiPageTIFF - * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - SaveAllAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves all images in buffer as a Multi-Page PDF file. - * @method WebTwain#SaveAllAsPDF - * @param {string} localFile the name of the Multi-Page PDF file to be saved. It should be an absolute path on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - SaveAllAsPDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the image of a specified index in buffer as a BMP file. - * @method WebTwain#SaveAsBMP - * @param {string} localFile the name of the BMP file to be saved. It should be an absolute path on the local disk. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - SaveAsBMP(localFile: string, sImageIndex: number): boolean; - - /** - * Saves the image of a specified index in buffer as a JPEG file. - * @method WebTwain#SaveAsJPEG - * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - SaveAsJPEG(localFile: string, sImageIndex: number): boolean; - - /** - * Saves the image of a specified index in buffer as a PDF file. - * @method WebTwain#SaveAsPDF - * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - SaveAsPDF(localFile: string, sImageIndex: number): boolean; - - /** - * Saves the image of a specified index in buffer as a PNG file. - * @method WebTwain#SaveAsPNG - * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - SaveAsPNG(localFile: string, sImageIndex: number): boolean; - - /** - * Saves the image of a specified index in buffer as a TIFF file. - * @method WebTwain#SaveAsTIFF - * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - SaveAsTIFF(localFile: string, sImageIndex: number): boolean; - - /** - * Saves the selected images in buffer as a Multipage PDF file. - * @method WebTwain#SaveSelectedImagesAsMultiPagePDF - * @param {string} localFile the name of the MultiPage PDF file to be saved. It should be an absolute path on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - SaveSelectedImagesAsMultiPagePDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the selected images in buffer as a Multipage TIFF file. - * @method WebTwain#SaveSelectedImagesAsMultiPageTIFF - * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - SaveSelectedImagesAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the selected images in buffer to base64 string. - * @method WebTwain#SaveSelectedImagesToBase64Binary - * @return {string} - */ - SaveSelectedImagesToBase64Binary(): string; - - /** - * [Deprecated.] Saves the selected images in buffer to a byte array in the specified file format. - * @method WebTwain#SaveSelectedImagesToBytes - * @param {int} bufferSize specified the buffer size. - * @param {Array} buffer A byte array of the image data. - * @return {int} - */ - SaveSelectedImagesToBytes(bufferSize: number, buffer: number[]): number; - - /** - * [Deprecated.] Sets current cookie into the Http Header to be used when uploading scanned images through POST. - * @method WebTwain#SetCookie - * @param {string} cookie the cookie on current page. - * @return {void} - */ - SetCookie(cookie: string): void; - - /** - * Sets a text parameter as a filed in a web form. This form is maintained by the component itself (meaning it's not on the page). All fields in this form will be passed to the server when uploading images. - * @method WebTwain#SetHTTPFormField - * @param {string} FieldName specifies the name of a text field in web form. - * @param {string} FieldValue specifies the value of a text field in web form. - * @return {bool} - */ - SetHTTPFormField(FieldName: string, FieldValue: string): boolean; - - /** - * Sets a custom tiff tag. Currently you can set up to 32 tags. The string to be set in a tag can be encoded with base64. - * @method WebTwain#SetTiffCustomTag - * @param {int} tag specifies the tag identifier. The value should be between 600 and 700. - * @param {string} content the string to be set for this tag. The string will be written to the .tiff file when you save/upload it. If the string is base64 encoded, we'll decode it before writing it. - * @param {bool} base64Str if you'd like to encode the string with base64, set this to true. Otherwise, the string will be plin text. - * @return {bool} - */ - SetTiffCustomTag(tag: number, content: string, base64Str: boolean): boolean; - - /** - * Show save file dialog or show open file dialog. - * @method WebTwain#ShowFileDialog - * @param {bool} SaveDialog True -- show save file dialog, False -- show open file dialog. - * @param {string} Filter The filter name specifies the filter pattern (for example, "*.TXT"). To specify multiple filter patterns for a single display string, use a semicolon to separate the patterns (for example, "*.TXT;*.DOC;*.BAK"). A pattern string can be a combination of valid file name characters and the asterisk (*) wildcard character. Do not include spaces in the pattern string. To retrieve a shortcut's target without filtering, use the string "All Files\0*.*\0\0", but the program will replace "\0" with "|" automatically. - * @param {int} FilterIndex The index of the currently selected filter in the File Types control. The buffer pointed to by Filter contains pairs of strings that define the filters. The index is 0-based. - * @param {string} DefExtension Define the default extension. GetOpenFileName and GetSaveFileName append this extension to the file name only if the user fails to type an extension. If this member is NULL and the user fails to type an extension, no extension is appended. - * @param {string} InitialDir The initial directory. The algorithm for selecting the initial directory varies on different platforms. - * @param {bool} AllowMultiSelect True -- allows users to select more than one file, False -- only allows to select one file. - * @param {bool} OverwritePrompt True -- If a file already exists with the same name, the old file will be simply overwritten, False -- not allows to save and overwrite a same name file. - * @param {int} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and parameters "AllowMultiSelect" and "OverwritePrompt" will be useless. - * @return {bool} - */ - ShowFileDialog(SaveDialog: boolean, Filter: string, FilterIndex: number, DefExtension: string, InitialDir: string, AllowMultiSelect: boolean, OverwritePrompt: boolean, Flags: number): boolean; - - /** - * Gets information of the capability specified by the Capability property. - * @method WebTwain#CapGet - * @return {bool} - */ - CapGet(): boolean; - - /** - * Returns the Source's current Value for the specified capability. - * @method WebTwain#CapGetCurrent - * @return {bool} - */ - CapGetCurrent(): boolean; - - /** - * Returns the Source's Default Value for the specified capability. This is the Source's preferred default value. - * @method WebTwain#CapGetDefault - * @return {bool} - */ - CapGetDefault(): boolean; - - /** - * Returns the value of the bottom-most edge of the specified frame. - * @method WebTwain#CapGetFrameBottom - * @param {short} index specifies the value of which frame to get. The index is 0-based. - * @return {float} - */ - CapGetFrameBottom(index: number): number; - - /** - * Returns the value (in Unit) of the left-most edge of the specified frame. - * @method WebTwain#CapGetFrameLeft - * @param {short} index specifies the value of which frame to get. The index is 0-based. - * @return {float} - */ - CapGetFrameLeft(index: number): number; - - /** - * Returns the value (in Unit) of the left-most edge of the specified frame. - * @method WebTwain#CapGetFrameRight - * @param {short} index specifies the value of which frame to get. The index is 0-based. - * @return {float} - */ - CapGetFrameRight(index: number): number; - - /** - * Returns the value (in Unit) of the top-most edge of the specified frame. - * @method WebTwain#CapGetFrameTop - * @param {short} index specifies the value of which frame to get. The index is 0-based. - * @return {float} - */ - CapGetFrameTop(index: number): number; - - /** - * Queries whether the Source supports a particular operation on the capability. - * @method WebTwain#CapIfSupported - * @param {EnumDWT_MessageType} messageType specifies the type of capability operation. - * @return {bool} - */ - CapIfSupported(messageType: EnumDWT_MessageType): boolean; - - /** - * Changes the Current Value of the capability specified by Capability property back to its power-on value. - * @method WebTwain#CapReset - * @return {bool} - */ - CapReset(): boolean; - - /** - * Sets the current capability using the container type specified by CapType property. The current capability is specified by Capability property. - * @method WebTwain#CapSet - * @return {bool} - */ - CapSet(): boolean; - - /** - * Sets the values of the specified frame. - * @method WebTwain#CapSetFrame - * @param {short} index specifies the values of which frame to set. The index is 0-based. - * @param {float} left the value (in Unit) of the left-most edge of the specified frame. - * @param {float} top the value (in Unit) of the top-most edge of the specified frame. - * @param {float} right the value (in Unit) of the right-most edge of the specified frame. - * @param {float} bottom the value (in Unit) of the bottom-most edge of the specified frame. - * @return {bool} - */ - CapSetFrame(index: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Get the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. - * @method WebTwain#GetCapItems - * @param {int} index Index is 0-based. It is the index of the cap item. - * @return {double} - */ - GetCapItems(index: number): number; - - /** - * Returns the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. - * @method WebTwain#GetCapItemsString - * @param {int} index Index is 0-based. It is the index of the cap item. - * @return {string} - */ - GetCapItemsString(index: number): string; - - /** - * Set the value of the specified cap item. - * @method WebTwain#SetCapItems - * @param {int} index Index is 0-based. It is the index of the cap item. - * @param {double} newVal The Double type of CapItems property is used to present Double, Single(float), Long, int and even boolean types. For string type, please use CapItemsstring property. - * @return {void} - */ - SetCapItems(index: number, newVal: number): void; - - /** - * Set the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. - * @method WebTwain#SetCapItemsString - * @param {int} index Index is 0-based. It is the index of the cap item. - * @param {string} newVal The new value to be set. - * @return {void} - */ - SetCapItemsString(index: number, newVal: string): void; - // --- SCAN end -- - - // --- View & Edit start -- - - /** - * Add text on an image. - * @method WebTwain#AddText - * @param {short} sImageIndex the index of the image that you want to add text to. - * @param {int} x the x coordinate for the text. - * @param {int} y the y coordinate for the text. - * @param {string} text the content of the text that you want to add. - * @param {int} txtColor the color for the text. - * @param {int} backgroundColor the background color. - * @param {float} backgroundRoundRadius ranging from 0 to 0.5. Please NOTE that MAC version does not support this parameter. - * @param {float} backgroundOpacity specifies the opacity of the background of the added text, it ranges from 0 to 1.0. Please NOTE that Mac version only supports value 0 and 1 - * @return {bool} - */ - AddText(sImageIndex: number, x: number, y: number, text: string, txtColor: number, backgroundColor: number, backgroundRoundRadius: number, backgroundOpacity: number): boolean; - - /** - * Create the font for adding text using the method AddText. - * @method WebTwain#CreateTextFont - * @param {int} height Specifies the desired height (in logical units) of the font.The absolute value of nHeight must not exceed 16,384 device units after it is converted.For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size or the smallest font if all the fonts exceed the requested size. - * @param {int} width Specifies the average width (in logical units) of characters in the font. If Width is 0, the aspect ratio of the device will be matched against the digitization aspect ratio of the available fonts to find the closest match, which is determined by the absolute value of the difference. - * @param {int} escapement Specifies the angle (in 0.1-degree units) between the escapement vector and the x-axis of the display surface. The escapement vector is the line through the origins of the first and last characters on a line. The angle is measured counterclockwise from the x-axis. - * @param {int} orientation Specifies the angle (in 0.1-degree units) between the baseline of a character and the x-axis.The angle is measured counterclockwise from the x-axis for coordinate systems in which the y-direction is down and clockwise from the x-axis for coordinate systems in which the y-direction is up. - * @param {int} weight Specifies the font weight (in inked pixels per 1000). The described valuesare approximate; the actual appearance depends on the typeface. Some fonts haveonly FW_NORMAL, FW_REGULAR, and FW_BOLD weights. If FW_DONTCARE is specified, a default weight is used. - * @param {short} italic Specifies an italic font if set to TRUE. - * @param {short} underline Specifies an underlined font if set to TRUE. - * @param {short} strikeOut A strikeout font if set to TRUE. - * @param {short} charSet Specifies the font's character set. The OEM character set is system-dependent. Fonts with other character sets may exist in the system. An application that uses a font with an unknown character set must not attempt to translate or interpret strings that are to be rendered with that font. - * @param {short} outputPrecision Specifies the desired output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, and pitch. - * @param {short} clipPrecision Specifies the desired clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. - * @param {short} quality Specifies the font's output quality, which defines how carefully the GDI must attempt to match the logical-font attributes to those of an actual physical font. - * @param {short} pitchAndFamily The pitch and family of the font. - * @param {string} faceName the typeface name, the length of this string must not exceed 32 characters, including the terminating null character. - * @return {bool} - */ - CreateTextFont(height: number, width: number, escapement: number, orientation: number, weight: number, italic: number, underline: number, strikeOut: number, charSet: number, outputPrecision: number, clipPrecision: number, quality: number, pitchAndFamily: number, faceName: string): boolean; - - /** - * Copies the image of a specified index in buffer to clipboard in DIB format. - * @method WebTwain#CopyToClipboard - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - CopyToClipboard(sImageIndex: number): boolean; - - /** - * Clears the specified area of a specified image, and fill the area with the fill color. - * @method WebTwain#Erase - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {bool} - */ - Erase(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Returns the pixel bit depth of the selected image. - * @method WebTwain#GetImageBitDepth - * @param {short} sImageIndex specifies the index of image. The index is 0-based. - * @return {short} - */ - GetImageBitDepth(sImageIndex: number): number; - - /** - * Returns the width (pixels) of the selected image. This is a read-only property. - * @method WebTwain#GetImageWidth - * @param {short} sImageIndex specifies the index of image. The index is 0-based. - * @return {int} - */ - GetImageWidth(sImageIndex: number): number; - - /** - * Returns the height (pixels) of the selected image. This is a read-only property. - * @method WebTwain#GetImageHeight - * @param {short} sImageIndex specifies the index of image. The index is 0-based. - * @return {int} - */ - GetImageHeight(sImageIndex: number): number; - - /** - * Returns the file size of the new image resized from the image of a specified index in buffer. - * @method WebTwain#GetImageSize - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} iWidth specifies the pixel width of the new image. - * @param {int} iHeight specifies the pixel height of the new image. - * @return {double} - */ - GetImageSize(sImageIndex: number, iWidth: number, iHeight: number): number; - - /** - * Pre-calculate the file size of the local image file that is saved from an image of a specified index in buffer. - * @method WebTwain#GetImageSizeWithSpecifiedType - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {short} sImageType specifies the type of an image file.. - * @return {int} - */ - GetImageSizeWithSpecifiedType(sImageIndex: number, sImageType: number): number; - - /** - * Return the horizontal resolution of the specified image. - * @method WebTwain#GetImageXResolution - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {int} - */ - GetImageXResolution(sImageIndex: number): number; - - /** - * Return the vertical resolution of the specified image. - * @method WebTwain#GetImageYResolution - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {int} - */ - GetImageYResolution(sImageIndex: number): number; - - /** - * Returns the index of the selected image. - * @method WebTwain#GetSelectedImageIndex - * @param {short} sSelectedIndex specifies the index of the selected image. - * @return {short} - */ - GetSelectedImageIndex(sSelectedIndex: number): number; - - /** - * You can use the method to select images programatically which is ususally done by mouse clicking. - * @method WebTwain#SetSelectedImageIndex - * @param {short} sSelectedIndex this is the index of an array that holds the indices of selected images. - * @param {short} newVal specifies the index of an image that you want to select. - * @return {void} - */ - SetSelectedImageIndex(selectedIndex: number, newVal: number): void; - - /** - * Pre-calculate the file size of the local image file that is saved from the selected images in buffer. - * @method WebTwain#GetSelectedImagesSize - * @param {int} iImageType specifies the type of an image file. - * @return {int} - */ - GetSelectedImagesSize(iImageType: number): number; - - /** - * Check the skew angle of an image by its index in buffer. - * @method WebTwain#GetSkewAngle - * @param {short} sImageIndex the index of the image in the buffer. - * @return {double} - */ - GetSkewAngle(sImageIndex: number): number; - - /** - * Check the skew angle of a rectangular part of an image by its index in buffer. - * @method WebTwain#GetSkewAngleEx - * @param {short} sImageIndex the index of the image in the buffer. - * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {double} - */ - GetSkewAngleEx(sImageIndex: number, left: number, top: number, right: number, bottom: number): number; - - /** - * [Deprecated.] Detects whether a certain area on an image is blank. - * @method WebTwain#IsBlankImageEx - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @param {bool} bFuzzyMatch specifies whether use fuzzy matching when detecting. - * @return {bool} - */ - IsBlankImageEx(sImageIndex: number, left: number, top: number, right: number, bottom: number, bFuzzyMatch: boolean): boolean; - - /** - * Mirrors the image of a specified index in buffer. - * @method WebTwain#Mirror - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - Mirror(sImageIndex: number): boolean; - - /** - * Decorates image of a specified index in buffer with rectangles of transparent color. - * @method WebTwain#OverlayRectangle - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @param {int} color Specifies the fill color of the rectangle. The byte-ordering of the RGB value is 0xBBGGRR. BB represents blue, GG represents green, RR represents red. - * @param {float} fOpacity Specifies the opacity of the rectangle. The value represents opacity. 1.0 is 100% opaque and 0.0 is totally transparent. - * @return {bool} - */ - OverlayRectangle(sImageIndex: number, left: number, top: number, right: number, bottom: number, color: number, fOpacity: number): boolean; - - /** - * Removes all images in buffer. - * @method WebTwain#RemoveAllImages - * @return {void} - */ - RemoveAllImages(): void; - - /** - * Removes selected images in buffer. - * @method WebTwain#RemoveAllSelectedImages - * @return {bool} - */ - RemoveAllSelectedImages(): boolean; - - /** - * Removes the image of a specified index in buffer. - * @method WebTwain#RemoveImage - * @param {short} sImageIndexToBeDeleted specifies the index of the image to be deleted in buffer. The index is 0-based. - * @return {bool} - */ - RemoveImage(sImageIndexToBeDeleted: number): boolean; - - // Image Operate - /** - * Rotates the image of a specified index in buffer by specified angle. - * @method WebTwain#Rotate - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {float} fAngle Specifies the rotation angle. - * @param {bool} bKeepSize Keep size or not. - * @return {bool} - */ - Rotate(sImageIndex: number, fAngle: number, bKeepSize: boolean): boolean; - - /** - * Rotates the image of a specified index in buffer by specified angle. - * @method WebTwain#RotateEx - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {float} fAngle Specifies the rotation angle. - * @param {bool} bKeepSize Keep size or not. - * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. - * @return {bool} - */ - RotateEx(sImageIndex: number, fAngle: number, bKeepSize: boolean, newVal: EnumDWT_InterpolationMethod): boolean; - - /** - * Rotates the image of a specified index in buffer by 90 degrees counter-clockwise. - * @method WebTwain#RotateLeft - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - RotateLeft(sImageIndex: number): boolean; - - /** - * Rotates the image of a specified index in buffer by 90 degrees clockwise. - * @method WebTwain#RotateRight - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - RotateRight(sImageIndex: number): boolean; - - /** - * Changes width and height of the image of a specified index in the buffer. Please note the file size of the image will be changed proportionately. - * @method WebTwain#ChangeImageSize - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} iNewWidth specifies the pixel width of the new image. - * @param {int} iNewHeight specifies the pixel height of the new image. - * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. - * @return {bool} - */ - ChangeImageSize(sImageIndex: number, iNewWidth: number, iNewHeight: number, newVal: EnumDWT_InterpolationMethod): boolean; - - /** - * Flips the image of a specified index in buffer. - * @method WebTwain#Flip - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - Flip(sImageIndex: number): boolean; - - /** - * Crops the image of a specified index in buffer. - * @method WebTwain#Crop - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {bool} - */ - Crop(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Crops the image of a specified index in buffer to clipboard in DIB format. - * @method WebTwain#CropToClipboard - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {bool} - */ - CropToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Cuts the image data in the specified area to the system clipboard in DIB format. - * @method WebTwain#CutFrameToClipboard - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {bool} - */ - CutFrameToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Cuts the image of a specified index in buffer to clipboard in DIB format. - * @method WebTwain#CutToClipboard - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - CutToClipboard(sImageIndex: number): boolean; - - /** - * Change the DPI (dots per inch) for the specified image. - * @method WebTwain#SetDPI - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} xResolution The horizontal resolution. - * @param {int} yResolution The vertical resolution. - * @param {bool} bResampleImage Whether to resample the image. (The image size will be changed if this is set to true). - * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. - * @return {bool} - */ - SetDPI(sImageIndex: number, xResolution: number, yResolution: number, bResampleImage: boolean, newVal: EnumDWT_InterpolationMethod): boolean; - - /** - * Sets the view mode that images are displayed in Dynamic Web TWAIN. You can use this method to display multiple images in Dynamic Web TWAIN. - * @method WebTwain#SetViewMode - * @param {short} sHorizontalImageCount specifies how many columns can be displayed in Dynamic Web TWAIN. - * @param {short} sVerticalImageCount specifies how many rows can be displayed in Dynamic Web TWAIN.. - * @return {void} - */ - SetViewMode(sHorizontalImageCount: number, sVerticalImageCount: number): void; - - /** - * Moves a specified image. - * @method WebTwain#MoveImage - * @param {short} sSourceImageIndex Specifies the source index of image in buffer. The index is 0-based. - * @param {short} sTargetImageIndex Specifies the target index of image in buffer. The index is 0-based. - * @return {bool} - */ - MoveImage(sSourceImageIndex: number, sTargetImageIndex: number): boolean; - - /** - * Switchs two images of specified indices in buffer. - * @method WebTwain#SwitchImage - * @param {short} sImageIndex1 specifies the index of image in buffer. The index is 0-based. - * @param {short} sImageIndex2 specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - SwitchImage(sImageIndex1: number, sImageIndex2: number): boolean; - - /** - * Shows the GUI of Image Printer. - * @method WebTwain#Print - * @return {bool} - */ - Print(): boolean; - // --- View & Edit end -- - - // --- Upload & Save end -- - - // --- Others --- - /** - * Shows the GUI of Image Editor. - * @method WebTwain#ShowImageEditor - * @return {bool} - */ - ShowImageEditor(): boolean; - - /** - * Unbinds an event from the specified function, so that the function stops receiving notifications when the event fires. - * @method WebTwain#UnregisterEvent - * @param {string} name the name of the event. - * @param {object} evt specified the function to be unbound. - * @return {bool} - */ - UnregisterEvent(name: string, evt: object): boolean; - // --- Others end --- - - /** - * Enables the source to accept image. - * @method WebTwain#EnableSource - * @return {bool} - */ - EnableSource(): boolean; - - /** - * Displays the source's built-in interface to acquire image. - * @method WebTwain#AcquireImage - * @param {object} optionalDeviceConfig a JS object used to set up the device for image acquisition. - * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - AcquireImage(optionalDeviceConfig?: object, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - // start from 10.0 - /** - * Change the width of an image in buffer. - * @method WebTwain#SetImageWidth - * @param {short} sImageIndex specifies which image you'd like to change. - * @param {int} iNewWidth specifies how wide you'd like to change the image. - * @return {bool} - */ - SetImageWidth(sImageIndex: number, iNewWidth: number): boolean; - - // Set custom DS data (DAT_CUSTOMDSDATA), the input string is encoded with base64 - /** - * Sets custom DS data to be used for scanning, the input string is encoded with base64. Custom DS data means a specific scanning profile. - * @method WebTwain#SetCustomDSDataEx - * @param {string} value the input string which is encoded with base64. - * @return {bool} - */ - SetCustomDSDataEx(value: string): boolean; - - // Set custom DS data, load data from the specified file - /** - * Sets custom DS data to be used for scanning, the data is stored in a file. Custom DS data means a specific scanning profile. - * @method WebTwain#SetCustomDSData - * @param {string} fileName the absolute path of the file where the custom data source data is stored. - * @return {bool} - */ - SetCustomDSData(fileName: string): boolean; - - // Get custom DS data, and returned string is encoded with base64 - /** - * Gets custom DS data, the returned string is base64 encoded. - * @method WebTwain#GetCustomDSDataEx - * @return {string} - */ - GetCustomDSDataEx(): string; - - // Get custom DS data, and save the data to the specified file - /** - * Gets custom DS data and save the data in a specified file. - * @method WebTwain#GetCustomDSData - * @param {string} fileName the path of the file used for storing custom DS data. - * @return {bool} - */ - GetCustomDSData(fileName: string): boolean; - - /** - * Changes the bitdepth of a specified image. - * @method WebTwain#ChangeBitDepth - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {short} sBitDepth specifies the target bit depth. - * @param {bool} bHighQuality specifies whether or not to keep high quality while changing the bit depth. When it's true, it takes more time. - * @return {bool} - */ - ChangeBitDepth(sImageIndex: number, sBitDepth: number, bHighQuality: boolean): boolean; - - /** - * Changes a specified image to gray scale. - * @method WebTwain#ConvertToGrayScale - * @param {short} sIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - ConvertToGrayScale(sIndex: number): boolean; - - /** - * [Deprecated.] Shows the GUI of Image Editor with custom settings. - * @method WebTwain#ShowImageEditorEx - * @param {int} x specifies the new position of the left top corner of the window. - * @param {int} y specifies the new position of the left top corner of the window. - * @param {int} cx specifies the width of the window. - * @param {int} cy specifies the height of the window. - * @param {int} nCmdShow specifices how the window should be shown. - * @return {bool} - */ - ShowImageEditorEx(x: number, y: number, cx: number, cy: number, nCmdShow: number): boolean; - - /** - * [Deprecated.] Detects whether an image is blank. - * @method WebTwain#IsBlankImage - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - IsBlankImage(sImageIndex: number): boolean; - - /** - * Detects whether a specific image is blank. - * @method WebTwain#IsBlankImageExpress - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {bool} - */ - IsBlankImageExpress(sImageIndex: number): boolean; - - /** - * [Deprecated.] Detects whether a specific image is blank. - * @method WebTwain#GetBarcodeInfo - * @param {int} barcodeInfoType Defined in TWAIN Specification. - * @param {int} barcodeIndex Specifies which barcode to check. The index is 0-based. - * @return {object} - */ - GetBarcodeInfo(barcodeInfoType: number, barcodeIndex: number): object; - - /** - * [Deprecated.] Gets the content from a specified barcode. - * @method WebTwain#GetBarcodeText - * @param {int} barcodeIndex Specifies which barcode to check. The index is 0-based. - * @return {bool} - */ - GetBarcodeText(barcodeIndex: number): boolean; - - /** - * Sets the default source to use. It's only valid when IfUseTWAINDSM is set to true. - * @method WebTwain#SetDefaultSource - * @param {short} sImageIndex specifies the index of the default source. The index is 0-based. - * @return {bool} - */ - SetDefaultSource(sImageIndex: number): boolean; - - /** - * Draws a rectangle on the viewer which represents the selected area. - * @method WebTwain#SetSelectedImageArea - * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {int} left The X axis of the left border. - * @param {int} top The Y axis of the top border. - * @param {int} right The X axis of the right border. - * @param {int} bottom The Y axis of the bottom border. - * @return {bool} - */ - SetSelectedImageArea(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Converts the images specified by the indices to base64. - * @method WebTwain#ConvertToBase64 - * @param {Array} indices indices specifies which images are to be converted to base64. - * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. - * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {bool} - */ - ConvertToBase64(indices: number[], enumImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Returns the direct URL of an image specified by index, if iWidth or iHeight is set to -1, you get the original image, otherwise you get the image with specified iWidth or iHeight while keeping the same aspect ratio. - * @method WebTwain#GetImageURL - * @param {short} index the index of the image. - * @param {int} iWidth the width of the image. - * @param {int} iHeight the height of the image. - * @return {string} - */ - GetImageURL(index: number, iWidth: number, iHeight: number): string; - - /** - * Sets a header for the current HTTP Post request. - * @method WebTwain#SetHTTPHeader - * @param {string} key the key of the header. - * @param {string} value the value of the header. - * @return {bool} - */ - SetHTTPHeader(key: string, value: string): boolean; +interface Base64Result { + getLength(): number; + getData(offset: number, length: number): string; + getMD5(): string; +} + +/** + * Copied from lib.d.ts (Typescript) + */ +interface Blob { + readonly size: number; + readonly type: string; + msClose(): void; + msDetachStream(): any; + slice(start?: number, end?: number, contentType?: string): Blob; +} + +/** + * Details for each license + */ +interface LicenseDetailItem { + readonly Browser: string; + readonly EnumLicenseType: string; + readonly ExpireDate: string; + readonly LicenseType: string; + readonly OS: string; + readonly Trial: string; + readonly Version: string; } diff --git a/types/dwt/index.d.ts b/types/dwt/index.d.ts index 12e4ac0521..78b0846eb7 100644 --- a/types/dwt/index.d.ts +++ b/types/dwt/index.d.ts @@ -1,3788 +1,17 @@ -// Type definitions for dwt 14.2 +// Type definitions for dwt 14.4 // Project: http://www.dynamsoft.com/Products/WebTWAIN_Overview.aspx // Definitions by: Xiao Ling // Josh Hall // Lincoln Hu // Tom Kent // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 - -/*! -* Based on Dynamsoft WebTwain JavaScript Intellisense -* Product: Dynamsoft Web Twain -* Web Site: http://www.dynamsoft.com -* -* Copyright 2018, Dynamsoft Corporation -* Author: Dynamsoft Support Team -* Version: 14.2 -*/ - -/** - * @namespace Dynamsoft - */ -declare namespace Dynamsoft { - namespace Lib { - /*ignored - Addon_Events Addon_Sendback_Events AttachAndShowImage BIO DOM DynamicLoadAddonFuns DynamicWebTwain EnumMouseButton - Errors Events IntToColorStr LS OnGetImageByURL OnGetImageFromServer Path ProgressBar UI Uri - addEventListener ajax all appendMessage appendRichMessage aryControlLoadImage attachAddon attachProperty - base64 bio cancelFrome clearMessage closeAll closeProgress colorStrToInt config css currentStyle - debug*/ - - let detect: { - /*ignored - OnCreatWS OnDetectNext OnWebTwainPostExecute OnWebTwainPreExecute StartWSByIPTimeoutId StartWSTimeoutId - aryReconnectSTwains arySTwains arySTwainsByIP bFirst bNeedUpgradeEvent bNoControlEvent bOK bPromptJSOrServerOutdated - cUrlIndex dcpCallbackType dcpStatus detectType getVersionArray global_dlg hideMask isDWTVersionLatest onNoControl - onNotAllowedForChrome ports scriptLoaded showMask starting tryTimes*/ - ssl: boolean; - }; - - /*ignored - detectButton dialog dialogShowStatus dlgProgress dlgRef drawBoxBorder drawImageWithHermite - each empty endsWith - */ - - let env: { - WSSession: number, WSVersion: string, - bChrome: boolean, bEdge: boolean, bFileSystem: boolean, bFirefox: boolean, - bIE: boolean, bLinux: boolean, bMac: boolean, bSafari: boolean, bWin: boolean, bWin64: boolean, - basePath: string, iPluginLength: number, isX64: boolean, pathType: number, - strChromeVersion: string, strFirefoxVersion: string, strIEVersion: string - }; - - /*ignored - error escapeHtml escapeRegExp extend filter fireEvent fromUnicode get getColor getCss - getElDimensions getHex getHexColor getHttpUrl getLogger getOffset getRandom getRealPath getScript - getWS getWSUrl getWheelDelta globalEval guid hide html5 imageControlCount indexOf install - io isArray isBoolean isDef isFunction isLocalIP isNaN isNull isNumber isObject - isPlainObject isString isUndef isUndefined isWindow keys log main makeArray mix - needShowTwiceShowDialog nil noop now obj one page param parse parseHTML parser - product progressMessage ready removeEventListener replaceAll replaceControl show showProgress startWS - startWSByIP startsWith stopPropagation stringify style support switchEvent tmp toggle trim - type unEscapeHtml unparam upperCaseFirst urlDecode urlEncode utf8 win - ...other internal ones - */ - } - namespace WebTwainEnv { - let ActiveXInstallWithCAB: boolean; - let ActiveXVersion: string; - let AutoLoad: boolean; - function CloseDialog(): void; - let ContainerMap: {}; - let Containers: Container[]; - function CreateDWTObject(newObjID: string, successFn: (dwtObject: WebTwain) => void, failurefn: (...args: any[]) => void): void; - function CreateDWTObject(newObjID: string, ip: number | string, port: number | string, portSSL: number | string, successFn: (dwtObject: WebTwain) => void, failurefn: (...args: any[]) => void): void; - let Debug: boolean; - function DeleteDWTObject(objID: string): void; - let DynamicContainers: string[]; - let DynamicDWTMap: {}; - function GetWebTwain(cid: string): WebTwain; - let IfUpdateService: boolean; - let IfUseActiveXForIE10Plus: boolean; - let JSVersion: string; - function Load(): void; - - /*ignored - OnWebTwainInitMessage OnWebTwainNeedUpgrade OnWebTwainNeedUpgradeWebJavascript OnWebTwainNotFound OnWebTwainOldPluginNotAllowed - */ - - function OnWebTwainPostExecute(): void; - function OnWebTwainPreExecute(): void; - - /*ignored - OnWebTwainReady - */ - - let PluginVersion: string; - let ProductKey: string; - function RegisterEvent(event: string, fn: (...args: any[]) => void): void; - function RemoveAllAuthorizations(): void; - let ResourcesPath: string; - let ServerVersionInfo: string; - function ShowDialog(_dialogWidth: number, _dialogHeight: number, _strDialogMessageWithHtmlFormat: string, _bChangeImage: boolean, bHideCloseButton: boolean): void; - let Trial: boolean; - function Unload(): void; - let UseDefaultInstallUI: boolean; - let initQueue: any[]; - let inited: boolean; - } -} - -/** Border Styles */ -declare enum EnumDWT_BorderStyle { - /** No border. */ - TWBS_NONE = 0, - /** Flat border. */ - TWBS_SINGLEFLAT = 1, - /** 3D border. */ - TWBS_SINGLE3D = 2 -} - -/** Capabilities */ -declare enum EnumDWT_Cap { - /** Nothing. */ - CAP_NONE = 0, - /** The application is willing to accept this number of images. */ - CAP_XFERCOUNT = 1, - /** Allows the application and Source to identify which compression schemes they have in - * common for Buffered Memory and File transfers. - * Note for File transfers: - * Since only certain file formats support compression, this capability must be negotiated after - * setting the desired file format with ICAP_IMAGEFILEFORMAT. - */ - ICAP_COMPRESSION = 256, - /** The type of pixel data that a Source is capable of acquiring (for example, black and white, gray, RGB, etc.). */ - ICAP_PIXELTYPE = 257, - /** Unless a quantity is dimensionless or uses a specified unit of measure, ICAP_UNITS determines - * the unit of measure for all quantities. - */ - ICAP_UNITS = 258, - /** Allows the application and Source to identify which transfer mechanisms the source supports. */ - ICAP_XFERMECH = 259, - /** The name or other identifying information about the Author of the image. It may include a copyright string. */ - CAP_AUTHOR = 4096, - /** A general note about the acquired image. */ - CAP_CAPTION = 4097, - /** If TRUE, Source must acquire data from the document feeder acquire area and other feeder - * capabilities can be used. If FALSE, Source must acquire data from the non-feeder acquire area - * and no other feeder capabilities can be used. - */ - CAP_FEEDERENABLED = 4098, - /** Reflect whether there are documents loaded in the Source's feeder. */ - CAP_FEEDERLOADED = 4099, - /** The date and time the image was acquired. - * Stored in the form "YYYY/MM/DD HH:mm:SS.sss" where YYYY is the year, MM is the - * numerical month, DD is the numerical day, HH is the hour, mm is the minute, SS is the second, - * and sss is the millisecond. - */ - CAP_TIMEDATE = 4100, - /** Returns a list of all the capabilities for which the Source will answer inquiries. Does not indicate - * which capabilities the Source will allow to be set by the application. Some capabilities can only - * be set if certain setup work has been done so the Source cannot globally answer which - * capabilities are "set-able." - */ - CAP_SUPPORTEDCAPS = 4101, - /** Allows the application and Source to negotiate capabilities to be used in States 5 and 6. */ - CAP_EXTENDEDCAPS = 4102, - /** If TRUE, the Source will automatically feed the next page from the document feeder after the - * number of frames negotiated for capture from each page are acquired. CAP_FEEDERENABLED - * must be TRUE to use this capability. - */ - CAP_AUTOFEED = 4103, - /** If TRUE, the Source will eject the current page being acquired from and will leave the feeder - * acquire area empty. - * If CAP_AUTOFEED is TRUE, a fresh page will be advanced. - * CAP_FEEDERENABLED must equal TRUE to use this capability. - * This capability must have been negotiated as an extended capability to be used in States 5 and 6. - */ - CAP_CLEARPAGE = 4104, - /** If TRUE, the Source will eject the current page and advance the next page in the document feeder - * into the feeder acquire area. - * If CAP_AUTOFEED is TRUE, the same action just described will occur and CAP_AUTOFEED will - * remain active. - * CAP_FEEDERENABLED must equal TRUE to use this capability. - * This capability must have been negotiated as an extended capability to be used in States 5 and 6. - */ - CAP_FEEDPAGE = 4105, - /** If TRUE, the Source will return the current page to the input side of the document feeder and - * feed the last page from the output side of the feeder back into the acquisition area. - * If CAP_AUTOFEED is TRUE, automatic feeding will continue after all negotiated frames from this - * page are acquired. - * CAP_FEEDERENABLED must equal TRUE to use this capability. - * This capability must have been negotiated as an extended capability to be used in States 5 and 6. - */ - CAP_REWINDPAGE = 4106, - /** If TRUE, the Source will display a progress indicator during acquisition and transfer, regardless - * of whether the Source's user interface is active. If FALSE, the progress indicator will be - * suppressed if the Source's user interface is inactive. - * The Source will continue to display device-specific instructions and error messages even with - * the Source user interface and progress indicators turned off. - */ - CAP_INDICATORS = 4107, - /** Returns a list of all the capabilities for which the Source will answer inquiries. Does not indicate - * which capabilities the Source will allow to be set by the application. Some capabilities can only - * be set if certain setup work has been done so the Source cannot globally answer which - * capabilities are "set-able." - */ - CAP_SUPPORTEDCAPSEXT = 4108, - /** This capability determines whether the device has a paper sensor that can detect documents on the ADF or Flatbed. */ - CAP_PAPERDETECTABLE = 4109, - /** If TRUE, indicates that this Source supports acquisition with the UI disabled; i.e., - * TW_USERINTERFACE's ShowUI field can be set to FALSE. If FALSE, indicates that this Source - * can only support acquisition with the UI enabled. - */ - CAP_UICONTROLLABLE = 4110, - /** If TRUE, the physical hardware (e.g., scanner, digital camera, image database, etc.) that - * represents the image source is attached, powered on, and communicating. - */ - CAP_DEVICEONLINE = 4111, - /** This capability is intended to boost the performance of a Source. The fundamental assumption - * behind AutoScan is that the device is able to capture the number of images indicated by the - * value of CAP_XFERCOUNT without waiting for the Application to request the image transfers. - * This is only possible if the device has internal buffers capable of caching the images it captures. - * The default behavior is undefined, because some high volume devices are incapable of anything - * but CAP_AUTOSCAN being equal to TRUE. However, if a Source supports FALSE, it should use it - * as the mandatory default, since this best describes the behavior of pre-1.8 TWAIN Applications. - */ - CAP_AUTOSCAN = 4112, - /** Allows an application to request the delivery of thumbnail representations for the set of images - * that are to be delivered. - * Setting CAP_THUMBNAILSENABLED to TRUE turns on thumbnail mode. Images transferred - * thereafter will be sent at thumbnail size (exact thumbnail size is determined by the Data Source). - * Setting this capability to FALSE turns thumbnail mode off and returns full size images. - */ - CAP_THUMBNAILSENABLED = 4113, - /** This indicates whether the scanner supports duplex. If so, it further indicates whether one-path - * or two-path duplex is supported. - */ - CAP_DUPLEX = 4114, - /** The user can set the duplex option to be TRUE or FALSE. If TRUE, the scanner scans both sides - * of a paper; otherwise, the scanner will scan only one side of the image. - */ - CAP_DUPLEXENABLED = 4115, - /** Allows an application to query a source to see if it implements the new user interface settings dialog. */ - CAP_ENABLEDSUIONLY = 4116, - CAP_CUSTOMDSDATA = 4117, - /** Allows the application to specify the starting endorser / imprinter number. All other endorser/ - * imprinter properties should be handled through the data source's user interface. - * The user can set the starting number for the endorser. - */ - CAP_ENDORSER = 4118, - /** Turns specific audible alarms on and off. */ - CAP_ALARMS = 4120, - /** The volume of a device's audible alarm. Note that this control affects the volume of all alarms; - * no specific volume control for individual types of alarms is provided. - */ - CAP_ALARMVOLUME = 4121, - /** The number of images to automatically capture. This does not refer to the number of images to - * be sent to the Application, use CAP_XFERCOUNT for that. - */ - CAP_AUTOMATICCAPTURE = 4122, - /** For automatic capture, this value selects the number of milliseconds before the first picture is to - * be taken, or the first image is to be scanned. - */ - CAP_TIMEBEFOREFIRSTCAPTURE = 4123, - /** For automatic capture, this value selects the milliseconds to wait between pictures taken, or images scanned. */ - CAP_TIMEBETWEENCAPTURES = 4124, - /** CapGet() reports the presence of data in the scanner's buffers. CapSet() with a value of TWCB_CLEAR immediately clears the buffers. */ - CAP_CLEARBUFFERS = 4125, - /** Describes the number of pages that the scanner can buffer when CAP_AUTOSCAN is enabled. */ - CAP_MAXBATCHBUFFERS = 4126, - /** The date and time of the device's clock. - * Managed in the form "YYYY/MM/DD HH:mm:SS:sss" where YYYY is the year, MM is the - * numerical month, DD is the numerical day, HH is the hour, mm is the minute, SS is the second, - * and sss is the millisecond. - */ - CAP_DEVICETIMEDATE = 4127, - /** CapGet() reports the kinds of power available to the device. CapGetCurrent() reports the current power supply in use. */ - CAP_POWERSUPPLY = 4128, - /** This capability queries the Source for UI support for preview mode. If TRUE, the Source supports preview UI. */ - CAP_CAMERAPREVIEWUI = 4129, - /** A string containing the serial number of the currently selected device in the Source. Multiple - * devices may all report the same serial number. - */ - CAP_SERIALNUMBER = 4132, - /** CapGet() returns the current list of available printer devices, along with the one currently being used for negotiation. - * CapSet() selects the current device for negotiation, and optionally constrains the list. - * Top/Bottom refers to duplex devices, and indicates if the printer is writing on the top or the bottom of the sheet of paper. - * Simplex devices use the top settings. Before/After indicates whether printing occurs before or after the sheet of paper has been scanned. - */ - CAP_PRINTER = 4134, - /** Turns the current CAP_PRINTER device on or off. */ - CAP_PRINTERENABLED = 4135, - /** The User can set the starting number for the current CAP_PRINTER device. */ - CAP_PRINTERINDEX = 4136, - /** Specifies the appropriate current CAP_PRINTER device mode. - * Note: - * • TWPM_SINGLESTRING specifies that the printed text will consist of a single string. - * • TWPM _MULTISTRING specifies that the printed text will consist of an enumerated list of - * strings to be printed in order. - * • TWPM _COMPOUNDSTRING specifies that the printed string will consist of a compound of a - * String followed by a value followed by a suffix string. - */ - CAP_PRINTERMODE = 4137, - /** Specifies the string(s) that are to be used in the string component when the current - * CAP_PRINTER device is enabled. - */ - CAP_PRINTERSTRING = 4138, - /** Specifies the string that shall be used as the current CAP_PRINTER device's suffix. */ - CAP_PRINTERSUFFIX = 4139, - /** Allows Application and Source to identify which languages they have in common for the exchange of string data, - * and to select the language of the internal UI. Since the TWLG_xxxx codes include language and country data, there is no separate - * capability for selecting the country. - */ - CAP_LANGUAGE = 4140, - /** Helps the Application determine any special actions it may need to take when negotiating - * frames with the Source. Allowed values are listed in . - * TWFA_NONE: The alignment is free-floating. Applications should assume - * that the origin for frames is on the left. - * TWFA_LEFT: The alignment is to the left. - * TWFA_CENTER: The alignment is centered. This means that the paper will - * be fed in the middle of the ICAP_PHYSICALWIDTH of the - * device. If this is set, then the Application should calculate - * any frames with a left offset of zero. - * TWFA_RIGHT: The alignment is to the right. - */ - CAP_FEEDERALIGNMENT = 4141, - /** TWFO_FIRSTPAGEFIRST if the feeder starts with the top of the first page. - * TWFO_LASTPAGEFIRST is the feeder starts with the top of the last page. - */ - CAP_FEEDERORDER = 4142, - /** Indicates whether the physical hardware (e.g. scanner, digital camera) is capable of acquiring - * multiple images of the same page without changes to the physical registration of that page. - */ - CAP_REACQUIREALLOWED = 4144, - /** The minutes of battery power remaining to the device. */ - CAP_BATTERYMINUTES = 4146, - /** When used with CapGet(), return the percentage of battery power level on camera. If -1 is returned, it indicates that the battery is not present. */ - CAP_BATTERYPERCENTAGE = 4147, - /** Added 1.91 */ - CAP_CAMERASIDE = 4148, - /** Added 1.91 */ - CAP_SEGMENTED = 4149, - /** Added 2.0 */ - CAP_CAMERAENABLED = 4150, - /** Added 2.0 */ - CAP_CAMERAORDER = 4151, - /** Added 2.0 */ - CAP_MICRENABLED = 4152, - /** Added 2.0 */ - CAP_FEEDERPREP = 4153, - /** Added 2.0 */ - CAP_FEEDERPOCKET = 4154, - /** Added 2.1 */ - CAP_AUTOMATICSENSEMEDIUM = 4155, - /** Added 2.1 */ - CAP_CUSTOMINTERFACEGUID = 4156, - /** TRUE enables and FALSE disables the Source's Auto-brightness function (if any). */ - ICAP_AUTOBRIGHT = 4352, - /** The brightness values available within the Source. */ - ICAP_BRIGHTNESS = 4353, - /** The contrast values available within the Source. */ - ICAP_CONTRAST = 4355, - /** Specifies the square-cell halftone (dithering) matrix the Source should use to halftone the image. */ - ICAP_CUSTHALFTONE = 4356, - /** Specifies the exposure time used to capture the image, in seconds. */ - ICAP_EXPOSURETIME = 4357, - /** Describes the color characteristic of the subtractive filter applied to the image data. Multiple - * filters may be applied to a single acquisition. - */ - ICAP_FILTER = 4358, - /** Specifies whether or not the image was acquired using a flash. */ - ICAP_FLASHUSED = 4359, - /** Gamma correction value for the image data. */ - ICAP_GAMMA = 4360, - /** A list of names of the halftone patterns available within the Source. */ - ICAP_HALFTONES = 4361, - /** Specifies which value in an image should be interpreted as the lightest "highlight." All values - * "lighter" than this value will be clipped to this value. Whether lighter values are smaller or - * larger can be determined by examining the Current value of ICAP_PIXELFLAVOR. - */ - ICAP_HIGHLIGHT = 4362, - /** Informs the application which file formats the Source can generate (CapGet()). Tells the Source which file formats the application can handle (CapSet()). - * TWFF_TIFF Used for document - * TWFF_PICT Native Macintosh - * TWFF_BMP Native Microsoft - * TWFF_XBM Used for document - * TWFF_JFIF Wrapper for JPEG - * TWFF_FPX FlashPix, used with digital - * TWFF_TIFFMULTI Multi-page TIFF files - * TWFF_PNG An image format standard intended for use on the web, replaces GIF - * TWFF_SPIFF A standard from JPEG, intended to replace JFIF, also supports JBIG - * TWFF_EXIF File format for use with digital cameras. - */ - ICAP_IMAGEFILEFORMAT = 4364, - /** TRUE means the lamp is currently, or should be set to ON. Sources may not support CapSet() operations. */ - ICAP_LAMPSTATE = 4365, - /** Describes the general color characteristic of the light source used to acquire the image. */ - ICAP_LIGHTSOURCE = 4366, - /** Defines which edge of the "paper" the image's "top" is aligned with. This information is used to adjust the frames to match the - * scanning orientation of the paper. For instance, if an ICAP_SUPPORTEDSIZE of TWSS_ISOA4 has been negotiated, - * and ICAP_ORIENTATION is set to TWOR_LANDSCAPE, then the Source must rotate the frame it downloads to the scanner to reflect the - * orientation of the paper. Please note that setting ICAP_ORIENTATION does not affect the values reported by ICAP_FRAMES; - * it just causes the Source to use them in a different way. The upper-left of the image is defined as the location where both the primary and - * secondary scans originate. (The X axis is the primary scan direction and the Y axis is the secondary scan direction.) - * For a flatbed scanner, the light bar moves in the secondary scan direction. For a handheld scanner, the scanner is drug in the - * secondary scan direction. For a digital camera, the secondary direction is the vertical axis when the viewed image is considered upright. - */ - ICAP_ORIENTATION = 4368, - /** The maximum physical width (X-axis) the Source can acquire (measured in units of ICAP_UNITS). */ - ICAP_PHYSICALWIDTH = 4369, - /** The maximum physical height (Y-axis) the Source can acquire (measured in units of ICAP_UNITS). */ - ICAP_PHYSICALHEIGHT = 4370, - /** Specifies which value in an image should be interpreted as the darkest "shadow." All values - * "darker" than this value will be clipped to this value. - */ - ICAP_SHADOW = 4371, - /** The list of frames the Source will acquire on each page. */ - ICAP_FRAMES = 4372, - /** The native optical resolution along the X-axis of the device being controlled by the Source. Most - * devices will respond with a single value (TW_ONEVALUE). - * This is NOT a list of all resolutions that can be generated by the device. Rather, this is the - * resolution of the device's optics. Measured in units of pixels per unit as defined by - * ICAP_UNITS (pixels per TWUN_PIXELS yields dimensionless data). - */ - ICAP_XNATIVERESOLUTION = 4374, - /** The native optical resolution along the Y-axis of the device being controlled by the Source. - * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS - * yields dimensionless data). - */ - ICAP_YNATIVERESOLUTION = 4375, - /** All the X-axis resolutions the Source can provide. - * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS - * yields dimensionless data). That is, when the units are TWUN_PIXELS, both - * ICAP_XRESOLUTION and ICAP_YRESOLUTION shall report 1 pixel/pixel. Some data sources - * like to report the actual number of pixels that the device reports, but that response is more - * appropriate in ICAP_PHYSICALHEIGHT and ICAP_PHYSICALWIDTH. - */ - ICAP_XRESOLUTION = 4376, - /** All the Y-axis resolutions the Source can provide. - * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS - * yields dimensionless data). That is, when the units are TWUN_PIXELS, both - * ICAP_XRESOLUTION and ICAP_YRESOLUTION shall report 1 pixel/pixel. Some data sources - * like to report the actual number of pixels that the device reports, but that response is more - * appropriate in ICAP_PHYSICALHEIGHT and ICAP_PHYSICALWIDTH. - */ - ICAP_YRESOLUTION = 4377, - /** The maximum number of frames the Source can provide or the application can accept per page. - * This is a bounding capability only. It does not establish current or future behavior. - */ - ICAP_MAXFRAMES = 4378, - /** This is used with buffered memory transfers. If TRUE, Source can provide application with tiled image data. */ - ICAP_TILES = 4379, - /** Specifies how the bytes in an image are filled by the Source. TWBO_MSBFIRST indicates that the leftmost bit in the byte (usually bit 7) is - * the byte's Most Significant Bit. - */ - ICAP_BITORDER = 4380, - /** Used for CCITT Group 3 2-dimensional compression. The 'K' factor indicates how often the - * new compression baseline should be re-established. A value of 2 or 4 is common in facsimile - * communication. A value of zero in this field will indicate an infinite K factor—the baseline is - * only calculated at the beginning of the transfer. - */ - ICAP_CCITTKFACTOR = 4381, - /** Describes whether the image was captured transmissively or reflectively. */ - ICAP_LIGHTPATH = 4382, - /** Sense of the pixel whose numeric value is zero (minimum data value). */ - ICAP_PIXELFLAVOR = 4383, - /** Allows the application and Source to identify which color data formats are available. There are - * two options, "planar" and "chunky." - */ - ICAP_PLANARCHUNKY = 4384, - /** How the Source can/should rotate the scanned image data prior to transfer. This doesn't use - * ICAP_UNITS. It is always measured in degrees. Any applied value is additive with any - * rotation specified in ICAP_ORIENTATION. - */ - ICAP_ROTATION = 4385, - /** For devices that support fixed frame sizes. - * Defined sizes match typical page sizes. This specifies the size(s) the Source can/should use to acquire image data. - */ - ICAP_SUPPORTEDSIZES = 4386, - /** Specifies the dividing line between black and white. This is the value the Source will use to - * threshold, if needed, when ICAP_PIXELTYPE:TWPT_BW. - * The value is normalized so there are no units of measure associated with this ICAP. - */ - ICAP_THRESHOLD = 4387, - /** All the X-axis scaling values available. A value of '1.0' is equivalent to 100% scaling. Do not use values less than or equal to zero. */ - ICAP_XSCALING = 4388, - /** All the Y-axis scaling values available. A value of '1.0' is equivalent to 100% scaling. Do not use values less than or equal to zero. - * There are no units inherent with this data as it is normalized to 1.0 being "unscaled." - */ - ICAP_YSCALING = 4389, - /** Used for CCITT data compression only. Indicates the bit order representation of the stored compressed codes. */ - ICAP_BITORDERCODES = 4390, - /** Used only for CCITT data compression. Specifies whether the compressed codes' pixel "sense" - * will be inverted from the Current value of ICAP_PIXELFLAVOR prior to transfer. - */ - ICAP_PIXELFLAVORCODES = 4391, - /** Allows the application and Source to agree upon a common set of color descriptors that are - * made available by the Source. This ICAP is only useful for JPEG-compressed buffered memory image transfers. - */ - ICAP_JPEGPIXELTYPE = 4392, - /** Used only with CCITT data compression. Specifies the minimum number of words of compressed codes (compressed data) to be transmitted per line. */ - ICAP_TIMEFILL = 4394, - /** Specifies the pixel bit depths for the Current value of ICAP_PIXELTYPE. For example, when - * using ICAP_PIXELTYPE:TWPT_GRAY, this capability specifies whether this is 8-bit gray or 4-bit gray. - * This depth applies to all the data channels (for instance, the R, G, and B channels will all have - * this same bit depth for RGB data). - */ - ICAP_BITDEPTH = 4395, - /** Specifies the Reduction Method the Source should use to reduce the bit depth of the data. Most - * commonly used with ICAP_PIXELTYPE:TWPT_BW to reduce gray data to black and white. - */ - ICAP_BITDEPTHREDUCTION = 4396, - /** If TRUE the Source will issue a MSG_XFERREADY before starting the scan. - * Note: The Source may need to scan the image before initiating the transfer. This is the case if - * the scanned image is rotated or merged with another scanned image. - */ - ICAP_UNDEFINEDIMAGESIZE = 4397, - /** Allows the application to query the data source to see if it supports extended image attribute capabilities, - * such as Barcode Recognition, Shaded Area Detection and Removal, Skew detection and Removal, and so on. - */ - ICAP_EXTIMAGEINFO = 4399, - /** Allows the source to define the minimum height (Y-axis) that the source can acquire. */ - ICAP_MINIMUMHEIGHT = 4400, - /** Allows the source to define theminimum width (X-axis) that the source can acquire. */ - ICAP_MINIMUMWIDTH = 4401, - /** Use this capability to have the Source discard blank images. The Application never sees these - * images during the scanning session. - * TWBP_DISABLE – this must be the default state for the Source. It indicates that all images will - * be delivered to the Application, none of them will be discarded. - * TWBP_AUTO – if this is used, then the Source will decide if an image is blank or not and discard - * as appropriate. - * If the specified value is a positive number in the range 0 to 231–1, then this capability will use it - * as the byte size cutoff point to identify which images are to be discarded. If the size of the image - * is less than or equal to this value, then it will be discarded. If the size of the image is greater - * than this value, then it will be kept so that it can be transferred to the Application. - */ - ICAP_AUTODISCARDBLANKPAGES = 4404, - /** Flip rotation is used to properly orient images that flip orientation every other image. - * TWFR_BOOK The images to be scanned are viewed in book form, flipping each page from left to right or right to left. - * TWFR_FANFOLD The images to be scanned are viewed in fanfold paper style, flipping each page up or down. - */ - ICAP_FLIPROTATION = 4406, - /** Turns bar code detection on and off. */ - ICAP_BARCODEDETECTIONENABLED = 4407, - /** Provides a list of bar code types that can be detected by the current Data Source. */ - ICAP_SUPPORTEDBARCODETYPES = 4408, - /** The maximum number of supported search priorities. */ - ICAP_BARCODEMAXSEARCHPRIORITIES = 4409, - /** A prioritized list of bar code types dictating the order in which bar codes will be sought. */ - ICAP_BARCODESEARCHPRIORITIES = 4410, - /** Restricts bar code searching to certain orientations, or prioritizes one orientation over the other. */ - ICAP_BARCODESEARCHMODE = 4411, - /** Restricts the number of times a search will be retried if none are found on each page. */ - ICAP_BARCODEMAXRETRIES = 4412, - /** Restricts the total time spent on searching for a bar code on each page. */ - ICAP_BARCODETIMEOUT = 4413, - /** When used with CapGet(), returns all camera supported lens zooming range. */ - ICAP_ZOOMFACTOR = 4414, - /** Turns patch code detection on and off. */ - ICAP_PATCHCODEDETECTIONENABLED = 4415, - /** A list of patch code types that may be detected by the current Data Source. */ - ICAP_SUPPORTEDPATCHCODETYPES = 4416, - /** The maximum number of supported search priorities. */ - ICAP_PATCHCODEMAXSEARCHPRIORITIES = 4417, - /** A prioritized list of patch code types dictating the order in which patch codes will be sought. */ - ICAP_PATCHCODESEARCHPRIORITIES = 4418, - /** Restricts patch code searching to certain orientations, or prioritizes one orientation over the other. */ - ICAP_PATCHCODESEARCHMODE = 4419, - /** Restricts the number of times a search will be retried if none are found on each page. */ - ICAP_PATCHCODEMAXRETRIES = 4420, - /** Restricts the total time spent on searching for a patch code on each page. */ - ICAP_PATCHCODETIMEOUT = 4421, - /** For devices that support flash. CapSet() selects the flash to be used (if any). CapGet() reports the current setting. - * This capability replaces ICAP_FLASHUSED, which is only able to negotiate the flash being on or off. - */ - ICAP_FLASHUSED2 = 4422, - /** For devices that support image enhancement filtering. This capability selects the algorithm used to improve the quality of the image. */ - ICAP_IMAGEFILTER = 4423, - /** For devices that support noise filtering. This capability selects the algorithm used to remove noise. */ - ICAP_NOISEFILTER = 4424, - /** Overscan is used to scan outside of the boundaries described by ICAP_FRAMES, and is used to help acquire image data that - * may be lost because of skewing. - * This is primarily of use for transport scanners which rely on edge detection to begin scanning. - * If overscan is supported, then the device is capable of scanning in the inter-document gap to get the skewed image information. - */ - ICAP_OVERSCAN = 4425, - /** Turns automatic border detection on and off. */ - ICAP_AUTOMATICBORDERDETECTION = 4432, - /** Turns automatic deskew correction on and off. */ - ICAP_AUTOMATICDESKEW = 4433, - /** When TRUE this capability depends on intelligent features within the Source to automatically - * rotate the image to the correct position. - */ - ICAP_AUTOMATICROTATE = 4434, - /** Added 1.9 */ - ICAP_JPEGQUALITY = 4435, - /** Added 1.91 */ - ICAP_FEEDERTYPE = 4436, - /** Added 1.91 */ - ICAP_ICCPROFILE = 4437, - /** Added 2.0 */ - ICAP_AUTOSIZE = 4438, - /** Added 2.1 */ - ICAP_AUTOMATICCROPUSESFRAME = 4439, - /** Added 2.1 */ - ICAP_AUTOMATICLENGTHDETECTION = 4440, - /** Added 2.1 */ - ICAP_AUTOMATICCOLORENABLED = 4441, - /** Added 2.1 */ - ICAP_AUTOMATICCOLORNONCOLORPIXELTYPE = 4442, - /** Added 2.1 */ - ICAP_COLORMANAGEMENTENABLED = 4443, - /** Added 2.1 */ - ICAP_IMAGEMERGE = 4444, - /** Added 2.1 */ - ICAP_IMAGEMERGEHEIGHTTHRESHOLD = 4445, - /** Added 2.1 */ - ICAP_SUPPORTEDEXTIMAGEINFO = 4446 -} - -/** ICAP_BITORDER values. */ -declare enum EnumDWT_CapBitOrder { - TWBO_LSBFIRST = 0, - /** Indicates that the leftmost bit in the byte (usually bit 7) is the byte's Most Significant Bit. */ - TWBO_MSBFIRST = 1 -} - -/** ICAP_BITDEPTHREDUCTION values. */ -declare enum EnumDWT_CapBitdepthReduction { - TWBR_THRESHOLD = 0, - TWBR_HALFTONE = 1, - TWBR_CUSTHALFTONE = 2, - TWBR_DIFFUSION = 3 -} - -/** CAP_FEEDERALIGNMENT values. */ -declare enum EnumDWT_CapFeederAlignment { - /** The alignment is free-floating. Applications should assume that the origin for frames is on the left. */ - TWFA_NONE = 0, - /** The alignment is to the left. */ - TWFA_LEFT = 1, - /** The alignment is centered. This means that the paper will be fed in the middle of the ICAP_PHYSICALWIDTH of the - * device. If this is set, then the Application should calculate any frames with a left offset of zero. - */ - TWFA_CENTER = 2, - /** The alignment is to the right. */ - TWFA_RIGHT = 3 -} - -/** CAP_FEEDERORDER values. */ -declare enum EnumDWT_CapFeederOrder { - /** The feeder starts with the top of the first page. */ - TWFO_FIRSTPAGEFIRST = 0, - /** The feeder starts with the top of the last page. */ - TWFO_LASTPAGEFIRST = 1 -} - -/** ICAP_FILTER values. */ -declare enum EnumDWT_CapFilterType { - TWFT_RED = 0, - TWFT_GREEN = 1, - TWFT_BLUE = 2, - TWFT_NONE = 3, - TWFT_WHITE = 4, - TWFT_CYAN = 5, - TWFT_MAGENTA = 6, - TWFT_YELLOW = 7, - TWFT_BLACK = 8 -} - -/** ICAP_FLASHUSED2 values. */ -declare enum EnumDWT_CapFlash { - TWFL_NONE = 0, - TWFL_OFF = 1, - TWFL_ON = 2, - TWFL_AUTO = 3, - TWFL_REDEYE = 4 -} - -/** ICAP_FLIPROTATION values. */ -declare enum EnumDWT_CapFlipRotation { - /** The images to be scanned are viewed in book form, flipping each page from left to right or right to left. */ - TWFR_BOOK = 0, - /** The images to be scanned are viewed in fanfold paper style, flipping each page up or down. */ - TWFR_FANFOLD = 1 -} - -/** ICAP_IMAGEFILTER values. */ -declare enum EnumDWT_CapImageFilter { - TWIF_NONE = 0, - TWIF_AUTO = 1, - /** Good for halftone images. */ - TWIF_LOWPASS = 2, - /** Good for improving text. */ - TWIF_BANDPASS = 3, - /** Good for improving fine lines. */ - TWIF_HIGHPASS = 4, - TWIF_TEXT = 3, - TWIF_FINELINE = 4 -} - -/** CAP_LANGUAGE values. */ -declare enum EnumDWT_CapLanguage { - /** Danish */ - TWLG_DAN = 0, - /** Dutch */ - TWLG_DUT = 1, - /** International English */ - TWLG_ENG = 2, - /** French Canadian */ - TWLG_FCF = 3, - /** Finnish */ - TWLG_FIN = 4, - /** French */ - TWLG_FRN = 5, - /** German */ - TWLG_GER = 6, - /** Icelandic */ - TWLG_ICE = 7, - /** Italian */ - TWLG_ITN = 8, - /** Norwegian */ - TWLG_NOR = 9, - /** Portuguese */ - TWLG_POR = 10, - /** Spanish */ - TWLG_SPA = 11, - /** Swedish */ - TWLG_SWE = 12, - /** U.S. English */ - TWLG_USA = 13, - /** Added for 1.8 */ - TWLG_USERLOCALE = -1, - TWLG_AFRIKAANS = 14, - TWLG_ALBANIA = 15, - TWLG_ARABIC = 16, - TWLG_ARABIC_ALGERIA = 17, - TWLG_ARABIC_BAHRAIN = 18, - TWLG_ARABIC_EGYPT = 19, - TWLG_ARABIC_IRAQ = 20, - TWLG_ARABIC_JORDAN = 21, - TWLG_ARABIC_KUWAIT = 22, - TWLG_ARABIC_LEBANON = 23, - TWLG_ARABIC_LIBYA = 24, - TWLG_ARABIC_MOROCCO = 25, - TWLG_ARABIC_OMAN = 26, - TWLG_ARABIC_QATAR = 27, - TWLG_ARABIC_SAUDIARABIA = 28, - TWLG_ARABIC_SYRIA = 29, - TWLG_ARABIC_TUNISIA = 30, - /** United Arabic Emirates */ - TWLG_ARABIC_UAE = 31, - TWLG_ARABIC_YEMEN = 32, - TWLG_BASQUE = 33, - TWLG_BYELORUSSIAN = 34, - TWLG_BULGARIAN = 35, - TWLG_CATALAN = 36, - TWLG_CHINESE = 37, - TWLG_CHINESE_HONGKONG = 38, - /** People's Republic of China */ - TWLG_CHINESE_PRC = 39, - TWLG_CHINESE_SINGAPORE = 40, - TWLG_CHINESE_SIMPLIFIED = 41, - TWLG_CHINESE_TAIWAN = 42, - TWLG_CHINESE_TRADITIONAL = 43, - TWLG_CROATIA = 44, - TWLG_CZECH = 45, - TWLG_DANISH = 0, - TWLG_DUTCH = 1, - TWLG_DUTCH_BELGIAN = 46, - TWLG_ENGLISH = 2, - TWLG_ENGLISH_AUSTRALIAN = 47, - TWLG_ENGLISH_CANADIAN = 48, - TWLG_ENGLISH_IRELAND = 49, - TWLG_ENGLISH_NEWZEALAND = 50, - TWLG_ENGLISH_SOUTHAFRICA = 51, - TWLG_ENGLISH_UK = 52, - TWLG_ENGLISH_USA = 13, - TWLG_ESTONIAN = 53, - TWLG_FAEROESE = 54, - TWLG_FARSI = 55, - TWLG_FINNISH = 4, - TWLG_FRENCH = 5, - TWLG_FRENCH_BELGIAN = 56, - TWLG_FRENCH_CANADIAN = 3, - TWLG_FRENCH_LUXEMBOURG = 57, - TWLG_FRENCH_SWISS = 58, - TWLG_GERMAN = 6, - TWLG_GERMAN_AUSTRIAN = 59, - TWLG_GERMAN_LUXEMBOURG = 60, - TWLG_GERMAN_LIECHTENSTEIN = 61, - TWLG_GERMAN_SWISS = 62, - TWLG_GREEK = 63, - TWLG_HEBREW = 64, - TWLG_HUNGARIAN = 65, - TWLG_ICELANDIC = 7, - TWLG_INDONESIAN = 66, - TWLG_ITALIAN = 8, - TWLG_ITALIAN_SWISS = 67, - TWLG_JAPANESE = 68, - TWLG_KOREAN = 69, - TWLG_KOREAN_JOHAB = 70, - TWLG_LATVIAN = 71, - TWLG_LITHUANIAN = 72, - TWLG_NORWEGIAN = 9, - TWLG_NORWEGIAN_BOKMAL = 73, - TWLG_NORWEGIAN_NYNORSK = 74, - TWLG_POLISH = 75, - TWLG_PORTUGUESE = 10, - TWLG_PORTUGUESE_BRAZIL = 76, - TWLG_ROMANIAN = 77, - TWLG_RUSSIAN = 78, - TWLG_SERBIAN_LATIN = 79, - TWLG_SLOVAK = 80, - TWLG_SLOVENIAN = 81, - TWLG_SPANISH = 11, - TWLG_SPANISH_MEXICAN = 82, - TWLG_SPANISH_MODERN = 83, - TWLG_SWEDISH = 12, - TWLG_THAI = 84, - TWLG_TURKISH = 85, - TWLG_UKRANIAN = 86, - /** More stuff added for 1.8 */ - TWLG_ASSAMESE = 87, - TWLG_BENGALI = 88, - TWLG_BIHARI = 89, - TWLG_BODO = 90, - TWLG_DOGRI = 91, - TWLG_GUJARATI = 92, - TWLG_HARYANVI = 93, - TWLG_HINDI = 94, - TWLG_KANNADA = 95, - TWLG_KASHMIRI = 96, - TWLG_MALAYALAM = 97, - TWLG_MARATHI = 98, - TWLG_MARWARI = 99, - TWLG_MEGHALAYAN = 100, - TWLG_MIZO = 101, - TWLG_NAGA = 102, - TWLG_ORISSI = 103, - TWLG_PUNJABI = 104, - TWLG_PUSHTU = 105, - TWLG_SERBIAN_CYRILLIC = 106, - TWLG_SIKKIMI = 107, - TWLG_SWEDISH_FINLAND = 108, - TWLG_TAMIL = 109, - TWLG_TELUGU = 110, - TWLG_TRIPURI = 111, - TWLG_URDU = 112, - TWLG_VIETNAMESE = 113 -} - -/** ICAP_LIGHTPATH values. */ -declare enum EnumDWT_CapLightPath { - TWLP_REFLECTIVE = 0, - TWLP_TRANSMISSIVE = 1 -} - -/** ICAP_LIGHTSOURCE values. */ -declare enum EnumDWT_CapLightSource { - TWLS_RED = 0, - TWLS_GREEN = 1, - TWLS_BLUE = 2, - TWLS_NONE = 3, - TWLS_WHITE = 4, - TWLS_UV = 5, - TWLS_IR = 6 -} - -/** ICAP_NOISEFILTER values. */ -declare enum EnumDWT_CapNoiseFilter { - TWNF_NONE = 0, - TWNF_AUTO = 1, - TWNF_LONEPIXEL = 2, - TWNF_MAJORITYRULE = 3 -} - -/** ICAP_ORIENTATION values. */ -declare enum EnumDWT_CapORientation { - TWOR_ROT0 = 0, - TWOR_ROT90 = 1, - TWOR_ROT180 = 2, - TWOR_ROT270 = 3, - TWOR_PORTRAIT = 0, - TWOR_LANDSCAPE = 3, - /** 2.0 */ - TWOR_AUTO = 4, - /** 2.0 */ - TWOR_AUTOTEXT = 5, - /** 2.0 */ - TWOR_AUTOPICTURE = 6 -} - -/** ICAP_OVERSCAN values. */ -declare enum EnumDWT_CapOverscan { - TWOV_NONE = 0, - TWOV_AUTO = 1, - TWOV_TOPBOTTOM = 2, - TWOV_LEFTRIGHT = 3, - TWOV_ALL = 4 -} - -/** ICAP_PIXELFLAVOR values. */ -declare enum EnumDWT_CapPixelFlavor { - /** Zero pixel represents darkest shade. zero pixel represents darkest shade */ - TWPF_CHOCOLATE = 0, - /** Zero pixel represents lightest shade. zero pixel represents lightest shade */ - TWPF_VANILLA = 1 -} - -/** ICAP_PLANARCHUNKY values. */ -declare enum EnumDWT_CapPlanarChunky { - TWPC_CHUNKY = 0, - TWPC_PLANAR = 1 -} - -/** CAP_PRINTER values. */ -declare enum EnumDWT_CapPrinter { - TWPR_IMPRINTERTOPBEFORE = 0, - TWPR_IMPRINTERTOPAFTER = 1, - TWPR_IMPRINTERBOTTOMBEFORE = 2, - TWPR_IMPRINTERBOTTOMAFTER = 3, - TWPR_ENDORSERTOPBEFORE = 4, - TWPR_ENDORSERTOPAFTER = 5, - TWPR_ENDORSERBOTTOMBEFORE = 6, - TWPR_ENDORSERBOTTOMAFTER = 7 -} - -/** CAP_PRINTERMODE values. */ -declare enum EnumDWT_CapPrinterMode { - /** Specifies that the printed text will consist of a single string. */ - TWPM_SINGLESTRING = 0, - /** Specifies that the printed text will consist of an enumerated list of strings to be printed in order. */ - TWPM_MULTISTRING = 1, - /** Specifies that the printed string will consist of a compound of a String followed by a value followed by a suffix string. */ - TWPM_COMPOUNDSTRING = 2 -} - -/** TWAIN Supported sizes. */ -declare enum EnumDWT_CapSupportedSizes { - /** 0 */ - TWSS_NONE = 0, - /** 1 */ - TWSS_A4LETTER = 1, - /** 2 */ - TWSS_B5LETTER = 2, - /** 3 */ - TWSS_USLETTER = 3, - /** 4 */ - TWSS_USLEGAL = 4, - /** Added 1.5 - * 5 - */ - TWSS_A5 = 5, - /** 6 */ - TWSS_B4 = 6, - /** 7 */ - TWSS_B6 = 7, - /** Added 1.7 - * 9 - */ - TWSS_USLEDGER = 9, - /** 10 */ - TWSS_USEXECUTIVE = 10, - /** 11 */ - TWSS_A3 = 11, - /** 12 */ - TWSS_B3 = 12, - /** 13 */ - TWSS_A6 = 13, - /** 14 */ - TWSS_C4 = 14, - /** 15 */ - TWSS_C5 = 15, - /** 16 */ - TWSS_C6 = 16, - /** Added 1.8 - * 17 - */ - TWSS_4A0 = 17, - /** 18 */ - TWSS_2A0 = 18, - /** 19 */ - TWSS_A0 = 19, - /** 20 */ - TWSS_A1 = 20, - /** 21 */ - TWSS_A2 = 21, - /** 1 */ - TWSS_A4 = 1, - /** 22 */ - TWSS_A7 = 22, - /** 23 */ - TWSS_A8 = 23, - /** 24 */ - TWSS_A9 = 24, - /** 25 */ - TWSS_A10 = 25, - /** 26 */ - TWSS_ISOB0 = 26, - /** 27 */ - TWSS_ISOB1 = 27, - /** 28 */ - TWSS_ISOB2 = 28, - /** 12 */ - TWSS_ISOB3 = 12, - /** 6 */ - TWSS_ISOB4 = 6, - /** 29 */ - TWSS_ISOB5 = 29, - /** 7 */ - TWSS_ISOB6 = 7, - /** 30 */ - TWSS_ISOB7 = 30, - /** 31 */ - TWSS_ISOB8 = 31, - /** 32 */ - TWSS_ISOB9 = 32, - /** 33 */ - TWSS_ISOB10 = 33, - /** 34 */ - TWSS_JISB0 = 34, - /** 35 */ - TWSS_JISB1 = 35, - /** 36 */ - TWSS_JISB2 = 36, - /** 37 */ - TWSS_JISB3 = 37, - /** 38 */ - TWSS_JISB4 = 38, - /** 2 */ - TWSS_JISB5 = 2, - /** 39 */ - TWSS_JISB6 = 39, - /** 40 */ - TWSS_JISB7 = 40, - /** 41 */ - TWSS_JISB8 = 41, - /** 41 */ - TWSS_JISB9 = 42, - /** 43 */ - TWSS_JISB10 = 43, - /** 44 */ - TWSS_C0 = 44, - /** 45 */ - TWSS_C1 = 45, - /** 46 */ - TWSS_C2 = 46, - /** 47 */ - TWSS_C3 = 47, - /** 48 */ - TWSS_C7 = 48, - /** 49 */ - TWSS_C8 = 49, - /** 50 */ - TWSS_C9 = 50, - /** 51 */ - TWSS_C10 = 51, - /** 52 */ - TWSS_USSTATEMENT = 52, - /** 53 */ - TWSS_BUSINESSCARD = 53, - /** 54. Added 2.1 */ - TWSS_MAXSIZE = 54 -} - -/** Capabilities exist in many varieties but all have a Default Value, Current Value, and may have other values available that can be supported if selected. - * To help categorize the supported values into clear structures, TWAIN defines four types of containers for capabilities = - * TW_ONEVALUE, TW_ARRAY, TW_RANGE and TW_ENUMERATION. - */ -declare enum EnumDWT_CapType { - /** Nothing. */ - TWON_NONE = 0, - /** A rectangular array of values that describe a logical item. It is similar to the TW_ONEVALUE because the current and default values are the same and - * there are no other values to select from. For example, a list of the names, such as the supported capabilities list returned by the CAP_SUPPORTEDCAPS - * capability, would use this type of container. - */ - TWON_ARRAY = 3, - /** This is the most general type because it defines a list of values from which the Current Value can be chosen. - * The values do not progress uniformly through a range and there is not a consistent step size between the values. - * For example, if a Source's resolution options do not occur in even step sizes then an enumeration would be used (for example, 150, 400, and 600). - */ - TWON_ENUMERATION = 4, - /** A single value whose current and default values are coincident. The range of available values for this type of capability is simply this single value. - * For example, a capability that indicates the presence of a document feeder could be of this type. - */ - TWON_ONEVALUE = 5, - /** Many capabilities allow users to select their current value from a range of regularly spaced values. - * The capability can specify the minimum and maximum acceptable values and the incremental step size between the values. - * For example, resolution might be supported from 100 to 600 in steps of 50 (100, 150, 200, ..., 550, 600). - */ - TWON_RANGE = 6 -} - -/** The kind of data stored in the container. */ -declare enum EnumDWT_CapValueType { - TWTY_INT8 = 0, - /** Means Item is a TW_INT16 */ - TWTY_INT16 = 1, - /** Means Item is a TW_INT32 */ - TWTY_INT32 = 2, - /** Means Item is a TW_UINT8 */ - TWTY_UINT8 = 3, - /** Means Item is a TW_UINT16 */ - TWTY_UINT16 = 4, - /** Means Item is a TW_int */ - TWTY_int = 5, - /** Means Item is a TW_BOOL */ - TWTY_BOOL = 6, - /** Means Item is a TW_FIX32 */ - TWTY_FIX32 = 7, - /** Means Item is a TW_FRAME */ - TWTY_FRAME = 8, - /** Means Item is a TW_STR32 */ - TWTY_STR32 = 9, - /** Means Item is a TW_STR64 */ - TWTY_STR64 = 10, - /** Means Item is a TW_STR128 */ - TWTY_STR128 = 11, - /** Means Item is a TW_STR255 */ - TWTY_STR255 = 12 -} - -/** ICAP_DUPLEX values. */ -declare enum EnumDWT_DUPLEX { - TWDX_NONE = 0, - TWDX_1PASSDUPLEX = 1, - TWDX_2PASSDUPLEX = 2 -} - -/** Data source status. */ -declare enum EnumDWT_DataSourceStatus { - /** Indicate the data source is closed. */ - TWDSS_CLOSED = 0, - /** Indicate the data source is opened. */ - TWDSS_OPENED = 1, - /** Indicate the data source is enabled. */ - TWDSS_ENABLED = 2, - /** Indicate the data source is acquiring image. */ - TWDSS_ACQUIRING = 3 -} - -declare enum EnumDWT_Error { - ModuleNotExists = -2371 -} - -/** ICAP_IMAGEFILEFORMAT values. */ -declare enum EnumDWT_FileFormat { - /** Used for document imaging. Tagged Image File Format */ - TWFF_TIFF = 0, - /** Native Macintosh format. Macintosh PICT */ - TWFF_PICT = 1, - /** Native Microsoft format. Windows Bitmap */ - TWFF_BMP = 2, - /** Used for document imaging. X-Windows Bitmap */ - TWFF_XBM = 3, - /** Wrapper for JPEG images. JPEG File Interchange Format */ - TWFF_JFIF = 4, - /** FlashPix, used with digital cameras. Flash Pix */ - TWFF_FPX = 5, - /** Multi-page TIFF files. Multi-page tiff file */ - TWFF_TIFFMULTI = 6, - /** An image format standard intended for use on the web, replaces GIF. */ - TWFF_PNG = 7, - /** A standard from JPEG, intended to replace JFIF, also supports JBIG. */ - TWFF_SPIFF = 8, - /** File format for use with digital cameras. */ - TWFF_EXIF = 9, - /** A file format from Adobe. 1.91 NB: this is not PDF/A */ - TWFF_PDF = 10, - /** A file format from the Joint Photographic Experts Group. 1.91 */ - TWFF_JP2 = 11, - /** 1.91 */ - TWFF_JPN = 12, - /** 1.91 */ - TWFF_JPX = 13, - /** A file format from LizardTech. 1.91 */ - TWFF_DEJAVU = 14, - /** A file format from Adobe. 2.0 */ - TWFF_PDFA = 15, - /** 2.1 Adobe PDF/A, Version 2 */ - TWFF_PDFA2 = 16 -} - -/** Fit window type */ -declare enum EnumDWT_FitWindowType { - /** Fit the image to the width and height of the window */ - enumFitWindow = 0, - /** Fit the image to the height of the window */ - enumFitWindowHeight = 1, - /** Fit the image to the width of the window */ - enumFitWindowWidth = 2 -} - -/** Image type */ -declare enum EnumDWT_ImageType { - /** Native Microsoft format. */ - IT_BMP = 0, - /** JPEG format. */ - IT_JPG = 1, - /** Tagged Image File Format. */ - IT_TIF = 2, - /** An image format standard intended for use on the web, replaces GIF. */ - IT_PNG = 3, - /** A file format from Adobe. */ - IT_PDF = 4, - /** All supported formats which are bmp, jpg, tif, png and pdf */ - IT_ALL = 5 -} - -declare enum EnumDWT_InitMsg { - Info = 1, - Error = 2, - NotInstalledError = 3, - DownloadError = 4, - DownloadNotRestartError = 5 -} - -/** The method to do interpolation. */ -declare enum EnumDWT_InterpolationMethod { - IM_NEARESTNEIGHBOUR = 1, - IM_BILINEAR = 2, - IM_BICUBIC = 3, - IM_BESTQUALITY = 5 -} - -declare enum EnumDWT_Language { - English = 0, - French = 1, - Arabic = 2, - Spanish = 3, - Portuguese = 4, - German = 5, - Italian = 6, - Russian = 7, - Chinese = 8 -} - -/** TWEI_MAGTYPE values. (MD_ means Mag Type) Added 2.0 */ -declare enum EnumDWT_MagType { - /** Added 2.0 */ - TWMD_MICR = 0, - /** added 2.1 */ - TWMD_RAW = 1, - /** added 2.1 */ - TWMD_INVALID = 2 -} - -/** For query the operation that are supported by the data source on a capability . - * Application gets these through DG_CONTROL/DAT_CAPABILITY/MSG_QUERYSUPPORT - */ -declare enum EnumDWT_MessageType { - TWQC_GET = 1, - TWQC_SET = 2, - TWQC_GETDEFAULT = 4, - TWQC_GETCURRENT = 8, - TWQC_RESET = 16 -} - -declare enum EnumDWT_MouseShape { - Default = 0, - Hand = 1, - Crosshair = 2, - Zoom = 3 -} - -/** PDF file compression type. */ -declare enum EnumDWT_PDFCompressionType { - /** Auto mode. */ - PDF_AUTO = 0, - /** CCITT Group 3 fax encoding. */ - PDF_FAX3 = 1, - /** CCITT Group 4 fax encoding */ - PDF_FAX4 = 2, - /** Lempel Ziv and Welch */ - PDF_LZW = 3, - /** CCITT modified Huffman RLE. */ - PDF_RLE = 4, - /** JPEG compression. */ - PDF_JPEG = 5 -} - -/** ICAP_PIXELTYPE values (PT_ means Pixel Type) */ -declare enum EnumDWT_PixelType { - TWPT_BW = 0, - TWPT_GRAY = 1, - TWPT_RGB = 2, - TWPT_PALLETE = 3, - TWPT_CMY = 4, - TWPT_CMYK = 5, - TWPT_YUV = 6, - TWPT_YUVK = 7, - TWPT_CIEXYZ = 8, - TWPT_LAB = 9, - TWPT_SRGB = 10, - TWPT_SCRGB = 11, - TWPT_INFRARED = 16 -} - -declare enum EnumDWT_PlatformType { - /// Fit the image to the width and height of the window - enumWindow = 0, - /// Fit the image to the height of the window - enumMac = 1, - /// Fit the image to the width of the window - enumLinux = 2 -} - -declare enum EnumDWT_ShowMode { - /** Activates the window and displays it in its current size and position. */ - SW_ACTIVE = 0, - /** Maximizes the window */ - SW_MAX = 1, - /** Minimize the window */ - SW_MIN = 2, - /** Close the latest opened editor window */ - SW_CLOSE = 3, - /** Check whether a window exists */ - SW_IFLIVE = 4 -} - -/** TIFF file compression type. */ -declare enum EnumDWT_TIFFCompressionType { - /** Auto mode. */ - TIFF_AUTO = 0, - /** Dump mode. */ - TIFF_NONE = 1, - /** CCITT modified Huffman RLE. */ - TIFF_RLE = 2, - /** CCITT Group 3 fax encoding. */ - TIFF_FAX3 = 3, - /** CCITT T.4 (TIFF 6 name). */ - TIFF_T4 = 3, - /** CCITT Group 4 fax encoding */ - TIFF_FAX4 = 4, - /** CCITT T.6 (TIFF 6 name). */ - TIFF_T6 = 4, - /** Lempel Ziv and Welch */ - TIFF_LZW = 5, - TIFF_JPEG = 7, - TIFF_PACKBITS = 32773 -} - -/** ICAP_XFERMECH values. */ -declare enum EnumDWT_TransferMode { - /** Native transfers require the data to be transferred to a single large block of RAM. Therefore, - * they always face the risk of having an inadequate amount of RAM available to perform the transfer successfully. - */ - TWSX_NATIVE = 0, - /** Disk File Mode Transfers. */ - TWSX_FILE = 1, - /** Buffered Memory Mode Transfers. */ - TWSX_MEMORY = 2/*,*/ - /** added 1.91 , not supported in DWT yet*/ - /** TWSX_MEMFILE = 4*/ -} - -/** ICAP_UNITS values. */ -declare enum EnumDWT_UnitType { - TWUN_INCHES = 0, - TWUN_CENTIMETERS = 1, - TWUN_PICAS = 2, - TWUN_POINTS = 3, - TWUN_TWIPS = 4, - TWUN_PIXELS = 5, - TWUN_MILLIMETERS = 6 -} - -declare enum EnumDWT_UploadDataFormat { - Binary = 0, - Base64 = 1 -} - -/** - * interface for a DWT container which basically defines a DIV on the page - */ -interface Container { - ContainerId: string; - Width: string | number; - Height: string | number; -} - -/** - * interface for a base64 result - */ -interface Base64Result { - getLength(): number; - getData(offset: number, length: number): string; - getMD5(): string; -} - -/** - * Copied from lib.d.ts (Typescript) - */ -interface Blob { - readonly size: number; - readonly type: string; - msClose(): void; - msDetachStream(): any; - slice(start?: number, end?: number, contentType?: string): Blob; -} - -/** - * Details for each license - */ -interface LicenseDetailItem { - readonly Browser: string; - readonly EnumLicenseType: string; - readonly ExpireDate: string; - readonly LicenseType: string; - readonly OS: string; - readonly Trial: string; - readonly Version: string; -} - -/** - * @class - */ -// properties (get/set) / sync functions -interface WebTwain { - /** - * Returns whether the instance of a DWT is initialized - * @type {boolean} - */ - bReady: boolean; - - /** - * Returns the runtime id of the dwt object - * @type {string} - */ - readonly clientId: string; - - /** - * Returns the runtime class for the dwt container DIV - * @type {string} - */ - containerClass: string; - - /*ignored - httpUrl - objectName - - ...other internal ones - */ - - /* - * Properties - */ - - /** - * Returns or sets whether multi-page selection is supported. - * @type {boolean} - */ - AllowMultiSelect: boolean; - - /** - * [Deprecated.] Returns or sets whether allowing the plugin to send authentication request. The default value of this property is TRUE. - * @type {boolean} - */ - AllowPluginAuthentication: boolean; - - /** - * [Deprecated.] Returns or sets whether the async mode is activated. With this mode, Dynamic Web TWAIN is able to upload/download files via HTTP/FTP asynchronously. The default value is false. - * @type {boolean} - */ - AsyncMode: boolean; - - /** - * Returns or sets the background color of the main control. It is a value specifying the 24-bit RGB value. - * @type {number} - */ - BackgroundColor: number; - - /** - * Returns or sets the fill color of the selected area of an image when it is cut, erased or rotated. It is a value specifying the 24-bit RGB value. - * @type {number} - */ - BackgroundFillColor: number; - - /** - * Returns or sets the pixel bit depths for the current value of PixelType property. This is a runtime property. - * @type {number} - */ - BitDepth: number; - - /** - * Returns the current deviation of the pixels in the image. - * @type {number} - */ - readonly BlankImageCurrentStdDev: number; - - /** - * Returns or sets the standard deviation of the pixels in the image. - * @type {number} - */ - BlankImageMaxStdDev: number; - - /** - * Returns or sets the dividing line between black and white. The default value is 128. - * @type {number} - */ - BlankImageThreshold: number; - - /** - * [Deprecated.] Returns or sets the border style. - * @type {EnumDWT_BorderStyle} - */ - BorderStyle: EnumDWT_BorderStyle; - - /** - * Returns or sets the brightness values available within the Source. This is a runtime property. - * @type {number} - */ - Brightness: number; - - /** - * [Deprecated.] Sets or returns whether brokerprocess is enabled for scanning. - * @type {number} - */ - BrokerProcessType: number; - - /** - * Sets or returns how much physical memory is allowed for storing images currently loaded in Dynamic Web TWAIN. Once the limit is reached, images will be cached on the hard disk. - * @type {number} - */ - BufferMemoryLimit: number; - - /** - * Sets or returns the index (0-based) of a list to indicate the Current Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. - * @type {number} - */ - CapCurrentIndex: number; - - /** - * Sets or returns the current value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. - * @type {number} - */ - CapCurrentValue: number; - - /** - * Returns the index (0-based) of a list to indicate the Default Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime, read-only property. - * @type {number} - */ - readonly CapDefaultIndex: number; - - /** - * Returns the default value in a range when the value of the CapType property is TWON_RANGE. This is a runtime, read-only property. - * @type {number} - */ - CapDefaultValue: number; - - /** - * Retruns the description for a capability - * @type {string} - */ - CapDescription: string; - - /** - * Sets or returns the maximum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. - * @type {number} - */ - CapMaxValue: number; - - /** - * Sets or returns the minimum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. - * @type {number} - */ - CapMinValue: number; - - /** - * [Deprecated.] Sets or returns how many items are in the list when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. For String data type, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. - * @type {number} - */ - CapNumItems: number; - - /** - * Sets or returns the step size in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. - * @type {number} - */ - CapStepSize: number; - - /** - * Sets or returns the type of capability container used to exchange capability information between application and source. This is a runtime property. - * @type {EnumDWT_CapType} - */ - CapType: EnumDWT_CapType; - - /** - * Returns or sets the value of the capability specified by Capability property when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. - * @type {number} - */ - CapValue: number; - - /** - * Sets or returns the string value for a capability when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. - * @type {string} - */ - CapValueString: string; - - /** - * Sets or returns the value type for reading the value of a capability. This is a runtime property. - * @type {number} - */ - CapValueType: number; - - /** - * Specifies the capabiltiy to be negotiated. This is a runtime property. - * @type {EnumDWT_Cap} - */ - Capability: EnumDWT_Cap; - - /** - * Returns or sets the contrast values available within the Source. This is a runtime property. - * @type {number} - */ - Contrast: number; - - /** - * Returns or sets current index of image in buffer. This is a runtime property. - * @type {number} - */ - CurrentImageIndexInBuffer: number; - - /** - * Returns the device name of current source. This is a runtime, read-only property. - * @type {string} - */ - readonly CurrentSourceName: string; - - /** - * Returns the value indicating the data source status. This is a runtime, read-only property. - * @type {number} - */ - readonly DataSourceStatus: number; - - /** - * Returns the device name of default source. This is a runtime, read-only property. - * @type {string} - */ - readonly DefaultSourceName: string; - - /** - * Returns whether the source supports duplex. If so, it further returns the level of duplex the Source supports (one pass or two pass duplex). This is a runtime, read-only property. - * @type {EnumDWT_DUPLEX} - */ - readonly Duplex: EnumDWT_DUPLEX; - - /** - * [Deprecated.] Returns or sets whether the user can zoom image using hot key. - * @type {boolean} - */ - EnableInteractiveZoom: boolean; - - /** - * Returns the error code. This is a runtime, read-only property. - * @type {number} - */ - readonly ErrorCode: number; - - /** - * Returns the error string. This is a runtime, read-only property. - * @type {string} - */ - readonly ErrorString: string; - - /** - * Returns or sets the password used to log into the FTP server. - * @type {string} - */ - FTPPassword: string; - - /** - * Returns or sets the port number of the FTP server. - * @type {number} - */ - FTPPort: number; - - /** - * Returns or sets the user name used to log into the FTP server. - * @type {string} - */ - FTPUserName: string; - - /** - * Returns or sets whether to resize the image to fit the image to the width or height of the window. To use the property, the view mode should be set to -1 by -1. You can use SetViewMode method to set the view mode. - * @type {EnumDWT_FitWindowType} - */ - FitWindowType: EnumDWT_FitWindowType; - - /** - * Returns the response string from the HTTP server if an error occurs for HTTPUploadThroughPost() method. This is a runtime, read-only property. - * @type {string} - */ - readonly HTTPPostResponseString: string; - - /** - * Returns whether a HTTP request has credentials - * @type {boolean} - */ - HTTPRequestswithCredentials: boolean; - - /** - * Returns or sets the height of the dwt viewer object - * @type {string|number} - */ - Height: string | number; - - /** - * Returns how many images are in buffer. This is a runtime, read-only property. - * @type {number} - */ - readonly HowManyImagesInBuffer: number; - - /** - * Specifies the content type of a http upload. - * @type {string} - */ - HttpContentTypeFieldValue: string; - - /** - * Specifies the field name of uploaded image through POST. - * @type {string} - */ - HttpFieldNameOfUploadedImage: string; - - /** - * [Deprecated.] Sets or returns the password used to log into the HTTP server. - * @type {string} - */ - HTTPPassword: string; - - /** - * Returns or sets the port number of the HTTP server. - * @type {number|string} - */ - HTTPPort: number | string; - - /** - * [Deprecated.] Returns or sets the user name used to log into the HTTP server. - * @type {string} - */ - HTTPUserName: string; - - /** - * Returns or sets whether the feature of disk caching is enabled. - * @type {boolean} - */ - IfAllowLocalCache: boolean; - - /** - * Returns or sets whether insert or append new scanned images. - * @type {boolean} - */ - IfAppendImage: boolean; - - /** - * Returns or sets whether the Source's Auto-brightness function is enabled. This is a runtime property. - * @type {boolean} - */ - IfAutoBright: boolean; - - /** - * Returns or sets whether the data source (scanner) will discard blank images during scanning. The property works only if the device and its driver support discarding blank pages. You can find whether your device supports this capbility from its user manual. Or, you can use the built-in methods of Dynamic Web TWAIN to detect blank images: IsBlankImage, IsBlankImageEx. - * @type {boolean} - */ - IfAutoDiscardBlankpages: boolean; - - /** - * Returns or sets whether the Source enable automatic document feeding process. This is a runtime property. - * @type {boolean} - */ - IfAutoFeed: boolean; - - /** - * Returns or sets whether the Source enables the automatic document scanning process. This is a runtime property. - * @type {boolean} - */ - IfAutoScan: boolean; - - /** - * Specifies whether or not to automatically scroll to the last image or stay on the current image when loading or acquiring images - * @type {boolean} - */ - IfAutoScroll: boolean; - - /** - * Turns automatic border detection on and off. The property works only if the device and its driver support detecting the border automatically. You can find whether your device supports this capbility from its user manual. - * @type {boolean} - */ - IfAutomaticBorderDetection: boolean; - - /** - * Turns automatic skew correction on and off. - * @type {boolean} - */ - IfAutomaticDeskew: boolean; - - /** - * Returns or sets whether close the Data Source User Interface after acquire all images. Default value of this property is FALSE. - * @type {boolean} - */ - IfDisableSourceAfterAcquire: boolean; - - /** - * Returns or sets whether the Source supports duplex. If TRUE, the scanner scans both sides of a paper; otherwise, the scanner will scan only one side of the image. This is a runtime property. - * @type {boolean} - */ - IfDuplexEnabled: boolean; - - /** - * Returns or sets whether the Automatic Document Feeder (ADF) is enabled. This is a runtime property. - * @type {boolean} - */ - IfFeederEnabled: boolean; - - /** - * Returns whether or not there are documents loaded in the Source's feeder when IfFeederEnabled and IfPaperDetectable are TRUE. This is a runtime, read-only property. - * @type {boolean} - */ - readonly IfFeederLoaded: boolean; - - /** - * Returns or sets whether to resize the image to fit the size of window when the view mode is set to -1 by -1. You can use SetViewMode method to set the view mode. - * @type {boolean} - */ - IfFitWindow: boolean; - - /** - * [Deprecated.] Returns or sets whether the UI (User Interface) of Source runs in modal state. Default value of this property is TRUE. - * @type {boolean} - */ - IfModalUI: boolean; - - /** - * Sets or returns whether Dynamic Web TWAIN uses Graphics Device Interface (GDI) when decoding images. - * @type {boolean} - */ - IfOpenImageWithGDIPlus: boolean; - - /** - * Returns or sets whether FTP passive mode is enabled. - * @type {boolean} - */ - IfPASVMode: boolean; - - /** - * Returns the value whether the Source has a paper sensor that can detect documents on the ADF or Flatbed. This is a runtime, read-only property. - * @type {boolean} - */ - readonly IfPaperDetectable: boolean; - - /** - * Returns or sets whether SSL is used when uploading or downloading images. - * @type {boolean} - */ - IfSSL: boolean; - - /** - * [Deprecated.] Returns or sets whether communicate with device in a separate thread. Default value of this property is FALSE. - * @type {boolean} - */ - IfScanInNewThread: boolean; - - /** - * Sets or returns whether to show the cancel dialog when uploading images to server. - * @type {boolean} - */ - IfShowCancelDialogWhenImageTransfer: boolean; - - /** - * Returns or sets whether to show the file dialog box when saving scanned images or loading images from local folder. - * @type {boolean} - */ - IfShowFileDialog: boolean; - - /** - * Returns or sets whether the Source displays a progress indicator during acquisition and transfer, regardless of whether the Source's user interface is active. This is a runtime property. - * @type {boolean} - */ - IfShowIndicator: boolean; - - /** - * [Deprecated.] Returns or sets whether the driver of the printer displays the User Interface. - * @type {boolean} - */ - IfShowPrintUI: boolean; - - /** - * Returns or sets whether the progress bar will be displayed during the transaction. This is a runtime property. - * @type {boolean} - */ - IfShowProgressBar: boolean; - - /** - * Returns or sets whether the Source displays the User Interface. - * @type {boolean} - */ - IfShowUI: boolean; - - /** - * Returns or sets whether to throw exceptions - * @type {boolean} - */ - IfThrowException: boolean; - - /** - * Return or sets whether the Source allows to save many images in one TIFF file. The default value is FALSE. - * @type {boolean} - */ - IfTiffMultiPage: boolean; - - /** - * Returns whether the Source supports acquisition with the UI (User Interface) disabled. If FALSE, indicates that this Source can only support acquisition with the UI enabled. This is a runtime, read-only property. - * @type {boolean} - */ - readonly IfUIControllable: boolean; - - /** - * Sets or returns whether Dynamic Web TWAIN uses the new TWAIN Data Source Manager (TWAINDSM.dll) when acquiring images from TWAIN devices. - * @type {boolean} - */ - IfUseTwainDSM: boolean; - - /** - * [Deprecated.] The number of bits in each image pixel (or bit depth). This is a runtime, read-only property. - * @type {number} - */ - ImageBitsPerPixel: number; - - /** - * Returns or sets whether a TWAIN driver or Native Scan of Mac OS X is used for document scanning. This property works for Mac edition only. - * @type {number} - */ - ImageCaptureDriverType: number; - - /** - * [Deprecated.] Returns or sets whether the image enumerator is enabled in Image Editor. - * @type {boolean} - */ - ImageEditorIfEnableEnumerator: boolean; - - /** - * [Deprecated.] Returns or sets whether the Image Editor is a modal window. - * @type {boolean} - */ - ImageEditorIfModal: boolean; - - /** - * [Deprecated.] Returns or sets whether the Image Editor is read-only. - * @type {boolean} - */ - ImageEditorIfReadonly: boolean; - - /** - * [Deprecated.] Returns or sets the title of Image Editor window. - * @type {string} - */ - ImageEditorWindowTitle: string; - - /** - * Returns the document number of the current image. This is a runtime, read-only property. - * @type {number} - */ - readonly ImageLayoutDocumentNumber: number; - - /** - * Returns the value of the bottom-most edge of the current image frame (in Unit). This is a read-only runtime property. - * @type {number} - */ - readonly ImageLayoutFrameBottom: number; - - /** - * Returns the value of the left-most edge of the current image frame (in Unit). This is a runtime, read-only property. - * @type {number} - */ - readonly ImageLayoutFrameLeft: number; - - /** - * Returns the frame number of the current image. This is a runtime, read-only property. - * @type {number} - */ - readonly ImageLayoutFrameNumber: number; - - /** - * Returns the value of the right-most edge of the current image frame (in Unit). This is a runtime, read-only property. - * @type {number} - */ - readonly ImageLayoutFrameRight: number; - - /** - * Returns the value of the top-most edge of the current image frame (in Unit). This is a runtime, read-only property. - * @type {number} - */ - readonly ImageLayoutFrameTop: number; - - /** - * Returns the page number of the current image. This is a runtime, read-only property. - * @type {Long} - */ - readonly ImageLayoutPageNumber: number; - - /** - * [Deprecated.] Returns how tall/long, in pixels, the image is. This is a runtime, read-only property. - * @type {number} - */ - ImageLength: number; - - /** - * Returns or sets the margin between images when multiple images are displayed in Dynamic Web TWAIN. - * @type {number} - */ - ImageMargin: number; - - /** - * Returns the pixel type of the current image. This is a runtime, read-only property. Please note the property is only valid in OnPreTransfer and OnPostTransfer event. - * @type {EnumDWT_PixelType} - */ - readonly ImagePixelType: EnumDWT_PixelType; - - /** - * [Deprecated.] Returns how width, in pixels, the image is. This is a runtime, read-only property. - * @type {number} - */ - ImageWidth: number; - - /** - * [Deprecated.] Returns the X resolution of the current image. X resolution is the number of pixels per Unit in the horizontal direction. This is a runtime, read-only property. - * @type {number} - */ - ImageXResolution: number; - - /** - * [Deprecated.] Returns the Y resolution of the current image. Y resolution is the number of pixels per Unit in the vertical direction. This is a runtime, read-only property. - * @type {number} - */ - ImageYResolution: number; - - /** - * Returns or sets the quality of JPEG files and PDF files using JPEG compression. - * @type {number} - */ - JPEGQuality: number; - - /** - * Returns or sets the log level for debugging. - * @type {number} - */ - LogLevel: number; - - /** - * Return the magnetic data if the scanner support magnetic data recognition. - * @type {string} - */ - readonly MagData: string; - - /** - * Return the magnetic type if the scanner support magnetic data recognition. - * @type {number} - */ - readonly MagType: number; - - /** - * Sets or returns the manufacture string for the application identity. - * @type {string} - */ - Manufacturer: string; - - /** - * Returns or sets the maximum number of images can be held in buffer. - * @type {number} - */ - MaxImagesInBuffer: number; - - /** - * [Deprecated.] Returns or sets how many threads can be used when you upload files through POST. - * @type {number} - */ - MaxInternetTransferThreads: number; - - /** - * Sets or returns the maximum allowed size when Dynamic Web TWAIN uploads a document. - * @type {number} - */ - MaxUploadImageSize: number; - - /** - * Returns or sets the shape of the mouse. - * @type {boolean} - */ - MouseShape: boolean; - - /** - * Returns the X co-ordinate of the mouse. This is a runtime property. - * @type {number} - */ - readonly MouseX: number; - - /** - * Returns the Y co-ordinate of the mouse. This is a runtime property. - * @type {number} - */ - readonly MouseY: number; - - /** - * Returns or sets the name of the person who creates the PDF document. - * @type {string} - */ - PDFAuthor: string; - - /** - * Returns or sets the compression type of PDF files. This is a runtime property. - * @type {EnumDWT_PDFCompressionType} - */ - PDFCompressionType: EnumDWT_PDFCompressionType; - - /** - * Returns or sets the date when the PDF document is created. - * @type {string} - */ - PDFCreationDate: string; - - /** - * Returns or sets the name of the application that created the original document, if the PDF document is converted from another form. - * @type {string} - */ - PDFCreator: string; - - /** - * Returns or sets the keywords associated with the PDF document. - * @type {string} - */ - PDFKeywords: string; - - /** - * Returns or sets the date when the PDF document is last modified. - * @type {string} - */ - PDFModifiedDate: string; - - /** - * Returns or sets the name of the application that converted the PDF document from its native. - * @type {string} - */ - PDFProducer: string; - - /** - * Returns or sets the subject of the PDF document. - * @type {string} - */ - PDFSubject: string; - - /** - * Returns or sets the title of the PDF document. - * @type {string} - */ - PDFTitle: string; - - /** - * Returns or sets the value of the PDF version. - * @type {string} - */ - PDFVersion: string; - - /** - * Returns or sets the page size(s) the Source can/should use to acquire image data. This is a runtime property. - * @type {EnumDWT_CapSupportedSizes} - */ - PageSize: EnumDWT_CapSupportedSizes; - - /** - * Returns the number of transfers the Source is ready to supply, upon demand. This is a runtime, read-only property. - * @type {number} - */ - readonly PendingXfers: number; - - /** - * Returns or sets the pixel flavor for acquired images. This is a runtime property. - * @type {number} - */ - PixelFlavor: number; - - /** - * Returns or sets the pixel type of current data source. This is a runtime property. Using this property after calling OpenSource() method and before calling AcquireImage(). - * @type {EnumDWT_PixelType} - */ - PixelType: EnumDWT_PixelType; - - /** - * Sets or returns the product family string for the application identity. - * @type {string} - */ - ProductFamily: string; - - /** - * Sets the product key. A product key is generated in Licensing Tool which is intalled with Dynamic Web TWAIN. Each product key corresponds with a license. - * @type {string} - */ - ProductKey: string; - - /** - * Sets or returns the product name string for the application identity. - * @type {string} - */ - ProductName: string; - - /** - * [Deprecated.] Returns or sets the name of the proxy server. - * @type {string} - */ - ProxyServer: string; - - /** - * Returns or sets the current resolution for acquired images. This is a runtime property. - * @type {number} - */ - Resolution: number; - - /** - * Returns or sets how many scanned images are selected. - * @type {number} - */ - SelectedImagesCount: number; - - /** - * Returns or sets the border color of the selected image. It is a value specifying the 24-bit RGB value. - * @type {number} - */ - SelectionImageBorderColor: number; - - /** - * Specifies a fixed aspect ratio to be used for selecting an area. - * @type {number} - */ - SelectionRectAspectRatio: number; - - /** - * Specifies whether to show the page number - * @type {boolean} - */ - ShowPageNumber: boolean; - - /** - * Returns how many sources are installed in the system. This is a runtime, read-only property. - * @type {number} - */ - readonly SourceCount: number; - - /** - * Returns or sets the compression type of TIFF files. This is a runtime property. - * @type {EnumDWT_TIFFCompressionType} - */ - TIFFCompressionType: EnumDWT_TIFFCompressionType; - - /** - * Sets or returns the transfer mode. - * @type {EnumDWT_TransferMode} - */ - TransferMode: EnumDWT_TransferMode; - - /** - * Returns or sets the unit of measure. This is a runtime property. - * @type {EnumDWT_UnitType} - */ - Unit: EnumDWT_UnitType; - - /** - * Specifies whether to show the vertical scroll bar - * @type {boolean} - */ - VScrollBar: boolean; - - /** - * Sets or returns the version info string for the application identity. - * @type {string} - */ - readonly VersionInfo: string; - - /** - * Returns or sets the width of the dwt object viewer - * @type {string|number} - */ - Width: string | number; - - /** - * Returns and sets the number of images you are willing to transfer per session. This is a runtime property. - * @type {number} - */ - XferCount: number; - - /** - * Returns or sets zoom factor for the image, only valid When the view mode is set to -1 by -1. - * @type {number} - */ - Zoom: number; - - /* ignored - style - _AutoCropMethod - */ - - /* - *Methods - */ - - /** - * Displays the source's built-in interface to acquire image. - * @method WebTwain#AcquireImage - * @param {object} optionalDeviceConfig a JS object used to set up the device for image acquisition. - * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - AcquireImage(optionalDeviceConfig?: object, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Add text on an image. - * @method WebTwain#AddText - * @param {number} sImageIndex the index of the image that you want to add text to. - * @param {number} x the x coordinate for the text. - * @param {number} y the y coordinate for the text. - * @param {string} text the content of the text that you want to add. - * @param {number} txtColor the color for the text. - * @param {number} backgroundColor the background color. - * @param {number} backgroundRoundRadius ranging from 0 to 0.5. Please NOTE that MAC version does not support this parameter. - * @param {number} backgroundOpacity specifies the opacity of the background of the added text, it ranges from 0 to 1.0. Please NOTE that Mac version only supports value 0 and 1 - * @return {boolean} - */ - AddText(sImageIndex: number, x: number, y: number, text: string, txtColor: number, backgroundColor: number, backgroundRoundRadius: number, backgroundOpacity: number): boolean; - - /** - * Cancels all pending transfers. - * @method WebTwain#CancelAllPendingTransfers - * @return {boolean} - */ - CancelAllPendingTransfers(): boolean; - - /** - * Gets information of the capability specified by the Capability property. - * @method WebTwain#CapGet - * @return {boolean} - */ - CapGet(): boolean; - - /** - * Returns the Source's current Value for the specified capability. - * @method WebTwain#CapGetCurrent - * @return {boolean} - */ - CapGetCurrent(): boolean; - - /** - * Returns the Source's Default Value for the specified capability. This is the Source's preferred default value. - * @method WebTwain#CapGetDefault - * @return {boolean} - */ - CapGetDefault(): boolean; - - /** - * Returns the value of the bottom-most edge of the specified frame. - * @method WebTwain#CapGetFrameBottom - * @param {number} index specifies the value of which frame to get. The index is 0-based. - * @return {number} - */ - CapGetFrameBottom(index: number): number; - - /** - * Returns the value (in Unit) of the left-most edge of the specified frame. - * @method WebTwain#CapGetFrameLeft - * @param {number} index specifies the value of which frame to get. The index is 0-based. - * @return {number} - */ - CapGetFrameLeft(index: number): number; - - /** - * Returns the value (in Unit) of the left-most edge of the specified frame. - * @method WebTwain#CapGetFrameRight - * @param {number} index specifies the value of which frame to get. The index is 0-based. - * @return {number} - */ - CapGetFrameRight(index: number): number; - - /** - * Returns the value (in Unit) of the top-most edge of the specified frame. - * @method WebTwain#CapGetFrameTop - * @param {number} index specifies the value of which frame to get. The index is 0-based. - * @return {number} - */ - CapGetFrameTop(index: number): number; - - /* ignored - * CapGetHelp - * CapGetLabel - * CapGetLabels - */ - - /** - * Queries whether the Source supports a particular operation on the capability. - * @method WebTwain#CapIfSupported - * @param {EnumDWT_MessageType} messageType specifies the type of capability operation. - * @return {boolean} - */ - CapIfSupported(messageType: EnumDWT_MessageType): boolean; - - /** - * Changes the Current Value of the capability specified by Capability property back to its power-on value. - * @method WebTwain#CapReset - * @return {boolean} - */ - CapReset(): boolean; - - /** - * Sets the current capability using the container type specified by CapType property. The current capability is specified by Capability property. - * @method WebTwain#CapSet - * @return {boolean} - */ - CapSet(): boolean; - - /** - * Sets the values of the specified frame. - * @method WebTwain#CapSetFrame - * @param {number} index specifies the values of which frame to set. The index is 0-based. - * @param {number} left the value (in Unit) of the left-most edge of the specified frame. - * @param {number} top the value (in Unit) of the top-most edge of the specified frame. - * @param {number} right the value (in Unit) of the right-most edge of the specified frame. - * @param {number} bottom the value (in Unit) of the bottom-most edge of the specified frame. - * @return {boolean} - */ - CapSetFrame(index: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Changes the bitdepth of a specified image. - * @method WebTwain#ChangeBitDepth - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} sBitDepth specifies the target bit depth. - * @param {boolean} bHighQuality specifies whether or not to keep high quality while changing the bit depth. When it's true, it takes more time. - * @return {boolean} - */ - ChangeBitDepth(sImageIndex: number, sBitDepth: number, bHighQuality: boolean): boolean; - - /** - * Changes width and height of the image of a specified index in the buffer. Please note the file size of the image will be changed proportionately. - * @method WebTwain#ChangeImageSize - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} iNewWidth specifies the pixel width of the new image. - * @param {number} iNewHeight specifies the pixel height of the new image. - * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. - * @return {boolean} - */ - ChangeImageSize(sImageIndex: number, iNewWidth: number, iNewHeight: number, newVal: EnumDWT_InterpolationMethod): boolean; - - /** - * Clears all the web forms which are used for image uploading. - * @method WebTwain#ClearAllHTTPFormField - * @return {boolean} - */ - ClearAllHTTPFormField(): boolean; - - /** - * Clears the content of all custom tiff tags. - * @method WebTwain#ClearTiffCustomTag - * @return {void} - */ - ClearTiffCustomTag(): void; - - /** - * Closes Data Source. - * @method WebTwain#CloseSource - * @return {boolean} - */ - CloseSource(): boolean; - - /** - * Closes and unloads Data Source Manager. - * @method WebTwain#CloseSourceManager - * @return {boolean} - */ - CloseSourceManager(): boolean; - - /** - * Closes the current process used to scan - * @method WebTwain#CloseWorkingProcess - * @return {boolean} - */ - CloseWorkingProcess(): boolean; - - /** - * Converts the images specified by the indices to base64 synchronously. - * @method WebTwain#ConvertToBase64 - * @param {Array} indices indices specifies which images are to be converted to base64. - * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. - * @return {Base64Result} - - ConvertToBase64(indices: number[], enumImageType: EnumDWT_ImageType): Base64Result; - */ - - /** - * Converts the images specified by the indices to base64 asynchronously. - * @method WebTwain#ConvertToBase64 - * @param {Array} indices indices specifies which images are to be converted to base64. - * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. - * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - ConvertToBase64(indices: number[], enumImageType: EnumDWT_ImageType, asyncSuccessFunc: (result: Base64Result) => void, asyncFailureFunc: (errorCode: number, errorString: string) => void): boolean; - - /** - * Converts the images specified by the indices to blob synchronously. - * @method WebTwain#ConvertToBlob - * @param {Array} indices indices specifies which images are to be converted to base64. - * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. - * @return {Blob} - */ - ConvertToBlob(indices: number[], enumImageType: EnumDWT_ImageType): Blob; - - /** - * Converts the images specified by the indices to blob asynchronously. - * @method WebTwain#ConvertToBlob - * @param {Array} indices indices specifies which images are to be converted to base64. - * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. - * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - ConvertToBlob(indices: number[], enumImageType: EnumDWT_ImageType, asyncSuccessFunc: (result: any) => void, asyncFailureFunc: (errorCode: number, errorString: string) => void): boolean; - - /** - * Changes a specified image to gray scale. - * @method WebTwain#ConvertToGrayScale - * @param {number} sIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - ConvertToGrayScale(sIndex: number): boolean; - - /** - * Copies the image of a specified index in buffer to clipboard in DIB format. - * @method WebTwain#CopyToClipboard - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - CopyToClipboard(sImageIndex: number): boolean; - - /** - * Create the font for adding text using the method AddText. - * @method WebTwain#CreateTextFont - * @param {number} height Specifies the desired height (in logical units) of the font.The absolute value of nHeight must not exceed 16,384 device units after it is converted.For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size or the smallest font if all the fonts exceed the requested size. - * @param {number} width Specifies the average width (in logical units) of characters in the font. If Width is 0, the aspect ratio of the device will be matched against the digitization aspect ratio of the available fonts to find the closest match, which is determined by the absolute value of the difference. - * @param {number} escapement Specifies the angle (in 0.1-degree units) between the escapement vector and the x-axis of the display surface. The escapement vector is the line through the origins of the first and last characters on a line. The angle is measured counterclockwise from the x-axis. - * @param {number} orientation Specifies the angle (in 0.1-degree units) between the baseline of a character and the x-axis.The angle is measured counterclockwise from the x-axis for coordinate systems in which the y-direction is down and clockwise from the x-axis for coordinate systems in which the y-direction is up. - * @param {number} weight Specifies the font weight (in inked pixels per 1000). The described valuesare approximate; the actual appearance depends on the typeface. Some fonts haveonly FW_NORMAL, FW_REGULAR, and FW_BOLD weights. If FW_DONTCARE is specified, a default weight is used. - * @param {number} italic Specifies an italic font if set to TRUE. - * @param {number} underline Specifies an underlined font if set to TRUE. - * @param {number} strikeOut A strikeout font if set to TRUE. - * @param {number} charSet Specifies the font's character set. The OEM character set is system-dependent. Fonts with other character sets may exist in the system. An application that uses a font with an unknown character set must not attempt to translate or interpret strings that are to be rendered with that font. - * @param {number} outputPrecision Specifies the desired output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, and pitch. - * @param {number} clipPrecision Specifies the desired clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. - * @param {number} quality Specifies the font's output quality, which defines how carefully the GDI must attempt to match the logical-font attributes to those of an actual physical font. - * @param {number} pitchAndFamily The pitch and family of the font. - * @param {string} faceName the typeface name, the length of this string must not exceed 32 characters, including the terminating null character. - * @return {boolean} - */ - CreateTextFont(height: number, width: number, escapement: number, orientation: number, weight: number, italic: number, underline: number, strikeOut: number, charSet: number, outputPrecision: number, clipPrecision: number, quality: number, pitchAndFamily: number, faceName: string): boolean; - - /** - * Crops the image of a specified index in buffer. - * @method WebTwain#Crop - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {boolean} - */ - Crop(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Crops the image of a specified index in buffer to clipboard in DIB format. - * @method WebTwain#CropToClipboard - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {boolean} - */ - CropToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Cuts the image data in the specified area to the system clipboard in DIB format. - * @method WebTwain#CutFrameToClipboard - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {boolean} - */ - CutFrameToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Cuts the image of a specified index in buffer to clipboard in DIB format. - * @method WebTwain#CutToClipboard - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - CutToClipboard(sImageIndex: number): boolean; - - /** - * Disable the source. If the source's user interface is displayed when the source is enabled, it will be closed. - * @method WebTwain#DisableSource - * @return {boolean} - */ - DisableSource(): boolean; - - /** - * Enables the source to accept image. - * @method WebTwain#EnableSource - * @return {boolean} - */ - EnableSource(): boolean; - - /** - * Clears the specified area of a specified image, and fill the area with the fill color. - * @method WebTwain#Erase - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {boolean} - */ - Erase(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * Downloads an image from the FTP server. - * @method WebTwain#FTPDownload - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPDownload(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Directly download a file from the FTP server to local disk without loading it into Dynamic Web TWAIN. - * @method WebTwain#FTPDownloadDirectly - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. - * @param {string} localFile specify a full path to store the file. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPDownloadDirectly(FTPServer: string, FTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Downloads an image from the FTP server. - * @method WebTwain#FTPDownloadEx - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. - * @param {EnumDWT_ImageType} lImageType simage format of the file to be downloaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPDownloadEx(FTPServer: string, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the image of a specified index in the buffer to the FTP server. - * @method WebTwain#FTPUpload - * @param {string} FTPServer the name of the FTP server. - * @param {number} sImageIndex specifies the index of the image in the buffer. The index is 0-based. - * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPUpload(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Directly upload a specific file to the FTP server without loading it into Dynamic Web TWAIN. - * @method WebTwain#FTPUploadDirectly - * @param {string} FTPServer the name of the FTP server. - * @param {string} localFile specify the the full path of a local file. - * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPUploadDirectly(FTPServer: string, localFile: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the image of a specified index in the buffer to the FTP server as a specified image format. - * @method WebTwain#FTPUploadEx - * @param {string} FTPServer the name of the FTP server. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. - * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPUploadEx(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads all images in buffer to the FTP server as Multi-Page TIFF. - * @method WebTwain#FTPUploadAllAsMultiPageTIFF - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPUploadAllAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads all images in buffer to the FTP server as Multi-Page PDF. - * @method WebTwain#FTPUploadAllAsPDF - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPUploadAllAsPDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the selected images in buffer to the FTP server as Multi-Page PDF. - * @method WebTwain#FTPUploadAsMultiPagePDF - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPUploadAsMultiPagePDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Uploads the selected images in buffer to the FTP server as Multi-Page TIFF. - * @method WebTwain#FTPUploadAsMultiPageTIFF - * @param {string} FTPServer the name of the FTP server. - * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - FTPUploadAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Sets the Source to eject the current page and advance the next page in the document feeder into the feeder acquire area when IfFeederEnabled is TRUE. - * @method WebTwain#FeedPage - * @return {boolean} - */ - FeedPage(): boolean; - - /** - * Check whether a certain file exists on the local disk. - * @method WebTwain#FileExists - * @param {string} localFile specifies the absolute path of the local file. - * @return {boolean} - */ - FileExists(localFile: string): boolean; - - /** - * Flips the image of a specified index in buffer. - * @method WebTwain#Flip - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - Flip(sImageIndex: number): boolean; - - /** - * Get the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. - * @method WebTwain#GetCapItems - * @param {number} index Index is 0-based. It is the index of the cap item. - * @return {number} - */ - GetCapItems(index: number): number; - - /** - * Returns the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. - * @method WebTwain#GetCapItemsString - * @param {number} index Index is 0-based. It is the index of the cap item. - * @return {string} - */ - GetCapItemsString(index: number): string; - - // Get custom DS data, and returned string is encoded with base64 - /** - * Gets custom DS data, the returned string is base64 encoded. - * @method WebTwain#GetCustomDSDataEx - * @return {string | boolean} - */ - GetCustomDSDataEx(): string | boolean; - - // Get custom DS data, and save the data to the specified file - /** - * Gets custom DS data and save the data in a specified file. - * @method WebTwain#GetCustomDSData - * @param {string} fileName the path of the file used for storing custom DS data. - * @return {boolean} - */ - GetCustomDSData(fileName: string): boolean; - - /** - * Retrieve the device type of the currently selected data source, it might be a scanner, a web camera, etc. - * @method WebTwain#GetDeviceType - * @return {number | boolean} - */ - GetDeviceType(): number | boolean; - - /** - * Returns the pixel bit depth of the selected image. - * @method WebTwain#GetImageBitDepth - * @param {number} sImageIndex specifies the index of image. The index is 0-based. - * @return {number} - */ - GetImageBitDepth(sImageIndex: number): number; - - /** - * Returns the height (pixels) of the selected image. This is a read-only property. - * @method WebTwain#GetImageHeight - * @param {number} sImageIndex specifies the index of image. The index is 0-based. - * @return {number} - */ - GetImageHeight(sImageIndex: number): number; - - /** - * Returns the direct URL of an image specified by index, if iWidth and iHeight are not specified, you get the original image, otherwise you get the image with specified iWidth or iHeight while keeping the same aspect ratio. The returned string is like this 'dwt://dwt_trial_13000404/img?id=306159652&index=0&t=1502184632022' - * @method WebTwain#GetImagePartURL - * @param {number} index the index of the image. - * @param {number} iWidth the width of the image, it must be 150 or bigger - * @param {number} iHeight the height of the image, it must be 150 or bigger - * @return {string} - */ - GetImagePartURL(index: number, iWidth?: number, iHeight?: number): string; - - /** - * Returns the file size of the new image resized from the image of a specified index in buffer. - * @method WebTwain#GetImageSize - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} iWidth specifies the pixel width of the new image. - * @param {number} iHeight specifies the pixel height of the new image. - * @return {number} - */ - GetImageSize(sImageIndex: number, iWidth: number, iHeight: number): number; - - /** - * Pre-calculate the file size of the local image file that is saved from an image of a specified index in buffer. - * @method WebTwain#GetImageSizeWithSpecifiedType - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {EnumDWT_ImageType} sImageType specifies the type of an image file.. - * @return {number} - */ - GetImageSizeWithSpecifiedType(sImageIndex: number, sImageType: EnumDWT_ImageType): number; - - /** - * Returns the direct URL of an image specified by index, if iWidth or iHeight is set to -1, you get the original image, otherwise you get the image with specified iWidth or iHeight while keeping the same aspect ratio. - * @method WebTwain#GetImageURL - * @param {number} index the index of the image. - * @param {number} iWidth the width of the image. - * @param {number} iHeight the height of the image. - * @return {string} - */ - GetImageURL(index: number, iWidth: number, iHeight: number): string; - - /** - * Returns the width (pixels) of the selected image. This is a read-only property. - * @method WebTwain#GetImageWidth - * @param {number} sImageIndex specifies the index of image. The index is 0-based. - * @return {number} - */ - GetImageWidth(sImageIndex: number): number; - - /** - * Return the horizontal resolution of the specified image. - * @method WebTwain#GetImageXResolution - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {number} - */ - GetImageXResolution(sImageIndex: number): number; - - /** - * Return the vertical resolution of the specified image. - * @method WebTwain#GetImageYResolution - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {number} - */ - GetImageYResolution(sImageIndex: number): number; - - /** - * Return the runtime license info. - * @method WebTwain#GetLicenseInfo - */ - GetLicenseInfo(optionalAsyncSuccessFunc?: (result: any) => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Returns the index of the selected image. - * @method WebTwain#GetSelectedImageIndex - * @param {number} sSelectedIndex specifies the index of the selected image. - * @return {number} - */ - GetSelectedImageIndex(sSelectedIndex: number): number; - - /** - * Pre-calculate the file size of the local image file that is saved from the selected images in buffer. - * @method WebTwain#GetSelectedImagesSize - * @param {EnumDWT_ImageType} iImageType specifies the type of an image file. - * @return {number} - */ - GetSelectedImagesSize(iImageType: EnumDWT_ImageType): number; - - /** - * Check the skew angle of an image by its index in buffer. - * @method WebTwain#GetSkewAngle - * @param {number} sImageIndex the index of the image in the buffer. - * @return {number} - */ - GetSkewAngle(sImageIndex: number): number; - - /** - * Check the skew angle of a rectangular part of an image by its index in buffer. - * @method WebTwain#GetSkewAngleEx - * @param {number} sImageIndex the index of the image in the buffer. - * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @return {number} - */ - GetSkewAngleEx(sImageIndex: number, left: number, top: number, right: number, bottom: number): number; - - /** - * Get the source name according to the source index. - * @method WebTwain#GetSourceNameItems - * @param {number} index number index. Index is 0-based and can not be greater than SourceCount property. - * @return {string} - */ - GetSourceNameItems(index: number): string; - - /*ignored - GetSourceNames - GetSourceType - GetVersionInfoAsync - */ - - /** - * Downloads an image from the HTTP server. - * @method WebTwain#HTTPDownload - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} HTTPRemoteFile the name of the image to be downloaded. It should be the relative path of the file on the HTTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPDownload(HTTPServer: string, HTTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Directly downloads a file from the HTTP server to a local disk without loading it into Dynamic Web TWAIN. - * @method WebTwain#HTTPDownloadDirectly - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} HTTPRemoteFile The relative path of the file on the HTTP server. - * @param {string} localFile specify the location to store the downloaded file. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPDownloadDirectly(HTTPServer: string, HTTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Downloads an image from the HTTP server. - * @method WebTwain#HTTPDownloadEx - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) - * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPDownloadEx(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /*ignored - HTTPDownloadStreamThroughPost - HTTPDownloadThroughGet - */ - - /** - * Download an image from the server using a HTTP Post call. - * @method WebTwain#HTTPDownloadThroughPost - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) - * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPDownloadThroughPost(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * Uploads just a form created by SetHTTPFormField and SetHTTPHeader - * @method WebTwain#HTTPUpload - * @param {string} url the url where the images are sent in a POST request. - * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPUpload(url: string, asyncSuccessFunc: (httppostresponsestring: string) => void, asyncFailureFunc: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * Uploads the images specified by the indices to the HTTP server. - * @method WebTwain#HTTPUpload - * @param {string} url the url where the images are sent in a POST request. - * @param {Array} indices indices specifies which images are to be uploaded. - * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be uploaded. - * @param {EnumDWT_UploadDataFormat} dataFormat whether to upload the images as binary or a base64-based string. - * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPUpload(url: string, indices: number[], enumImageType: EnumDWT_ImageType, dataFormat: EnumDWT_UploadDataFormat, asyncSuccessFunc: (httppostresponsestring: string) => void, asyncFailureFunc: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * Uploads all images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. - * @method WebTwain#HTTPUploadAllThroughPostAsMultiPageTIFF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {boolean} - */ - HTTPUploadAllThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * Uploads all images in the buffer to the HTTP server through HTTP Post method as a Multi-Page PDF. - * @method WebTwain#HTTPUploadAllThroughPostAsPDF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {boolean} - */ - HTTPUploadAllThroughPostAsPDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. - * @method WebTwain#HTTPUploadAllThroughPutAsMultiPageTIFF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} RemoteFileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPUploadAllThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. - * @method WebTwain#HTTPUploadAllThroughPutAsPDF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} RemoteFileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPUploadAllThroughPutAsPDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /*ignored - HTTPUploadStreamThroughPost - */ - - /** - * Uploads the image of a specified index in the buffer to the HTTP server through the HTTP POST method. - * @method WebTwain#HTTPUploadThroughPost - * @param {string} HTTPServer the name of the HTTP server. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {boolean} - */ - HTTPUploadThroughPost(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. - * @method WebTwain#HTTPUploadThroughPostAsMultiPageTIFF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {boolean} - */ - HTTPUploadThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page PDF. - * @method WebTwain#HTTPUploadThroughPostAsMultiPagePDF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {boolean} - */ - HTTPUploadThroughPostAsMultiPagePDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * Directly upload a specific local file to the HTTP server through the HTTP POST method without loading it into Dynamic Web TWAIN. - * @method WebTwain#HTTPUploadThroughPostDirectly - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} localFile specifies the path of a local file . - * @param {string} ActionPage the specified page for posting files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the file to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. - * @return {boolean} - */ - HTTPUploadThroughPostDirectly(HTTPServer: string, localFile: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP POST method. - * @method WebTwain#HTTPUploadThroughPostEx - * @param {string} HTTPServer the name of the HTTP server. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". - * @param {string} fileName the name of the image to be uploaded. - * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server.s - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadFailure. - * @return {boolean} - */ - HTTPUploadThroughPostEx(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string, httppostresponsestring: string) => void): boolean; - - /** - * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server through the HTTP PUT method. - * @method WebTwain#HTTPUploadThroughPut - * @param {string} HTTPServer the name of the HTTP server. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} RemoteFileName the name of the image to be created on the HTTP server. It should a relative path on the web server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPUploadThroughPut(HTTPServer: string, sImageIndex: number, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. - * @method WebTwain#HTTPUploadThroughPutAsMultiPageTIFF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} RemoteFileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPUploadThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. - * @method WebTwain#HTTPUploadThroughPutAsMultiPagePDF - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} RemoteFileName the name of the image to be uploaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPUploadThroughPutAsMultiPagePDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Directly uploads a specific local file to the HTTP server through the HTTP PUT method without loading it into Dynamic Web TWAIN. - * @method WebTwain#HTTPUploadThroughPutDirectly - * @param {string} HTTPServer the name of the HTTP server. - * @param {string} localFile specifies the path of a local file. - * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPUploadThroughPutDirectly(HTTPServer: string, localFile: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP PUT method. - * @method WebTwain#HTTPUploadThroughPutEx - * @param {string} HTTPServer the name of the HTTP server. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. - * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - HTTPUploadThroughPutEx(HTTPServer: string, sImageIndex: number, RemoteFileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Detects whether an image is blank. - * @method WebTwain#IsBlankImage - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - IsBlankImage(sImageIndex: number): boolean; - - /** - * [Deprecated.] Detects whether a certain area on an image is blank. - * @method WebTwain#IsBlankImageEx - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @param {boolean} bFuzzyMatch specifies whether use fuzzy matching when detecting. - * @return {boolean} - */ - IsBlankImageEx(sImageIndex: number, left: number, top: number, right: number, bottom: number, bFuzzyMatch: boolean): boolean; - - /** - * Detects whether a specific image is blank. - * @method WebTwain#IsBlankImageExpress - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - IsBlankImageExpress(sImageIndex: number): boolean; - - /** - * Loads a DIB format image from Clipboard into the Dynamic Web TWAIN. - * @method WebTwain#LoadDibFromClipboard - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - LoadDibFromClipboard(optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Loads an image into the Dynamic Web TWAIN. - * @method WebTwain#LoadImage - * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - LoadImage(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Loads an image into the Dynamic Web TWAIN. - * @method WebTwain#LoadImageEx - * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. - * @param {EnumDWT_ImageType} lImageType the image format of the file to be loaded. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - LoadImageEx(localFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Loads image from a base64 byte array with the specified file format. - * @method WebTwain#LoadImageFromBase64Binary - * @param {string} bry specifies the base64 string data. - * @param {EnumDWT_ImageType} lImageType specifies the file format. - * @return {boolean} - */ - LoadImageFromBase64Binary(bry: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * [Deprecated.] Loads image from a byte array with the specified file format. - * @method WebTwain#LoadImageFromBytes - * @param {number} lBufferSize Specifies the buffer size. - * @param {Array} buffer A byte array of the image data. - * @param {EnumDWT_ImageType} lImageType Specifies the file format. - * @return {boolean} - */ - LoadImageFromBytes(lBufferSize: number, buffer: number[], lImageType: EnumDWT_ImageType): boolean; - - /** - * Mirrors the image of a specified index in buffer. - * @method WebTwain#Mirror - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - Mirror(sImageIndex: number): boolean; - - /** - * Moves a specified image. - * @method WebTwain#MoveImage - * @param {number} sSourceImageIndex Specifies the source index of image in buffer. The index is 0-based. - * @param {number} sTargetImageIndex Specifies the target index of image in buffer. The index is 0-based. - * @return {boolean} - */ - MoveImage(sSourceImageIndex: number, sTargetImageIndex: number): boolean; - - /*ignored - OnRefreshUI - */ - - /** - * Loads the specified Source into main memory and causes its initialization, - * placing Dynamic Web TWAIN into Capability Negotiation state. If no source is - * specified (no SelectSource() or SelectSourceByIndex() is called), opens the default source. - * @method WebTwain#OpenSource - * @return {boolean} - */ - OpenSource(): boolean; - - /** - * Loads and opens Data Source Manager. - * @method WebTwain#OpenSourceManager - * @return {boolean} - */ - OpenSourceManager(): boolean; - - /** - * Decorates image of a specified index in buffer with rectangles of transparent color. - * @method WebTwain#OverlayRectangle - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} left specifies the x-coordinate of the upper-left corner of the rectangle. - * @param {number} top specifies the y-coordinate of the upper-left corner of the rectangle. - * @param {number} right specifies the x-coordinate of the lower-right corner of the rectangle. - * @param {number} bottom specifies the y-coordinate of the lower-right corner of the rectangle. - * @param {number} color Specifies the fill color of the rectangle. The byte-ordering of the RGB value is 0xBBGGRR. BB represents blue, GG represents green, RR represents red. - * @param {number} fOpacity Specifies the opacity of the rectangle. The value represents opacity. 1.0 is 100% opaque and 0.0 is totally transparent. - * @return {boolean} - */ - OverlayRectangle(sImageIndex: number, left: number, top: number, right: number, bottom: number, color: number, fOpacity: number): boolean; - - /** - * Shows the GUI of Image Printer. - * @method WebTwain#Print - * @param {boolean} bUseSystemDefaultPrintUI specifies whether to use the system Print UI or not. - * @return {boolean} - */ - Print(bUseSystemDefaultPrintUI: boolean): boolean; - - /** - * Binds a specified function to an event, so that the function gets called whenever the event fires. - * @method WebTwain#RegisterEvent - * @param {string} name the name of the event that the function is bound to. - * @param {any} evt specifies the function to call when event fires. - * @return {boolean} - */ - RegisterEvent(name: string, evt: any): boolean; - - /** - * Removes all images in buffer. - * @method WebTwain#RemoveAllImages - * @return {boolean} - */ - RemoveAllImages(): boolean; - - /** - * Removes selected images in buffer. - * @method WebTwain#RemoveAllSelectedImages - * @return {boolean} - */ - RemoveAllSelectedImages(): boolean; - - /** - * Removes the image of a specified index in buffer. - * @method WebTwain#RemoveImage - * @param {number} sImageIndexToBeDeleted specifies the index of the image to be deleted in buffer. The index is 0-based. - * @return {boolean} - */ - RemoveImage(sImageIndexToBeDeleted: number): boolean; - - /** - * Reverts the current image layout to the Data Source's default. - * @method WebTwain#ResetImageLayout - * @return {boolean} - */ - ResetImageLayout(): boolean; - - /** - * Sets the Source to return the current page to the input side of the document feeder and - * feed the last page from the outside of the feeder back into the acquisition area if IfFeederEnabled is TRUE. - * @method WebTwain#RewindPage - * @return {boolean} - */ - RewindPage(): boolean; - - /** - * Rotates the image of a specified index in buffer by specified angle. - * @method WebTwain#Rotate - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} fAngle Specifies the rotation angle. - * @param {boolean} bKeepSize Keep size or not. - * @return {boolean} - */ - Rotate(sImageIndex: number, fAngle: number, bKeepSize: boolean): boolean; - - /** - * Rotates the image of a specified index in buffer by specified angle. - * @method WebTwain#RotateEx - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} fAngle Specifies the rotation angle. - * @param {boolean} bKeepSize Keep size or not. - * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. - * @return {boolean} - */ - RotateEx(sImageIndex: number, fAngle: number, bKeepSize: boolean, newVal: EnumDWT_InterpolationMethod): boolean; - - /** - * Rotates the image of a specified index in buffer by 90 degrees counter-clockwise. - * @method WebTwain#RotateLeft - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - RotateLeft(sImageIndex: number): boolean; - - /** - * Rotates the image of a specified index in buffer by 90 degrees clockwise. - * @method WebTwain#RotateRight - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - RotateRight(sImageIndex: number): boolean; - - /** - * Saves all images in buffer as a MultiPage TIFF file. - * @method WebTwain#SaveAllAsMultiPageTIFF - * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - SaveAllAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves all images in buffer as a Multi-Page PDF file. - * @method WebTwain#SaveAllAsPDF - * @param {string} localFile the name of the Multi-Page PDF file to be saved. It should be an absolute path on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - SaveAllAsPDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the image of a specified index in buffer as a BMP file. - * @method WebTwain#SaveAsBMP - * @param {string} localFile the name of the BMP file to be saved. It should be an absolute path on the local disk. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - SaveAsBMP(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /*ignored - SaveAsGIF - */ - - /** - * Saves the image of a specified index in buffer as a JPEG file. - * @method WebTwain#SaveAsJPEG - * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - SaveAsJPEG(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the image of a specified index in buffer as a PDF file. - * @method WebTwain#SaveAsPDF - * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - SaveAsPDF(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the image of a specified index in buffer as a PNG file. - * @method WebTwain#SaveAsPNG - * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - SaveAsPNG(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the image of a specified index in buffer as a TIFF file. - * @method WebTwain#SaveAsTIFF - * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - SaveAsTIFF(localFile: string, sImageIndex: number, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the selected images in buffer as a Multipage PDF file. - * @method WebTwain#SaveSelectedImagesAsMultiPagePDF - * @param {string} localFile the name of the MultiPage PDF file to be saved. It should be an absolute path on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - SaveSelectedImagesAsMultiPagePDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the selected images in buffer as a Multipage TIFF file. - * @method WebTwain#SaveSelectedImagesAsMultiPageTIFF - * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. - * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. - * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. - * @return {boolean} - */ - SaveSelectedImagesAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; - - /** - * Saves the selected images in buffer to base64 string. - * @method WebTwain#SaveSelectedImagesToBase64Binary - * @return {string|boolean} - */ - SaveSelectedImagesToBase64Binary(optionalAsyncSuccessFunc?: (result: string[]) => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): string | boolean; - - /** - * [Deprecated.] Saves the selected images in buffer to a byte array in the specified file format. - * @method WebTwain#SaveSelectedImagesToBytes - * @param {number} bufferSize specified the buffer size. - * @param {Array} buffer A byte array of the image data. - * @return {number} - */ - SaveSelectedImagesToBytes(bufferSize: number, buffer: number[]): number; - - /** - * Brings up the TWAIN Data Source Manager's Source Selection User Interface (UI) - * so that user can choose which Data Source to be the current Source. - * @method WebTwain#SelectSource - * @return {boolean} - */ - SelectSource(): boolean; - - /** - * Selects the index-the source in SourceNameItems property as the current source. - * @method WebTwain#SelectSourceByIndex - * @param {number} index It is the index of SourceNameItems property. - * @return {boolean} - */ - SelectSourceByIndex(index: number): boolean; - - /*ignored - SetCancel - */ - - /** - * Set the value of the specified cap item. - * @method WebTwain#SetCapItems - * @param {number} index Index is 0-based. It is the index of the cap item. - * @param {number} newVal For string type, please use CapItemsstring property. - * @return {void} - */ - SetCapItems(index: number, newVal: number): void; - - /** - * Set the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. - * @method WebTwain#SetCapItemsString - * @param {number} index Index is 0-based. It is the index of the cap item. - * @param {string} newVal The new value to be set. - * @return {void} - */ - SetCapItemsString(index: number, newVal: string): void; - - /** - * [Deprecated.] Sets current cookie into the Http Header to be used when uploading scanned images through POST. - * @method WebTwain#SetCookie - * @param {string} cookie the cookie on current page. - * @return {void} - */ - SetCookie(cookie: string): void; - - // Set custom DS data (DAT_CUSTOMDSDATA), the input string is encoded with base64 - /** - * Sets custom DS data to be used for scanning, the input string is encoded with base64. Custom DS data means a specific scanning profile. - * @method WebTwain#SetCustomDSDataEx - * @param {string} value the input string which is encoded with base64. - * @return {boolean} - */ - SetCustomDSDataEx(value: string): boolean; - - // Set custom DS data, load data from the specified file - /** - * Sets custom DS data to be used for scanning, the data is stored in a file. Custom DS data means a specific scanning profile. - * @method WebTwain#SetCustomDSData - * @param {string} fileName the absolute path of the file where the custom data source data is stored. - * @return {boolean} - */ - SetCustomDSData(fileName: string): boolean; - - /** - * Change the DPI (dots per inch) for the specified image. - * @method WebTwain#SetDPI - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} xResolution The horizontal resolution. - * @param {number} yResolution The vertical resolution. - * @param {boolean} bResampleImage Whether to resample the image. (The image size will be changed if this is set to true). - * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. - * @return {boolean} - */ - SetDPI(sImageIndex: number, xResolution: number, yResolution: number, bResampleImage: boolean, newVal: EnumDWT_InterpolationMethod): boolean; - - /** - * Sets file name and file format information used in File Transfer Mode. - * @method WebTwain#SetFileXferInfo - * @param {string} fileName the name of the file to be used in transfer. - * @param {EnumDWT_FileFormat} fileFormat an enumerated value indicates the format of the image. - * @return {boolean} - */ - SetFileXferInfo(fileName: string, fileFormat: EnumDWT_FileFormat): boolean; - - /** - * Sets a text parameter as a filed in a web form. This form is maintained by the component itself (meaning it's not on the page). All fields in this form will be passed to the server when uploading images. - * @method WebTwain#SetHTTPFormField - * @param {string} FieldName specifies the name of a text field in web form. - * @param {string} FieldValue specifies the value of a text field in web form. - * @return {boolean} - */ - SetHTTPFormField(FieldName: string, FieldValue: string): boolean; - - /** - * Sets a text parameter as a filed in a web form. This form is maintained by the component itself (meaning it's not on the page). All fields in this form will be passed to the server when uploading images. - * @method WebTwain#SetHTTPFormField - * @param {string} FieldName specifies the name of the field which could later be used to retrieve the blob - * @param {Blob} blobValue specifies the blob to be put in the form. - * @param {string} optionalFileName specifies the file name for the blob - * @return {boolean} - */ - SetHTTPFormField(FieldName: string, blobValue: Blob, optionalFileName?: string): boolean; - - /** - * Sets a header for the current HTTP Post request. - * @method WebTwain#SetHTTPHeader - * @param {string} key the key of the header. - * @param {string} value the value of the header. - * @return {boolean} - */ - SetHTTPHeader(key: string, value: string): boolean; - - /** - * Sets the left, top, right, and bottom sides of the image layout rectangle for the current Data Source. - * @method WebTwain#SetImageLayout - * @param {number} left specifies the floating point number for the left side of the image layout rectangle. - * @param {number} top specifies the floating point number for the top side of the image layout rectangle. - * @param {number} right specifies the floating point number for the right side of the image layout rectangle. - * @param {number} bottom specifies the floating point number for the bottom side of the image layout rectangle. - * @return {boolean} - */ - SetImageLayout(left: number, top: number, right: number, bottom: number): boolean; - - /** - * Change the width of an image in buffer. - * @method WebTwain#SetImageWidth - * @param {number} sImageIndex specifies which image you'd like to change. - * @param {number} iNewWidth specifies how wide you'd like to change the image. - * @return {boolean} - */ - SetImageWidth(sImageIndex: number, iNewWidth: number): boolean; - - /** - * Set the language for the authorization dialogs. - * @method WebTwain#SetLanguage - * @param {EnumDWT_Language} language specify the language - * @return {boolean} - */ - SetLanguage(language: EnumDWT_Language): boolean; - - /** - * Sets the time-out used to open a specified Data Source. - * @method WebTwain#SetOpenSourceTimeout - * @param {number} iMilliseconds specifies the number of milliseconds. - * @return {boolean} - */ - SetOpenSourceTimeout(iMilliseconds: number): boolean; - - /** - * Draws a rectangle on the viewer which represents the selected area. - * @method WebTwain#SetSelectedImageArea - * @param {number} sImageIndex specifies the index of image in buffer. The index is 0-based. - * @param {number} left The X axis of the left border. - * @param {number} top The Y axis of the top border. - * @param {number} right The X axis of the right border. - * @param {number} bottom The Y axis of the bottom border. - * @return {boolean} - */ - SetSelectedImageArea(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; - - /** - * You can use the method to select images programatically which is ususally done by mouse clicking. - * @method WebTwain#SetSelectedImageIndex - * @param {number} sSelectedIndex this is the index of an array that holds the indices of selected images. - * @param {number} newVal specifies the index of an image that you want to select. - * @return {boolean} - */ - SetSelectedImageIndex(selectedIndex: number, newVal: number): boolean; - - /** - * Sets a custom tiff tag. Currently you can set up to 32 tags. The string to be set in a tag can be encoded with base64. - * @method WebTwain#SetTiffCustomTag - * @param {number} tag specifies the tag identifier. The value should be between 600 and 700. - * @param {string} content the string to be set for this tag. The string will be written to the .tiff file when you save/upload it. If the string is base64 encoded, we'll decode it before writing it. - * @param {boolean} base64Str if you'd like to encode the string with base64, set this to true. Otherwise, the string will be plin text. - * @return {boolean} - */ - SetTiffCustomTag(tag: number, content: string, base64Str: boolean): boolean; - - /** - * Configures how segmented upload is done. - * @method WebTwain#SetUploadSegment - * @param {number} segmentUploadThreshold specifies the threshold (in MB) over which segmented upload will be invoked. - * @param {number} moduleSize specifies the size of each segment (in KB). - * @return {boolean} - */ - SetUploadSegment(segmentUploadThreshold: number, moduleSize: number): boolean; - - /** - * Sets the view mode that images are displayed in Dynamic Web TWAIN. You can use this method to display multiple images in Dynamic Web TWAIN. - * @method WebTwain#SetViewMode - * @param {number} sHorizontalImageCount specifies how many columns can be displayed in Dynamic Web TWAIN. - * @param {number} sVerticalImageCount specifies how many rows can be displayed in Dynamic Web TWAIN.. - * @return {void} - */ - SetViewMode(sHorizontalImageCount: number, sVerticalImageCount: number): void; - - /** - * Show save file dialog or show open file dialog. - * @method WebTwain#ShowFileDialog - * @param {boolean} SaveDialog True -- show save file dialog, False -- show open file dialog. - * @param {string} Filter The filter name specifies the filter pattern (for example, "*.TXT"). To specify multiple filter patterns for a single display string, use a semicolon to separate the patterns (for example, "*.TXT;*.DOC;*.BAK"). A pattern string can be a combination of valid file name characters and the asterisk (*) wildcard character. Do not include spaces in the pattern string. To retrieve a shortcut's target without filtering, use the string "All Files\0*.*\0\0", but the program will replace "\0" with "|" automatically. - * @param {number} FilterIndex The index of the currently selected filter in the File Types control. The buffer pointed to by Filter contains pairs of strings that define the filters. The index is 0-based. - * @param {string} DefExtension Define the default extension. GetOpenFileName and GetSaveFileName append this extension to the file name only if the user fails to type an extension. If this member is NULL and the user fails to type an extension, no extension is appended. - * @param {string} InitialDir The initial directory. The algorithm for selecting the initial directory varies on different platforms. - * @param {boolean} AllowMultiSelect True -- allows users to select more than one file, False -- only allows to select one file. - * @param {boolean} OverwritePrompt True -- If a file already exists with the same name, the old file will be simply overwritten, False -- not allows to save and overwrite a same name file. - * @param {number} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and parameters "AllowMultiSelect" and "OverwritePrompt" will be useless. - * @return {boolean} - */ - ShowFileDialog(SaveDialog: boolean, Filter: string, FilterIndex: number, DefExtension: string, InitialDir: string, AllowMultiSelect: boolean, OverwritePrompt: boolean, Flags: number): boolean; - - /** - * Shows the GUI of Image Editor. - * @method WebTwain#ShowImageEditor - * @return {boolean} - */ - ShowImageEditor(): boolean; - - /** - * [Deprecated.] Shows the GUI of Image Editor with custom settings. - * @method WebTwain#ShowImageEditorEx - * @param {number} x specifies the new position of the left top corner of the window. - * @param {number} y specifies the new position of the left top corner of the window. - * @param {number} cx specifies the width of the window. - * @param {number} cy specifies the height of the window. - * @param {number} nCmdShow specifices how the window should be shown. - * @return {boolean} - */ - ShowImageEditorEx(x: number, y: number, cx: number, cy: number, nCmdShow: number): boolean; - - /*ingored - SourceNameItems - */ - - /** - * Switchs two images of specified indices in buffer. - * @method WebTwain#SwitchImage - * @param {number} sImageIndex1 specifies the index of image in buffer. The index is 0-based. - * @param {number} sImageIndex2 specifies the index of image in buffer. The index is 0-based. - * @return {boolean} - */ - SwitchImage(sImageIndex1: number, sImageIndex2: number): boolean; - - /** - * Unbinds an event from the specified function, so that the function stops receiving notifications when the event fires. - * @method WebTwain#UnregisterEvent - * @param {string} name the name of the event. - * @param {object} evt specified the function to be unbound. - * @return {boolean} - */ - UnregisterEvent(name: string, evt: object): boolean; - - /*ignored - checkErrorString - first - getInstance - last - next - on - onEvent - previous - - ...other internal ones - */ -} +// TypeScript Version: 2.4 + +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/dwt/mbc.d.ts b/types/dwt/mbc.d.ts new file mode 100644 index 0000000000..3c27fd8ac0 --- /dev/null +++ b/types/dwt/mbc.d.ts @@ -0,0 +1,1047 @@ +/**`constructor` MBC() + * Syntax:* `new MBC(license)` + * | parameter | type | description | + * | | | | + * | license | `String` | | + * example:* +```javascript + // MBC without a license can be used for evaluation purposes. It is not stable for long time usage. + var painter = new MBC(); + // MBC need a license in production environments. + painter = new MBC('xxxxx'); +``` + */ +declare namespace MBC { + /** + * Tell this painter the directory where you place`cv-wasm.js` and`cv-wasm.wasm`. + + * Syntax:* `MBC.cvFolder = 'js';` + */ + let cvFolder: string; + + /** + * You should call`MBC.loadCvScriptAsync()` first before use`Free Transform` and`Brush` module. + + * Syntax:* `MBC.loadCvScriptAsync(callback)` + + | parameter | type | description | + | | | | + | callback | `function(boolean bSuccess)` | | + + @example +```javascript + MBC.loadCvScriptAsync(function(bSuccess){ + if(bSuccess){ + console.log('load cv script success.'); + painter.enterFreeTransformModeAsync(); + }else{ + console.log('load cv script fail.'); + } + }); +``` + */ + function loadCvScriptAsync(): any; +} + +interface rectangle { + left: number; + top: number; + right: number; + bottom: number; +} + +interface point { + x: number; + y: number; +} + +interface cornerPoints { + leftTop: point; + rightTop: point; + leftBottom: point; + rightBottom: point; +} + +declare class TaskQueue { + _queue: any[]; + isWorking: boolean; + timeout: number; + /** + * Constructs a new task queue + */ + constructor(); +} + +interface TaskQueue { + push(task: any, context?: any, args?: any): void; + unshift(task: any, context?: any, args?: any): void; + next(): void; +} + +declare class KPainter { + /** + * Constructs a new KPainter + */ + constructor(mbcKey?: string); + /** + * @example +```javascript + var painterDom = painter.getHtmlElement(); + painterDom.style.width = '100%'; + painterDom.style.height = '100%'; + document.getElementById('painter-container').appendChild(painterDom); +``` + * + */ + getHtmlElement(): HTMLDivElement; + + /** + * Get the current showing image index a in MBC instance. + */ + getCurIndex(): number; + + /** + * Get the image count in a MBC instance. + */ + getCount(): number; + + /** + * Identify whether the MBC instance is in `Editing` mode. + */ + isEditing(): boolean; + + /** + * +@example +```javascript + // A way to access to inner data. Don't modify it if you are not sure. + var imgOri = painter.getImage(true); + // This image can be used in any place and free to modify it. + var imgCopyed = painter.getImage(); + imgCopyed.style.width = '100px'; + imgCopyed.style.height = '100px'; + document.getElementById('image-container').appendChild(imgCopyed); +``` + */ + getImage(isOri: boolean, index: number): HTMLImageElement; + + /** + * Binding a function that would be called when starting an expensive operation. + * Syntax:* `function(){}` +@example +```javascript + painter.onStartLoading = function(){ + document.getElementById('animation').show(); + }; +``` + */ + onStartLoading: () => void; + + /** + * Binding a function that would be called when finishing an expensive operation. + + * Syntax:* `function(){}` + + @example```javascript + painter.onFinishLoading = function(){ + document.getElementById('animation').hide(); + }; + ``` + */ + onFinishLoading: () => void; + + // Image Store + + /** + * Show file choose window by click the hidden file input.Can't process during `Editing` mode. + * @example +```javascript + document.getElementById('btn-add-image').addEventListener('click', function(){ + painter.showFileChooseWindow(); + }); +``` + */ + showFileChooseWindow(): boolean; + + /** + * @example +```javascript + // warning: never redefine it if you are not sure + // painter.defaultFileInput = document.createElement('input'); + painter.defaultFileInput.accept = "image/png"; + painter.defaultFileInput.multiple = false; +``` + */ + defaultFileInput: HTMLInputElement; + + /** + * Binding a function that would be called when`defaultFileInput` change by`showFileChooseWindow()`. + + * Syntax:* `function(event, callback){}` + + @example +```javascript + painter.beforeAddImgFromFileChooseWindow = function(ev, callback){ + var files = ev.target.files; + var newBlobs = []; + var finishedIndex = 0; + for(var i = 0; i < files.length; ++i){ + var file = files[i]; + doSomeWorkToGetANewBlob(file, function(blob){ + newBlobs.push(blob); + if(files.length == ++finishedIndex){ + callback(newBlobs); + } + }); + } + }; +``` + */ + beforeAddImgFromFileChooseWindow: () => void; + + /** + * Binding a function that would be called after adding image from`defaultFileInput`. + + * Syntax:* `function(){}` + + @example +```javascript + painter.afterAddImgFromFileChooseWindow = function(bSuccess){ + if(bSuccess){console.log('The new image(s) has been added from file choose window.');} + }; +``` + */ + afterAddImgFromFileChooseWindow: () => void; + + /*** + * Syntax:* `function(event, callback){}` + @example +```javascript + painter.beforeAddImgFromDropFile = function(ev, callback){ + var files = ev.dataTransfer.files; + var newBlobs = []; + var finishedIndex = 0; + for(var i = 0; i < files.length; ++i){ + var file = files[i]; + doSomeWorkToGetANewBlob(file, function(blob){ + newBlobs.push(blob); + if(files.length == ++finishedIndex){ + callback(newBlobs); + } + }); + } + }; +``` + */ + beforeAddImgFromDropFile: () => any; + + /** + * + * Syntax:* `function(){}` + + @example +```javascript + painter.afterAddImgFromDropFile = function(bSuccess){ + if(bSuccess){console.log('The new image(s) has been added from dropping.');} + }; +``` + * + */ + afterAddImgFromDropFile: () => void; + + /** + * Syntax:* `.addImageAsync(imgData, callback)` + + | parameter | type | description | + | | | | + | imgData | `Blob`, `HTMLCanvasElement`, `HTMLImageElement`, `String` * (url) *, `Array` * (a array of source)*, `FileList` | | + | callback * (optional) * | `function(bSuccess)` | | + + @example +```javascript + painter.addImageAsync(image, function(bSuccess){ + console.log('Add success'); + }); +``` + */ + addImageAsync(imgData: Blob | HTMLCanvasElement | HTMLImageElement | string | string[], callback?: () => void): void; + + /** + The image whose width or height larger than`addedImageMaxWH` would be compressed when adding. + + * Syntax:* `.addedImageMaxWH = 4096;` + */ + addedImageMaxWH: number; + + /** + * Whether`changePage` to the new added image. + + * Syntax:* `.isShowNewImgWhenAdd = true;` + */ + isShowNewImgWhenAdd: boolean; + + /** + * Update the`htmlElement` of a MBC instance.Should call it manually when the`htmlElement` resize. + + * Syntax:* `.updateUIOnResize(isLazy, callback)` + + | parameter | type | description | + | | | | + | isLazy * (optional) *| `boolean` | Default false.Set true to avoid to update too frequently. | + | callback | `function()` | Callback of finish updating.Might abort the earlier callback when`isLazy` is true. | + + @example +```javascript + window.addEventListener('resize',function(){ + painter.updateUIOnResize(true, function(){ + console.log('painter update'); + }); + }); +``` + */ + updateUIOnResize(isLazy?: boolean, callback?: () => void): void; + + /** + * Binding a function that would be called when current image index or total length change. + + * Syntax:* `function(Number curIndex, Number length){}` + + @example +```javascript + painter.onNumChange = function(curIndex, length){ + console.log('curIndex: '+curIndex+', length:'+length); + }; +``` + */ + onNumChange: (curIndex: number, length: number) => void; + + /** + * Change index of the current page.Can only process in `Viewing` mode. + + * Syntax:* `.changePage(cmd)` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + | cmd | `Number` * (index) *, `String` * ('f', 'p', 'n', 'l') * | Index number, or command string of 'f'(first), 'p'(pre), 'n'(next), 'l'(last). | + + @example +```javascript + document.getElementById('btn-first').addEventListener('click', function(){ + painter.changePage('f'); + }); + document.getElementById('btn-pre').addEventListener('click', function(){ + painter.changePage('p'); + }); + document.getElementById('btn-next').addEventListener('click', function(){ + painter.changePage('n'); + }); + document.getElementById('btn-last').addEventListener('click', function(){ + painter.changePage('l'); + }); + document.getElementById('btn-toThisPage').addEventListener('click', function(){ + painter.changePage(parseInt(document.getElementById('ipt-page').value)); + }); +``` + */ + changePage(cmd: number | string): boolean; + + /** + * Delete a image.Can only process in `Viewing` mode. + + * Syntax:* `.del(index)` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + | index * (optional) * | `Number` | Default current index. | + + */ + del(index: number): boolean; + + /** + * Get width of current image in the MBC instance. + + * Syntax:* `.getWidth(index)` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | | + | index * (optional) * | `Number` | Default current index. | + */ + getWidth(index: number): number; + + /** + * Get height of current image in the MBC instance. + + * Syntax:* `.getHeight(index)` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | | + | index * (optional) * | `Number` | Default current index. | + */ + getHeight(index: number): number; + + /** + * Get the image data in `Blob` type. + + * Syntax:* `.getBlob(index)` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | | + | index * (optional) * | `Number` | Default current index. | + */ + getBlob(index: number): Blob; + + /** + * Download the image to users' local system. The function should be invoked directly by the user. Async invoking may have problems. + + * Syntax:* `.download(filename, index)` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | | + | filename * (optional) * | `String` | | + | index * (optional) * | `Number` | Default current index. | + + @example +```javascript + document.getElementById('btn-download').addEventListener('click', function(){ + for(var i = 0; i < painter.getCount(); ++i){ + painter.download(null, i); + } + }); +``` + */ + download(filename?: string, index?: number): number; + + /** + * Syntax:* `.bindThumbnailBox(container, funWrap, maxWH)` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + | container | `HTMLElement` | | + | funWrap * (optional) * | `HTMLElement function(HTMLCanvasElement cvs)` | | + | maxWH * (optional) * | `Number` | Default 256. | + + @example +```javascript + painter.bindThumbnailBox(document.getElementById('div-thumbnailContainer'), function(cvs){ + console.log(cvs.className);// 'kPainterThumbnailCanvas', never remove this class + var box = document.createElement('div'); + box.className = 'div-thumbnailBox'; + box.appendChild(cvs); + box.addEventListener('click', function(){ + var idx = box.getKPainterIndex();// get index + painter.changePage(idx); + }); + return box; + }); +``` + */ + bindThumbnailBox(container: HTMLElement, funWrap?: () => HTMLElement, maxWH?: number): boolean; + + /** + * Syntax:* `.unbindThumbnailBox(container)` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + | container | `HTMLElement` | | + + @example +```javascript + painter.bindThumbnailBox(document.getElementById('div-thumbnailContainer')); +``` + */ + unbindThumbnailBox(container: HTMLElement): boolean; + + // Gesture + + /** + * + Set the zoom rate when user left double click. + + * Syntax:* `.leftDoubleClickZoomRate = 2;` + + */ + leftDoubleClickZoomRate: number; + + /** + * Set the zoom rate when user right double click. + + * Syntax:* `.rightDoubleClickZoomRate = 0.5;` + */ + rightDoubleClickZoomRate: number; + + /** + * Whether allow switch from last to first or from first to last by`touchmove` gesture. + + * Syntax:* `.allowedTouchMoveSwitchImgOverBoundary = true;` + */ + allowedTouchMoveSwitchImgOverBoundary: boolean; + + /** + * Binding a function that would be called when the performence of the current image or canvas(in `Editing` mode) update. + + * Syntax:* `function(){}` + + @example +```javascript + painter.onUpdateImgPosZoom(function(){ + console.log(painter.getZoom()); + console.log(painter.getEditWidth()); + console.log(painter.getEditHeight()); + }); +``` + */ + onUpdateImgPosZoom: () => void; + + /** + * Get the zoom of current image or canvas(in `Editing` mode). + + * Syntax:* `.getZoom()` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | | + */ + getZoom(): number; + + /** + * Set the zoom of current image or canvas(in `Editing` mode). + + * Syntax:* `.setZoom(num, isRate)` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | The finally effective zoom. | + | num | `Number` | | + | isRate | `boolean` | | + */ + setZoom(num: number, isRate: boolean): number; + + // Basic Editor + + /** + * The can - not - store step(freeTransform, brush) will generate a step image.If the step images' count over `stepImgsGCThreshold`, oldest not protected one would be GC. + + * Syntax:* `.stepImgsGCThreshold = 10;` + */ + stepImgsGCThreshold: number; + + /** + * Add a protected step.Then this step would not be GC.Can only process in `Editing` mode. + + * Syntax:* `.addProtectedStep(index)` + + | parameter | type | description | + | | | | + | index | `Number` | | + + @example +```javascript + // sample code: save and give up editing about freeTransform mode + document.getElementById('btn-enterFreeTransformMode').addEventListener('click', function(){ + // pretect step when enter freeTransform mode + painter.addProtectedStep(painter.getCurStep()); + // presume that `MBC.loadCvScriptAsync(callback)` has been called and success + painter.enterFreeTransformModeAsync(); + }); + + document.getElementById('btn-saveFreeTransform').addEventListener('click', function(){ + // remove the the last pretect step + var protectedSteps = painter.getProtectedSteps(); + painter.removeProtectedStep(protectedSteps[protectedSteps.length - 1]); + // transform and exitFreeTransformMode + painter.freeTransformAsync(function(){ + painter.exitFreeTransformModeAsync(); + }); + }); + + document.getElementById('btn-giveUpFreeTransform').addEventListener('click', function(){ + // pretect step when enter freeTransform mode + var protectedSteps = painter.getProtectedSteps(); + var lastPretectedStep = protectedSteps[protectedSteps.length - 1]; + // remove the the last pretect step + painter.removeProtectedStep(lastPretectedStep); + // exitFreeTransformMode + painter.exitFreeTransformModeAsync(function(){ + // jump to the last pretect step + painter.setCurStepAsync(lastPretectedStep); + }); + }); +``` + */ + addProtectedStep(index: number): boolean; + + /** + * Remove a protected step.Then this step can be GC.Can only process in `Editing` mode. + + * Syntax:* `.removeProtectedStep(index)` + + | parameter | type | description | + | | | | + | index | `Number` | | + + */ + removeProtectedStep(index: number): boolean; + + /** + * Get All protected steps.Can only process in `Editing` mode. + + * Syntax:* `.getProtectedSteps()` + + | parameter | type | description | + | | | | + | * (return value)* | `Array` | A array of the protected numbers. | + */ + getProtectedSteps(): number[]; + + /** + * Undo an editing step.Can only process in `Editing` mode. + + * Syntax:* `.undo(callback)` + + | parameter | type | description | + | | | | + | callback | `function(boolean bSuccess)` | | + */ + undo(callback: () => void): void; + + /** + * Redo an editing step.Can only process in `Editing` mode. + + * Syntax:* `.redo(callback)` + + | parameter | type | description | + | | | | + | callback | `function(boolean bSuccess)` | | + */ + redo(callback: () => void): void; + + /** + * Get count of editing steps.Can only process in `Editing` mode. + + * Syntax:* `.getStepCount()` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | | + */ + getStepCount(): number; + + /** + * Get current editing step.Can only process in `Editing` mode. + + * Syntax:* `.getCurStep()` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | | + */ + getCurStep(): number; + + /** + * Set current editing step.Can only process in `Editing` mode. + + * Syntax:* `.setCurStepAsync(index, callback)` + + | parameter | type | description | + | | | | + | index | `Number` | | + | callback | `function(boolean bSuccess)` | | + */ + setCurStepAsync(index: number, callback: () => void): void; + + /** + * Enter the`Editing` mode. + + * Syntax:* `.enterEditAsync(callback)` + + | parameter | type | description | + | | | | + | callback | `function(boolean bSuccess)` | | + */ + enterEditAsync(callback: () => void): void; + + /** + * Leave the`Editing` mode without saving change. + + * Syntax:* `.cancelEdit(callback)` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + */ + cancelEdit(callback: () => void): boolean; + + /** + * Save change and leave the`Editing` mode. + + * Syntax:* `.saveEditAsync(callback, isCover)` + + | parameter | type | description | + | | | | + | callback | `function(boolean bSuccess)` | | + | isCover | `boolean` | | + */ + saveEditAsync(callback: () => void, isCover: boolean): void; + + /** + * Rotate right.Can only process in `Editing` mode. + + * Syntax:* `.rotateRight()` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + */ + rotateRight(): boolean; + + /** + * Rotate left.Can only process in `Editing` mode. + + * Syntax:* `.rotateLeft()` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + */ + rotateLeft(): boolean; + + /** + * Mirror.Can only process in `Editing` mode. + + * Syntax:* `.mirror()` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + */ + mirror(): boolean; + + /** + * Flip.Can only process in `Editing` mode. + + * Syntax:* `.flip()` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + */ + flip(): boolean; + + /** + * Resize.Can only process in `Editing` mode. + + * Syntax:* `.resizeAsync(newWidth, newHeight, callback)` + + | parameter | type | description | + | | | | + | newWidth | `Number` | | + | newHeight | `Number` | | + | callback | `function(boolean bSuccess)` | | + */ + resizeAsync(newWidth: number, newHeight: number, callback: () => void): void; + + /** + * Get width of current editing canvas. + + * Syntax:* `.getEditWidth()` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | | + */ + getEditWidth(): number; + + /** + * Get height of current editing canvas. + + * Syntax:* `.getEditHeight()` + + | parameter | type | description | + | | | | + | * (return value)* | `Number` | | + */ + getEditHeight(): number; + + // Crop + + /** + * Whether show`Crop Rect` UI when enter`Editing` mode + + * Syntax:* `.isAutoShowCropUI = true;` + */ + isAutoShowCropUI: boolean; + + /** + Show`Crop Rect`.Can only process in `Editing` mode. + + * Syntax:* `.showCropRect()` + */ + showCropRect(): void; + + /** + * Hide`Crop Rect`.Can only process in `Editing` mode. + + * Syntax:* `.hideCropRect()` + */ + hideCropRect(): void; + + /** + * Default 0. + 0: touch / click moving inside`Crop Rect` will move the back canvas. + 1: touch / click moving inside`Crop Rect` will move the`Crop Rect`. + + * Syntax:* `.setCropRectStyle(styleNo)` + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + | styleNo | `Number` | 0, 1 | + */ + setCropRectStyle(styleNo: number): boolean; + + /** + * `Crop Rect` min width. + + * Syntax:* `.cropRectMinW = 50;` + */ + cropRectMinW: number; + + /** + `Crop Rect` min height. + + * Syntax:* `.cropRectMinH = 50;` + */ + cropRectMinH: number; + + /** + * Binding a function that would be called when the`Crop Rect` change. + + * Syntax:* `function(){}` + + @example +```javascript + painter.onCropRectChange = function(){ + var cropArea = painter.getCropRectArea(true); + document.getElementById('cropWidth').innerText = cropArea[2] - cropArea[0]; + document.getElementById('cropHeight').innerText = cropArea[3] - cropArea[1]; + }; +``` + */ + onCropRectChange: () => void; + + /** + * + * Syntax:* `.setCropRectArea(left, top, right, bottom)` + `Crop Rect` select an area. + + | parameter | type | description | + | | | | + | * (return value)* | `boolean` | | + | left * (optional) * | `Number` | -0.5 ~0.5, default -0.5. | + | top * (optional) * | `Number` | -0.5 ~0.5, default -0.5. | + | right * (optional) * | `Number` | -0.5 ~0.5, default 0.5. | + | bottom * (optional) * | `Number` | -0.5 ~0.5, default 0.5. | + */ + setCropRectArea(left: number, top: number, right: number, bottom: number): boolean; + + /** + * Syntax:* `.getCropRectArea(isAbsolute)` + + | parameter | type | description | + | | | | + | * (return value)* | `Array` | A array of[left, top, right, bottom]. | + | isAbsolute | `boolean` | Default`false`, get precentage(-50 % ~50 %) array. | + + */ + getCropRectArea(isAbsolute: boolean): rectangle[]; + + /** + * Crop the selected area.Can only process in `Editing` mode. + + * Syntax:* `.cropAsync(callback, array)` + + | parameter | type | description | + | | | | + | callback * (optional) * | `function([left, top, right, bottom])` | | + | array * (optional) * | `Array` | A array of[left, top, right, bottom]\(each - 0.5 ~0.5\).Default use an area accroding to`Crop Rect`. | + + */ + cropAsync(callback?: () => void, array?: rectangle[]): void; + + // Free Transform + + /** + * You should call`KPainter.loadCvScriptAsync()` first before use`FreeTransform` mode. + */ + + /** + * Detect a document.Would auto call`setFreeTransformCornerPos()` after detected.Can only process in `FreeTransform` mode. + + * Syntax:* `.documentDetectAsync(callback, importSrc)` + + | parameter | type | description | + | | | | + | callback * (optional) * | `function([[x0,y0], [x1,y1], [x2,y2], [x3,y3]])` | x0, y0...is from - 0.5 to 0.5. | + | importSrc * (optional) * | | TUDO.Not easy enough to use now. | + */ + documentDetectAsync(callback?: () => void, importSrc?: any): void; + + /** + * Set the`FreeTransform` corner position.Can only process in `FreeTransform` mode. + + * Syntax:* `.setFreeTransformCornerPos(cornerPoints)` + + | parameter | type | description | + | | | | + | cornerPoints | `Array` | A array of[[x0, y0], [x1, y1], [x2, y2], [x3, y3]].x0, y0...is from - 0.5 to 0.5. | + + */ + setFreeTransformCornerPos(cornerPoints: cornerPoints): any; + + /** + * Get the`FreeTransform` corner position. + + * Syntax:* `.getFreeTransformCornerPos()` + + | parameter | type | description | + | | | | + | * (return value)* | `Array` | A array of[[x0, y0], [x1, y1], [x2, y2], [x3, y3]].x0, y0...is from - 0.5 to 0.5.| + + */ + getFreeTransformCornerPos(): cornerPoints[]; + + /** + * Binding a function that would be called when the`FreeTransform` corner position change. + + * Syntax:* `function()` + + @example +```javascript + painter.onFreeTransformCornerPosChange = function(){ + console.log(painter.getFreeTransformCornerPos()); + }; +``` + */ + onFreeTransformCornerPosChange: () => void; + + /** + * + * `freeTransformAsync()` is a really expensive operation. `freeTransformMaxWH` would limit the max width and height of the result. + + * Syntax:* `.freeTransformMaxWH = 2048;` + */ + freeTransformMaxWH: number; + + /** + * + Transform the quadrilateral surround by the`FreeTransform` corner into a rectangle.Can only process in `FreeTransform` mode. + + * Syntax:* `.freeTransformAsync(callback, cornerPoints, importSrc)` + + | parameter | type | description | + | | | | + | callback * (optional) * | `function(boolean bSuccess)` | | + | cornerPoints * (optional) * | `Array` | A array of[[x0, y0], [x1, y1], [x2, y2], [x3, y3]].x0, y0...is from - 0.5 to 0.5. | + | importSrc * (optional) * | | TUDO.Not show for user. | + */ + freeTransformAsync(callback?: () => void, cornerPoints?: cornerPoints[], importSrc?: any): any; + + /** + * + Enter`FreeTransform` mode.Can only process in `Editing` mode. + + * Syntax:* `.enterFreeTransformModeAsync(callback)` + + | parameter | type | description | + | | | | + | callback * (optional) * | `function(boolean bSuccess)` | | + */ + enterFreeTransformModeAsync(callback: () => void): any; + + /** + * Exist`FreeTransform` mode. + + * Syntax:* `.exitFreeTransformModeAsync(callback)` + + | parameter | type | description | + | | | | + | callback * (optional) * | `function(boolean bSuccess)` | | + */ + exitFreeTransformModeAsync(callback?: () => void): any; + + // Video + + videoSettings: MediaStreamConstraints; + + // `MediaStreamConstraints`.videoSettings + /** + A[MediaStreamConstraints](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints). + + * reference:* [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) + + * Syntax:* `.showVideo(callback, videoSettings)` + + | parameter | type | description | + | | | | + | callback * (optional) * | `function(boolean bSuccess)` | | + | videoSettings * (optional) * | `MediaStreamConstraints` | A[MediaStreamConstraints](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints). *reference:* [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) | + */ + showVideo(callback?: () => void, videoSettings?: MediaStreamConstraints): boolean; + + /** + * Syntax:* `.grabVideo()` + + Grab a image from the video and return the image. + + | parameter | type | description | + | | | | + | * (return value)* | `HTMLCanvasElement` | | + * Syntax:* `.grabVideo(true, callback)` + + Grab a image from the video and auto add image to the painter.Can only process in `Viewing` mode. + + | parameter | type | description | + | | | | + | callback * (optional) * | `function(boolean bSuccess)` | | + */ + grabVideo(isAutoAdd?: boolean, callback?: () => void): HTMLCanvasElement | void; + + /** + * Syntax:* `.hideVideo()` + */ + hideVideo(): boolean; + + /** + * Syntax:* `function(canvas, callback){}` + + @example +```javascript + painter.beforeAddImgFromGrabVideoBtn = function(canvas, callback){ + doSomeWorkToGetNewSrc(canvas, function(srcValidForAddImage){ + callback(srcValidForAddImage); + }); + }; +``` + */ + beforeAddImgFromGrabVideoBtn: () => void; + + /** + * Syntax:* `function(){}` + + @example +```javascript + painter.afterAddImgFromGrabVideoBtn = function(bSuccess){ + if(bSuccess){console.log('The new image(s) has been added from video.');} + }; +``` + */ + afterAddImgFromGrabVideoBtn: () => void; +} diff --git a/types/dwt/tsconfig.json b/types/dwt/tsconfig.json index 13f35fcfbf..60686cd69f 100644 --- a/types/dwt/tsconfig.json +++ b/types/dwt/tsconfig.json @@ -2,11 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -17,8 +18,15 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts", + "addon.ocr.d.ts", + "addon.ocrp.d.ts", "addon.pdf.d.ts", - "dwt-tests.ts" + "addon.webcam.d.ts", + "dbr.d.ts", + "dwt-tests.ts", + "dwt.d.ts", + "index.d.ts", + "Dynamsoft.d.ts", + "mbc.d.ts" ] -} \ No newline at end of file +} diff --git a/types/dwt/v12/dwt-tests.ts b/types/dwt/v12/dwt-tests.ts deleted file mode 100644 index b1a5cc6b09..0000000000 --- a/types/dwt/v12/dwt-tests.ts +++ /dev/null @@ -1,101 +0,0 @@ -function dwtOnReady() { - const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer' - if (DWObject) { - let count = DWObject.SourceCount; - if (count === 0) { - DWObject.CloseSourceManager(); - DWObject.ImageCaptureDriverType = 0; - DWObject.OpenSourceManager(); - count = DWObject.SourceCount; - } - } -} - -function acquireImage() { - const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); - if (DWObject) { - DWObject.SelectSourceByIndex(0); // Use method SelectSourceByIndex to avoid the 'Select Source' dialog - DWObject.OpenSource(); - DWObject.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/closed automatically after the scan. - DWObject.AcquireImage({}, () => {}, (errorCode: number, errorString: string) => {DWObject.CloseSource(); }); - } -} - -function registerEvent() { - const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); - if (DWObject) { - // The event OnPostTransfer fires after each image is scanned and transferred - DWObject.RegisterEvent("OnPostTransfer", function () {}); - - // The event OnPostLoad fires after the images from a local directory have been loaded into the control - DWObject.RegisterEvent("OnPostLoad", function () {}); - - // The event OnMouseClick fires when the mouse clicks on an image on Dynamic Web TWAIN viewer - DWObject.RegisterEvent("OnMouseClick", function () {}); - - // The event OnTopImageInTheViewChanged fires when the top image currently displayed in the viewer changes - DWObject.RegisterEvent("OnTopImageInTheViewChanged", function (index: number) { - DWObject.CurrentImageIndexInBuffer = index; - }); - } -} - -function editImage() { - const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); - if (DWObject) { - if (DWObject.HowManyImagesInBuffer > 0) - DWObject.RotateLeft(DWObject.CurrentImageIndexInBuffer); - - if (DWObject.HowManyImagesInBuffer > 0) - DWObject.RotateRight(DWObject.CurrentImageIndexInBuffer); - - if (DWObject.HowManyImagesInBuffer > 0) - DWObject.Mirror(DWObject.CurrentImageIndexInBuffer); - - if (DWObject.HowManyImagesInBuffer > 0) - DWObject.Flip(DWObject.CurrentImageIndexInBuffer); - } -} - -function showImageEditor() { - const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); - if (DWObject) { - DWObject.ShowImageEditor(); - } -} - -function saveImage() { - const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); - if (DWObject) { - DWObject.ConvertToGrayScale(DWObject.CurrentImageIndexInBuffer); - DWObject.SaveAsJPEG("DynamicWebTWAIN.jpg", DWObject.CurrentImageIndexInBuffer); - DWObject.SaveAllAsMultiPageTIFF("DynamicWebTWAIN.tiff", () => {}, (errorCode: number, errorString: string) => {}); - DWObject.SaveAllAsPDF("DynamicWebTWAIN.pdf", () => {}, (errorCode: number, errorString: string) => {}); - } -} - -function updateLargeViewer() { - const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); - const DWObjectLargeViewer = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainerLargeViewer'); - if (DWObject) { - DWObject.CopyToClipboard(DWObject.CurrentImageIndexInBuffer); // Copy the current image in the thumbnail to clipboard in DIB format. - DWObjectLargeViewer.LoadDibFromClipboard(); // Load the image from Clipboard into the large viewer. - } -} - -function uploadImage() { - const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); - if (DWObject) { - DWObject.HTTPPort = 80; - DWObject.IfSSL = false; - DWObject.HTTPUploadThroughPost("www.dynamsoft.com", DWObject.CurrentImageIndexInBuffer, "upload", "tmp.jpg", () => {}, (errorCode: number, errorString: string) => {}); - } -} - -function downloadImage() { - const DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); - if (DWObject) { - DWObject.HTTPPort = 80; - DWObject.HTTPDownload("www.dynamsoft.com", "img.png", () => {}, (errorCode: number, errorString: string) => {}); - } -} diff --git a/types/dwt/v12/tslint.json b/types/dwt/v12/tslint.json deleted file mode 100644 index cb4a75513c..0000000000 --- a/types/dwt/v12/tslint.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "jsdoc-format": false, - "max-line-length": [false], - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-trailing-whitespace": false, - "space-before-function-paren": false, - "only-arrow-functions": [false] - } -} diff --git a/types/elliptic/elliptic-tests.ts b/types/elliptic/elliptic-tests.ts index d587be5e8d..8af88b46a4 100644 --- a/types/elliptic/elliptic-tests.ts +++ b/types/elliptic/elliptic-tests.ts @@ -1,4 +1,5 @@ import elliptic = require('elliptic'); +import BN = require('bn.js'); const ec = new elliptic.ec('secp256k1'); @@ -45,3 +46,49 @@ const newKey = ec.keyFromPublic(pub, 'hex'); // Verify signature console.log(key.verify(msgHash, signature)); + +// EDDSA tests +const eddsa = new elliptic.eddsa('ed25519'); +const msg = Buffer.from('dead', 'hex'); +const priv = 'deadbeef'; + +const sig = eddsa.sign(msg, priv); +sig.toHex(); +sig.toBytes(); +eddsa.sign(msg.toString('hex'), priv).toHex(); + +const edkey = eddsa.keyFromSecret(priv); +edkey.verify(msg, sig); +edkey.verify(msg.toString('hex'), sig.toBytes()); + +const edkey2 = eddsa.keyFromPublic(key.getPublic()); +edkey2.verify(msg, sig); + +eddsa.verify(msg, sig, edkey2.getPublic('hex')); +eddsa.verify(msg.toString('hex'), sig.toBytes(), edkey2.getPublic()); +eddsa.verify(msg, sig.toHex(), edkey2.getPublic()); + +// Curves Tests +elliptic.curve.base.BasePoint; + +const c = new elliptic.curve.edwards({ + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: -1, + c: 1, + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', +}); + +const p = c.pointFromX(5555); +p.eq(p); +eddsa.isPoint(p); +c.validate(p.add(p).mul(new BN(3)).dbl()); + +const sc = new elliptic.curve.short({ + a: 1, + b: 0, + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', +}); + +const p2 = sc.pointFromX(123456789); +sc.validate(p2.add(p2).mul(new BN(5)).dbl()); +sc.pointFromJSON(p2.toJSON(), false).toJSON(); diff --git a/types/elliptic/index.d.ts b/types/elliptic/index.d.ts index 7ae7972150..fa8e19a2cf 100644 --- a/types/elliptic/index.d.ts +++ b/types/elliptic/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for elliptic 6.4 // Project: https://github.com/indutny/elliptic // Definitions by: Daniel Byrne +// Gaylor Bosson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import BN = require('bn.js'); @@ -8,151 +9,286 @@ 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; // ? - } + /** + * @description Base class for the curves + */ + class base { + p: BN; + type: string; + red: any; // ? + zero: BN; + one: BN; + two: BN; + n: BN; + g: base.BasePoint; + redN: BN; - 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; // ? - } + constructor(type: string, conf: base.BaseCurveOptions) - interface BaseCurveOptions { - p: number | string | number[] | Buffer | BN; - prime?: BN | string; - n?: number | BN | Buffer; - g?: any; // ? - gRed?: any; // ? - } + validate(point: base.BasePoint): boolean; + decodePoint(bytes: Buffer | string, enc?: 'hex'): base.BasePoint; + } - interface PrecomputedValues { - doubles: any; // ? - naf: any; // ? - beta: any; // ? - } - } + namespace base { + class BasePoint { + curve: base; + type: string; + precomputed: PrecomputedValues | null; + + constructor(curve: base, type: string); + + encode(enc: string, compact: boolean): string | Buffer; + encodeCompressed(enc: string): BN; + validate(): boolean; + precompute(power: number): BasePoint; + dblp(k: number): BasePoint; + inspect(): string; + isInfinity(): boolean; + add(p: BasePoint): BasePoint; + mul(k: BN): BasePoint; + dbl(): BasePoint; + getX(): BN; + getY(): BN; + eq(p: BasePoint): boolean; + neg(): BasePoint; + } + + interface BaseCurveOptions { + p: number | string | number[] | Buffer | BN; + prime?: BN | string; + n?: number | BN | Buffer; + g?: BasePoint; + gRed?: any; // ? + } + + interface PrecomputedValues { + doubles: any; // ? + naf: any; // ? + beta: any; // ? + } + } + + class edwards extends base { + a: BN; + c: BN; + c2: BN; + d: BN; + dd: BN; + + constructor(conf: edwards.EdwardsConf); + + point(x: BNInput, y: BNInput, z?: BNInput, t?: BNInput): edwards.EdwardsPoint; + pointFromX(x: BNInput, odd?: boolean): edwards.EdwardsPoint; + pointFromY(y: BNInput, odd?: boolean): edwards.EdwardsPoint; + pointFromJSON(obj: BNInput[]): edwards.EdwardsPoint; + } + + namespace edwards { + interface EdwardsConf extends base.BaseCurveOptions { + a: BNInput; + c: BNInput; + d: BNInput; + } + + class EdwardsPoint extends base.BasePoint { + x: BN; + y: BN; + z: BN; + t: BN; + + normalize(): EdwardsPoint; + eqXToP(x: BN): boolean; + } + } + + class short extends base { + a: BNInput; + b: BNInput; + g: short.ShortPoint; + + constructor(conf: short.ShortConf); + + point(x: BNInput, y: BNInput, isRed?: boolean): short.ShortPoint; + pointFromX(x: BNInput, odd?: boolean): short.ShortPoint; + pointFromJSON(obj: BNInput[], red: boolean): short.ShortPoint; + } + + namespace short { + interface ShortConf extends base.BaseCurveOptions { + a: BNInput; + b: BNInput; + beta?: BNInput; + lambda?: BNInput; + } + + class ShortPoint extends base.BasePoint { + x: BN; + y: BN; + inf: boolean; + + toJSON(): BNInput[]; + } + } } export namespace curves { - class PresetCurve { - constructor(options: PresetCurve.Options) - type: string; - g: any; // ? - n: BN | undefined | null; - hash: any; // ? - } + class PresetCurve { + 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; // ? - } - } + constructor(options: PresetCurve.Options) + } + + 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; + 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; + constructor(options: string | curves.PresetCurve) + + keyPair(options: ec.KeyPairOptions): ec.KeyPair; + keyFromPrivate(priv: Buffer | string | ec.KeyPair, enc?: string): ec.KeyPair; + keyFromPublic(pub: Buffer | string | 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 GenKeyPairOptions { + pers: any; + entropy: any; + persEnc?: string; + entropyEnc?: string; + } - interface SignOptions { - pers: any; - persEnc?: string; - canonical?: boolean; - k?: BN; - } + 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 KeyPair { + static fromPublic(ec: ec, pub: Buffer | string | KeyPair, enc?: string): KeyPair; + static fromPrivate(ec: ec, priv: Buffer | string | KeyPair, enc?: string): KeyPair; - class Signature { - constructor(options: SignatureOptions | Signature, enc?: string) - r: BN; - s: BN; - recoveryParam: number | null; - toDER(enc?: string | null): any; // ? - } + ec: ec; - interface SignatureOptions { - r: BNInput; - s: BNInput; - recoveryParam?: number; - } + constructor(ec: ec, options: KeyPairOptions) - interface KeyPairOptions { - priv?: Buffer; - privEnc?: string; - pub?: Buffer; - pubEnc?: string; - } + 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 { + r: BN; + s: BN; + recoveryParam: number | null; + + constructor(options: SignatureOptions | Signature, enc?: string) + + toDER(enc?: string | null): any; // ? + } + + interface SignatureOptions { + r: BNInput; + s: BNInput; + recoveryParam?: number; + } + + interface KeyPairOptions { + priv?: Buffer; + privEnc?: string; + pub?: Buffer; + pubEnc?: string; + } +} + +export class eddsa { + curve: curve.edwards; + + constructor(name: 'ed25519'); + + sign(message: eddsa.Bytes, secret: eddsa.Bytes): eddsa.Signature; + verify(message: eddsa.Bytes, sig: eddsa.Bytes | eddsa.Signature, pub: eddsa.Bytes | eddsa.Point | eddsa.KeyPair): boolean; + hashInt(): BN; + keyFromPublic(pub: eddsa.Bytes): eddsa.KeyPair; + keyFromSecret(secret: eddsa.Bytes): eddsa.KeyPair; + makeSignature(sig: eddsa.Signature | Buffer | string): eddsa.Signature; + encodePoint(point: eddsa.Point): Buffer; + decodePoint(bytes: eddsa.Bytes): eddsa.Point; + encodeInt(num: BN): Buffer; + decodeInt(bytes: BNInput): BN; + isPoint(val: any): boolean; +} + +export namespace eddsa { + type Point = curve.base.BasePoint; + type Bytes = string | Buffer; + + class Signature { + constructor(eddsa: eddsa, sig: Signature | Bytes); + + toBytes(): Buffer; + toHex(): string; + } + + class KeyPair { + constructor(eddsa: eddsa, params: KeyPairOptions); + + static fromPublic(eddsa: eddsa, pub: Bytes): KeyPair; + static fromSecret(eddsa: eddsa, secret: Bytes): KeyPair; + + secret(): Buffer; + sign(message: Bytes): Signature; + verify(message: Bytes, sig: Signature | Bytes): boolean; + getSecret(enc: 'hex'): string; + getSecret(): Buffer; + getPublic(enc: 'hex'): string; + getPublic(): Buffer; + } + + interface KeyPairOptions { + secret: Buffer; + pub: Buffer | Point; + } } diff --git a/types/ember-qunit/ember-qunit-tests.ts b/types/ember-qunit/ember-qunit-tests.ts index acd9650f98..9e85253ae9 100644 --- a/types/ember-qunit/ember-qunit-tests.ts +++ b/types/ember-qunit/ember-qunit-tests.ts @@ -139,4 +139,11 @@ module('foo service', function(hooks) { setupTest(hooks); }); +// RFC-232 equivalent of https://github.com/ember-engines/ember-engines#unitintegration-testing-for-in-repo-engines +module('engine foo component', function(hooks) { + setupTest(hooks, { + resolver: Ember.Resolver.create() + }); +}); + start(); diff --git a/types/ember-qunit/index.d.ts b/types/ember-qunit/index.d.ts index 6b3188fdfc..1ce6f90483 100644 --- a/types/ember-qunit/index.d.ts +++ b/types/ember-qunit/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Derek Wickern // Mike North // Steve Calvert +// Dan Freeman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -46,6 +47,13 @@ declare module 'ember-qunit' { */ export function setResolver(resolver: Ember.Resolver): void; + interface SetupTestOptions { + /** + * The resolver to use when instantiating container-managed entities in the test. + */ + resolver?: Ember.Resolver; + } + /** * Sets up acceptance tests. * @@ -58,7 +66,7 @@ declare module 'ember-qunit' { * * `this.pauseTest` and `this.resumeTest` - allow easy pausing/resuming of tests. * * `this.element` which returns the DOM element representing the application's root element. */ - export function setupApplicationTest(hooks: NestedHooks): void; + export function setupApplicationTest(hooks: NestedHooks, options?: SetupTestOptions): void; /** * Sets up tests that need to render snippets of templates. @@ -79,7 +87,7 @@ declare module 'ember-qunit' { * * this.$(...) - When jQuery is present, executes a jQuery selector with * the current this.element as its root */ - export function setupRenderingTest(hooks: NestedHooks): void; + export function setupRenderingTest(hooks: NestedHooks, options?: SetupTestOptions): void; /** * Sets up tests that do not need to render snippets of templates. @@ -94,7 +102,7 @@ declare module 'ember-qunit' { * * this.set / this.setProperties - Allows setting values on the test context. * * this.get / this.getProperties - Retrieves values from the test context. */ - export function setupTest(hooks: NestedHooks): void; + export function setupTest(hooks: NestedHooks, options?: SetupTestOptions): void; export class QUnitAdapter extends Ember.Test.Adapter { } diff --git a/types/ember__string/ember__string-tests.ts b/types/ember__string/ember__string-tests.ts index 1f045b849d..500c67546e 100644 --- a/types/ember__string/ember__string-tests.ts +++ b/types/ember__string/ember__string-tests.ts @@ -1,4 +1,4 @@ -import { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w } from '@ember/string'; +import { dasherize, camelize, capitalize, classify, decamelize, htmlSafe, loc, underscore, w, isHTMLSafe } from '@ember/string'; import { SafeString } from 'handlebars'; dasherize(); // $ExpectError @@ -36,3 +36,11 @@ loc("_Hello %@ %@", ["John", "Smith"]); // $ExpectType string const handlebarsSafeString: SafeString = htmlSafe('lorem ipsum...'); htmlSafe('lorem ipsum...'); // $ExpectType SafeString const regularString: string = htmlSafe('lorem ipsum...'); // $ExpectError + +function isSafeTest(a: string|Handlebars.SafeString) { + if (isHTMLSafe(a)) { + a = a.toString(); + } + + camelize(a); +} diff --git a/types/ember__string/index.d.ts b/types/ember__string/index.d.ts index 8a2a46c022..66b5199bfd 100644 --- a/types/ember__string/index.d.ts +++ b/types/ember__string/index.d.ts @@ -11,8 +11,8 @@ export function capitalize(str: string): string; export function classify(str: string): string; export function dasherize(str: string): string; export function decamelize(str: string): string; -export function htmlSafe(str: string): Handlebars.SafeString; -export function isHTMLSafe(str: string): boolean; +export function htmlSafe(str: string): SafeString; +export function isHTMLSafe(str: any): str is SafeString; export function loc(template: string, args?: string[]): string; export function underscore(str: string): string; export function w(str: string): string[]; diff --git a/types/ember__test-helpers/ember__test-helpers-tests.ts b/types/ember__test-helpers/ember__test-helpers-tests.ts index 9fe9e4c297..89b536e51f 100644 --- a/types/ember__test-helpers/ember__test-helpers-tests.ts +++ b/types/ember__test-helpers/ember__test-helpers-tests.ts @@ -11,6 +11,7 @@ import { blur, triggerEvent, triggerKeyEvent, + typeIn, fillIn, render, find, @@ -54,6 +55,7 @@ test('DOM interactions', async () => { await triggerEvent(messageElement, 'custom-event'); await triggerKeyEvent(messageElement, 'keydown', 'Enter', { ctrlKey: true }); await fillIn(messageElement, 'content'); + await typeIn(messageElement, 'content'); const allMessages = findAll('.message'); for (const element of allMessages) { diff --git a/types/ember__test-helpers/index.d.ts b/types/ember__test-helpers/index.d.ts index 8a3d6f0ef9..0c7dc544b9 100644 --- a/types/ember__test-helpers/index.d.ts +++ b/types/ember__test-helpers/index.d.ts @@ -22,6 +22,7 @@ declare module '@ember/test-helpers' { export { default as triggerEvent } from '@ember/test-helpers/dom/trigger-event'; export { default as triggerKeyEvent } from '@ember/test-helpers/dom/trigger-key-event'; export { default as fillIn } from '@ember/test-helpers/dom/fill-in'; + export { default as typeIn } from '@ember/test-helpers/dom/type-in'; // DOM Query Helpers @@ -117,6 +118,12 @@ declare module '@ember/test-helpers/dom/fill-in' { export default function(target: Target, text: string): Promise; } +declare module '@ember/test-helpers/dom/type-in' { + import { Target } from '@ember/test-helpers'; + + export default function(target: Target, text: string, options?: {delay: number}): Promise; +} + declare module '@ember/test-helpers/dom/find' { export default function(selector: string): Element | null; } diff --git a/types/emoji-mart/index.d.ts b/types/emoji-mart/index.d.ts index a92bcb77ff..8ea741ca9f 100644 --- a/types/emoji-mart/index.d.ts +++ b/types/emoji-mart/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for emoji-mart 2.8 // Project: https://github.com/missive/emoji-mart -// Definitions by: Jessica Franco +// Definitions by: Jessica Franco // Nick Winans // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 0711243d0c..0c7e2c2e90 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -35,6 +35,10 @@ interface MyComponentState { stateProperty: string; } +function toComponentType(Component: ComponentClass | StatelessComponent): ComponentClass | StatelessComponent { + return Component; +} + class MyComponent extends Component { handleEcho(value: string) { return value; @@ -59,6 +63,8 @@ const MyStatelessComponent = (props: StatelessProps) => ; const AnotherStatelessComponent = (props: AnotherStatelessProps) => ; +const ComponentType = toComponentType(MyComponent); + // Enzyme.configure function configureTest() { const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} }; @@ -859,6 +865,14 @@ function ReactWrapperTest() { reactWrapper = new ReactWrapper(, undefined, { attachTo: document.createElement('div') }); reactWrapper = new ReactWrapper(, reactWrapper, { attachTo: document.createElement('div') }); } + + function test_component_type() { + const wrapper1 = shallow(
); + wrapper1.find(ComponentType).props().stringProp; // $ExpectType string + + const wrapper2 = mount(
); + wrapper2.find(ComponentType).props().stringProp; // $ExpectType string + } } // CheerioWrapper diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 0818b4e5ce..58e5938a8f 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -27,7 +27,9 @@ export interface ComponentClass { new(props: Props, context?: any): Component; } -export type StatelessComponent = (props: Props, context?: any) => JSX.Element; +export type StatelessComponent = (props: Props, context?: any) => JSX.Element | null; + +export type ComponentType = ComponentClass | StatelessComponent; /** * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the @@ -372,8 +374,8 @@ export class ShallowWrapper

{ * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ - find(component: ComponentClass): ShallowWrapper; find(statelessComponent: StatelessComponent): ShallowWrapper; + find(component: ComponentType): ShallowWrapper; find(props: EnzymePropSelector): ShallowWrapper; find(selector: string): ShallowWrapper; @@ -381,8 +383,8 @@ export class ShallowWrapper

{ * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ShallowWrapper; filter(statelessComponent: StatelessComponent): ShallowWrapper; + filter(component: ComponentType): ShallowWrapper; filter(props: EnzymePropSelector | string): ShallowWrapper; /** @@ -394,8 +396,8 @@ export class ShallowWrapper

{ * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ - children(component: ComponentClass): ShallowWrapper; children(statelessComponent: StatelessComponent): ShallowWrapper; + children(component: ComponentType): ShallowWrapper; children(selector: string): ShallowWrapper; children(props?: EnzymePropSelector): ShallowWrapper; @@ -425,8 +427,8 @@ export class ShallowWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - parents(component: ComponentClass): ShallowWrapper; parents(statelessComponent: StatelessComponent): ShallowWrapper; + parents(component: ComponentType): ShallowWrapper; parents(selector: string): ShallowWrapper; parents(props?: EnzymePropSelector): ShallowWrapper; @@ -436,8 +438,8 @@ export class ShallowWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - closest(component: ComponentClass): ShallowWrapper; closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(component: ComponentType): ShallowWrapper; closest(props: EnzymePropSelector): ShallowWrapper; closest(selector: string): ShallowWrapper; @@ -487,8 +489,8 @@ export class ReactWrapper

{ * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. */ - find(component: ComponentClass): ReactWrapper; find(statelessComponent: StatelessComponent): ReactWrapper; + find(component: ComponentType): ReactWrapper; find(props: EnzymePropSelector): ReactWrapper; find(selector: string): ReactWrapper; @@ -501,16 +503,16 @@ export class ReactWrapper

{ * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ - filter(component: ComponentClass): ReactWrapper; filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(component: ComponentType): ReactWrapper; filter(props: EnzymePropSelector | string): ReactWrapper; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector * can be provided and it will filter the children by this selector. */ - children(component: ComponentClass): ReactWrapper; children(statelessComponent: StatelessComponent): ReactWrapper; + children(component: ComponentType): ReactWrapper; children(selector: string): ReactWrapper; children(props?: EnzymePropSelector): ReactWrapper; @@ -526,8 +528,8 @@ export class ReactWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - parents(component: ComponentClass): ReactWrapper; parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(component: ComponentType): ReactWrapper; parents(selector: string): ReactWrapper; parents(props?: EnzymePropSelector): ReactWrapper; @@ -537,8 +539,8 @@ export class ReactWrapper

{ * * Note: can only be called on a wrapper of a single node. */ - closest(component: ComponentClass): ReactWrapper; closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(component: ComponentType): ReactWrapper; closest(props: EnzymePropSelector): ReactWrapper; closest(selector: string): ReactWrapper; diff --git a/types/eslint/eslint-tests.ts b/types/eslint/eslint-tests.ts index ed211d220e..6d175716b3 100644 --- a/types/eslint/eslint-tests.ts +++ b/types/eslint/eslint-tests.ts @@ -539,4 +539,12 @@ ruleTester.run('my-rule', rule, { ] }); +ruleTester.run('simple-valid-test', rule, { + valid: [ + 'foo', + 'bar', + { code: 'foo', options: [{ allowFoo: true }] }, + ] +}); + //#endregion diff --git a/types/eslint/index.d.ts b/types/eslint/index.d.ts index 01f39ee83e..f1a585046c 100644 --- a/types/eslint/index.d.ts +++ b/types/eslint/index.d.ts @@ -540,7 +540,7 @@ export class RuleTester { name: string, rule: Rule.RuleModule, tests: { - valid?: RuleTester.ValidTestCase[]; + valid?: Array; invalid?: RuleTester.InvalidTestCase[]; }, ): void; diff --git a/types/events/events-tests.ts b/types/events/events-tests.ts index 67fe352225..868ad8efde 100644 --- a/types/events/events-tests.ts +++ b/types/events/events-tests.ts @@ -16,6 +16,12 @@ const listener3 = (arg1: string) => { const listener4 = () => { console.log('type of number'); }; +const listener5 = () => { + console.log('prepend listener'); +}; +const listener6 = () => { + console.log('prepend once listener'); +}; emitter.setMaxListeners(100); @@ -29,12 +35,20 @@ emitter.once('send', listener); emitter.once(1, listener4); +emitter.prependListener('send', listener5); + +emitter.prependOnceListener('send', listener6); + emitter.listeners('send'); emitter.listenerCount('send'); +emitter.rawListeners('send'); EventEmitter.defaultMaxListeners = 100; console.log(`count(static): ${EventEmitter.listenerCount(emitter, 'send')}`); console.log(`ncount: ${emitter.listenerCount('send')}`); +console.log(`maxListeners: ${emitter.getMaxListeners()}`); +console.log(`eventNames: ${emitter.eventNames().join(', ')}`); +console.log(`rawListeners count: ${emitter.rawListeners('send').length}`); setTimeout(() => { console.log('\n'); @@ -47,6 +61,12 @@ setTimeout(() => { emitter.removeListener('send', listener2); }, 2000); +setTimeout(() => { + console.log('\n'); + emitter.emit('send'); + emitter.off('send', listener3); +}, 2000); + setTimeout(() => { console.log('\n'); emitter.emit('send', 'params1'); diff --git a/types/events/index.d.ts b/types/events/index.d.ts index c9b08a4575..a6cf834285 100644 --- a/types/events/index.d.ts +++ b/types/events/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for events 1.2 +// Type definitions for events 3.0 // Project: https://github.com/Gozala/events // Definitions by: Yasunori Ohoka +// Shenwei Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export type Listener = (...args: any[]) => void; @@ -9,13 +10,19 @@ export class EventEmitter { static listenerCount(emitter: EventEmitter, type: string | number): number; static defaultMaxListeners: number; + eventNames(): Array; setMaxListeners(n: number): this; + getMaxListeners(): number; emit(type: string | number, ...args: any[]): boolean; addListener(type: string | number, listener: Listener): this; on(type: string | number, listener: Listener): this; once(type: string | number, listener: Listener): this; + prependListener(type: string | number, listener: Listener): this; + prependOnceListener(type: string | number, listener: Listener): this; removeListener(type: string | number, listener: Listener): this; + off(type: string | number, listener: Listener): this; removeAllListeners(type?: string | number): this; listeners(type: string | number): Listener[]; listenerCount(type: string | number): number; + rawListeners(type: string | number): Listener[]; } diff --git a/types/eventsource/eventsource-tests.ts b/types/eventsource/eventsource-tests.ts index c1b53030cd..d06c79cdde 100644 --- a/types/eventsource/eventsource-tests.ts +++ b/types/eventsource/eventsource-tests.ts @@ -10,9 +10,9 @@ let openState: number = eventSource.OPEN; openState = EventSource.OPEN; let url: string = eventSource.url; let withCredentials: boolean = eventSource.withCredentials; -eventSource.onmessage = (event: Event) => {}; -eventSource.onerror = (event: Event) => {}; -eventSource.onopen = (event: Event) => {}; +eventSource.onmessage = (event: MessageEvent) => {}; +eventSource.onerror = (event: MessageEvent) => {}; +eventSource.onopen = (event: MessageEvent) => {}; eventSource.addEventListener = (type: string, listener: (e: Event) => void) => {}; eventSource.dispatchEvent = (event: Event) => true; eventSource.removeEventListener = (type: string, listener: (e: Event) => void) => {}; @@ -30,9 +30,9 @@ openState = eventSource.OPEN; openState = EventSource.OPEN; url = eventSourcePolyfill.url; withCredentials = eventSource.withCredentials; -eventSourcePolyfill.onmessage = (event: Event) => {}; -eventSourcePolyfill.onerror = (event: Event) => {}; -eventSourcePolyfill.onopen = (event: Event) => {}; +eventSourcePolyfill.onmessage = (event: MessageEvent) => {}; +eventSourcePolyfill.onerror = (event: MessageEvent) => {}; +eventSourcePolyfill.onopen = (event: MessageEvent) => {}; eventSourcePolyfill.addEventListener = (type: string, listener: (e: Event) => void) => {}; eventSourcePolyfill.dispatchEvent = (event: Event) => true; eventSourcePolyfill.removeEventListener = (type: string, listener: (e: Event) => void) => {}; diff --git a/types/eventsource/index.d.ts b/types/eventsource/index.d.ts index 1308515917..f0dcd7513f 100644 --- a/types/eventsource/index.d.ts +++ b/types/eventsource/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for eventsource 1.0 +// Type definitions for eventsource 1.1 // Project: http://github.com/EventSource/eventsource // Definitions by: Scott Lee Davis // Ali Afroozeh +// Pedro Gámez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -18,9 +19,9 @@ declare class EventSource { readonly url: string; readonly readyState: number; readonly withCredentials: boolean; - onopen: EventListener; - onmessage: EventListener; - onerror: EventListener; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; addEventListener(type: string, listener: EventListener): void; dispatchEvent(evt: Event): boolean; removeEventListener(type: string, listener?: EventListener): void; @@ -28,7 +29,7 @@ declare class EventSource { } declare namespace EventSource { - enum ReadyState {CONNECTING = 0, OPEN = 1, CLOSED = 2} + enum ReadyState { CONNECTING = 0, OPEN = 1, CLOSED = 2 } interface EventSourceInitDict { withCredentials?: boolean; diff --git a/types/eventsource/lib/eventsource-polyfill/index.d.ts b/types/eventsource/lib/eventsource-polyfill/index.d.ts index 86b82105cc..74e3e22faa 100644 --- a/types/eventsource/lib/eventsource-polyfill/index.d.ts +++ b/types/eventsource/lib/eventsource-polyfill/index.d.ts @@ -11,9 +11,9 @@ declare class EventSource { readonly url: string; readonly readyState: number; readonly withCredentials: boolean; - onopen: EventListener; - onmessage: EventListener; - onerror: EventListener; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; addEventListener(type: string, listener: EventListener): void; dispatchEvent(evt: Event): boolean; removeEventListener(type: string, listener?: EventListener): void; diff --git a/types/execall/execall-tests.ts b/types/execall/execall-tests.ts new file mode 100644 index 0000000000..8a9d3b7768 --- /dev/null +++ b/types/execall/execall-tests.ts @@ -0,0 +1,3 @@ +import execall = require('execall'); + +execall(/(\d+)/g, '$200 and $400'); // $ExpectType Match[] diff --git a/types/execall/index.d.ts b/types/execall/index.d.ts new file mode 100644 index 0000000000..29e7d3945e --- /dev/null +++ b/types/execall/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for execall 1.0 +// Project: https://github.com/sindresorhus/execall +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = execall; + +/** + * Find multiple RegExp matches in a string. Instead of having to iterate over + * `RegExp#exec`, immutable, and with a nicer result format. + * + * @param re Regular expression to match against the `input`. + * @returns An array of matches. + */ +declare function execall(re: RegExp, input: string): execall.Match[]; + +declare namespace execall { + interface Match { + match: string; + sub: string[]; + index: number; + } +} diff --git a/types/execall/tsconfig.json b/types/execall/tsconfig.json new file mode 100644 index 0000000000..70a42a9a18 --- /dev/null +++ b/types/execall/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", + "execall-tests.ts" + ] +} diff --git a/types/execall/tslint.json b/types/execall/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/execall/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/exif/exif-tests.ts b/types/exif/exif-tests.ts new file mode 100644 index 0000000000..57d29fc80b --- /dev/null +++ b/types/exif/exif-tests.ts @@ -0,0 +1,18 @@ +import Exif = require('exif'); +const ExifImage = Exif.ExifImage; + +new ExifImage({ image: 'myImage.jpg' }, (error, exifData) => { + if (error) { + console.log(`Error: ${error.message}`); + } else { + console.log(exifData); + } +}); + +Exif('myImage.jpg', (error, exifData, dataPath) => { + if (error) { + console.log(`Error: ${error.message}`); + } else { + console.log(exifData, dataPath); + } +}); diff --git a/types/exif/index.d.ts b/types/exif/index.d.ts new file mode 100644 index 0000000000..78a1859517 --- /dev/null +++ b/types/exif/index.d.ts @@ -0,0 +1,143 @@ +// Type definitions for exif 0.6 +// Project: https://github.com/gomfunkel/node-exif#readme +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Exif { + interface ExifData { + image: { + Copyright?: string; + ExifOffset?: number; + ImageHeight?: number; + ImageWidth?: number; + Make?: string; + Model?: string; + ModifyDate?: string; + Orientation?: number; + ResolutionUnit?: number; + Software?: string; + XResolution?: number; + YCbCrPositioning?: number; + YResolution?: number; + }; + thumbnail: { + Compression?: number; + Orientation?: number; + ResolutionUnit?: number; + ThumbnailLength?: number; + ThumbnailOffset?: number; + XResolution?: number; + YCbCrPositioning?: number; + YResolution?: number; + }; + exif: { + ApertureValue?: number; + BrightnessValue?: number; + ColorSpace?: number; + ComponentsConfiguration?: Buffer; + CompressedBitsPerPixel?: number; + CreateDate?: string; + DateTimeOriginal?: string; + ExifImageHeight?: number; + ExifImageWidth?: number; + ExifVersion?: Buffer; + ExposureCompensation?: number; + ExposureMode?: number; + ExposureProgram?: number; + ExposureTime?: number; + FileSource?: Buffer; + Flash?: number; + FlashpixVersion?: Buffer; + FNumber?: number; + FocalLength?: number; + FocalLengthIn35mmFormat?: number; + FocalPlaneResolutionUnit?: number; + FocalPlaneXResolution?: number; + FocalPlaneYResolution?: number; + ImageUniqueID?: string; + InteropOffset?: number; + ISO?: number; + MakerNote?: Buffer; + MaxApertureValue?: number; + MeteringMode?: number; + SceneCaptureType?: number; + SceneType?: Buffer; + SensingMethod?: number; + ShutterSpeedValue?: number; + UserComment?: Buffer; + WhiteBalance?: number; + }; + gps: { + GPSAltitude?: number; + GPSAltitudeRef?: number; + GPSDateStamp?: string; + GPSLatitude?: number[]; + GPSLatitudeRef?: string; + GPSLongitude?: number[]; + GPSLongitudeRef?: string; + GPSTimeStamp?: number[]; + GPSVersionId?: number[]; + }; + interoperability: { + InteropIndex?: string; + InteropVersion?: Buffer; + }; + makernote: { + AutoBracketing?: number; + BlurWarning?: number; + ExposureWarning?: number; + error?: string; + FlashExposureComp?: number; + FocusMode?: number; + FocusWarning?: number; + FujiFlashMode?: number; + Macro?: number; + Quality?: string; + Sharpness?: number; + SlowSync?: number; + Version?: Buffer; + WhiteBalance?: number; + }; + } + + interface ExifOptions { + agfaMaxEntries?: number; + epsonMaxEntries?: number; + /** node-exif corrects the thumbnail offset in order to have an offset from the start of the buffer/file. */ + fixThumbnailOffset?: boolean; + fujifilmMaxEntries?: number; + ifd0MaxEntries?: number; + ifd1MaxEntries?: number; + /** + * The image to get Exif data from can be either a filesystem path or a Buffer. + * + * If `image` is not specified, the developer must call `loadImage()` to parse the image. + */ + image?: string | Buffer; + /** Specifies the maximum entries to be parsed */ + maxEntries?: number; + maxGpsEntries?: number; + maxInteroperabilityEntries?: number; + noPadding?: boolean; + olympusMaxEntries?: number; + panasonicMaxEntries?: number; + sanyoMaxEntries?: number; + /** An object named "offsets" is added to exifData and contains lot of offsets needed to get thumbnail and other things. */ + tiffOffsets?: number; + } + + type ExifImageCallback = (error: Error | null, data: ExifData) => void; + type ExifCallback = (error: Error | null, data: ExifData, dataPath: string) => void; + + class ExifImage { + constructor(options: ExifOptions | string | Buffer, callback: ExifImageCallback); + constructor(); + loadImage(file: string | Buffer, callback: ExifImageCallback): void; + } +} + +declare function Exif(path: string, callback: Exif.ExifCallback): void; + +export = Exif; diff --git a/types/exif/tsconfig.json b/types/exif/tsconfig.json new file mode 100644 index 0000000000..4c0c12d69a --- /dev/null +++ b/types/exif/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", + "exif-tests.ts" + ] +} diff --git a/types/exif/tslint.json b/types/exif/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/exif/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/expect-puppeteer/index.d.ts b/types/expect-puppeteer/index.d.ts index b77bc948bd..018e342ce8 100644 --- a/types/expect-puppeteer/index.d.ts +++ b/types/expect-puppeteer/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Josh Goldberg // Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 /// diff --git a/types/expired/expired-tests.ts b/types/expired/expired-tests.ts new file mode 100644 index 0000000000..b03818ff13 --- /dev/null +++ b/types/expired/expired-tests.ts @@ -0,0 +1,29 @@ +import expired = require('expired'); + +const headers = ` +Age: 0 +Cache-Control: public, max-age=300 +Content-Encoding: gzip +Content-Type: application/json;charset=utf-8 +Date: Fri, 23 Dec 2016 05:50:31 GMT +Last-Modified: Fri, 23 Dec 2016 05:23:23 GMT`; + +expired(headers); // $ExpectType boolean +expired.in(headers); // $ExpectType number +expired.on(headers); // $ExpectType Date + +const parsedHeaders = { + age: '0', + 'cache-control': 'public, max-age=300', + 'content-encoding': 'gzip', + 'content-type': 'application/json;charset=utf-8', + date: 'Fri, 23 Dec 2016 05:50:31 GMT', + 'last-modified': 'Fri, 23 Dec 2016 05:23:23 GMT', +}; + +expired(parsedHeaders); // $ExpectType boolean + +const date = new Date(); + +expired(headers, date); // $ExpectType boolean +expired.in(headers, date); // $ExpectType number diff --git a/types/expired/index.d.ts b/types/expired/index.d.ts new file mode 100644 index 0000000000..2ff9fad895 --- /dev/null +++ b/types/expired/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for expired 1.3 +// Project: https://github.com/lukechilds/expired +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = expired; + +declare const expired: expired; + +interface expired { + /** + * @returns A boolean relating to whether the resource has expired or not. + * `true` means it's expired, `false` means it's fresh. + */ + (headers: expired.Headers, compareWith?: Date): boolean; + /** + * @returns The amount of milliseconds from the current date until the resource will expire. + * If the resource has already expired it will return a negative integer. + */ + in(headers: expired.Headers, compareWith?: Date): number; + /** + * @returns A JavaScript `Date` object for the date the resource will expire. + */ + on(headers: expired.Headers): Date; +} + +declare namespace expired { + type Headers = string | { [header: string]: string | string[] | undefined }; +} diff --git a/types/expired/tsconfig.json b/types/expired/tsconfig.json new file mode 100644 index 0000000000..4602fb95b1 --- /dev/null +++ b/types/expired/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", + "expired-tests.ts" + ] +} diff --git a/types/expired/tslint.json b/types/expired/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/expired/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 481c1b27c4..10045e57e6 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Text, AccessibilityInfo } from 'react-native'; +import { Text } from 'react-native'; import { Accelerometer, @@ -154,7 +154,6 @@ Audio.setAudioModeAsync({ interruptionModeIOS: 2, interruptionModeAndroid: 1, allowsRecordingIOS: true, - playThroughEarpieceAndroid: false }); Audio.setIsEnabledAsync(true); @@ -233,7 +232,7 @@ Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE === 3; Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY; Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY; async () => { - const result = await Audio.Sound.create({uri: 'uri'}, { + const result = await Audio.Sound.createAsync({uri: 'uri'}, { volume: 0.55, rate: 16.5 }, null, true); @@ -268,7 +267,7 @@ const barcodeReadCallback = () => {}; type="front" torchMode="off" barCodeTypes={[BarCodeScanner.Constants.BarCodeType.aztec]} - onBarCodeRead={barcodeReadCallback} /> + onBarCodeScanned={barcodeReadCallback} /> ); () => ( @@ -408,7 +407,7 @@ async () => { }; async () => { - const result = await ImageManipulator.manipulate('url', [ + const result = await ImageManipulator.manipulateAsync('url', [ { rotate: 90 }, { resize: { width: 300 } }, { resize: { height: 300 } }, @@ -963,7 +962,7 @@ const userLocationCallback = (event: EventUserLocation) => console.log(event); // #endregion async () => { - const updateEventListener: Updates.UpdateEventListener = ({ type, manifest, message }) => { + const updateEventListener: Updates.UpdateEventListener = ({ type }) => { switch (type) { case Updates.EventType.DOWNLOAD_STARTED: case Updates.EventType.DOWNLOAD_PROGRESS: diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 171dbc52b6..f48d01b75d 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for expo 31.0 +// Type definitions for expo 32.0 // Project: https://github.com/expo/expo-sdk // Definitions by: Konstantin Kai // Martynas Kadiša @@ -15,6 +15,7 @@ // Pavel Ihm // Bartosz Dotryw // Jason Killian +// Satyajit Sahoo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -22,11 +23,21 @@ export * from 'react-native-maps'; export { default as MapView } from 'react-native-maps'; import { EventSubscription } from 'fbemitter'; -import { Component, ComponentClass, ComponentType, Ref } from 'react'; -import { ImageRequireSource, ImageURISource, LinkingStatic as ReactNativeLinkingStatic, StyleProp, ViewProps, ViewStyle } from 'react-native'; +import { Component, ComponentClass, Ref, ComponentType } from 'react'; +import { + ColorPropType, + ImageRequireSource, + ImageURISource, + LinkingStatic as ReactNativeLinkingStatic, + NativeEventEmitter, + ViewProps, + ViewStyle, + Permission, + StyleProp +} from 'react-native'; export type Axis = number; -export type BarCodeReadCallback = (params: { type: string; data: string; }) => void; +export type BarCodeScannedCallback = (result: { type: string; data: string; }) => void; export type Md5 = string; export type Orientation = 'portrait' | 'landscape'; export type RequireSource = ImageRequireSource; @@ -401,9 +412,6 @@ export namespace Audio { /** an enum selecting how your experience’s audio should interact with the audio from other apps on Android: */ interruptionModeAndroid: InterruptionModeAndroid; - - /** Boolean selecting if audio should go to earpiece (only on Android). */ - playThroughEarpieceAndroid: boolean; } function setIsEnabledAsync(value: boolean): Promise; @@ -420,7 +428,7 @@ export namespace Audio { * - `sound`: The newly created and loaded Sound object. * - `status`: The PlaybackStatus of the Sound object. See the AV documentation for further information. */ - static create( + static createAsync( /** * The source of the sound. The following forms are supported: * @@ -565,7 +573,7 @@ export interface PlaybackStatusToSet { volume?: number; } -export type PlaybackSource = RequireSource | { uri: string, headers?: { [header: string]: string }, overrideFileExtensionAndroid?: string } | Asset; +export type PlaybackSource = RequireSource | { uri: string } | Asset; export class PlaybackObject { /** @@ -711,7 +719,7 @@ export interface BarCodeScannerProps extends ViewProps { type?: 'front' | 'back'; torchMode?: 'on' | 'off'; barCodeTypes?: string[]; - onBarCodeRead?: BarCodeReadCallback; + onBarCodeScanned?: BarCodeScannedCallback; } export class BarCodeScanner extends Component { @@ -769,10 +777,10 @@ export namespace Brightness { * Camera */ export interface PictureOptions { - quality?: number; - base64?: boolean; - exif?: boolean; - onPictureSaved?: (data: PictureResponse) => void; + quality?: number; + base64?: boolean; + exif?: boolean; + onPictureSaved?: (data: PictureResponse) => void; } export interface PictureResponse { @@ -797,24 +805,28 @@ export class CameraObject { } export interface CameraProps extends ViewProps { - autoFocus?: string | number | boolean; - barCodeTypes?: Array; - faceDetectionClassifications?: number; - faceDetectionLandmarks?: number; - faceDetectionMode?: number; - flashMode?: string | number; + zoom?: number; + ratio?: string; /** Distance to plane of sharpest focus. A value between `0` and `1`. `0`: infinity focus, `1`: focus as close as possible. Default: `0`. For Android this is available only for some devices and when `useCamera2Api` is set to `true`. */ focusDepth?: number; - onBarCodeRead?: BarCodeReadCallback; + type?: number | string; onCameraReady?: () => void; + useCamera2Api?: boolean; + flashMode?: number | string; + whiteBalance?: number | string; + autoFocus?: string | boolean | number; + pictureSize?: string; + videoStabilizationMode?: number; + onMountError?: (error: { message: string }) => void; + barCodeScannerSettings?: { barCodeTypes?: Array; }; + onBarCodeScanned?: BarCodeScannedCallback; + faceDetectorSettings?: { + mode?: number; + runClassifications?: number; + detectLandmarks?: number; + }; onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void; - onMountError?: () => void; - ratio?: string; ref?: Ref; - type?: string | number; - whiteBalance?: string | number; - /** A value between `0` and `1` being a percentage of device's max zoom. `0`: not zoomed, `1`: maximum zoom. Default: `0`. */ - zoom?: number; } export interface CameraConstants { @@ -1540,15 +1552,62 @@ export namespace FacebookAds { setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; } - function withNativeAd(component: Component<{ - icon?: string; - coverImage?: string; - title?: string; - subtitle?: string; - description?: string; - callToActionText?: string; + interface NativeAd { + /** + * The headline the advertiser entered when they created their ad. This is usually the ad's main + * title. + */ + headline?: string; + + /** + * The link description which is additional information that the advertiser may have entered + */ + linkDescription?: string; + + /** + * The name of the Facebook Page or mobile app that represents the business running the ad + */ + advertiserName?: string; + + /** + * The ad's social context, such as, "Over half a million users" + */ socialContext?: string; - }>): Component<{ adsManager: NativeAdsManager }, { ad: any, canRequestAds: boolean }>; + + /** + * The call-to-action phrase of the ad, such as, "Install Now" + */ + callToActionText?: string; + + /** + * The body text, truncated to 90 characters, that contains the text the advertiser entered when + * they created their ad to tell people what the ad promotes + */ + bodyText?: string; + + /** + * The word "ad", translated into the viewer's language + */ + adTranslation?: string; + + /** + * The word "promoted", translated into the viewer's language + */ + promotedTranslation?: string; + + /** + * The word "sponsored", translated into the viewer's language + */ + sponsoredTranslation?: string; + } + + function withNativeAd

(component: Component

): Component< + { + adsManager: NativeAdsManager, + onAdLoaded?: ((ad: NativeAd) => void) | null; + } & P, + { ad: NativeAd | null, canRequestAds: boolean } + >; /** * Banner View @@ -1564,6 +1623,16 @@ export namespace FacebookAds { class BannerView extends Component { } + type AdTriggerViewProps

= { + renderInteractiveComponent?: (props: P) => React.ReactElement

; + } & P; + + class AdTriggerView

extends Component> { } + + class AdIconView extends Component { } + + class AdMediaView extends Component { } + /** * Ad Settings */ @@ -1657,6 +1726,8 @@ export namespace FaceDetector { * FileSystem */ export namespace FileSystem { + type EncodingType = "utf8" | "base64"; + type FileInfo = { exists: true; isDirectory: boolean; @@ -1669,6 +1740,16 @@ export namespace FileSystem { isDirectory: false; }; + interface ReadingOptions { + encoding?: EncodingType; + position?: number; + length?: number; + } + + interface WritingOptions { + encoding?: EncodingType; + } + interface DownloadResult { uri: string; status: number; @@ -1680,8 +1761,8 @@ export namespace FileSystem { const cacheDirectory: string; function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; - function readAsStringAsync(fileUri: string): Promise; - function writeAsStringAsync(fileUri: string, contents: string): Promise; + function readAsStringAsync(fileUri: string, options?: ReadingOptions): Promise; + function writeAsStringAsync(fileUri: string, contents: string, options?: WritingOptions): Promise; function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; function moveAsync(options: { from: string, to: string; }): Promise; function copyAsync(options: { from: string, to: string; }): Promise; @@ -1742,6 +1823,14 @@ export namespace LocalAuthentication { error: string }; + interface AuthenticationTypeType { + FINGERPRINT: number; + FACIAL_RECOGNITION: number; + } + + /** Determine the auhentication types supported on the device. */ + function supportedAuthenticationTypesAsync(): Promise; + /** Determine whether a face or fingerprint scanner is available on the device. */ function hasHardwareAsync(): Promise; @@ -1887,8 +1976,6 @@ export namespace ImageManipulator { format?: 'jpeg' | 'png'; } - function manipulate(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise; - function manipulateAsync(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise; } @@ -2075,9 +2162,10 @@ export const Linking: LinkingStatic; */ export namespace Location { interface LocationOptions { - enableHighAccuracy?: boolean; + accuracy: number; timeInterval?: number; distanceInterval?: number; + timeout?: number; } interface LocationProps { @@ -2120,6 +2208,20 @@ export namespace Location { name: string; } + interface LocationTaskOptions { + accuracy?: number; + showsBackgroundLocationIndicator?: boolean; + } + + interface Region { + identifier?: string; + latitude: number; + longitude: number; + radius: number; + notifyOnEnter?: boolean; + notifyOnExit?: boolean; + } + type LocationCallback = (data: LocationData) => void; function getCurrentPositionAsync(options: LocationOptions): Promise; @@ -2127,8 +2229,16 @@ export namespace Location { function getProviderStatusAsync(): Promise; function getHeadingAsync(): Promise; function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; - function geocodeAsync(address: string): Promise; + function geocodeAsync(address: string): Promise; function reverseGeocodeAsync(location: LocationProps): Promise; + function requestPermissionsAsync(): Promise; + function hasServicesEnabledAsync(): Promise; + function startgeocodUpdatesAsync(taskName: string, options: LocationTaskOptions): Promise; + function stopLocationUpdatesAsync(taskName: string): Promise; + function hasStartedLocationUpdatesAsync(taskName: string): Promise; + function startGeofencingAsync(taskName: string, regions: Region[]): Promise; + function stopGeofencingAsync(taskName: string): Promise; + function hasStartedGeofencingAsync(taskName: string): Promise; function setApiKey(key: string): void; } @@ -2166,46 +2276,72 @@ export namespace Notifications { sound?: boolean }; android?: { - sound?: boolean; + channelId?: string; icon?: string; color?: string; - priority?: 'min' | 'low' | 'high' | 'max'; sticky?: boolean; - vibrate?: boolean | number[]; - link?: string; }; } - interface SchedulingOptions { - time: Date | number; - repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; - intervalMs?: number; - } - - interface ChannelAndroid { - name: string; - description?: string; - sound?: boolean; - priority?: 'min' | 'low' | 'default' | 'high' | 'max'; - vibrate?: boolean | number[]; - badge?: boolean; - } - type LocalNotificationId = string | number; - function addListener(listener: (notification: Notification) => any): EventSubscription; + interface Channel { + name: string; + description?: string; + priority?: string; + sound?: boolean; + vibrate?: boolean | number[]; + badge?: boolean; + } + + interface ActionType { + actionId: string; + buttonTitle: string; + isDestructive?: boolean; + isAuthenticationRequired?: boolean; + textInput?: { + submitButtonTitle: string; + placeholder: string; + }; + } + + function createCategoryAsync(categoryId: string, actions: ActionType[]): Promise; + function deleteCategoryAsync(categoryId: string): Promise; function getExpoPushTokenAsync(): Promise; - function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; - function scheduleLocalNotificationAsync( - localNotification: LocalNotification, - schedulingOptions: SchedulingOptions - ): Promise; - function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; - function dismissAllNotificationsAsync(): Promise; - function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; - function cancelAllScheduledNotificationsAsync(): Promise; - function createChannelAndroidAsync(id: string, channel: ChannelAndroid): Promise; + function getDevicePushTokenAsync(config: { + gcmSenderId?: string; + }): Promise<{ type: string; data: string }>; + function createChannelAndroidAsync(id: string, channel: Channel): Promise; function deleteChannelAndroidAsync(id: string): Promise; + + /* Shows a notification instantly */ + function presentLocalNotificationAsync( + notification: LocalNotification + ): Promise; + + /** Schedule a notification at a later date */ + function scheduleLocalNotificationAsync( + notification: LocalNotification, + options?: { + time?: Date | number; + repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + intervalMs?: number; + } + ): Promise; + + /** Dismiss currently shown notification with ID (Android only) */ + function dismissNotificationAsync(notificationId: LocalNotificationId): Promise; + + /** Dismiss all currently shown notifications (Android only) */ + function dismissAllNotificationsAsync(): Promise; + + /** Cancel scheduled notification notification with ID */ + function cancelScheduledNotificationAsync(notificationId: LocalNotificationId): Promise; + + /** Cancel all scheduled notifications */ + function cancelAllScheduledNotificationsAsync(): Promise; + + function addListener(listener: (notification: Notification) => any): EventSubscription; function getBadgeNumberAsync(): Promise; function setBadgeNumberAsync(number: number): Promise; } @@ -2332,11 +2468,14 @@ export namespace Segment { function identify(userId: string): void; function identifyWithTraits(userId: string, traits: object): void; function track(event: string): void; + function alias(newId: string, options?: { [key: string]: any }): Promise; function reset(): void; function trackWithProperties(event: string, properties: object): void; function screen(screenName: string): void; function screenWithProperties(screenName: string, properties: object): void; function flush(): void; + function getEnabledAsync(): void; + function setEnabledAsync(enabled: boolean): void; } /** @@ -2350,7 +2489,7 @@ export namespace Speech { onStart?: () => void; onStopped?: () => void; onDone?: () => void; - onError?: (error: string) => void; + onError?: (error: Error) => void; } function speak(text: string, options?: SpeechOptions): void; @@ -2451,6 +2590,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { @@ -2561,13 +2702,14 @@ export class Svg extends Component<{ width: number, height: number, viewBox?: st * Take Snapshot */ export function takeSnapshotAsync( - view?: (number | React.ReactElement), + node: number | React.ReactElement | React.RefObject, options?: { - width?: number, - height?: number, - format?: 'png' | 'jpg' | 'jpeg' | 'webm', - quality?: number, - result?: 'file' | 'base64' | 'data-uri', + width?: number; + height?: number; + format: 'png' | 'jpg' | 'raw' | 'webm'; + quality: number; + snapshotContentContainer: boolean; + result: "tmpfile" | "base64" | "data-uri" | "zip-base64"; } ): Promise; diff --git a/types/expo/v24/index.d.ts b/types/expo/v24/index.d.ts index 35d1e9be92..7c515a0268 100644 --- a/types/expo/v24/index.d.ts +++ b/types/expo/v24/index.d.ts @@ -1949,6 +1949,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v25/index.d.ts b/types/expo/v25/index.d.ts index 766c055911..9e2da6c790 100644 --- a/types/expo/v25/index.d.ts +++ b/types/expo/v25/index.d.ts @@ -1978,6 +1978,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v26/index.d.ts b/types/expo/v26/index.d.ts index 9804579e66..e8386db63c 100644 --- a/types/expo/v26/index.d.ts +++ b/types/expo/v26/index.d.ts @@ -2006,6 +2006,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v27/index.d.ts b/types/expo/v27/index.d.ts index a80fb657ee..179315ba69 100644 --- a/types/expo/v27/index.d.ts +++ b/types/expo/v27/index.d.ts @@ -2083,6 +2083,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v30/index.d.ts b/types/expo/v30/index.d.ts index d5891bad2d..8a77777c49 100644 --- a/types/expo/v30/index.d.ts +++ b/types/expo/v30/index.d.ts @@ -2083,6 +2083,8 @@ export interface SvgCommonProps { export interface SvgRectProps extends SvgCommonProps { width: number | string; height: number | string; + rx?: number | string; + ry?: number | string; } export interface SvgCircleProps extends SvgCommonProps { diff --git a/types/expo/v31/expo-tests.tsx b/types/expo/v31/expo-tests.tsx new file mode 100644 index 0000000000..10045e57e6 --- /dev/null +++ b/types/expo/v31/expo-tests.tsx @@ -0,0 +1,1263 @@ +import * as React from 'react'; +import { Text } from 'react-native'; + +import { + Accelerometer, + AdMobAppEvent, + AdMobBanner, + AdMobInterstitial, + AdMobRewarded, + Amplitude, + AppLoading, + Asset, + Audio, + AuthSession, + BarCodeScanner, + BlurView, + Brightness, + Calendar, + Camera, + CameraObject, + Constants, + Contacts, + DocumentPicker, + EdgeInsets, + EdgePadding, + EventUserLocation, + Facebook, + FacebookAds, + FaceDetector, + FileSystem, + Haptic, + ImageManipulator, + ImagePicker, + IntentLauncherAndroid, + KeepAwake, + KmlMapEvent, + LinearGradient, + Linking, + Location, + MailComposer, + MapEvent, + MapStyleElement, + MapView, + MediaLibrary, + Permissions, + PublisherBanner, + Region, + registerRootComponent, + ScreenOrientation, + SecureStore, + Svg, + Updates +} from 'expo'; + +const reverseGeocode: Promise = Location.reverseGeocodeAsync({ + latitude: 0, + longitude: 0 +}); + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +() => ( + console.log(error)} + style={{ flex: 1 }} + /> +); + +() => ( + console.log(error)} + onAdMobDispatchAppEvent={(event: AdMobAppEvent) => console.log(event)} + style={{ flex: 1 }} + /> +); + +AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/1033173712'); // Test ID, Replace with your-admob-unit-id +AdMobInterstitial.setTestDeviceID('EMULATOR'); +async () => { + await AdMobInterstitial.requestAdAsync(); + await AdMobInterstitial.showAdAsync(); +}; + +AdMobRewarded.setAdUnitID('ca-app-pub-3940256099942544/1033173712'); // Test ID, Replace with your-admob-unit-id +AdMobRewarded.setTestDeviceID('EMULATOR'); +async () => { + await AdMobRewarded.requestAdAsync(); + await AdMobRewarded.showAdAsync(); +}; + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', ['value']); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: undefined +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true, +}); +Audio.setIsEnabledAsync(true); + +Audio.INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS === 0; +Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_IOS_DUCK_OTHERS === 2; + +Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS === 2; + +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP === 1; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4 === 2; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB === 3; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB === 4; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF === 5; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS === 6; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP === 7; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS === 8; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM === 9; + +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB === 1; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB === 2; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC === 3; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC === 4; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD === 5; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS === 6; + +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM === 'lpcm'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3 === 'ac-3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3 === 'cac3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4 === 'ima4'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC === 'aac '; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP === 'celp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC === 'hvxc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ === 'twvq'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3 === 'MAC3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6 === 'MAC6'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW === 'ulaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW === 'alaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN === 'QDMC'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2 === 'QDM2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM === 'Qclp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1 === '.mp1'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2 === '.mp2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3 === '.mp3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS === 'alac'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE === 'aach'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD === 'aacl'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD === 'aace'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR === 'aacf'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2 === 'aacg'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2 === 'aacp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL === 'aacs'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR === 'samr'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB === 'sawb'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE === 'AUDB'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC === 'ilbc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA === 0x6d730011; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM === 0x6d730031; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3 === 'aes3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3 === 'ec-3'; + +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN === 0; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW === 0x20; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM === 0x40; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH === 0x60; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX === 0x7f; + +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT === 0; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE === 1; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED === 2; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE === 3; + +Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY; +Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY; +async () => { + const result = await Audio.Sound.createAsync({uri: 'uri'}, { + volume: 0.55, + rate: 16.5 + }, null, true); + + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + const _status = await sound.getStatusAsync(); + await sound.loadAsync({uri: 'uri'}); +}; + +() => ( + Promise.resolve()} + onFinish={() => {}} + onError={(error) => console.log(error)} /> +); +() => ( + +); + +const barcodeReadCallback = () => {}; +() => ( + +); + +() => ( + +); + +async () => { + await Brightness.setBrightnessAsync(0.65); + await Brightness.setSystemBrightnessAsync(0.75); + const br1 = await Brightness.getBrightnessAsync(); + const br2 = await Brightness.getSystemBrightnessAsync(); +}; + +Camera.Constants.AutoFocus; +Camera.Constants.Type; +Camera.Constants.FlashMode; +Camera.Constants.WhiteBalance; +Camera.Constants.VideoQuality; +Camera.Constants.BarCodeType; +() => { + return( { + if (component) { + component.recordAsync(); + } + }} />); +}; +async (camera: CameraObject) => { + const picture = await camera.takePictureAsync({ + quality: 0.5, + base64: true, + exif: true + }); + + picture.uri; + picture.width; + picture.height; + picture.exif; + picture.base64; + + camera.takePictureAsync({ + quality: 1, + onPictureSaved: pic => { + pic.uri; + pic.width; + pic.height; + pic.exif; + pic.base64; + } + }); +}; + +async () => { + const result = await DocumentPicker.getDocumentAsync(); + + if (result.type === 'success') { + result.name; + result.uri; + result.size; + } +}; + +async () => { + const { type, expires, token } = await Facebook.logInWithReadPermissionsAsync("appId"); +}; + +() => ( + {}} + onError={() => {}} /> +); + +async () => { + const info = await FileSystem.getInfoAsync('file'); + + info.exists; + info.isDirectory; + + if (info.exists) { + info.md5; + info.uri; + info.size; + info.modificationTime; + } + + const string: string = await FileSystem.readAsStringAsync('file'); + await FileSystem.writeAsStringAsync('file', 'content'); + await FileSystem.deleteAsync('file'); + await FileSystem.moveAsync({ from: 'from', to: 'to'}); + await FileSystem.copyAsync({ from: 'from', to: 'to' }); + await FileSystem.makeDirectoryAsync('dir'); + const dirs: string[] = await FileSystem.readDirectoryAsync('dir'); + const result = await FileSystem.downloadAsync('from', 'to'); + + result.headers; + result.status; + result.uri; + result.md5; +}; + +async () => { + // Video test + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Videos, + }); + + if (!result.cancelled) { + result.uri; + result.width; + result.height; + result.duration; + result.type; + } +}; + +async () => { + // Image test + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Images, + base64: true, + aspect: [4, 3], + quality: 1, + exif: true, + }); + + if (!result.cancelled) { + result.uri; + result.width; + result.height; + result.exif; + result.base64; + result.type; + } +}; + +async () => { + const result = await ImageManipulator.manipulateAsync('url', [ + { rotate: 90 }, + { resize: { width: 300 } }, + { resize: { height: 300 } }, + { resize: { height: 300, width: 300 } }, + ], { + compress: 0.75 + }); + + result.height; + result.uri; + result.width; +}; + +async () => { + const result = await ImageManipulator.manipulateAsync('url', [ + { rotate: 360 }, + { resize: { width: 300 } }, + { resize: { height: 300 } }, + { resize: { height: 300, width: 300 } }, + ], { + compress: 0.75 + }); + + result.height; + result.uri; + result.width; +}; + +FaceDetector.Constants.Mode.fast; +FaceDetector.Constants.Mode.accurate; +FaceDetector.Constants.Landmarks.all; +FaceDetector.Constants.Landmarks.none; +FaceDetector.Constants.Classifications.all; +FaceDetector.Constants.Classifications.none; +async () => { + const result = await FaceDetector.detectFaces('url', { + mode: FaceDetector.Constants.Mode.fast, + detectLandmarks: FaceDetector.Constants.Landmarks.all, + runClassifications: FaceDetector.Constants.Classifications.none + }); + + result.faces[0]; +}; + +async () => { + function isBoolean(x: boolean) { + } + function isString(x: string) { + } + // Two examples of members inherited from react-native Linking + // to prove that inheritence is working. + Linking.addEventListener('url', (e) => { + e.url === ''; + }); + isBoolean(await Linking.canOpenURL('expo://')); + + // Extensions added by expo. + + isString(Linking.makeUrl('path')); + isString(Linking.makeUrl('path', { q: 2, u: 'ery', })); + + const { + path, + queryParams, + } = Linking.parse(''); + isString(path); + isString(queryParams['x'] || ''); + + const { + path: path2, + queryParams: queryParams2, + } = await Linking.parseInitialURLAsync(); + isString(path2); + isString(queryParams2['y'] || ''); +}; + +// #region securestore +async () => { + await SecureStore.setItemAsync('some-key', 'some-val', { + keychainService: "some-service", + keychainAccessible: SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY, + }); + const result = await SecureStore.getItemAsync('some-key', { keychainService: "some-service" }); + if (result != null) { + result.slice() === 'some-val'; + } + await SecureStore.deleteItemAsync('some-key', { keychainService: "some-service" }); +}; + +const allSecureStoreKeychainAccessibleValues: number[] = [ + SecureStore.WHEN_UNLOCKED, + SecureStore.AFTER_FIRST_UNLOCK, + SecureStore.ALWAYS, + SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY, + SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY, + SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY, + SecureStore.ALWAYS_THIS_DEVICE_ONLY, +]; +// #endregion + +() => ( + + + + + + + + + STROKED TEXT + + + + + + + + We go up and down, + then up again + + + + + + + + + + + + + + + + + + + + + + +); + +() => ( + +); + +IntentLauncherAndroid.ACTION_ACCESSIBILITY_SETTINGS === 'android.settings.ACCESSIBILITY_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_REDACTION === 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; +IntentLauncherAndroid.ACTION_CONDITION_PROVIDER_SETTINGS === 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_LISTENER_SETTINGS === 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_PRINT_SETTINGS === 'android.settings.ACTION_PRINT_SETTINGS'; +IntentLauncherAndroid.ACTION_ADD_ACCOUNT_SETTINGS === 'android.settings.ADD_ACCOUNT_SETTINGS'; +IntentLauncherAndroid.ACTION_AIRPLANE_MODE_SETTINGS === 'android.settings.AIRPLANE_MODE_SETTINGS'; +IntentLauncherAndroid.ACTION_APN_SETTINGS === 'android.settings.APN_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DETAILS_SETTINGS === 'android.settings.APPLICATION_DETAILS_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DEVELOPMENT_SETTINGS === 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_SETTINGS === 'android.settings.APPLICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_SETTINGS === 'android.settings.APP_NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_OPS_SETTINGS === 'android.settings.APP_OPS_SETTINGS'; +IntentLauncherAndroid.ACTION_BATTERY_SAVER_SETTINGS === 'android.settings.BATTERY_SAVER_SETTINGS'; +IntentLauncherAndroid.ACTION_BLUETOOTH_SETTINGS === 'android.settings.BLUETOOTH_SETTINGS'; +IntentLauncherAndroid.ACTION_CAPTIONING_SETTINGS === 'android.settings.CAPTIONING_SETTINGS'; +IntentLauncherAndroid.ACTION_CAST_SETTINGS === 'android.settings.CAST_SETTINGS'; +IntentLauncherAndroid.ACTION_DATA_ROAMING_SETTINGS === 'android.settings.DATA_ROAMING_SETTINGS'; +IntentLauncherAndroid.ACTION_DATE_SETTINGS === 'android.settings.DATE_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_INFO_SETTINGS === 'android.settings.DEVICE_INFO_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_NAME === 'android.settings.DEVICE_NAME'; +IntentLauncherAndroid.ACTION_DISPLAY_SETTINGS === 'android.settings.DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_DREAM_SETTINGS === 'android.settings.DREAM_SETTINGS'; +IntentLauncherAndroid.ACTION_HARD_KEYBOARD_SETTINGS === 'android.settings.HARD_KEYBOARD_SETTINGS'; +IntentLauncherAndroid.ACTION_HOME_SETTINGS === 'android.settings.HOME_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS === 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS === 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SETTINGS === 'android.settings.INPUT_METHOD_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS === 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; +IntentLauncherAndroid.ACTION_INTERNAL_STORAGE_SETTINGS === 'android.settings.INTERNAL_STORAGE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCALE_SETTINGS === 'android.settings.LOCALE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCATION_SOURCE_SETTINGS === 'android.settings.LOCATION_SOURCE_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_DEFAULT_APPS_SETTINGS === 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; +IntentLauncherAndroid.ACTION_MEMORY_CARD_SETTINGS === 'android.settings.MEMORY_CARD_SETTINGS'; +IntentLauncherAndroid.ACTION_MONITORING_CERT_INFO === 'android.settings.MONITORING_CERT_INFO'; +IntentLauncherAndroid.ACTION_NETWORK_OPERATOR_SETTINGS === 'android.settings.NETWORK_OPERATOR_SETTINGS'; +IntentLauncherAndroid.ACTION_NFCSHARING_SETTINGS === 'android.settings.NFCSHARING_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_PAYMENT_SETTINGS === 'android.settings.NFC_PAYMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_SETTINGS === 'android.settings.NFC_SETTINGS'; +IntentLauncherAndroid.ACTION_NIGHT_DISPLAY_SETTINGS === 'android.settings.NIGHT_DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS === 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_SETTINGS === 'android.settings.NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_PAIRING_SETTINGS === 'android.settings.PAIRING_SETTINGS'; +IntentLauncherAndroid.ACTION_PRIVACY_SETTINGS === 'android.settings.PRIVACY_SETTINGS'; +IntentLauncherAndroid.ACTION_QUICK_LAUNCH_SETTINGS === 'android.settings.QUICK_LAUNCH_SETTINGS'; +IntentLauncherAndroid.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS === 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; +IntentLauncherAndroid.ACTION_SECURITY_SETTINGS === 'android.settings.SECURITY_SETTINGS'; +IntentLauncherAndroid.ACTION_SETTINGS === 'android.settings.SETTINGS'; +IntentLauncherAndroid.ACTION_SHOW_ADMIN_SUPPORT_DETAILS === 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; +IntentLauncherAndroid.ACTION_SHOW_INPUT_METHOD_PICKER === 'android.settings.SHOW_INPUT_METHOD_PICKER'; +IntentLauncherAndroid.ACTION_SHOW_REGULATORY_INFO === 'android.settings.SHOW_REGULATORY_INFO'; +IntentLauncherAndroid.ACTION_SHOW_REMOTE_BUGREPORT_DIALOG === 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; +IntentLauncherAndroid.ACTION_SOUND_SETTINGS === 'android.settings.SOUND_SETTINGS'; +IntentLauncherAndroid.ACTION_STORAGE_MANAGER_SETTINGS === 'android.settings.STORAGE_MANAGER_SETTINGS'; +IntentLauncherAndroid.ACTION_SYNC_SETTINGS === 'android.settings.SYNC_SETTINGS'; +IntentLauncherAndroid.ACTION_SYSTEM_UPDATE_SETTINGS === 'android.settings.SYSTEM_UPDATE_SETTINGS'; +IntentLauncherAndroid.ACTION_TETHER_PROVISIONING_UI === 'android.settings.TETHER_PROVISIONING_UI'; +IntentLauncherAndroid.ACTION_TRUSTED_CREDENTIALS_USER === 'android.settings.TRUSTED_CREDENTIALS_USER'; +IntentLauncherAndroid.ACTION_USAGE_ACCESS_SETTINGS === 'android.settings.USAGE_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_INSERT === 'android.settings.USER_DICTIONARY_INSERT'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_SETTINGS === 'android.settings.USER_DICTIONARY_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_SETTINGS === 'android.settings.USER_SETTINGS'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_AIRPLANE_MODE === 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE === 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE === 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; +IntentLauncherAndroid.ACTION_VOICE_INPUT_SETTINGS === 'android.settings.VOICE_INPUT_SETTINGS'; +IntentLauncherAndroid.ACTION_VPN_SETTINGS === 'android.settings.VPN_SETTINGS'; +IntentLauncherAndroid.ACTION_VR_LISTENER_SETTINGS === 'android.settings.VR_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_WEBVIEW_SETTINGS === 'android.settings.WEBVIEW_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_IP_SETTINGS === 'android.settings.WIFI_IP_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_SETTINGS === 'android.settings.WIFI_SETTINGS'; +IntentLauncherAndroid.ACTION_WIRELESS_SETTINGS === 'android.settings.WIRELESS_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_AUTOMATION_SETTINGS === 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EVENT_RULE_SETTINGS === 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS === 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_PRIORITY_SETTINGS === 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS === 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SETTINGS === 'android.settings.ZEN_MODE_SETTINGS'; + +KeepAwake.activate(); +KeepAwake.deactivate(); + +() => ( + +); + +() => ( + +); + +Permissions.CAMERA === 'camera'; +Permissions.CAMERA_ROLL === 'cameraRoll'; +Permissions.AUDIO_RECORDING === 'audioRecording'; +Permissions.CONTACTS === 'contacts'; +Permissions.NOTIFICATIONS === 'notifications'; +Permissions.SYSTEM_BRIGHTNESS === 'systemBrightness'; +Permissions.USER_FACING_NOTIFICATIONS === 'userFacingNotifications'; +Permissions.REMINDERS === 'reminders'; +async () => { + const result = await Permissions.askAsync(Permissions.CAMERA, Permissions.CONTACTS); + + result.status === 'granted'; + result.status === 'denied'; + result.status === 'undetermined'; + + result.expires === 'never'; +}; + +ScreenOrientation.Orientation.ALL; +ScreenOrientation.allow(ScreenOrientation.Orientation.ALL); + +class __TestEntry__ extends React.Component { + render() { + return( + test + ); + } +} +registerRootComponent(__TestEntry__); + +Calendar.EntityTypes.EVENT === 'event'; +Calendar.EntityTypes.REMINDER === 'reminder'; + +Calendar.CalendarType.LOCAL === 'local'; +Calendar.CalendarType.CALDAV === 'caldav'; +Calendar.CalendarType.EXCHANGE === 'exchange'; +Calendar.CalendarType.SUBSCRIBED === 'subscribed'; +Calendar.CalendarType.BIRTHDAYS === 'birthdays'; + +async () => { + const result = await Calendar.getCalendarsAsync(Calendar.EntityTypes.EVENT); + result.length; + + const calendar = result[0]; + calendar.id === ''; + calendar.title === ''; + calendar.sourceId === ''; + calendar.type === Calendar.CalendarType.BIRTHDAYS; + calendar.color === ''; + calendar.entityType === Calendar.EntityTypes.EVENT; + calendar.allowsModifications === true; + calendar.allowedAvailabilities === ['']; + calendar.isPrimary === true; + calendar.name === ''; + calendar.ownerAccount === ''; + calendar.timeZone === ''; + calendar.allowedReminders === ['']; + calendar.allowedAttendeeTypes === ['']; + calendar.isVisible === false; + calendar.isSynced === false; + calendar.accessLevel === Calendar.CalendarAccessLevel.CONTRIBUTOR; + + if (calendar.source) { + calendar.source.id === ''; + calendar.source.type === ''; + calendar.source.name === ''; + calendar.source.isLocalAccount === false; + } + + const id1 = await Calendar.createCalendarAsync({ + accessLevel: Calendar.CalendarAccessLevel.EDITOR + }); + + id1 === ''; + + const id2 = await Calendar.updateCalendarAsync('1234', { + isVisible: false + }); + + id2 === ''; + + const id3 = await Calendar.updateCalendarAsync('1234', null); + + await Calendar.deleteCalendarAsync('1234'); + + const events = await Calendar.getEventsAsync( + ['123', '124'], + new Date(), + new Date() + ); + + const event1 = events[0]; + + event1.accessLevel === Calendar.EventAccessLevel.CONFIDENTIAL; + event1.alarms === []; + event1.allDay === true; + event1.availability === Calendar.Availability.FREE; + event1.calendarId === ''; + event1.creationDate === ''; + event1.endDate === ''; + event1.endTimeZone === ''; + event1.guestsCanInviteOthers === true; + event1.guestsCanModify === true; + event1.guestsCanSeeGuests === false; + event1.id === ''; + event1.instanceId === ''; + event1.isDetached === false; + + const event2 = await Calendar.getEventAsync('123', { + futureEvents: true + }); + + const eventId1 = await Calendar.createEventAsync('123'); + + const eventId2 = await Calendar.updateEventAsync('1234'); + + await Calendar.deleteEventAsync('1234'); + + const attendees = await Calendar.getAttendeesForEventAsync('123'); + + const aId1 = await Calendar.createAttendeeAsync('123'); + + const aId2 = await Calendar.updateAttendeeAsync('123'); + + await Calendar.deleteAttendeeAsync('123'); + + const reminders = await Calendar.getRemindersAsync(['123']); + + const reminder = await Calendar.getReminderAsync('123'); + + const remId1 = await Calendar.createReminderAsync('123'); + + const remId2 = await Calendar.updateReminderAsync('123'); + + await Calendar.deleteReminderAsync('123'); + + const sources = await Calendar.getSourcesAsync(); + + const source = await Calendar.getSourceAsync('123'); + + Calendar.openEventInCalendar('123'); +}; + +async () => { + const result = await MailComposer.composeAsync({ + subject: 'sss' + }); + + result.status === 'saved'; +}; + +// #region MapView +const initialRegion: Region = { + latitude: 0, + longitude: 0, + latitudeDelta: 0, + longitudeDelta: 0, +}; + +const edgePadding: EdgePadding = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const edgeInsets: EdgeInsets = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const mapStyleElements: MapStyleElement[] = [{ + featureType: 'featureType', + elementType: 'elementType', + stylers: [{}, {}], +}]; + +const mapEventCallback = (event: MapEvent) => console.log(event); +const regionCallback = (region: Region) => console.log(region); +const kmlCallback = (kml: KmlMapEvent) => console.log(kml); +const userLocationCallback = (event: EventUserLocation) => console.log(event); + +() => ( + ({})} + onKmlReady={kmlCallback} + onRegionChange={regionCallback} + onRegionChangeComplete={regionCallback} + onPress={mapEventCallback} + onLongPress={mapEventCallback} + onUserLocationChange={userLocationCallback} + onPanDrag={mapEventCallback} + onPoiClick={(event: MapEvent<{ placeId: string, name: string }>) => console.log(event)} + onMarkerPress={(event: MapEvent<{ action: 'marker-press', id: string }>) => console.log(event)} + onMarkerSelect={(event: MapEvent<{ action: 'marker-select', id: string }>) => console.log(event)} + onMarkerDeselect={(event: MapEvent<{ action: 'marker-deselect', id: string }>) => console.log(event)} + onCalloutPress={(event: MapEvent<{ action: 'callout-press' }>) => console.log(event)} + onMarkerDragStart={mapEventCallback} + onMarkerDrag={mapEventCallback} + onMarkerDragEnd={mapEventCallback} + + minZoomLevel={0} + maxZoomLevel={0} + kmlSrc="src" + style={{ flex: 1 }} + /> +); +// #endregion + +async () => { + const updateEventListener: Updates.UpdateEventListener = ({ type }) => { + switch (type) { + case Updates.EventType.DOWNLOAD_STARTED: + case Updates.EventType.DOWNLOAD_PROGRESS: + case Updates.EventType.DOWNLOAD_FINISHED: + case Updates.EventType.NO_UPDATE_AVAILABLE: + case Updates.EventType.ERROR: + return true; + } + }; + + Updates.reload(); + + Updates.reloadFromCache(); + + Updates.addListener(updateEventListener); + + const updateCheckResult = await Updates.checkForUpdateAsync(); + + if (updateCheckResult.isAvailable) { + console.log(updateCheckResult.manifest); + } + + Updates.fetchUpdateAsync({ eventListener: updateEventListener }); + + const bundleFetchResult = await Updates.fetchUpdateAsync(); + + if (bundleFetchResult.isNew) { + console.log(bundleFetchResult.manifest); + } +}; + +async () => { + const asset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('some-url'); + const getAssetsOptions: MediaLibrary.GetAssetsOptions = { + first: 0, + after: 'lastAssetId', + album: 'albumId', + sortBy: MediaLibrary.SortBy.creationTime, + mediaType: MediaLibrary.MediaType.photo + }; + const assetsList: MediaLibrary.GetAssetsResult = await MediaLibrary.getAssetsAsync(getAssetsOptions); + const endCursor: string = assetsList.endCursor; + const hasNextPage: boolean = assetsList.hasNextPage; + const totalCount: number = assetsList.totalCount; + const asset1: MediaLibrary.Asset = await MediaLibrary.getAssetInfoAsync(asset); + if (await MediaLibrary.deleteAssetsAsync(assetsList.assets)) { + console.log('assets deleted'); + } + const albums: MediaLibrary.Album[] = await MediaLibrary.getAlbumsAsync(); + const album: MediaLibrary.Album | null = await MediaLibrary.getAlbumAsync('albumName'); + const album1: MediaLibrary.Album = await MediaLibrary.createAlbumAsync('albumName', asset1); + if (await MediaLibrary.addAssetsToAlbumAsync([asset, asset1], album1, true)) { + console.log('assets added'); + } + + const moments: MediaLibrary.Album[] = await MediaLibrary.getMomentsAsync(); + + switch (getAssetsOptions.mediaType) { + case MediaLibrary.MediaType.audio: + case MediaLibrary.MediaType.photo: + case MediaLibrary.MediaType.video: + case MediaLibrary.MediaType.unknow: + return true; + } + + switch (getAssetsOptions.sortBy) { + case MediaLibrary.SortBy.default: + case MediaLibrary.SortBy.id: + case MediaLibrary.SortBy.creationTime: + case MediaLibrary.SortBy.modificationTime: + case MediaLibrary.SortBy.mediaType: + case MediaLibrary.SortBy.width: + case MediaLibrary.SortBy.height: + case MediaLibrary.SortBy.duration: + return true; + } +}; + +// #region MediaLibrary +async () => { + const mlAsset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('localUri'); + const mlAssetResult: MediaLibrary.GetAssetsResult = await MediaLibrary.getAssetsAsync({ + first: 0, + after: '', + album: 'Album', + sortBy: MediaLibrary.SortBy.creationTime, + mediaType: MediaLibrary.MediaType.photo + }); + const mlAsset1: MediaLibrary.Asset = await MediaLibrary.getAssetInfoAsync(mlAsset); + const areDeleted: boolean = await MediaLibrary.deleteAssetsAsync([mlAsset]); + const albums: MediaLibrary.Album[] = await MediaLibrary.getAlbumsAsync(); + const album: MediaLibrary.Album = await MediaLibrary.getAlbumAsync('album'); + const album1: MediaLibrary.Album = await MediaLibrary.createAlbumAsync('album', mlAsset); + const areAddedToAlbum: boolean = await MediaLibrary.addAssetsToAlbumAsync([mlAsset, mlAsset1], 'album'); + const areDeletedFromAlbum: boolean = await MediaLibrary.removeAssetsFromAlbumAsync([mlAsset, mlAsset1], 'album'); + const momuents: MediaLibrary.Album[] = await MediaLibrary.getMomentsAsync(); +}; +//#endregion + +// #region Haptic +Haptic.impact(Haptic.ImpactStyles.Heavy); +Haptic.impact(Haptic.ImpactStyles.Light); +Haptic.impact(Haptic.ImpactStyles.Medium); + +Haptic.notification(Haptic.NotificationType.Error); +Haptic.notification(Haptic.NotificationType.Success); +Haptic.notification(Haptic.NotificationType.Error); + +Haptic.selection(); +// #endregion + +// #region Constants +async () => { + const appOwnerShip = Constants.appOwnership; + const expoVersion = Constants.expoVersion; + const installationId = Constants.installationId; + const deviceId = Constants.deviceId; + const deviceName = Constants.deviceName; + const deviceYearClass = Constants.deviceYearClass; + const isDevice = Constants.isDevice; + const platform = Constants.platform; + const sessionId = Constants.sessionId; + const statusBarHeight = Constants.statusBarHeight; + const systemFonts = Constants.systemFonts; + const manifest = Constants.manifest; + const linkingUri = Constants.linkingUri; + const userAgent: string = await Constants.getWebViewUserAgentAsync(); +}; +// #endregion + +// #region Contacts +Contacts.Fields.ID === 'id'; +Contacts.Fields.Name === 'name'; +Contacts.Fields.FirstName === 'firstName'; +Contacts.Fields.MiddleName === 'middleName'; +Contacts.Fields.LastName === 'lastName'; +Contacts.Fields.NamePrefix === 'namePrefix'; +Contacts.Fields.NameSuffix === 'nameSuffix'; +Contacts.Fields.PhoneticFirstName === 'phoneticFirstName'; +Contacts.Fields.PhoneticMiddleName === 'phoneticMiddleName'; +Contacts.Fields.PhoneticLastName === 'phoneticLastName'; +Contacts.Fields.Birthday === 'birthday'; +Contacts.Fields.Emails === 'emails'; +Contacts.Fields.PhoneNumbers === 'phoneNumbers'; +Contacts.Fields.Addresses === 'addresses'; +Contacts.Fields.InstantMessageAddresses === 'instantMessageAddresses'; +Contacts.Fields.UrlAddresses === 'urlAddresses'; +Contacts.Fields.Company === 'company'; +Contacts.Fields.JobTitle === 'jobTitle'; +Contacts.Fields.Department === 'department'; +Contacts.Fields.ImageAvailable === 'imageAvailable'; +Contacts.Fields.Image === 'image'; +Contacts.Fields.Note === 'note'; +Contacts.Fields.Dates === 'dates'; +Contacts.Fields.Relationships === 'relationships'; +Contacts.Fields.Nickname === 'nickname'; +Contacts.Fields.RawImage === 'rawImage'; +Contacts.Fields.MaidenName === 'maidenName'; +Contacts.Fields.ContactType === 'contactType'; +Contacts.Fields.SocialProfiles === 'socialProfiles'; +Contacts.Fields.NonGregorianBirthday === 'nonGregorianBirthday'; + +const contact: Contacts.Contact = { + [Contacts.Fields.ID]: 'id', + [Contacts.Fields.Name]: 'name', + [Contacts.Fields.FirstName]: 'firstName', + [Contacts.Fields.MiddleName]: 'middleName', + [Contacts.Fields.LastName]: 'lastName', + [Contacts.Fields.NamePrefix]: 'namePrefix', + [Contacts.Fields.NameSuffix]: 'nameSuffix', + [Contacts.Fields.PhoneticFirstName]: 'phoneticFirstName', + [Contacts.Fields.PhoneticMiddleName]: 'phoneticMiddleName', + [Contacts.Fields.PhoneticLastName]: 'phoneticLastName', + [Contacts.Fields.Birthday]: { + day: 1, + month: 1, + year: 2010, + format: Contacts.CalendarFormats.Gregorian, + id: 'id', + label: 'label' + }, + [Contacts.Fields.Emails]: [{ + email: 'email', + isPrimary: true, + id: 'id', + label: 'label' + }], + [Contacts.Fields.PhoneNumbers]: [{ + number: 'number', + isPrimary: true, + digits: 'digits', + countryCode: 'countryCode', + id: 'id', + label: 'label' + }], + [Contacts.Fields.Addresses]: [{ + street: 'street', + city: 'city', + country: 'country', + region: 'region', + neighborhood: 'neighborhood', + postalCode: 'postalCode', + poBox: 'poBox', + isoCountryCode: 'isoCountryCode', + id: 'id', + label: 'label' + }], + [Contacts.Fields.InstantMessageAddresses]: [{ + service: 'service', + username: 'username', + localizedProfile: 'localizedProfile', + id: 'id', + label: 'label' + }], + [Contacts.Fields.UrlAddresses]: [{ + url: 'url', + id: 'id', + label: 'label' + }], + [Contacts.Fields.Company]: 'company', + [Contacts.Fields.JobTitle]: 'jobTitle', + [Contacts.Fields.Department]: 'department', + [Contacts.Fields.ImageAvailable]: true, + [Contacts.Fields.Image]: { + uri: 'uri' + }, + [Contacts.Fields.Note]: 'note', + [Contacts.Fields.Dates]: [{ + day: 1, + month: 1, + year: 2010, + format: Contacts.CalendarFormats.Gregorian, + id: 'id', + label: 'label' + }], + [Contacts.Fields.Relationships]: [{ + name: 'name', + id: 'id', + label: 'label' + }], + [Contacts.Fields.Nickname]: 'nickname', + [Contacts.Fields.RawImage]: { + uri: 'uri' + }, + [Contacts.Fields.MaidenName]: 'maidenName', + [Contacts.Fields.ContactType]: Contacts.ContactTypes.Person, + [Contacts.Fields.SocialProfiles]: [{ + service: 'service', + username: 'username', + localizedProfile: 'localizedProfile', + url: 'url', + userId: 'userId', + id: 'id', + label: 'label' + }], + [Contacts.Fields.NonGregorianBirthday]: { + day: 1, + month: 1, + year: 2010, + format: Contacts.CalendarFormats.Hebrew, + id: 'id', + label: 'label' + } +}; + +async () => { + const response1: Contacts.ContactResponse = await Contacts.getContactsAsync(); + const response2: Contacts.ContactResponse = await Contacts.getContactsAsync({ id: 'contactId' }); + + const response3: Contacts.Contact = await Contacts.getContactByIdAsync('contactId'); + const response4: Contacts.Contact = await Contacts.getContactByIdAsync('contactId', [Contacts.Fields.Name]); + + const response5: string = await Contacts.addContactAsync(contact); + const response6: string = await Contacts.addContactAsync(contact, 'containerId'); + + const response7: string = await Contacts.updateContactAsync(contact); + await Contacts.removeContactAsync('contactId'); + const response8: string = await Contacts.writeContactToFileAsync({ id: 'contactId' }); + await Contacts.presentFormAsync('contactId'); + await Contacts.addExistingGroupToContainerAsync('groupId', 'containerId'); + + const response9: string = await Contacts.createGroupAsync('groupId'); + const response10: string = await Contacts.createGroupAsync('groupId', 'containerId'); + + await Contacts.updateGroupNameAsync('groupName', 'groupId'); + await Contacts.removeGroupAsync('groupId'); + await Contacts.addExistingContactToGroupAsync('contactId', 'groupId'); + await Contacts.removeContactFromGroupAsync('contactId', 'groupId'); + + const response11 = await Contacts.getGroupsAsync({ groupName: 'groupName' }); + response11.forEach((_: Contacts.Group) => _); + + const response12: string = await Contacts.getDefaultContainerIdAsync(); + + const response13 = await Contacts.getContainersAsync({ containerId: 'containerId' }); + response13.forEach((_: Contacts.Container) => _); +}; +// #endregion diff --git a/types/expo/v31/index.d.ts b/types/expo/v31/index.d.ts new file mode 100644 index 0000000000..5f560a8546 --- /dev/null +++ b/types/expo/v31/index.d.ts @@ -0,0 +1,3606 @@ +// Type definitions for expo 31.0 +// Project: https://github.com/expo/expo-sdk +// Definitions by: Konstantin Kai +// Martynas Kadiša +// Jan Aagaard +// Sergio Sánchez +// Fernando Helwanger +// Umidbek Karimov +// Moshe Feuchtwanger +// Michael Prokopchuk +// Tina Roh +// Nathan Phillip Brink +// Martin Olsson +// Levan Basharuli +// Pavel Ihm +// Bartosz Dotryw +// Jason Killian +// Satyajit Sahoo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export * from 'react-native-maps'; +export { default as MapView } from 'react-native-maps'; + +import { EventSubscription } from 'fbemitter'; +import { Component, ComponentClass, Ref, ComponentType } from 'react'; +import { + ColorPropType, + ImageRequireSource, + ImageURISource, + LinkingStatic as ReactNativeLinkingStatic, + NativeEventEmitter, + ViewProps, + ViewStyle, + Permission, + StyleProp +} from 'react-native'; + +export type Axis = number; +export type BarCodeScannedCallback = (result: { type: string; data: string; }) => void; +export type Md5 = string; +export type Orientation = 'portrait' | 'landscape'; +export type RequireSource = ImageRequireSource; +export type ResizeModeContain = 'contain'; +export type ResizeModeCover = 'cover'; +export type ResizeModeStretch = 'stretch'; +export type URISource = ImageURISource; + +export interface HashMap { [key: string]: any; } +export interface StringHashMap { [key: string]: string; } + +/** Access the device accelerometer sensor(s) to respond to changes in acceleration in 3d space. */ +export namespace Accelerometer { + interface AccelerometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** + * Subscribe for updates to the accelerometer. + * @param listener A callback that is invoked when an accelerometer update is available. When invoked, the listener is provided a single argumument that is an object containing keys x, y, z. + * @returns An EventSubscription object that you can call remove() on when you would like to unsubscribe the listener. + */ + function addListener(listener: (obj: AccelerometerObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** + * Subscribe for updates to the accelerometer. + * @param intervalMs Desired interval in milliseconds between accelerometer updates. + */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Admob + */ +export type AdMobBannerSize = + | 'banner' + | 'largeBanner' + | 'mediumRectangle' + | 'fullBanner' + | 'leaderboard' + | 'smartBannerPortrait' + | 'smartBannerLandscape'; +export interface AdMobBannerProperties extends ViewProps { + bannerSize?: AdMobBannerSize; + adUnitID?: string; + testDeviceID?: string; + didFailToReceiveAdWithError?(errorDescription: string): void; + adViewDidReceiveAd?(): void; + adViewWillPresentScreen?(): void; + adViewWillDismissScreen?(): void; + adViewDidDismissScreen?(): void; + adViewWillLeaveApplication?(): void; +} + +export class AdMobBanner extends Component { } +export interface AdMobAppEvent { + name: string; + info: string; +} +export interface PublisherBannerProperties extends AdMobBannerProperties { + onAdMobDispatchAppEvent?(event: AdMobAppEvent): void; +} +export class PublisherBanner extends Component { } + +export type AdMobInterstitialEmptyEvent = + | 'interstitialDidLoad' + | 'interstitialDidOpen' + | 'interstitialDidClose' + | 'interstitialWillLeaveApplication'; +export type AdMobInterstitialEvent = AdMobInterstitialEmptyEvent | 'interstitialDidFailToLoad'; +export namespace AdMobInterstitial { + function setAdUnitID(id: string): void; + function setTestDeviceID(id: string): void; + function requestAdAsync(): Promise; + function showAdAsync(): Promise; + function dismissAdAsync(): Promise; + function getIsReadyAsync(): Promise; + function addEventListener(event: 'interstitialDidFailToLoad', handler: (error: string) => void): void; + function addEventListener(event: AdMobInterstitialEmptyEvent, handler: () => void): void; + function removeEventListener(event: 'interstitialDidFailToLoad', handler: (error: string) => void): void; + function removeEventListener(event: AdMobInterstitialEmptyEvent, handler: () => void): void; + function removeAllListeners(): void; +} + +export type AdMobRewardedEmptyEvent = + | 'rewardedVideoDidLoad' + | 'rewardedVideoDidOpen' + | 'rewardedVideoDidStart' + | 'rewardedVideoDidClose' + | 'rewardedVideoWillLeaveApplication'; +export type AdMobRewardedEvent = AdMobRewardedEmptyEvent | 'rewardedVideoDidRewardUser' | 'rewardedVideoDidFailToLoad'; +export namespace AdMobRewarded { + function setAdUnitID(id: string): void; + function setTestDeviceID(id: string): void; + function requestAdAsync(): Promise; + function showAdAsync(): Promise; + function dismissAdAsync(): Promise; + function getIsReadyAsync(): Promise; + function addEventListener(event: 'rewardedVideoDidRewardUser', handler: (type: string, amount: number) => void): void; + function addEventListener(event: 'rewardedVideoDidFailToLoad', handler: (error: string) => void): void; + function addEventListener(event: AdMobRewardedEmptyEvent, handler: () => void): void; + function removeEventListener(event: 'rewardedVideoDidRewardUser', handler: (type: string, amount: number) => void): void; + function removeEventListener(event: 'rewardedVideoDidFailToLoad', handler: (error: string) => void): void; + function removeEventListener(event: AdMobRewardedEmptyEvent, handler: () => void): void; + function removeAllListeners(): void; +} + +/** + * Provides access to Amplitude mobile analytics which basically lets you log various events to the Cloud. This module wraps Amplitude’s iOS and Android SDKs. + * + * Note: Session tracking may not work correctly when running Experiences in the main Expo app. It will work correctly if you create a standalone app. + */ +export namespace Amplitude { + /** Initializes Amplitude with your Amplitude API key. */ + function initialize(apiKey: string): void; + + /** Assign a user ID to the current user. If you don’t have a system for user IDs you don’t need to call this. */ + function setUserId(userId: string): void; + + /** Set properties for the current user. */ + function setUserProperties(userProperties: HashMap): void; + + /** Clear properties set by `setUserProperties()`. */ + function clearUserProperties(): void; + + /** Log an event to Amplitude. */ + function logEvent(eventName: string): void; + + /** Log an event to Amplitude with custom properties. */ + function logEventWithProperties( + eventName: string, + + /** A map of custom properties. */ + properties: HashMap + ): void; + + /** Add the current user to a group. */ + function setGroup( + /** The group name, e.g. `'sports'`. */ + groupType: string, + + /** An array of group names, e.g. `['tennis', 'soccer']`. */ + groupNames: string[] + ): void; +} + +// #region AppLoading +/** The following props are recommended, but optional for the sake of backwards compatibility (they were introduced in SDK21). If you do not provide any props, you are responsible for coordinating loading assets, handling errors, and updating state to unmount the `AppLoading` component. */ +export interface AppLoadingProps { + /** A `function` that returns a `Promise`. The `Promise` should resolve when the app is done loading data and assets. */ + startAsync?: () => Promise; + + /** Required if you provide `startAsync`. Called when `startAsync` resolves or rejects. This should be used to set state and unmount the `AppLoading` component. */ + onFinish?: () => void; + + /** If `startAsync` throws an error, it is caught and passed into the function provided to `onError`. */ + onError?: (error: Error) => void; +} + +/** + * A React component that tells Expo to keep the app loading screen open if it is the first and only component rendered in your app. When it is removed, the loading screen will disappear and your app will be visible. + * + * This is incredibly useful to let you download and cache fonts, logo and icon images and other assets that you want to be sure the user has on their device for an optimal experience before rendering they start using the app. + */ +export class AppLoading extends Component { } +// #endregion AppLoading + +/** This module provides an interface to Expo’s asset system. An asset is any file that lives alongside the source code of your app that the app needs at runtime. Examples include images, fonts and sounds. Expo’s asset system integrates with React Native’s, so that you can refer to files with require('path/to/file'). This is how you refer to static image files in React Native for use in an Image component, for example. */ +export class Asset { + constructor({ name, type, hash, uri, width, height }: { + name: string; + type: string; + hash: string; + uri: string; + width?: number; + height?: number; + }); + + /** The MD5 hash of the asset’s data. */ + hash: Md5; + + /** The name of the asset file without the extension. Also without the part from @ onward in the filename (used to specify scale factor for images). */ + name: string; + + /** The extension of the asset filename. */ + type: string; + + /** A URI that points to the asset’s data on the remote server. When running the published version of your app, this refers to the the location on Expo’s asset server where Expo has stored your asset. When running the app from XDE during development, this URI points to XDE’s server running on your computer and the asset is served directly from your computer. */ + uri: string; + + /** If the asset has been downloaded (by calling `downloadAsync()`), the `file://` URI pointing to the local file on the device that contains the asset data. */ + localUri: string; + + /** If the asset is an image, the width of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + width?: number; + + /** If the asset is an image, the height of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + height?: number; + + downloading: boolean; + downloaded: boolean; + downloadCallbacks: Array<{ resolve: () => any, reject: (e?: any) => any }>; + + /** Downloads the asset data to a local file in the device’s cache directory. Once the returned promise is fulfilled without error, the localUri field of this asset points to a local file containing the asset data. The asset is only downloaded if an up-to-date local file for the asset isn’t already present due to an earlier download. */ + downloadAsync(): Promise; + + /** Returns the `Expo.Asset` instance representing an asset given its module. */ + static fromModule(module: RequireSource): Asset; + + /** + * A helper that wraps `Expo.Asset.fromModule(module).downloadAsync` for convenience. + * @param moduleIds An array of `require('path/to/file')`. Can also be just one module without an Array. + */ + static loadAsync(module: RequireSource[] | RequireSource): Promise; +} + +/** + * Provides basic sample playback and recording. + * + * Note that Expo does not yet support backgrounding, so audio is not available to play in the background of your experience. Audio also automatically stops if headphones / bluetooth audio devices are disconnected. + */ +export namespace Audio { + enum InterruptionModeIos { + /** This is the default option. If this option is set, your experience’s audio is mixed with audio playing in background apps. */ + INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0, + + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1, + + /** If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS: 0; + const INTERRUPTION_MODE_IOS_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_IOS_DUCK_OTHERS: 2; + + enum InterruptionModeAndroid { + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1, + + /** This is the default option. If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_ANDROID_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_ANDROID_DUCK_OTHERS: 2; + + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP: 1; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4: 2; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB: 3; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB: 4; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF: 5; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS: 6; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP: 7; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS: 8; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM: 9; + + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB: 1; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB: 2; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC: 3; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC: 4; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD: 5; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS: 6; + + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM: 'lpcm'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3: 'ac-3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3: 'cac3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4: 'ima4'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC: 'aac '; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP: 'celp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC: 'hvxc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ: 'twvq'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3: 'MAC3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6: 'MAC6'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW: 'ulaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW: 'alaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN: 'QDMC'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2: 'QDM2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM: 'Qclp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1: '.mp1'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2: '.mp2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3: '.mp3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS: 'alac'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE: 'aach'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD: 'aacl'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD: 'aace'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR: 'aacf'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2: 'aacg'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2: 'aacp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL: 'aacs'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR: 'samr'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB: 'sawb'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE: 'AUDB'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC: 'ilbc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA: 0x6d730011; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM: 0x6d730031; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3: 'aes3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3: 'ec-3'; + + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN: 0; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW: 0x20; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM: 0x40; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH: 0x60; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX: 0x7f; + + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT: 0; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE: 1; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED: 2; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE: 3; + + type RecordingStatus = { + canRecord: false, + isDoneRecording: false + } | { + canRecord: true, + isRecording: boolean, + durationMillis: number + } | { + canRecord: false, + isDoneRecording: true, + durationMillis: number + }; + + const RECORDING_OPTIONS_PRESET_HIGH_QUALITY: RecordingOptions; + const RECORDING_OPTIONS_PRESET_LOW_QUALITY: RecordingOptions; + + interface RecordingOptions { + android: { + extension: string; + outputFormat: number; + audioEncoder: number; + sampleRate?: number; + numberOfChannels?: number; + bitRate?: number; + maxFileSize?: number; + }; + ios: { + extension: string; + outputFormat?: string | number; + audioQuality: number; + sampleRate: number; + numberOfChannels: number; + bitRate: number; + bitRateStrategy?: number; + bitDepthHint?: number; + linearPCMBitDepth?: number; + linearPCMIsBigEndian?: boolean; + linearPCMIsFloat?: boolean; + }; + } + + interface AudioMode { + /** Boolean selecting if your experience’s audio should play in silent mode on iOS. This value defaults to `false`. */ + playsInSilentModeIOS: boolean; + + /** Boolean selecting if recording is enabled on iOS. This value defaults to `false`. NOTE: when this flag is set to true, playback may be routed to the phone receiver instead of to the speaker. */ + allowsRecordingIOS: boolean; + + /** Enum selecting how your experience’s audio should interact with the audio from other apps on iOS. */ + interruptionModeIOS: InterruptionModeIos; + + /** Boolean selecting if your experience’s audio should automatically be lowered in volume ("duck") if audio from another app interrupts your experience. This value defaults to true. If false, audio from other apps will pause your audio. */ + shouldDuckAndroid: boolean; + + /** an enum selecting how your experience’s audio should interact with the audio from other apps on Android: */ + interruptionModeAndroid: InterruptionModeAndroid; + } + + function setIsEnabledAsync(value: boolean): Promise; + function setAudioModeAsync(mode: AudioMode): Promise; + + /** This class represents a sound corresponding to an Asset or URL. */ + class Sound extends PlaybackObject { + constructor(); + + /** + * Creates and loads a sound from source, with optional `initialStatus`, `onPlaybackStatusUpdate`, and `downloadFirst`. + * + * @returns A `Promise` that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: The newly created and loaded Sound object. + * - `status`: The PlaybackStatus of the Sound object. See the AV documentation for further information. + */ + static createAsync( + /** + * The source of the sound. The following forms are supported: + * + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to an audio file on the web. + * - `require('path/to/file')` for an audio file asset in the source code directory. + * - An `Expo.Asset` object for an audio file asset. + */ + source: PlaybackSource, + + /** The initial intended PlaybackStatusToSet of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter PlaybackStatus. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null, + + /** If set to true, the system will attempt to download the resource to the device before loading. This value defaults to `true`. Note that at the moment, this will only work for `source`s of the form `require('path/to/file')` or `Asset` objects. */ + downloadFirst?: boolean + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } + + class Recording { + constructor(); + + /** Gets the `status` of the `Recording`. */ + getStatusAsync(): Promise; + + /** Sets a function to be called regularly with the `status` of the `Recording`. */ + setOnRecordingStatusUpdate(onRecordingStatusUpdate?: (status: RecordingStatus) => void): void; + + /** Sets the interval with which onRecordingStatusUpdate is called while the recording can record. This value defaults to 500 milliseconds. */ + setProgressUpdateInterval(progressUpdateIntervalMillis: number): void; + + /** Loads the recorder into memory and prepares it for recording. This must be called before calling `startAsync()`. This method can only be called if the `Recording` instance has never yet been prepared. */ + prepareToRecordAsync( + /** Options for the recording, including sample rate, bitrate, channels, format, encoder, and extension. If no options are passed to `prepareToRecordAsync()`, the recorder will be created with options `Expo.Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY`. */ + options?: RecordingOptions + ): Promise; + + /** Begins recording. This method can only be called if the `Recording` has been prepared. */ + startAsync(): Promise; + + /** + * Pauses recording. This method can only be called if the Recording has been prepared. + * + * NOTE: This is only available on Android API version 24 and later. + */ + pauseAsync(): Promise; + + /** Stops the recording and deallocates the recorder from memory. This reverts the Recording instance to an unprepared state, and another Recording instance must be created in order to record again. This method can only be called if the `Recording` has been prepared. */ + stopAndUnloadAsync(): Promise; + + /** + * Gets the local URI of the Recording. Note that this will only succeed once the Recording is prepared to record. + * + * @returns A string with the local URI of the `Recording`, or `null` if the `Recording` is not prepared to record. + */ + getURI(): string | null | undefined; + + /** + * Creates and loads a new `Sound` object to play back the `Recording`. Note that this will only succeed once the `Recording` is done recording (once `stopAndUnloadAsync()` has been called). + * + * @returns A Promise that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: the newly created and loaded Sound object. + * - `status`: the PlaybackStatus of the Sound object. + */ + createNewLoadedSound( + /** The initial intended `PlaybackStatusToSet` of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter `PlaybackStatus`. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } +} + +/** + * AuthSession + */ +export namespace AuthSession { + type StartAsyncResponse = { + type: 'cancel'; + } | { + type: 'dismissed'; + } | { + type: 'success'; + params: HashMap; + event: HashMap; + } | { + type: 'error'; + params: HashMap; + errorCode: string; + event: HashMap; + }; + + function startAsync(options: { authUrl: string; returnUrl?: string; }): Promise; + function dismiss(): void; + function getRedirectUrl(): string; +} + +// #region AV +/** + * AV + */ +export type PlaybackStatus = { + isLoaded: false; + androidImplementation?: string; + + /** Populated exactly once when an error forces the object to unload. */ + error?: string; +} | { + isLoaded: true; + androidImplementation?: string; + uri: string; + progressUpdateIntervalMillis: number; + durationMillis?: number; + positionMillis: number; + playableDurationMillis?: number; + shouldPlay: boolean; + isPlaying: boolean; + isBuffering: boolean; + rate: number; + shouldCorrectPitch: boolean; + volume: number; + isMuted: boolean; + isLooping: boolean; + + /** True exactly once when the track plays to finish. */ + didJustFinish: boolean; +}; + +export interface PlaybackStatusToSet { + androidImplementation?: string; + isLooping?: boolean; + isMuted?: boolean; + positionMillis?: number; + progressUpdateIntervalMillis?: number; + /** The desired playback rate of the media. This value must be between `0.0` and `32.0`. Only available on Android API version 23 and later and iOS. */ + rate?: number; + shouldCorrectPitch?: boolean; + shouldPlay?: boolean; + /** A number between `0.0` (silence) and `1.0` (maximum volume). */ + volume?: number; +} + +export type PlaybackSource = RequireSource | { uri: string } | Asset; + +export class PlaybackObject { + /** + * Gets the `PlaybackStatus` of the `playbackObject`. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject`. + */ + getStatusAsync(): Promise; + + /** + * Loads the media from source into memory and prepares it for playing. This must be called before calling setStatusAsync() or any of the convenience set status methods. This method can only be called if the playbackObject is in an unloaded state. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is loaded, or rejects if loading failed. The `Promise` will also reject if the `playbackObject` was already loaded. See below for details on `PlaybackStatus`. + */ + loadAsync( + /** + * The source of the media. The following forms are supported: + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to a media file on the web. + * - `require('path/to/file')` for a media file asset in the source code directory. + * - An `Expo.Asset object` for a media file asset. + */ + source: PlaybackSource, + + /** The initial intended `PlaybackStatusToSet` of the `playbackObject`, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. See below for details on `PlaybackStatusToSet` and the default initial playback status. */ + initialStatus?: PlaybackStatusToSet, + + /** If set to `true`, the system will attempt to download the resource to the device before loading. This value defaults to true. Note that at the moment, this will only work for sources of the form `require('path/to/file')` or `Expo.Asset` objects. */ + downloadFirst?: boolean + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false })`. */ + pauseAsync(): Promise; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the `isPlaying` and `isBuffering` properties of the `PlaybackStatus`. + */ + playAsync(): Promise; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true, positionMillis: millis })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the isPlaying and `isBuffering` properties of the `PlaybackStatus`. + */ + playFromPositionAsync( + /** The desired position of playback in milliseconds. */ + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise; + + /** + * Replays the item. When using `playFromPositionAsync(0)` the item is seeked to the position at `0` ms. On iOS this method uses internal implementation of the player and is able to play the item from the beginning immediately. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. + */ + replayAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ isLooping: value })`. */ + setIsLoopingAsync( + /** A boolean describing if the media should play once (`false`) or loop indefinitely (`true`). */ + isLooping: boolean + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ isMuted: value })`. */ + setIsMutedAsync( + /** A boolean describing if the audio of this media should be muted. */ + isMuted: boolean + ): Promise; + + /** + * Sets a function to be called regularly with the `PlaybackStatus` of the `playbackObject`. See below for details on `PlaybackStatus` and an example use case of this function. + * + * `onPlaybackStatusUpdate` will be called whenever a call to the API for this `playbackObject` completes (such as `setStatusAsync()`, `getStatusAsync()`, or `unloadAsync()`), and will also be called at regular intervals while the media is in the loaded state. Set `progressUpdateIntervalMillis` via `setStatusAsync()` or `setProgressUpdateIntervalAsync()` to modify the interval with which `onPlaybackStatusUpdate` is called while loaded. + */ + setOnPlaybackStatusUpdate( + /** A function taking a single parameter `PlaybackStatus`. */ + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void + ): void; + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis })`. */ + setPositionAsync( + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ progressUpdateIntervalMillis: millis })`. */ + setProgressUpdateIntervalAsync( + /** The new minimum interval in milliseconds between calls of `onPlaybackStatusUpdate`. */ + progressUpdateIntervalMillis: number + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ rate: value, shouldCorrectPitch: shouldCorrectPitch })`. */ + setRateAsync( + /** The desired playback rate of the media. This value must be between `0.0` and `32.0`. Only available on Android API version 23 and later and iOS. */ + rate: number, + /** A boolean describing if we should correct the pitch for a changed rate. If set to `true`, the pitch of the audio will be corrected (so a rate different than `1.0` will timestretch the audio). */ + shouldCorrectPitch: boolean + ): Promise; + + /** Sets a new `PlaybackStatusToSet` on the `playbackObject`. This method can only be called if the media has been loaded. Return a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. */ + setStatusAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ volume: value })`. */ + setVolumeAsync( + /** A number between `0.0` (silence) and `1.0` (maximum volume). */ + volume: number + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false, positionMillis: 0 })`. */ + stopAsync(): Promise; + + /** + * Unloads the media from memory. `loadAsync()` must be called again in order to be able to play the media. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is unloaded, or rejects if unloading failed. See below for details on `PlaybackStatus`. + */ + unloadAsync(): Promise; +} +// #endregion + +// #region BarCodeScanner +/** + * BarCodeScanner + */ +export interface BarCodeScannerProps extends ViewProps { + type?: 'front' | 'back'; + torchMode?: 'on' | 'off'; + barCodeTypes?: string[]; + onBarCodeScanned?: BarCodeScannedCallback; +} + +export class BarCodeScanner extends Component { + static Constants: { + TorchMode: { + on: string; + off: string + } + } & CameraConstants; +} +// #endregion + +// #region BlurView +/** + * BlurView + */ +export interface BlurViewProps extends ViewProps { + tint: 'light' | 'default' | 'dark'; + intensity: number; +} +export class BlurView extends Component { } +// #endregion + +/** + * An API to get and set screen brightness. + */ +export namespace Brightness { + /** Sets screen brightness. */ + function setBrightnessAsync( + /** A number between `0` and `1`, representing the desired screen brightness. */ + brightnessValue: number + ): Promise; + + /** + * Gets screen brightness. + * @returns A Promise that is resolved with a number between `0` and `1`, representing the current screen brightness. + */ + function getBrightnessAsync(): Promise; + + /** + * Gets global system screen brightness. + * @returns A Promise that is resolved with a number between `0` and `1`, representing the current system screen brightness. + */ + function getSystemBrightnessAsync(): Promise; + + /** Sets global system screen brightness, requires `WRITE_SETTINGS` permissions on Android. */ + function setSystemBrightnessAsync( + /** A number between `0` and `1`, representing the desired screen brightness. */ + brightnessValue: number + ): Promise; +} + +// #region Camera +/** + * Camera + */ +export interface PictureOptions { + quality?: number; + base64?: boolean; + exif?: boolean; + onPictureSaved?: (data: PictureResponse) => void; +} + +export interface PictureResponse { + uri: string; + width: number; + height: number; + exif: string; + base64: string; +} + +export interface RecordingOptions { + quality?: string | number; + maxDuration?: number; + maxFileSize?: number; +} + +export class CameraObject { + takePictureAsync(options?: PictureOptions): Promise; + recordAsync(options: RecordingOptions): Promise<{ uri: string; }>; + stopRecording(): void; + getSupportedRatiosAsync(): Promise; // Android only +} + +export interface CameraProps extends ViewProps { + zoom?: number; + ratio?: string; + /** Distance to plane of sharpest focus. A value between `0` and `1`. `0`: infinity focus, `1`: focus as close as possible. Default: `0`. For Android this is available only for some devices and when `useCamera2Api` is set to `true`. */ + focusDepth?: number; + type?: number | string; + onCameraReady?: () => void; + useCamera2Api?: boolean; + flashMode?: number | string; + whiteBalance?: number | string; + autoFocus?: string | boolean | number; + pictureSize?: string; + videoStabilizationMode?: number; + onMountError?: (error: { message: string }) => void; + barCodeScannerSettings?: { barCodeTypes?: Array; }; + onBarCodeScanned?: BarCodeScannedCallback; + faceDetectorSettings?: { + mode?: number; + runClassifications?: number; + detectLandmarks?: number; + }; + onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void; + ref?: Ref; +} + +export interface CameraConstants { + readonly Type: { + back: string; + front: string; + }; + readonly FlashMode: { + on: string; + off: string; + auto: string; + torch: string; + }; + readonly AutoFocus: { + on: string; + off: string; + }; + readonly WhiteBalance: { + auto: string; + sunny: string; + cloudy: string; + shadow: string; + fluorescent: string; + incandescent: string; + }; + readonly VideoQuality: { + [videoQuality: string]: number; + }; + readonly BarCodeType: { + aztec: string; + codabar: string; + code39: string; + code93: string; + code128: string; + code138: string; + code39mod43: string; + datamatrix: string; + ean13: string; + ean8: string; + interleaved2of5: string; + itf14: string; + maxicode: string; + pdf417: string; + rss14: string; + rssexpanded: string; + upc_a: string; + upc_e: string; + upc_ean: string; + qr: string; + }; +} + +export class Camera extends Component { + static readonly Constants: CameraConstants; +} +// #endregion + +/** + * Constants + */ +export namespace Constants { + const appOwnership: 'expo' | 'standalone' | 'guest'; + const expoVersion: string; + const installationId: string; + const deviceId: string; + const deviceName: string; + const deviceYearClass: number; + const isDevice: boolean; + + interface Platform { + ios?: { + platform: string; + model: string; + userInterfaceIdiom: string; + buildNumber: string; + }; + android?: { + versionCode: string; + }; + } + const platform: Platform; + const sessionId: string; + const statusBarHeight: number; + const systemFonts: string[]; + + interface Manifest { + name: string; + description?: string; + slug?: string; + sdkVersion?: string; + version?: string; + orientation?: Orientation; + primaryColor?: string; + privacy?: 'public' | 'unlisted'; + scheme?: string; + icon?: string; + platforms?: string[]; + githubUrl?: string; + notification?: { + icon?: string, + color?: string, + androidMode?: 'default' | 'collapse', + androidCollapsedTitle?: string + }; + loading?: { + icon?: string, + exponentIconColor?: 'white' | 'blue', + exponentIconGrayscale?: 1 | 0, + backgroundImage?: string, + backgroundColor?: string, + hideExponentText?: boolean + }; + appKey?: string; + androidStatusBar?: { + barStyle?: 'light-content' | 'dark-content', + backgroundColor?: string + }; + androidShowExponentNotificationInShellApp?: boolean; + extra?: { + [propName: string]: any + }; + rnCliPath?: any; + entryPoint?: string; + packagerOpts?: { + hostType?: string, + dev?: boolean, + strict?: boolean, + minify?: boolean, + urlType?: string, + urlRandomness?: string, + lanType?: string, + [propName: string]: any + }; + ignoreNodeModulesValidation?: any; + nodeModulesPath?: string; + ios?: { + bundleIdentifier?: string, + buildNumber?: string, + config?: { + usesNonExemptEncryption?: boolean, + googleSignIn?: { + reservedClientId: string + } + }, + supportsTablet?: boolean, + infoPlist?: any + }; + android?: { + package?: string, + versionCode?: string, + config?: { + fabric?: { + apiKey: string, + buildSecret: string + }, + googleMaps?: { + apiKey: string + }, + googleSignIn?: { + apiKey: string, + certificateHash: string + } + } + }; + facebookScheme?: any; + facebookAppId?: string; + facebookDisplayName?: string; + splash?: { + backgroundColor?: string; + resizeMode?: ResizeModeContain | ResizeModeCover; + image?: string; + }; + assetBundlePatterns?: string[]; + releaseChannel: string; + [propName: string]: any; + } + const manifest: Manifest; + const linkingUri: string; + + function getWebViewUserAgentAsync(): Promise; +} + +/** + * Contacts + */ +export namespace Contacts { + // Constants + + namespace Fields { + type ID = 'id'; + type Name = 'name'; + type FirstName = 'firstName'; + type MiddleName = 'middleName'; + type LastName = 'lastName'; + type NamePrefix = 'namePrefix'; + type NameSuffix = 'nameSuffix'; + type PhoneticFirstName = 'phoneticFirstName'; + type PhoneticMiddleName = 'phoneticMiddleName'; + type PhoneticLastName = 'phoneticLastName'; + type Birthday = 'birthday'; + type Emails = 'emails'; + type PhoneNumbers = 'phoneNumbers'; + type Addresses = 'addresses'; + type InstantMessageAddresses = 'instantMessageAddresses'; + type UrlAddresses = 'urlAddresses'; + type Company = 'company'; + type JobTitle = 'jobTitle'; + type Department = 'department'; + type ImageAvailable = 'imageAvailable'; + type Image = 'image'; + type Note = 'note'; + type Dates = 'dates'; + type Relationships = 'relationships'; + type Nickname = 'nickname'; + type RawImage = 'rawImage'; + type MaidenName = 'maidenName'; + type ContactType = 'contactType'; + type SocialProfiles = 'socialProfiles'; + type NonGregorianBirthday = 'nonGregorianBirthday'; + + const ID: ID; + const Name: Name; + const FirstName: FirstName; + const MiddleName: MiddleName; + const LastName: LastName; + const NamePrefix: NamePrefix; + const NameSuffix: NameSuffix; + const PhoneticFirstName: PhoneticFirstName; + const PhoneticMiddleName: PhoneticMiddleName; + const PhoneticLastName: PhoneticLastName; + const Birthday: Birthday; + const Emails: Emails; + const PhoneNumbers: PhoneNumbers; + const Addresses: Addresses; + const InstantMessageAddresses: InstantMessageAddresses; + const UrlAddresses: UrlAddresses; + const Company: Company; + const JobTitle: JobTitle; + const Department: Department; + const ImageAvailable: ImageAvailable; + const Image: Image; + const Note: Note; + const Dates: Dates; + const Relationships: Relationships; + const Nickname: Nickname; + const RawImage: RawImage; + const MaidenName: MaidenName; + const ContactType: ContactType; + const SocialProfiles: SocialProfiles; + const NonGregorianBirthday: NonGregorianBirthday; + } + + type Field = + | Fields.ID + | Fields.Name + | Fields.FirstName + | Fields.MiddleName + | Fields.LastName + | Fields.NamePrefix + | Fields.NameSuffix + | Fields.PhoneticFirstName + | Fields.PhoneticMiddleName + | Fields.PhoneticLastName + | Fields.Birthday + | Fields.Emails + | Fields.PhoneNumbers + | Fields.Addresses + | Fields.InstantMessageAddresses + | Fields.UrlAddresses + | Fields.Company + | Fields.JobTitle + | Fields.Department + | Fields.ImageAvailable + | Fields.Image + | Fields.Note + | Fields.Dates + | Fields.Relationships + | Fields.Nickname + | Fields.RawImage + | Fields.MaidenName + | Fields.ContactType + | Fields.SocialProfiles + | Fields.NonGregorianBirthday; + + namespace FormTypes { + type New = 'new'; + type Unknown = 'unknown'; + type Default = 'default'; + + const New: New; + const Unknown: Unknown; + const Default: Default; + } + + type FormType = FormTypes.New | FormTypes.Unknown | FormTypes.Default; + + /** + * iOS Only + */ + namespace ContactTypes { + type Person = 'person'; + type Company = 'company'; + + const Person: Person; + const Company: Company; + } + + type ContactType = ContactTypes.Person | ContactTypes.Company; + + namespace SortTypes { + type FirstName = 'firstName'; + type LastName = 'lastName'; + type UserDefault = 'userDefault'; + + const FirstName: FirstName; + const LastName: LastName; + const UserDefault: UserDefault; + } + + type SortType = SortTypes.FirstName | SortTypes.LastName | SortTypes.UserDefault; + + /** + * iOS Only + */ + namespace ContainerTypes { + type Local = 'local'; + type Exchange = 'exchange'; + type CardDAV = 'cardDAV'; + type Unassigned = 'unassigned'; + + const Local: Local; + const Exchange: Exchange; + const CardDAV: CardDAV; + const Unassigned: Unassigned; + } + + type ContainerType = ContainerTypes.Local | ContainerTypes.Exchange | ContainerTypes.CardDAV | ContainerTypes.Unassigned; + + namespace CalendarFormats { + type Gregorian = 'gregorian'; + type Chinese = 'chinese'; + type Hebrew = 'hebrew'; + type Islamic = 'islamic'; + + const Gregorian: Gregorian; + const Chinese: Chinese; + const Hebrew: Hebrew; + const Islamic: Islamic; + } + + type CalendarFormat = CalendarFormats.Gregorian | CalendarFormats.Chinese | CalendarFormats.Hebrew | CalendarFormats.Islamic; + + // Types + + /** + * A set of fields that define information about a single entity. + */ + interface Contact { + id: string; + name: string; + firstName?: string; + middleName?: string; + lastName?: string; + maidenName?: string; + namePrefix?: string; + nameSuffix?: string; + nickname?: string; + phoneticFirstName?: string; + phoneticMiddleName?: string; + phoneticLastName?: string; + company?: string; + jobTitle?: string; + department?: string; + note?: string; + imageAvailable?: boolean; + image?: Image; + rawImage?: Image; + contactType: ContactType; + birthday?: ContactDate; + dates?: ContactDate[]; + relationships?: Relationship[]; + emails?: Email[]; + phoneNumbers?: PhoneNumber[]; + addresses?: Address[]; + instantMessageAddresses?: InstantMessageAddress[]; + urlAddresses?: UrlAddress[]; + /** + * iOS only + */ + nonGregorianBirthday?: ContactDate; + /** + * iOS only + */ + socialProfiles?: SocialProfile[]; + } + + interface ContactDate { + day: number; + month: number; + year: number; + format: CalendarFormat; + id: string; + label: string; + } + + interface Relationship { + name: string; + id: string; + label: string; + } + + interface Email { + email: string; + isPrimary: boolean; + id: string; + label: string; + } + + interface PhoneNumber { + number: string; + isPrimary: boolean; + digits: string; + countryCode: string; + id: string; + label: string; + } + + interface Address { + street: string; + city: string; + country: string; + region: string; + neighborhood: string; + postalCode: string; + poBox: string; + isoCountryCode: string; + id: string; + label: string; + } + + /** + * iOS only + */ + interface SocialProfile { + service: string; + username: string; + localizedProfile: string; + url: string; + userId: string; + id: string; + label: string; + } + + interface InstantMessageAddress { + service: string; + username: string; + localizedProfile: string; + id: string; + label: string; + } + + interface UrlAddress { + url: string; + id: string; + label: string; + } + + /** + * Information regarding thumbnail images + */ + interface Image { + uri: string; + /** + * iOS only + * In Android you can get dimensions using `ReactNative.Image.getSize` + */ + width?: number; + /** + * iOS only + * In Android you can get dimensions using `ReactNative.Image.getSize` + */ + height?: number; + /** + * Avoid using Base 64 in React Native + * iOS only + */ + base64?: string; + } + + /** + * A parent to contacts. A contact can belong to multiple groups. + * iOS Only + */ + interface Group { + id: string; + name: string; + } + + /** + * A parent to contacts and groups. + * iOS Only + */ + interface Container { + id: string; + name: string; + } + + /** + * Denotes the functionality of a native contact form + */ + interface FormOptions { + displayedPropertyKeys?: Field[]; + message?: string; + alternateName?: string; + cancelButtonTitle?: string; + groupId?: string; + allowsEditing?: boolean; + allowsActions?: boolean; + shouldShowLinkedContacts?: boolean; + isNew?: boolean; + preventAnimation?: boolean; + } + + /** + * Used to query contacts from the user's device + */ + interface ContactQuery { + fields?: Field[]; + pageSize?: number; + pageOffset?: number; + id?: string; + /** Android Only */ + sort?: SortType; + /** iOS Only */ + name?: string; + /** iOS Only */ + groupId?: string; + /** iOS Only */ + containerID?: string; + /** iOS Only */ + rawContacts?: boolean; + } + + interface ContactResponse { + data: Contact[]; + /** + * This will be true if there are more contacts to retrieve beyond what is returned + */ + hasNextPage: boolean; + /** + * `true` if there are previous contacts that weren't retrieved due to `pageOffset` + */ + hasPreviousPage: boolean; + } + + /** + * Used to query native contact groups. + * iOS Only + */ + interface GroupQuery { + groupName?: string; + groupId?: string; + containerId?: string; + } + + /** + * Used to query native contact containers. + * iOS Only + */ + interface ContainerQuery { + contactId?: string; + groupId?: string; + containerId?: string; + } + + // Methods + + /** + * Return a list of contacts that fit a given criteria. You can get all of the contacts by passing no criteria. + */ + function getContactsAsync(contactQuery?: ContactQuery): Promise; + /** + * Returns a contact matching the input id. Used for gathering precise data about a contact. + */ + function getContactByIdAsync(contactId: string, fields?: Field[]): Promise; + + // iOS Only - temporary + /** + * Creates a new contact and adds it to the system. + * iOS Only - temporary + */ + function addContactAsync(contact: Contact, containerId?: string): Promise; + /** + * Mutate the information of an existing contact. + * iOS Only - temporary + */ + function updateContactAsync(contact: Contact): Promise; + /** + * Delete a contact from the system. + * iOS Only - temporary + */ + function removeContactAsync(contactId: string): Promise; + /** + * Query a set of contacts and write them to a local uri that can be used for sharing with `ReactNative.Share`. + * iOS Only - temporary + */ + function writeContactToFileAsync(contactQuery: ContactQuery): Promise; + + // iOS Only + /** + * Present a native form for manipulating contacts. + * iOS Only + */ + function presentFormAsync(contactId: string, contact?: Contact, formOptions?: FormOptions): Promise; + /** + * Add a group to a container. + * iOS Only + */ + function addExistingGroupToContainerAsync(groupId: string, containerId: string): Promise; + /** + * Create a group with a name, and add it to a container. If the container is undefined, the default container will be targeted. + * iOS Only + */ + function createGroupAsync(groupName: string, containerId?: string): Promise; + /** + * Change the name of an existing group. + * iOS Only + */ + function updateGroupNameAsync(groupName: string, groupId: string): Promise; + /** + * Delete a group from the device. + * iOS Only + */ + function removeGroupAsync(groupId: string): Promise; + /** + * Add a contact as a member to a group. A contact can be a member of multiple groups. + * iOS Only + */ + function addExistingContactToGroupAsync(contactId: string, groupId: string): Promise; + /** + * Remove a contact's membership from a given group. This will not delete the contact. + * iOS Only + */ + function removeContactFromGroupAsync(contactId: string, groupId: string): Promise; + /** + * Query and return a list of system groups. + * iOS Only + */ + function getGroupsAsync(query: GroupQuery): Promise; + /** + * Get the default container's ID. + * iOS Only + */ + function getDefaultContainerIdAsync(): Promise; + /** + * Query a list of system containers. + * iOS Only + */ + function getContainersAsync(containerQuery: ContainerQuery): Promise; +} + +/** + * DocumentPicker + */ +export namespace DocumentPicker { + interface Options { + type?: string; + } + + type Response = { + type: 'success'; + uri: string; + name: string; + size: number; + } | { + type: 'cancel'; + }; + + function getDocumentAsync(options?: Options): Promise; +} + +/** + * ErrorRecovery + */ +export namespace ErrorRecovery { + function setRecoveryProps(props: HashMap): void; +} + +/** + * Facebook + */ +export namespace Facebook { + interface Options { + permissions?: string[]; + behavior?: 'web' | 'native' | 'browser' | 'system'; + } + interface Response { + type: 'cancel' | 'success'; + token?: string; + expires?: number; + } + function logInWithReadPermissionsAsync(appId: string, options?: Options): Promise; +} + +/** + * Facebook Ads + */ +export namespace FacebookAds { + /** + * Interstitial Ads + */ + namespace InterstitialAdManager { + function showAd(placementId: string): Promise; + } + + /** + * Native Ads + */ + type MediaCachePolicy = 'none' | 'icon' | 'image' | 'all'; + class NativeAdsManager { + constructor(placementId: string, numberOfAdsToRequest?: number); + disableAutoRefresh(): void; + setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; + } + + interface NativeAd { + /** + * The headline the advertiser entered when they created their ad. This is usually the ad's main + * title. + */ + headline?: string; + + /** + * The link description which is additional information that the advertiser may have entered + */ + linkDescription?: string; + + /** + * The name of the Facebook Page or mobile app that represents the business running the ad + */ + advertiserName?: string; + + /** + * The ad's social context, such as, "Over half a million users" + */ + socialContext?: string; + + /** + * The call-to-action phrase of the ad, such as, "Install Now" + */ + callToActionText?: string; + + /** + * The body text, truncated to 90 characters, that contains the text the advertiser entered when + * they created their ad to tell people what the ad promotes + */ + bodyText?: string; + + /** + * The word "ad", translated into the viewer's language + */ + adTranslation?: string; + + /** + * The word "promoted", translated into the viewer's language + */ + promotedTranslation?: string; + + /** + * The word "sponsored", translated into the viewer's language + */ + sponsoredTranslation?: string; + } + + function withNativeAd

(component: Component

): Component< + { + adsManager: NativeAdsManager, + onAdLoaded?: ((ad: NativeAd) => void) | null; + } & P, + { ad: NativeAd | null, canRequestAds: boolean } + >; + + /** + * Banner View + */ + type AdType = 'large' | 'rectangle' | 'standard'; + + interface BannerViewProps { + type: AdType; + placementId: string; + onPress: () => void; + onError: () => void; + } + + class BannerView extends Component { } + + type AdTriggerViewProps

= { + renderInteractiveComponent?: (props: P) => React.ReactElement

; + } & P; + + class AdTriggerView

extends Component> { } + + class AdIconView extends Component { } + + class AdMediaView extends Component { } + + /** + * Ad Settings + */ + namespace AdSettings { + const currentDeviceHash: string; + function addTestDevice(device: string): void; + function clearTestDevices(): void; + type SDKLogLevel = 'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'; + function setLogLevel(logLevel: SDKLogLevel): void; + function setIsChildDirected(isDirected: boolean): void; + function setMediationService(mediationService: string): void; + function setUrlPrefix(urlPrefix: string): void; + } +} + +/** + * FaceDetector + */ +export interface Point { + x: Axis; + y: Axis; +} + +export interface FaceFeature { + bounds: { + size: { + width: number; + height: number; + }, + origin: Point; + }; + smilingProbability?: number; + leftEarPosition?: Point; + rightEarPosition?: Point; + leftEyePosition?: Point; + leftEyeOpenProbability?: number; + rightEyePosition?: Point; + rightEyeOpenProbability?: number; + leftCheekPosition?: Point; + rightCheekPosition?: Point; + leftMouthPosition?: Point; + mouthPosition?: Point; + rightMouthPosition?: Point; + bottomMouthPosition?: Point; + noseBasePosition?: Point; + yawAngle?: number; + rollAngle?: number; +} + +export interface TrackedFaceFeature extends FaceFeature { + faceID?: number; +} + +export namespace FaceDetector { + interface DetectFaceResult { + faces: FaceFeature[]; + image: { + uri: string; + width: number; + height: number; + orientation: number; + }; + } + interface Mode { + fast: 'fast'; + accurate: 'accurate'; + } + interface _Shared { + all: 'all'; + none: 'none'; + } + type Landmarks = _Shared; + type Classifications = _Shared; + interface _Constants { + Mode: Mode; + Landmarks: Landmarks; + Classifications: Classifications; + } + + const Constants: _Constants; + + interface DetectionOptions { + mode?: keyof Mode; + detectLandmarks?: keyof Landmarks; + runClassifications?: keyof Classifications; + } + + function detectFaces(uri: string, options?: DetectionOptions): Promise; +} +/** + * FileSystem + */ +export namespace FileSystem { + type EncodingType = "utf8" | "base64"; + + type FileInfo = { + exists: true; + isDirectory: boolean; + uri: string; + size: number; + modificationTime: number; + md5?: Md5; + } | { + exists: false; + isDirectory: false; + }; + + interface ReadingOptions { + encoding?: EncodingType; + position?: number; + length?: number; + } + + interface WritingOptions { + encoding?: EncodingType; + } + + interface DownloadResult { + uri: string; + status: number; + headers: { [name: string]: string }; + md5?: Md5; + } + + const documentDirectory: string; + const cacheDirectory: string; + + function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; + function readAsStringAsync(fileUri: string, options?: ReadingOptions): Promise; + function writeAsStringAsync(fileUri: string, contents: string, options?: WritingOptions): Promise; + function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; + function moveAsync(options: { from: string, to: string; }): Promise; + function copyAsync(options: { from: string, to: string; }): Promise; + function makeDirectoryAsync(dirUri: string, options?: { intermediates: boolean }): Promise; + function readDirectoryAsync(dirUri: string): Promise; + function downloadAsync(uri: string, fileUri: string, options?: { md5?: boolean; }): Promise; + function createDownloadResumable( + uri: string, + fileUri: string, + options?: DownloadOptions, + callback?: (totalBytesWritten: number, totalBytesExpectedToWrite: number) => void, + resumeData?: string | null + ): DownloadResumable; + + interface PauseResult { + url: string; + fileUri: string; + options: { md5: boolean; }; + resumeData: string; + } + + interface DownloadOptions { + md5?: boolean; + headers?: { [name: string]: string }; + } + + interface DownloadProgressData { + totalBytesWritten: number; + totalBytesExpectedToWrite: number; + } + + type DownloadProgressCallback = (data: DownloadProgressData) => void; + + class DownloadResumable { + constructor( + url: string, + fileUri: string, + options: DownloadOptions, + callback?: DownloadProgressCallback, + resumeData?: string + ); + + downloadAsync(): Promise; + pauseAsync(): Promise; + resumeAsync(): Promise; + savable(): PauseResult; + } +} + +/** Use TouchID/FaceID (iOS) or the Fingerprint API (Android) to authenticate the user with a fingerprint scan. */ +export namespace LocalAuthentication { + type LocalAuthenticationResult = { + success: true + } | { + success: false, + + /** Error code in the case where authentication fails. */ + error: string + }; + + interface AuthenticationTypeType { + FINGERPRINT: number; + FACIAL_RECOGNITION: number; + } + + /** Determine the auhentication types supported on the device. */ + function supportedAuthenticationTypesAsync(): Promise; + + /** Determine whether a face or fingerprint scanner is available on the device. */ + function hasHardwareAsync(): Promise; + + /** Determine whether the device has saved fingerprints or facial data to use for authentication. */ + function isEnrolledAsync(): Promise; + + /** + * Attempts to authenticate via Fingerprint. Android: When using the fingerprint module on Android, you need to provide a UI component to prompt the user to scan their fingerprint, as the OS has no default alert for it. + * + * @param promptMessage A message that is shown alongside the TouchID/FaceID prompt. (iOS only) + */ + function authenticateAsync(promptMessageIOS?: string): Promise; + + /** Cancels the fingerprint authentication flow. (Android only) */ + function cancelAuthenticate(): void; +} + +/** + * Font + */ +export namespace Font { + interface FontMap { + [name: string]: RequireSource; + } + + function loadAsync(name: string, url: string): Promise; + function loadAsync(map: FontMap): Promise; +} + +// #region GLView +export interface ExpoWebGLRenderingContext extends WebGLRenderingContext { + endFrameEXP(): void; +} + +/** + * A View that acts as an OpenGL ES render target. On mounting, an OpenGL ES + * context is created. Its drawing buffer is presented as the contents of + * the View every frame. + */ +export interface GLViewProps extends ViewProps { + /** + * A function that will be called when the OpenGL ES context is created. + * Passes an object with a WebGLRenderingContext interface as an argument. + */ + onContextCreate(gl: ExpoWebGLRenderingContext): void; + + /** Number of MSAA samples to use on iOS. Defaults to 4. Ignored on Android. */ + msaaSamples?: number; +} + +export class GLView extends Component { } +// #endregion + +/** + * Google + */ +export namespace Google { + interface LogInConfig { + androidClientId?: string; + androidStandaloneAppClientId?: string; + iosClientId?: string; + iosStandaloneAppClientId?: string; + webClientId?: string; + behavior?: 'system' | 'web'; + scopes?: string[]; + } + + type LogInResult = { + type: 'cancel'; + } | { + type: 'success'; + accessToken: string; + idToken?: string; + refreshToken?: string; + serverAuthCode?: string; + user: { + id: string; + name: string; + givenName: string; + familyName: string; + photoUrl?: string; + email?: string; + } + }; + + function logInAsync(config: LogInConfig): Promise; +} + +/** Access the device gyroscope sensor to respond to changes in rotation in 3d space. */ +export namespace Gyroscope { + interface GyroscopeObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** A callback that is invoked when an gyroscope update is available. */ + function addListener(listener: (obj: GyroscopeObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** Subscribe for updates to the gyroscope. */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * ImageManipulator + */ +export namespace ImageManipulator { + type Action = Resize | Rotate | Flip | Crop; + + interface Resize { + resize: { width?: number, height?: number }; + } + + interface Rotate { + rotate: number; + } + + interface Flip { + flip?: { vertical?: boolean; horizontal?: boolean }; + } + + interface Crop { + originX: number; + originY: number; + width: number; + height: number; + } + + interface ImageResult { + uri: string; + width: number; + height: number; + base64?: string; + } + + interface SaveOptions { + base64?: boolean; + /** A value in range `0` - `1` specifying compression level of the result image. `1` means no compression and `0` the highest compression. */ + compress?: number; + format?: 'jpeg' | 'png'; + } + + function manipulateAsync(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise; +} + +/** + * Image Picker + */ +export namespace ImagePicker { + interface ImageInfo { + uri: string; + width: number; + height: number; + type: 'video' | 'image'; + base64?: string; + exif?: object; + duration?: number; + } + + type ImageResult = { cancelled: true } | ({ cancelled: false } & ImageInfo); + + interface _MediaTypeOptions { + All: 'All'; + Videos: 'Videos'; + Images: 'Images'; + } + + const MediaTypeOptions: _MediaTypeOptions; + + interface ImageLibraryOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + base64?: boolean; + exif?: boolean; + mediaTypes?: keyof _MediaTypeOptions; + } + + /** + * require Permissions.CAMERA_ROLL + */ + function launchImageLibraryAsync(options?: ImageLibraryOptions): Promise; + + interface CameraOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + base64?: boolean; + exif?: boolean; + } + + /** + * require Permissions.CAMERA_ROLL + */ + function launchCameraAsync(options?: CameraOptions): Promise; +} + +/** + * IntentLauncherAndroid + */ +export namespace IntentLauncherAndroid { + const ACTION_ACCESSIBILITY_SETTINGS: 'android.settings.ACCESSIBILITY_SETTINGS'; + const ACTION_APP_NOTIFICATION_REDACTION: 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; + const ACTION_CONDITION_PROVIDER_SETTINGS: 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; + const ACTION_NOTIFICATION_LISTENER_SETTINGS: 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; + const ACTION_PRINT_SETTINGS: 'android.settings.ACTION_PRINT_SETTINGS'; + const ACTION_ADD_ACCOUNT_SETTINGS: 'android.settings.ADD_ACCOUNT_SETTINGS'; + const ACTION_AIRPLANE_MODE_SETTINGS: 'android.settings.AIRPLANE_MODE_SETTINGS'; + const ACTION_APN_SETTINGS: 'android.settings.APN_SETTINGS'; + const ACTION_APPLICATION_DETAILS_SETTINGS: 'android.settings.APPLICATION_DETAILS_SETTINGS'; + const ACTION_APPLICATION_DEVELOPMENT_SETTINGS: 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; + const ACTION_APPLICATION_SETTINGS: 'android.settings.APPLICATION_SETTINGS'; + const ACTION_APP_NOTIFICATION_SETTINGS: 'android.settings.APP_NOTIFICATION_SETTINGS'; + const ACTION_APP_OPS_SETTINGS: 'android.settings.APP_OPS_SETTINGS'; + const ACTION_BATTERY_SAVER_SETTINGS: 'android.settings.BATTERY_SAVER_SETTINGS'; + const ACTION_BLUETOOTH_SETTINGS: 'android.settings.BLUETOOTH_SETTINGS'; + const ACTION_CAPTIONING_SETTINGS: 'android.settings.CAPTIONING_SETTINGS'; + const ACTION_CAST_SETTINGS: 'android.settings.CAST_SETTINGS'; + const ACTION_DATA_ROAMING_SETTINGS: 'android.settings.DATA_ROAMING_SETTINGS'; + const ACTION_DATE_SETTINGS: 'android.settings.DATE_SETTINGS'; + const ACTION_DEVICE_INFO_SETTINGS: 'android.settings.DEVICE_INFO_SETTINGS'; + const ACTION_DEVICE_NAME: 'android.settings.DEVICE_NAME'; + const ACTION_DISPLAY_SETTINGS: 'android.settings.DISPLAY_SETTINGS'; + const ACTION_DREAM_SETTINGS: 'android.settings.DREAM_SETTINGS'; + const ACTION_HARD_KEYBOARD_SETTINGS: 'android.settings.HARD_KEYBOARD_SETTINGS'; + const ACTION_HOME_SETTINGS: 'android.settings.HOME_SETTINGS'; + const ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS: 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; + const ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS: 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; + const ACTION_INPUT_METHOD_SETTINGS: 'android.settings.INPUT_METHOD_SETTINGS'; + const ACTION_INPUT_METHOD_SUBTYPE_SETTINGS: 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; + const ACTION_INTERNAL_STORAGE_SETTINGS: 'android.settings.INTERNAL_STORAGE_SETTINGS'; + const ACTION_LOCALE_SETTINGS: 'android.settings.LOCALE_SETTINGS'; + const ACTION_LOCATION_SOURCE_SETTINGS: 'android.settings.LOCATION_SOURCE_SETTINGS'; + const ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_DEFAULT_APPS_SETTINGS: 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; + const ACTION_MEMORY_CARD_SETTINGS: 'android.settings.MEMORY_CARD_SETTINGS'; + const ACTION_MONITORING_CERT_INFO: 'android.settings.MONITORING_CERT_INFO'; + const ACTION_NETWORK_OPERATOR_SETTINGS: 'android.settings.NETWORK_OPERATOR_SETTINGS'; + const ACTION_NFCSHARING_SETTINGS: 'android.settings.NFCSHARING_SETTINGS'; + const ACTION_NFC_PAYMENT_SETTINGS: 'android.settings.NFC_PAYMENT_SETTINGS'; + const ACTION_NFC_SETTINGS: 'android.settings.NFC_SETTINGS'; + const ACTION_NIGHT_DISPLAY_SETTINGS: 'android.settings.NIGHT_DISPLAY_SETTINGS'; + const ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS: 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; + const ACTION_NOTIFICATION_SETTINGS: 'android.settings.NOTIFICATION_SETTINGS'; + const ACTION_PAIRING_SETTINGS: 'android.settings.PAIRING_SETTINGS'; + const ACTION_PRIVACY_SETTINGS: 'android.settings.PRIVACY_SETTINGS'; + const ACTION_QUICK_LAUNCH_SETTINGS: 'android.settings.QUICK_LAUNCH_SETTINGS'; + const ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; + const ACTION_SECURITY_SETTINGS: 'android.settings.SECURITY_SETTINGS'; + const ACTION_SETTINGS: 'android.settings.SETTINGS'; + const ACTION_SHOW_ADMIN_SUPPORT_DETAILS: 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; + const ACTION_SHOW_INPUT_METHOD_PICKER: 'android.settings.SHOW_INPUT_METHOD_PICKER'; + const ACTION_SHOW_REGULATORY_INFO: 'android.settings.SHOW_REGULATORY_INFO'; + const ACTION_SHOW_REMOTE_BUGREPORT_DIALOG: 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; + const ACTION_SOUND_SETTINGS: 'android.settings.SOUND_SETTINGS'; + const ACTION_STORAGE_MANAGER_SETTINGS: 'android.settings.STORAGE_MANAGER_SETTINGS'; + const ACTION_SYNC_SETTINGS: 'android.settings.SYNC_SETTINGS'; + const ACTION_SYSTEM_UPDATE_SETTINGS: 'android.settings.SYSTEM_UPDATE_SETTINGS'; + const ACTION_TETHER_PROVISIONING_UI: 'android.settings.TETHER_PROVISIONING_UI'; + const ACTION_TRUSTED_CREDENTIALS_USER: 'android.settings.TRUSTED_CREDENTIALS_USER'; + const ACTION_USAGE_ACCESS_SETTINGS: 'android.settings.USAGE_ACCESS_SETTINGS'; + const ACTION_USER_DICTIONARY_INSERT: 'android.settings.USER_DICTIONARY_INSERT'; + const ACTION_USER_DICTIONARY_SETTINGS: 'android.settings.USER_DICTIONARY_SETTINGS'; + const ACTION_USER_SETTINGS: 'android.settings.USER_SETTINGS'; + const ACTION_VOICE_CONTROL_AIRPLANE_MODE: 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; + const ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE: 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; + const ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE: 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; + const ACTION_VOICE_INPUT_SETTINGS: 'android.settings.VOICE_INPUT_SETTINGS'; + const ACTION_VPN_SETTINGS: 'android.settings.VPN_SETTINGS'; + const ACTION_VR_LISTENER_SETTINGS: 'android.settings.VR_LISTENER_SETTINGS'; + const ACTION_WEBVIEW_SETTINGS: 'android.settings.WEBVIEW_SETTINGS'; + const ACTION_WIFI_IP_SETTINGS: 'android.settings.WIFI_IP_SETTINGS'; + const ACTION_WIFI_SETTINGS: 'android.settings.WIFI_SETTINGS'; + const ACTION_WIRELESS_SETTINGS: 'android.settings.WIRELESS_SETTINGS'; + const ACTION_ZEN_MODE_AUTOMATION_SETTINGS: 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; + const ACTION_ZEN_MODE_EVENT_RULE_SETTINGS: 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; + const ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS: 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; + const ACTION_ZEN_MODE_PRIORITY_SETTINGS: 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; + const ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS: 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; + const ACTION_ZEN_MODE_SETTINGS: 'android.settings.ZEN_MODE_SETTINGS'; + + function startActivityAsync(activity: string, data?: HashMap): Promise; +} + +/** + * KeepAwake + */ +export class KeepAwake extends Component { + static activate(): void; + static deactivate(): void; +} + +// #region LinearGradient +/** + * LinearGradient + */ +export interface LinearGradientProps { + colors: string[]; + start?: [number, number]; + end?: [number, number]; + locations?: number[]; + style?: StyleProp; +} + +export class LinearGradient extends Component { } +// #endregion + +/** + * Linking + */ +export interface LinkInfo { + path: string; + queryParams: Partial; +} + +export interface LinkingStatic extends ReactNativeLinkingStatic { + makeUrl(path: string, queryParams?: HashMap): string; + parse(url: string): LinkInfo; + parseInitialURLAsync(): Promise; +} +export const Linking: LinkingStatic; + +/** + * Location + */ +export namespace Location { + interface LocationOptions { + enableHighAccuracy?: boolean; + timeInterval?: number; + distanceInterval?: number; + timeout?: number; + } + + interface LocationProps { + latitude: number; + longitude: number; + } + + interface Coords extends LocationProps { + altitude: number; + accuracy: number; + } + + interface LocationData { + coords: { + heading: number; + speed: number + } & Coords; + timestamp: number; + } + + interface ProviderStatus { + locationServicesEnabled: boolean; + gpsAvailable?: boolean; + networkAvailable?: boolean; + passiveAvailable?: boolean; + } + + interface HeadingStatus { + magHeading: number; + trueHeading: number; + accuracy: number; + } + + interface GeocodeData { + city: string; + street: string; + region: string; + postalCode: string; + country: string; + name: string; + } + + type LocationCallback = (data: LocationData) => void; + + function getCurrentPositionAsync(options: LocationOptions): Promise; + function watchPositionAsync(options: LocationOptions, callback: LocationCallback): EventSubscription; + function getProviderStatusAsync(): Promise; + function getHeadingAsync(): Promise; + function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; + function geocodeAsync(address: string): Promise; + function reverseGeocodeAsync(location: LocationProps): Promise; + function setApiKey(key: string): void; +} + +/** + * Magnetometer + */ +export namespace Magnetometer { + interface MagnetometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: MagnetometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Notifications + */ +export namespace Notifications { + interface Notification { + origin: 'selected' | 'received'; + data: any; + remote: boolean; + isMultiple: boolean; + } + + interface LocalNotification { + title: string; + body?: string; + data?: any; + ios?: { + sound?: boolean + }; + android?: { + sound?: boolean; + icon?: string; + color?: string; + priority?: 'min' | 'low' | 'high' | 'max'; + sticky?: boolean; + vibrate?: boolean | number[]; + link?: string; + }; + } + + interface SchedulingOptions { + time: Date | number; + repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + intervalMs?: number; + } + + interface ChannelAndroid { + name: string; + description?: string; + sound?: boolean; + priority?: 'min' | 'low' | 'default' | 'high' | 'max'; + vibrate?: boolean | number[]; + badge?: boolean; + } + + type LocalNotificationId = string | number; + + function addListener(listener: (notification: Notification) => any): EventSubscription; + function getExpoPushTokenAsync(): Promise; + function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; + function scheduleLocalNotificationAsync( + localNotification: LocalNotification, + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } + ): Promise; + function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function dismissAllNotificationsAsync(): Promise; + function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function cancelAllScheduledNotificationsAsync(): Promise; + function createChannelAndroidAsync(id: string, channel: ChannelAndroid): Promise; + function deleteChannelAndroidAsync(id: string): Promise; + function getBadgeNumberAsync(): Promise; + function setBadgeNumberAsync(number: number): Promise; +} + +/** + * Pedometer + */ +export namespace Pedometer { + function isAvailableAsync(): Promise; + function getStepCountAsync(start: Date, end: Date): Promise<{ steps: number; }>; + function watchStepCount(callback: (params: { steps: number; }) => void): EventSubscription; +} + +/** + * Permissions + */ +export namespace Permissions { + type PermissionType = 'audioRecording' | 'calendar' | + 'cameraRoll' | 'camera' | 'contacts' | 'location' | 'reminders' | + 'notifications' | 'systemBrightness' | 'userFacingNotifications' | 'SMS'; + type PermissionStatus = 'undetermined' | 'granted' | 'denied'; + type PermissionExpires = 'never'; + + interface PermissionDetailsLocationIOS { + scope: 'whenInUse' | 'always'; + } + + interface PermissionDetailsLocationAndroid { + scope: 'fine' | 'coarse' | 'none'; + } + + interface SinglePermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + ios?: PermissionDetailsLocationIOS; + android?: PermissionDetailsLocationAndroid; + } + + interface PermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + permissions: { + [key in PermissionType]: SinglePermissionResponse + }; + } + + function getAsync(...permissionTypes: PermissionType[]): Promise; + function askAsync(...permissionTypes: PermissionType[]): Promise; + + const AUDIO_RECORDING: 'audioRecording'; + const CALENDAR: 'calendar'; + const CAMERA_ROLL: 'cameraRoll'; + const CAMERA: 'camera'; + const CONTACTS: 'contacts'; + const LOCATION: 'location'; + const NOTIFICATIONS: 'notifications'; + const REMINDERS: 'reminders'; + const SYSTEM_BRIGHTNESS: 'systemBrightness'; + const USER_FACING_NOTIFICATIONS: 'userFacingNotifications'; + /** + * Will be removed in SDK 32 + */ + const SMS: 'SMS'; +} + +/** + * Register Root Component + */ +export function registerRootComponent(component: ComponentType): void; + +/** + * ScreenOrientation + */ +export namespace ScreenOrientation { + interface Orientations { + ALL: 'ALL'; + ALL_BUT_UPSIDE_DOWN: 'ALL_BUT_UPSIDE_DOWN'; + PORTRAIT: 'PORTRAIT'; + PORTRAIT_UP: 'PORTRAIT_UP'; + PORTRAIT_DOWN: 'PORTRAIT_DOWN'; + LANDSCAPE: 'LANDSCAPE'; + LANDSCAPE_LEFT: 'LANDSCAPE_LEFT'; + LANDSCAPE_RIGHT: 'LANDSCAPE_RIGHT'; + } + + const Orientation: Orientations; + + function allow(orientation: keyof Orientations): void; +} + +/** + * SecureStore + */ +export namespace SecureStore { + interface SecureStoreOptions { + keychainService?: string; + } + + interface SecureStoreSetOptions extends SecureStoreOptions { + keychainAccessible?: number; + } + + function setItemAsync(key: string, value: string, options?: SecureStoreSetOptions): Promise; + function getItemAsync(key: string, options?: SecureStoreOptions): Promise; + function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise; + + const WHEN_UNLOCKED: number; + const AFTER_FIRST_UNLOCK: number; + const ALWAYS: number; + const WHEN_UNLOCKED_THIS_DEVICE_ONLY: number; + const WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: number; + const AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: number; + const ALWAYS_THIS_DEVICE_ONLY: number; +} + +/** + * Segment + */ +export namespace Segment { + function initialize(keys: { + androidWriteKey: string; + iosWriteKey: string; + }): void; + function identify(userId: string): void; + function identifyWithTraits(userId: string, traits: object): void; + function track(event: string): void; + function alias(newId: string, options?: { [key: string]: any }): Promise; + function reset(): void; + function trackWithProperties(event: string, properties: object): void; + function screen(screenName: string): void; + function screenWithProperties(screenName: string, properties: object): void; + function flush(): void; + function getEnabledAsync(): void; + function setEnabledAsync(enabled: boolean): void; +} + +/** + * Speech + */ +export namespace Speech { + interface SpeechOptions { + language?: string; + pitch?: number; + rate?: number; + onStart?: () => void; + onStopped?: () => void; + onDone?: () => void; + onError?: (error: Error) => void; + } + + function speak(text: string, options?: SpeechOptions): void; + function stop(): void; + function isSpeakingAsync(): Promise; + + /** Available on iOS only */ + function pause(): void; + + /** Available on iOS only */ + function resume(): void; +} + +/** + * SQLite + */ +export namespace SQLite { + type Error = any; + + interface Database { + transaction( + callback: (transaction: Transaction) => any, + error?: (error: Error) => any, // TODO def of error + success?: () => any + ): void; + } + + interface Transaction { + executeSql( + sqlStatement: string, + arguments?: string[] | number[], + success?: (transaction: Transaction, resultSet: ResultSet) => any, + error?: (transaction: Transaction, error: Error) => any + ): void; + } + + interface ResultSet { + insertId: number; + rowAffected: number; + rows: { + length: number; + item: (index: number) => any; + _array: HashMap[]; + }; + } + + function openDatabase( + name: string | { + name: string, + version?: string, + description?: string, + size?: number, + callback?: () => any + }, + version?: string, + description?: string, + size?: number, + callback?: () => any + ): any; +} + +// #region Svg +/** + * Svg + */ +export interface SvgCommonProps { + fill?: string; + fillOpacity?: number | string; + fillRule?: 'nonzero' | 'evenodd'; + opacity?: number | string; + stroke?: string; + strokeWidth?: number | string; + strokeOpacity?: number | string; + strokeLinecap?: string; + strokeLineJoin?: string; + strokeDasharray?: any[]; + strokeDashoffset?: any; + transform?: string | object; + x?: number | string; + y?: number | string; + rotate?: number | string; + rotation?: number | string; + scale?: number | string; + origin?: number | string; + originX?: number | string; + originY?: number | string; + id?: string; + disabled?: boolean; + onPress?: () => any; + onPressIn?: () => any; + onPressOut?: () => any; + onLongPress?: () => any; + delayPressIn?: number; + delayPressOut?: number; + delayLongPress?: number; +} + +export interface SvgRectProps extends SvgCommonProps { + width: number | string; + height: number | string; +} + +export interface SvgCircleProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + r: number | string; +} + +export interface SvgEllipseProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; +} + +export interface SvgLineProps extends SvgCommonProps { + x1: number | string; + y1: number | string; + x2: number | string; + y2: number | string; +} + +export interface SvgPolyProps extends SvgCommonProps { + points: string; +} + +export interface SvgPathProps extends SvgCommonProps { + d: string; +} + +export interface SvgTextProps extends SvgCommonProps { + textAnchor?: string; + fontSize?: number | string; + fontWeight?: string; +} + +export interface SvgTSpanProps extends SvgTextProps { + dx?: string; + dy?: string; +} + +export interface SvgTextPathProps extends SvgCommonProps { + href?: string; + startOffset?: string; +} + +export interface SvgUseProps extends SvgCommonProps { + href: string; + x: number | string; + y: number | string; + width?: number | string; + height?: number | string; +} + +export interface SvgSymbolProps extends SvgCommonProps { + viewBox: string; + preserveAspectRatio?: string; + width: number | string; + height: number | string; +} + +export interface SvgLinearGradientProps extends SvgCommonProps { + x1: number | string; + x2: number | string; + y1: number | string; + y2: number | string; +} + +export interface SvgRadialGradientProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; + fx: number | string; + fy: number | string; + gradientUnits?: string; +} + +export interface SvgStopProps extends SvgCommonProps { + offset?: string; + stopColor?: string; + stopOpacity?: string; +} + +export class Svg extends Component<{ width: number, height: number, viewBox?: string, preserveAspectRatio?: string }> { + static Circle: ComponentClass; + static ClipPath: ComponentClass; + static Defs: ComponentClass; + static Ellipse: ComponentClass; + static G: ComponentClass; + static Line: ComponentClass; + static LinearGradient: ComponentClass; + static Path: ComponentClass; + static Polygon: ComponentClass; + static Polyline: ComponentClass; + static RadialGradient: ComponentClass; + static Rect: ComponentClass; + static Stop: ComponentClass; + static Symbol: ComponentClass; + static Text: ComponentClass; + static TextPath: ComponentClass; + static TSpan: ComponentClass; + static Use: ComponentClass; +} +// #endregion + +/** + * Take Snapshot + */ +export function takeSnapshotAsync( + view?: (number | React.ReactElement), + options?: { + width?: number, + height?: number, + format?: 'png' | 'jpg' | 'jpeg' | 'webm', + quality?: number, + result?: 'file' | 'base64' | 'data-uri', + } +): Promise; + +/** Helpful utility functions that don’t fit anywhere else, including some localization and internationalization methods. */ +export namespace Util { + /** Returns the current device country code. */ + function getCurrentDeviceCountryAsync(): Promise; + + /** Returns the current device locale as a string. */ + function getCurrentLocaleAsync(): Promise; + + /** Returns the current device time zone name. */ + function getCurrentTimeZoneAsync(): Promise; + + /** Reloads the current experience. This will fetch and load the newest available JavaScript supported by the device’s Expo environment. This is useful for triggering an update of your experience if you have published a new version. */ + function reload(): void; + + /** _Android only_. Invokes a callback when a new version of your app is successfully downloaded in the background. */ + function addNewVersionListenerExperimental(listener: (event: { + manifest: object; + }) => void): { remove(): void; }; +} + +// #region Video +/** + * Expo Video + */ +export interface NaturalSize { + width: number; + height: number; + orientation: Orientation; +} + +export interface ReadyForDisplayEvent { + naturalSize: NaturalSize; + status: PlaybackStatus; +} + +export enum FullscreenUpdateVariants { + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT = 0, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT = 1, + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS = 2, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS = 3 +} + +export interface FullscreenUpdateEvent { + fullscreenUpdate: FullscreenUpdateVariants; + status: PlaybackStatus; +} + +export interface VideoProps { + source?: PlaybackSource | null; + posterSource?: URISource | RequireSource; + + resizeMode?: ResizeModeContain | ResizeModeCover | ResizeModeStretch; + useNativeControls?: boolean; + usePoster?: boolean; + + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void; + onReadyForDisplay?: (event: ReadyForDisplayEvent) => void; + onIOSFullscreenUpdate?: (event: FullscreenUpdateEvent) => void; + + onLoadStart?: () => void; + onLoad?: (status: PlaybackStatus) => void; + onError?: (error: string) => void; + + status?: PlaybackStatusToSet; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: number; + shouldCorrectPitch?: boolean; + volume?: number; + isMuted?: boolean; + isLooping?: boolean; + + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; + ref?: Ref; + style?: StyleProp; +} + +export interface VideoState { + showPoster: boolean; +} + +export class Video extends Component { + static RESIZE_MODE_CONTAIN: ResizeModeContain; + static RESIZE_MODE_COVER: ResizeModeCover; + static RESIZE_MODE_STRETCH: ResizeModeStretch; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS; +} +// #endregion + +/** + * Web Browser + */ +export namespace WebBrowser { + function openBrowserAsync(url: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function dismissBrowser(): Promise<{ type: 'dismissed' }>; +} + +// #region Calendar +/** + * Calendar + * + * Provides an API for interacting with the device’s system calendars, events, reminders, and associated records. + */ +export namespace Calendar { + interface Calendar { + /** Internal ID that represents this calendar on the device */ + id?: string; + + /** Visible name of the calendar */ + title?: string; + + sourceId?: string; // iOS + + /** Object representing the source to be used for the calendar */ + source?: Source; + + /** Type of calendar this object represents */ + type?: CalendarType; // iOS + + /** Color used to display this calendar’s events */ + color?: string; + + /** Whether the calendar is used in the Calendar or Reminders OS app */ + entityType?: EntityTypes; // iOS + + /** Boolean value that determines whether this calendar can be modified */ + allowsModifications?: boolean; + + /** Availability types that this calendar supports */ + allowedAvailabilities?: Availability[]; + + /** Boolean value indicating whether this is the device’s primary calendar */ + isPrimary?: boolean; // Android + + /** Internal system name of the calendar */ + name?: string; // Android + + /** Name for the account that owns this calendar */ + ownerAccount?: string; // Android + + /** Time zone for the calendar */ + timeZone?: string; // Android + + /** Alarm methods that this calendar supports */ + allowedReminders?: AlarmMethod[]; // Android + + /** Attendee types that this calendar supports */ + allowedAttendeeTypes?: AttendeeType[]; // Android + + /** Indicates whether the OS displays events on this calendar */ + isVisible?: boolean; // Android + + /** Indicates whether this calendar is synced and its events stored on the device */ + isSynced?: boolean; // Android + + /** Level of access that the user has for the calendar */ + accessLevel?: CalendarAccessLevel; // Android + } + + interface Source { + /** Internal ID that represents this source on the device */ + id?: string; // iOS only ?? + + /** Type of account that owns this calendar */ + type?: string; + + /** Name for the account that owns this calendar */ + name?: string; + + /** Whether this source is the local phone account */ + isLocalAccount?: boolean; // Android + } + + interface Event { + /** Internal ID that represents this event on the device */ + id?: string; + + /** ID of the calendar that contains this event */ + calendarId?: string; + + /** Visible name of the event */ + title?: string; + + /** Location field of the event */ + location?: string; + + /** Date when the event record was created */ + creationDate?: string; // iOS + + /** Date when the event record was last modified */ + lastModifiedDate?: string; // iOS + + /** Time zone the event is scheduled in */ + timeZone?: string; + + /** Time zone for the event end time */ + endTimeZone?: string; // Android + + /** URL for the event */ + url?: string; // iOS + + /** Description or notes saved with the event */ + notes?: string; + + /** Array of Alarm objects which control automated reminders to the user */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeating events. Null for one-time events. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the time when the event starts */ + startDate?: string | Date; + + /** Date object or string representing the time when the event ends */ + endDate?: string | Date; + + /** For recurring events, the start date for the first (original) instance of the event */ + originalStartDate?: string; // iOS + + /** Boolean value indicating whether or not the event is a detached (modified) instance of a recurring event */ + isDetached?: boolean; // iOS + + /** Whether the event is displayed as an all-day event on the calendar */ + allDay?: boolean; + + /** The availability setting for the event */ + availability?: Availability; // Availability + + /** Status of the event */ + status?: EventStatus; // Status + + /** Organizer of the event, as an Attendee object */ + organizer?: string; // Organizer - iOS + + /** Email address of the organizer of the event */ + organizerEmail?: string; // Android + + /** User’s access level for the event */ + accessLevel?: EventAccessLevel; // Android, + + /** Whether invited guests can modify the details of the event */ + guestsCanModify?: boolean; // Android, + + /** Whether invited guests can invite other guests */ + guestsCanInviteOthers?: boolean; // Android + + /** Whether invited guests can see other guests */ + guestsCanSeeGuests?: boolean; // Android + + /** For detached (modified) instances of recurring events, the ID of the original recurring event */ + originalId?: string; // Android + + /** For instances of recurring events, volatile ID representing this instance; not guaranteed to always refer to the same instance */ + instanceId?: string; // Android + } + + interface Attendee { + /** Internal ID that represents this attendee on the device */ + id?: string; // Android + + /** Indicates whether or not this attendee is the current OS user */ + isCurrentUser?: boolean; // iOS + + /** Displayed name of the attendee */ + name?: string; + + /** Role of the attendee at the event */ + role?: AttendeeRole; + + /** Status of the attendee in relation to the event */ + status?: AttendeeStatus; + + /** Type of the attendee */ + type?: AttendeeType; + + /** URL for the attendee */ + url?: string; // iOS + + /** Email address of the attendee */ + email?: string; // Android + } + + interface Reminder { + /** Internal ID that represents this reminder on the device */ + id?: string; + + /** ID of the calendar that contains this reminder */ + calendarId?: string; + + /** Visible name of the reminder */ + title?: string; + + /** Location field of the reminder */ + location?: string; + + /** Date when the reminder record was created */ + creationDate?: string; + + /** Date when the reminder record was last modified */ + lastModifiedDate?: string; + + /** Time zone the reminder is scheduled in */ + timeZone?: string; + + /** URL for the reminder */ + url?: string; + + /** Description or notes saved with the reminder */ + notes?: string; + + /** Array of Alarm objects which control automated alarms to the user about the task */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeated reminders. Null for one-time tasks. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the start date of the reminder task */ + startDate?: string; + + /** Date object or string representing the time when the reminder task is due */ + dueDate?: string; + + /** Indicates whether or not the task has been completed */ + completed?: boolean; + + /** Date object or string representing the date of completion, if completed is true */ + completionDate?: string; + } + + interface Alarm { + /** Date object or string representing an absolute time the alarm should occur; overrides relativeOffset and structuredLocation if specified alongside either */ + absoluteDate?: string; // iOS + + /** Number of minutes from the startDate of the calendar item that the alarm should occur; use negative values to have the alarm occur before the startDate */ + relativeOffset?: string; + structuredLocation?: { + // iOS + title?: string; + proximity?: string; // Proximity + radius?: number; + coords?: { + latitude?: number; + longitude?: number; + }; + }; + + /** Method of alerting the user that this alarm should use; on iOS this is always a notification */ + method?: AlarmMethod; // Method, Android + } + + interface RecurrenceRule { + /** How often the calendar item should recur */ + frequency: Frequency; // Frequency + + /** Interval at which the calendar item should recur. For example, an interval: 2 with frequency: DAILY would yield an event that recurs every other day. Defaults to 1 . */ + interval?: number; + + /** Date on which the calendar item should stop recurring; overrides occurrence if both are specified */ + endDate?: string; + + /** Number of times the calendar item should recur before stopping */ + occurrence?: number; + } + + enum EntityTypes { + EVENT = 'event', + REMINDER = 'reminder', + } + + enum CalendarType { + LOCAL = 'local', + CALDAV = 'caldav', + EXCHANGE = 'exchange', + SUBSCRIBED = 'subscribed', + BIRTHDAYS = 'birthdays' + } + + enum Availability { + NOT_SUPPORTED = 'notSupported', // iOS + BUSY = 'busy', + FREE = 'free', + TENTATIVE = 'tentative', + UNAVAILABLE = 'unavailable' // iOS + } + + enum AlarmMethod { + ALARM = 'alarm', + ALERT = 'alert', + EMAIL = 'email', + SMS = 'sms', + DEFAULT = 'default', + } + + enum AttendeeType { + UNKNOWN = 'unknown', // iOS + PERSON = 'person', // iOS + ROOM = 'room', // iOS + GROUP = 'group', // iOS + RESOURCE = 'resource', + OPTIONAL = 'optional', // Android + REQUIRED = 'required', // Android + NONE = 'none' // Android + } + + enum CalendarAccessLevel { + CONTRIBUTOR = 'contributor', + EDITOR = 'editor', + FREEBUSY = 'freebusy', + OVERRIDE = 'override', + OWNER = 'owner', + READ = 'read', + RESPOND = 'respond', + ROOT = 'root', + NONE = 'none' + } + + enum EventAccessLevel { + CONFIDENTIAL = 'confidential', + PRIVATE = 'private', + PUBLIC = 'public', + DEFAULT = 'default' + } + + enum EventStatus { + NONE = 'none', + CONFIRMED = 'confirmed', + TENTATIVE = 'tentative', + CANCELED = 'canceled' + } + + enum AttendeeRole { + UNKNOWN = 'unknown', // iOS + REQUIRED = 'required', // iOS + OPTIONAL = 'optional', // iOS + CHAIR = 'chair', // iOS + NON_PARTICIPANT = 'nonParticipant', // iOS + ATTENDEE = 'attendee', // Android + ORGANIZER = 'organizer', // Android + PERFORMER = 'performer', // Android + SPEAKER = 'speaker', // Android + NONE = 'none' // Android + } + + enum AttendeeStatus { + UNKNOWN = 'unknown', // iOS + PENDING = 'pending', // iOS + ACCEPTED = 'accepted', + DECLINED = 'declined', + TENTATIVE = 'tentative', + DELEGATED = 'delegated', // iOS + COMPLETED = 'completed', // iOS + IN_PROCESS = 'inProcess', // iOS + INVITED = 'invited', // Android + NONE = 'none' // Android + } + + enum Frequency { + DAILY = 'daily', + WEEKLY = 'weekly', + MONTHLY = 'monthly', + YEARLY = 'yearly' + } + + enum ReminderStatus { + COMPLETED = 'completed', + INCOMPLETE = 'incomplete' + } + + interface RecurringEventOptions { + futureEvents?: boolean; + instanceStartDate?: string; + } + + /** Gets an array of calendar objects with details about the different calendars stored on the device. */ + function getCalendarsAsync( + /** (iOS only) Not required, but if defined, filters the returned calendars to a specific entity type. */ + entityType?: EntityTypes + ): Promise; + + /** Creates a new calendar on the device, allowing events to be added later and displayed. */ + function createCalendarAsync(details: Calendar): Promise; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateCalendarAsync(id: string, details?: Calendar | null): Promise; + + /** Deletes an existing calendar and all associated events/reminders/attendees from the device. Use with caution. */ + function deleteCalendarAsync(id: string): Promise; + + /** Returns all events in a given set of calendars over a specified time period. */ + function getEventsAsync( + /** Array of IDs of calendars to search for events in. Required. */ + calendarIds: string[], + + /** Beginning of time period to search for events in. Required. */ + startDate: Date, + + /** End of time period to search for events in. Required. */ + endDate: Date + ): Promise; + + /** Returns a specific event selected by ID. If a specific instance of a recurring event is desired, the start date of this instance must also be provided, as instances of recurring events do not have their own unique and stable IDs on either iOS or Android. */ + function getEventAsync( + /** ID of the event to return. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise; + + /** Creates a new event on the specified calendar. */ + function createEventAsync( + /** ID of the calendar to create this event in. Required. */ + calendarId: string, + details?: Event + ): Promise; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateEventAsync( + /** ID of the event to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Event | null, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise; + + /** Deletes an existing event from the device. Use with caution. */ + function deleteEventAsync( + /** ID of the event to be deleted. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise; + + /** Gets all attendees for a given event (or instance of a recurring event). */ + function getAttendeesForEventAsync( + /** ID of the event to return attendees for. Required. */ + eventId: string, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise; + + /** Available on Android only. Creates a new attendee record and adds it to the specified event. Note that if eventId specifies a recurring event, this will add the attendee to every instance of the event. */ + function createAttendeeAsync( + /** ID of the event to add this attendee to. Required. */ + eventId: string, + + /** A map of details for the attendee to be created */ + details?: Attendee + ): Promise; + + /** Available on Android only. Updates an existing attendee record. To remove a property, explicitly set it to null in details. */ + function updateAttendeeAsync( + /** ID of the attendee record to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Attendee | null + ): Promise; + + /** Available on Android only. Deletes an existing attendee record from the device. Use with caution. */ + function deleteAttendeeAsync(id: string): Promise; + + /** Available on iOS only. Returns a list of reminders matching the provided criteria. */ + function getRemindersAsync( + /** Array of IDs of calendars to search for reminders in. Required. */ + calendarIds: string[], + + status?: ReminderStatus, + + /** Beginning of time period to search for reminders in. Required if status is defined. */ + startDate?: Date, + + /** End of time period to search for reminders in. Required if status is defined. */ + endDate?: Date + ): Promise; + + /** Available on iOS only. Returns a specific reminder selected by ID. */ + function getReminderAsync(id: string): Promise; + + /** Available on iOS only. Creates a new reminder on the specified calendar. */ + function createReminderAsync( + /** ID of the calendar to create this reminder in. Required. */ + calendarId: string, + + /** A map of details for the reminder to be created */ + details?: Reminder + ): Promise; + + /** Available on iOS only. Updates the provided details of an existing reminder stored on the device. To remove a property, explicitly set it to null in details. */ + function updateReminderAsync( + /** ID of the reminder to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Reminder | null + ): Promise; + + /** Available on iOS only. Deletes an existing reminder from the device. Use with caution. */ + function deleteReminderAsync(id: string): Promise; + + /** Available on iOS only. */ + function getSourcesAsync(): Promise; + + /** Available on iOS only. Returns a specific source selected by ID. */ + function getSourceAsync(id: string): Promise; + + /** Available on Android only. Sends an intent to open the specified event in the OS Calendar app. */ + function openEventInCalendar( + /** ID of the event to open. Required. */ + id: string + ): void; +} +// #endregion + +// #region MailComposer +/** + * An API to compose mails using OS specific UI. + */ +export namespace MailComposer { + interface ComposeOptions { + /** An array of e-mail addressess of the recipients. */ + recipients?: string[]; + + /** An array of e-mail addressess of the CC recipients. */ + ccRecipients?: string[]; + + /** An array of e-mail addressess of the BCC recipients. */ + bccRecipients?: string[]; + + /** Subject of the mail. */ + subject?: string; + + /** Body of the mail. */ + body?: string; + + /** Whether the body contains HTML tags so it could be formatted properly. Not working perfectly on Android. */ + isHtml?: boolean; + + /** An array of app’s internal file uris to attach. */ + attachments?: string[]; + } + + /** Resolves to a promise with object containing status field that could be either sent, saved or cancelled. Android does not provide such info so it always resolves to sent. */ + function composeAsync( + /** A map defining the data to fill the mail */ + options: ComposeOptions + ): Promise<{ status: 'sent' | 'saved' | 'cancelled' }>; +} +// #endregion + +export namespace Updates { + namespace EventType { + /** A new update is available and has started downloading. */ + type DownloadStart = 'downloadStart'; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + type DownloadProgress = 'downloadProgress'; + /** A new update has finished downloading and is now stored in the device's cache. */ + type DownloadFinished = 'downloadFinished'; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + type NoUpdateAvailable = 'noUpdateAvailable'; + /** An error occurred trying to fetch the latest update. */ + type Error = 'error'; + + /** A new update is available and has started downloading. */ + const DOWNLOAD_STARTED: DownloadStart; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + const DOWNLOAD_PROGRESS: DownloadProgress; + /** A new update has finished downloading and is now stored in the device's cache. */ + const DOWNLOAD_FINISHED: DownloadFinished; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + const NO_UPDATE_AVAILABLE: NoUpdateAvailable; + /** An error occurred trying to fetch the latest update. */ + const ERROR: Error; + } + + interface UpdateCheck { + /** True if an update is available, false if you're already running the most up-to-date JS bundle. */ + isAvailable: boolean; + /** If `isAvailable` is true, the manifest of the available update. Undefined otherwise. */ + manifest?: Constants.Manifest; + } + + interface UpdateBundle { + /** True if the fetched bundle is new (i.e. a different version that the what's currently running). */ + isNew: boolean; + /** Manifest of the fetched update. */ + manifest: Constants.Manifest; + } + + /** An object that is passed into each event listener when a new version is available. */ + interface UpdateEvent { + /** Type of the event */ + type: EventType.DownloadStart + | EventType.DownloadProgress + | EventType.DownloadFinished + | EventType.NoUpdateAvailable + | EventType.Error; + /** If `type === Expo.Updates.EventType.DOWNLOAD_FINISHED`, the manifest of the newly downloaded update. Undefined otherwise. */ + manifest?: Constants.Manifest; + /** If `type === Expo.Updates.EventType.ERROR`, the error message. Undefined otherwise. */ + message?: string; + } + + /** An optional params object passed to fetchUpdateAsync. */ + interface FetchUpdateAsyncParams { + eventListener: UpdateEventListener; + } + + type UpdateEventListener = (event: UpdateEvent) => any; + + /** + * Invokes a callback when updates-related events occur, + * either on the initial app load or as a result of a call to `Expo.Updates.fetchUpdateAsync`. + */ + function addListener(listener: UpdateEventListener): EventSubscription; + + /** + * Check if a new published version of your project is available. + * Does not actually download the update. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function checkForUpdateAsync(): Promise; + + /** + * Downloads the most recent published version of your experience to the device's local cache. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function fetchUpdateAsync(params?: FetchUpdateAsyncParams): Promise; + + /** + * Immediately reloads the current experience. + * This will use your app.json updates configuration to fetch and load the newest available JS supported by the device's Expo environment. + * This is useful for triggering an update of your experience if you have published a new version. + */ + function reload(): void; + + /** + * Immediately reloads the current experience using the most recent cached version. + * This is useful for triggering an update of your experience if you have published and already downloaded a new version. + */ + function reloadFromCache(): void; +} + +// #region MediaLibrary +/** + * https://docs.expo.io/versions/latest/sdk/media-library + * Provides access to user's media library + * Requires Permissions.CAMERA_ROLL permissions. + */ + +export namespace MediaLibrary { + /** + * Creates an asset from existing file. The most common use case is to save a picture taken by Camera. + */ + function createAssetAsync(localUri: string): Promise; + + /** + * Fetches a page of assets matching the provided criteria. + */ + function getAssetsAsync(options: GetAssetsOptions): Promise; + + /** + * Provides more informations about an asset, including GPS location, local URI and EXIF metadata. + */ + function getAssetInfoAsync(asset: string | Asset): Promise; + + /** + * Deletes assets from the library. On iOS it deletes assets from all albums they belong to, while on Android it keeps all copies of them + * (album is strictly connected to the asset). Also, there is additional dialog on iOS that requires user to confirm this action. + */ + function deleteAssetsAsync(asset: string[] | Asset[]): Promise; + + /** + * Queries for user-created albums in media gallery. + */ + function getAlbumsAsync(): Promise; + + /** + * Queries for an album with a specific name. + */ + function getAlbumAsync(albumName: string): Promise; + + /** + * Creates an album with given name and initial asset. + * The asset parameter is required on Android, since it's not possible to create empty album on this platform. + */ + function createAlbumAsync(albumName: string, asset: string | Asset): Promise; + + /** + * Adds array of assets to the album. + * On Android, by default it copies assets from the current album to provided one, however it's also possible to move them by passing false as copyAssets argument. + * In case they're copied you should keep in mind that getAssetsAsync will return duplicated assets. + */ + function addAssetsToAlbumAsync(assets: Asset[], album: string | Album, copyAssets?: boolean /* default true */): Promise; + + /** + * Removes given assets from album. + * On Android, album will be automatically deleted if there are no more assets inside. + */ + function removeAssetsFromAlbumAsync(assets: Asset[], album: string | Album): Promise; + + /** + * Available on iOS only. Fetches a list of moments, which is a group of assets taken around the same place and time. + */ + function getMomentsAsync(): Promise; + + enum MediaType { + audio = 'audio', + photo = 'photo', + video = 'video', + unknow = 'unknow' + } + + enum SortBy { + default = 'default', + id = 'id', + creationTime = 'creationTime', + modificationTime = 'modificationTime', + mediaType = 'mediaType', + width = 'width', + height = 'height', + duration = 'duration' + } + + // region Asset + interface AssetAndroid { + albumId?: string; + } + + interface AssetIos { + mediaSubtypes?: MediaType[]; + // * + orientation: number; + // * + isFavorite: boolean; + } + + interface Asset extends AssetAndroid, AssetIos { + id: string; + filename: string; + uri: string; + mediaType: string; + width: number; + height: number; + creationTime: number; + modificationTime: number; + duration: number; + // * + localUri?: string; + // * + location?: Location.LocationProps; + // * + exif?: object; + } + + /** + * These fields can be obtained only by calling getAssetInfoAsync method + */ + //#endregion + + // #region Album + interface AlbumIos { + type?: string; + // * + startTime: number; + // * + endTime: number; + // * + approximateLocation?: Location.LocationProps; + // * + locationNames?: string[]; + } + + /** + * These fields apply only to albums whose type is moment + */ + + interface Album extends AlbumIos { + id: string; + title: string; + assetCount: number; + } + // #endregion + + interface GetAssetsOptions { + first?: number; + after?: string; + album?: string | Album; + sortBy?: SortBy; + mediaType?: MediaType; + } + + interface GetAssetsResult { + assets: Asset[]; + endCursor: string; + hasNextPage: boolean; + totalCount: number; + } +} +// #endregion + +// #region Haptic +/** + * https://docs.expo.io/versions/latest/sdk/haptic + * Provides haptic feedback for iOS 10+ devices using the Taptic Engine. + * If this is used in Android the device will use ReactNative.Vibrate instead, it's best to just avoid this. + */ +export namespace Haptic { + /** + * Used to let a user know when a selection change has been registered + */ + function selection(): void; + function notification(notificationType?: NotificationType): void; + function impact(impactStyles?: ImpactStyles): void; + + enum ImpactStyles { + Light = 'light', + Medium = 'medium', + Heavy = 'heavy' + } + + enum NotificationType { + Success = 'success', + Warning = 'warning', + Error = 'error' + } +} +// #endregion diff --git a/types/expo/v31/tsconfig.json b/types/expo/v31/tsconfig.json new file mode 100644 index 0000000000..ae698d5f5e --- /dev/null +++ b/types/expo/v31/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "expo": [ + "expo/v31" + ], + "expo/*": [ + "expo/v31/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo-tests.tsx" + ] +} diff --git a/types/expo/v31/tslint.json b/types/expo/v31/tslint.json new file mode 100644 index 0000000000..8270136207 --- /dev/null +++ b/types/expo/v31/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "void-return": false, + "max-line-length": false + } +} diff --git a/types/expo__vector-icons/expo__vector-icons-tests.tsx b/types/expo__vector-icons/expo__vector-icons-tests.tsx index 7d918c917f..33e1056957 100644 --- a/types/expo__vector-icons/expo__vector-icons-tests.tsx +++ b/types/expo__vector-icons/expo__vector-icons-tests.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; import { View, Text, TabBarIOS } from 'react-native'; -import { createIconSet, MaterialIcons, FontAwesome, Ionicons } from 'expo__vector-icons'; +import { createIconSet, MaterialIcons, FontAwesome, AntDesign } from 'expo__vector-icons'; const glyphMap = { custom: 58918 @@ -48,7 +48,7 @@ class TabTest extends React.Component<{}, { selectedTab: string }> { render() { return ( - { onPress={() => this.setState({ selectedTab: 'tab1' })} > - + - { onPress={() => this.setState({ selectedTab: 'tab2' })} > - + ); } diff --git a/types/expo__vector-icons/index.d.ts b/types/expo__vector-icons/index.d.ts index 529142c0e9..7a7ac587ec 100644 --- a/types/expo__vector-icons/index.d.ts +++ b/types/expo__vector-icons/index.d.ts @@ -1,13 +1,16 @@ -// Type definitions for @expo/vector-icons 6.2 +// Type definitions for @expo/vector-icons 9.0 // Project: https://github.com/expo/vector-icons // Definitions by: Hyeonsu Lee +// Robert Ying // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; import { TextProps } from 'react-native'; +import { Icon } from 'react-native-vector-icons/Icon'; export { createIconSet, createIconSetFromFontello, createIconSetFromIcoMoon } from 'react-native-vector-icons'; +export { Icon as AntDesign }; export { default as Entypo } from 'react-native-vector-icons/Entypo'; export { default as EvilIcons } from 'react-native-vector-icons/EvilIcons'; export { default as Feather } from 'react-native-vector-icons/Feather'; diff --git a/types/express-http-proxy/express-http-proxy-tests.ts b/types/express-http-proxy/express-http-proxy-tests.ts index 16e03cc974..56156369cc 100644 --- a/types/express-http-proxy/express-http-proxy-tests.ts +++ b/types/express-http-proxy/express-http-proxy-tests.ts @@ -16,5 +16,13 @@ proxy('www.google.com', { console.log(proxyReqOpts.headers, proxyReqOpts.method); console.log(srcReq.url, srcReq.cookies); return proxyReqOpts; + }, + userResHeaderDecorator(headers, userReq, userRes, proxyReq, proxyRes) { + console.log(userReq.url, userRes.statusCode); + console.log(proxyReq.url, proxyRes.statusCode); + if (headers["content-type"] === "image/png") { + headers["x-custom-header"] = "additional-info"; + } + return headers; } }); diff --git a/types/express-http-proxy/index.d.ts b/types/express-http-proxy/index.d.ts index 031be01485..3a74bef6db 100644 --- a/types/express-http-proxy/index.d.ts +++ b/types/express-http-proxy/index.d.ts @@ -1,15 +1,18 @@ // Type definitions for express-http-proxy 1.5 // Project: https://github.com/villadora/express-http-proxy#readme -// Definitions by: ulrichb +// Definitions by: ulrichb +// Daniel Schopf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 import { RequestHandler, Request } from "express"; -import { RequestOptions } from "http"; +import { RequestOptions, IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; +import { Response } from "express-serve-static-core"; interface ProxyOptions { proxyReqPathResolver?: (req: Request) => string; proxyReqOptDecorator?: (proxyReqOpts: RequestOptions, srcReq: Request) => RequestOptions; + userResHeaderDecorator?: (headers: IncomingHttpHeaders, userReq: Request, userRes: Response, proxyReq: Request, proxyRes: Response) => OutgoingHttpHeaders; } declare function proxy(host: string, options?: ProxyOptions): RequestHandler; diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index 96c4c233c2..773a1e065b 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -44,6 +44,7 @@ export type RequestHandlerParams = RequestHandler | ErrorRequestHandler | Array< export interface IRouterMatcher { (path: PathParams, ...handlers: RequestHandler[]): T; (path: PathParams, ...handlers: RequestHandlerParams[]): T; + (path: PathParams, subApplication: Application): T; } export interface IRouterHandler { diff --git a/types/express/express-tests.ts b/types/express/express-tests.ts index 07bf2fc5c3..37cf543df5 100644 --- a/types/express/express-tests.ts +++ b/types/express/express-tests.ts @@ -138,6 +138,9 @@ namespace express_tests { res.req; }); + // Test mounting sub-apps + app.use('/sub-app', express()); + // Test on mount event app.on('mount', (parent) => true); diff --git a/types/express/index.d.ts b/types/express/index.d.ts index 81821ca98c..ddc4509805 100644 --- a/types/express/index.d.ts +++ b/types/express/index.d.ts @@ -30,6 +30,13 @@ declare namespace e { */ var json: typeof bodyParser.json; + /** + * These are the exposed prototypes. + */ + var application: Application; + var request: Request; + var response: Response; + /** * This is a built-in middleware function in Express. It serves static files and is based on serve-static. */ diff --git a/types/extra-watch-webpack-plugin/extra-watch-webpack-plugin-tests.ts b/types/extra-watch-webpack-plugin/extra-watch-webpack-plugin-tests.ts new file mode 100644 index 0000000000..7eb729eb31 --- /dev/null +++ b/types/extra-watch-webpack-plugin/extra-watch-webpack-plugin-tests.ts @@ -0,0 +1,6 @@ +import ExtraWatchWebpackPlugin = require("extra-watch-webpack-plugin"); + +new ExtraWatchWebpackPlugin(); +new ExtraWatchWebpackPlugin({}); +new ExtraWatchWebpackPlugin({ files: "string", dirs: "string" }); +new ExtraWatchWebpackPlugin({ files: ["array"], dirs: ["array"] }); diff --git a/types/extra-watch-webpack-plugin/index.d.ts b/types/extra-watch-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..058dae79e7 --- /dev/null +++ b/types/extra-watch-webpack-plugin/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for extra-watch-webpack-plugin 1.0 +// Project: https://github.com/pigcan/extra-watch-webpack-plugin#readme +// Definitions by: Dave Cardwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin } from "webpack"; + +export = ExtraWatchWebpackPlugin; + +declare class ExtraWatchWebpackPlugin extends Plugin { + constructor(options?: ExtraWatchWebpackPlugin.Options); +} + +declare namespace ExtraWatchWebpackPlugin { + interface Options { + /** + * `string` (absolute path or glob pattern) or `array`, default `[]`, attach extra files to webpack's watch system + */ + files?: string | ReadonlyArray; + /** + * `string` or `array`, default `[]`, attach extra dirs to webpack's watch system + */ + dirs?: string | ReadonlyArray; + } +} diff --git a/types/extra-watch-webpack-plugin/tsconfig.json b/types/extra-watch-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..0e52bc6c44 --- /dev/null +++ b/types/extra-watch-webpack-plugin/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "extra-watch-webpack-plugin-tests.ts"] +} diff --git a/types/extra-watch-webpack-plugin/tslint.json b/types/extra-watch-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/extra-watch-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 60ec11648f..68c0a73efe 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -614,6 +614,10 @@ interface IPatternOptions { * The source for the pattern */ source: string | HTMLImageElement; + /** + * Transform matrix to change the pattern, imported from svgs + */ + patternTransform?: number[]; } export interface Pattern extends IPatternOptions { } export class Pattern { @@ -1801,10 +1805,12 @@ export class Image { initialize(element?: string | HTMLImageElement, options?: IImageOptions): void; /** - * Applies filters assigned to this image (from "filters" array) - * @param callback Callback is invoked when all filters have been applied and new image is generated + * Applies filters assigned to this image (from "filters" array) or from filter param + * @param {Array} filters to be applied + * @return {thisArg} return the fabric.Image object + * @chainable */ - applyFilters(callback: Function): void; + applyFilters(filters?: IBaseFilter[]): Image; /** * Returns a clone of an instance * @param callback Callback is invoked with a clone as a first argument @@ -2234,7 +2240,20 @@ interface IObjectOptions { */ clipTo?: Function; - /** + /** + * A fabricObject that, without stroke define a clipping area with their shape. filled in black + * the clipPath object gets used when the object has rendered, and the context is placed in the center + * of the object cacheCanvas. + * If you want 0,0 of a clipPath to align with an object center, use clipPath.originX/Y to 'center' + */ + clipPath?: Object; + + /** + * When set to `true`, object's cache will be rerendered next render call. + */ + dirty?: boolean; + + /** * When `true`, object horizontal movement is locked */ lockMovementX?: boolean; @@ -3717,17 +3736,29 @@ interface IAllFilters { */ new(options?: any): IBaseFilter; }; - Blend: { + BlendColor: { /** * Constructor * @param [options] Options object */ - new(options?: { color?: string; mode?: string; alpha?: number; image?: Image }): IBlendFilter; + new(options?: { color?: string; mode?: string; alpha?: number; }): IBlendColorFilter; /** * Returns filter instance from an object representation * @param object Object to create an instance from */ - fromObject(object: any): IBlendFilter + fromObject(object: any): IBlendColorFilter + }; + BlendImage: { + /** + * Constructor + * @param [options] Options object + */ + new(options?: { image?: Image; mode?: string; alpha?: number; }): IBlendImageFilter; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IBlendImageFilter }; Brightness: { new(options?: { @@ -3910,7 +3941,14 @@ interface IBaseFilter { */ toJSON(): string; } -interface IBlendFilter extends IBaseFilter { +interface IBlendColorFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} +interface IBlendImageFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to @@ -3931,63 +3969,63 @@ interface IConvoluteFilter extends IBaseFilter { */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface IGradientTransparencyFilter { +interface IGradientTransparencyFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface IGrayscaleFilter { +interface IGrayscaleFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface IInvertFilter { +interface IInvertFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface IMaskFilter { +interface IMaskFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface IMultiplyFilter { +interface IMultiplyFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface INoiseFilter { +interface INoiseFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface IPixelateFilter { +interface IPixelateFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface IRemoveWhiteFilter { +interface IRemoveWhiteFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface IResizeFilter { +interface IResizeFilter extends IBaseFilter { /** * Resize type */ @@ -4013,21 +4051,21 @@ interface IResizeFilter { */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface ISepiaFilter { +interface ISepiaFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface ISepia2Filter { +interface ISepia2Filter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to */ applyTo(canvasEl: HTMLCanvasElement): void; } -interface ITintFilter { +interface ITintFilter extends IBaseFilter { /** * Applies filter to canvas element * @param canvasEl Canvas element to apply filter to @@ -4604,6 +4642,11 @@ interface IUtilMisc { */ qrDecompose(a: number[]): { angle: number, scaleX: number, scaleY: number, skewX: number, skewY: number, translateX: number, translateY: number }; + /** + * Creates a transform matrix with the specified scale and skew + */ + customTransformMatrix(scaleX: number, scaleY: number, skewX: number): number[]; + /** * Returns string representation of function body * @param fn Function to get body of diff --git a/types/facebook-js-sdk/facebook-js-sdk-tests.ts b/types/facebook-js-sdk/facebook-js-sdk-tests.ts index 46b9f331f5..db8b13686e 100644 --- a/types/facebook-js-sdk/facebook-js-sdk-tests.ts +++ b/types/facebook-js-sdk/facebook-js-sdk-tests.ts @@ -22,6 +22,14 @@ FB.getLoginStatus(function(response: fb.StatusResponse) { const authResponse: fb.AuthResponse = FB.getAuthResponse(); console.log(authResponse.accessToken); +FB.login(); + +FB.login(function(response: fb.StatusResponse) { + console.log(response); + console.log(response.status); + console.log(response.authResponse.accessToken); +}); + FB.login(function(response: fb.StatusResponse) { console.log(response); console.log(response.status); diff --git a/types/facebook-js-sdk/index.d.ts b/types/facebook-js-sdk/index.d.ts index 86ca521c88..c4f3b78c31 100644 --- a/types/facebook-js-sdk/index.d.ts +++ b/types/facebook-js-sdk/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for the Facebook Javascript SDK 3.1 +// Type definitions for the Facebook Javascript SDK 3.2 // Project: https://developers.facebook.com/docs/javascript // Definitions by: Amrit Kahlon // Mahmoud Zohdi @@ -50,7 +50,7 @@ declare namespace facebook { * @param callback function to handle the response. * @param options optional ILoginOption to add params such as scope. */ - login(callback: (response: StatusResponse) => void, options: LoginOptions): void; + login(callback: (response: StatusResponse) => void, options?: LoginOptions): void; /** * Use this function to log the user in @@ -61,12 +61,12 @@ declare namespace facebook { * * @param options optional ILoginOption to add params such as scope. */ - login(options: LoginOptions): void; + login(options?: LoginOptions): void; /** * The method FB.logout() logs the user out of your site and, in some cases, Facebook. * - * @param callback function to handle the response + * @param callback optional function to handle the response */ logout(callback?: (response: StatusResponse) => void): void; diff --git a/types/faker/index.d.ts b/types/faker/index.d.ts index a9d044cfcb..55c20ce235 100644 --- a/types/faker/index.d.ts +++ b/types/faker/index.d.ts @@ -117,7 +117,7 @@ declare namespace Faker { image: { image(): string; avatar(): string; - imageUrl(width?: number, height?: number, category?: string): string; + imageUrl(width?: number, height?: number, category?: string, randomize?: boolean, https?: boolean): string; abstract(width?: number, height?: number): string; animals(width?: number, height?: number): string; business(width?: number, height?: number): string; diff --git a/types/fastify-favicon/fastify-favicon-tests.ts b/types/fastify-favicon/fastify-favicon-tests.ts new file mode 100644 index 0000000000..cb556bf71d --- /dev/null +++ b/types/fastify-favicon/fastify-favicon-tests.ts @@ -0,0 +1,5 @@ +import fastifyFavicon = require("fastify-favicon"); + +const options: fastifyFavicon.FastifyFaviconOptions = { + path: './public', +}; diff --git a/types/fastify-favicon/index.d.ts b/types/fastify-favicon/index.d.ts new file mode 100644 index 0000000000..204cc6030d --- /dev/null +++ b/types/fastify-favicon/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for fastify-favicon 0.3 +// Project: https://github.com/smartiniOnGitHub/fastify-favicon +// Definitions by: Philipp Gfeller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function defaultFaviconPlugin(): void; + +declare namespace defaultFaviconPlugin { + interface FastifyFaviconOptions { + path?: string; + } +} + +export = defaultFaviconPlugin; diff --git a/types/fastify-favicon/tsconfig.json b/types/fastify-favicon/tsconfig.json new file mode 100644 index 0000000000..772917a271 --- /dev/null +++ b/types/fastify-favicon/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "fastify-favicon-tests.ts"], + "exclude": ["node-modules"] +} diff --git a/types/fastify-favicon/tslint.json b/types/fastify-favicon/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fastify-favicon/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fastify-jwt/fastify-jwt-tests.ts b/types/fastify-jwt/fastify-jwt-tests.ts deleted file mode 100644 index fc68ac8bcc..0000000000 --- a/types/fastify-jwt/fastify-jwt-tests.ts +++ /dev/null @@ -1,72 +0,0 @@ -import fastify = require("fastify"); -import fastifyJwt = require("fastify-jwt"); - -const app = fastify(); - -app.register(fastifyJwt, { - secret: "super-secret", -}); - -app.register(fastifyJwt, { - secret: (request, reply, callback) => { - return ""; - }, -}); - -app.get("/path", (request, reply) => { - request.jwtVerify(); - request.jwtVerify({}); - request.jwtVerify({}, () => "string"); - request.jwtVerify(() => "string", () => "string"); - - reply.jwtSign("payload"); - reply.jwtSign("payload", {}); - reply.jwtSign("payload", {}, () => "string"); - reply.jwtSign({ a: "b" }, {}, () => "string"); - reply.jwtSign([], {}, () => "string"); - reply.jwtSign(new Buffer("buffer"), {}, () => "string"); - reply.jwtSign("payload", () => "string", () => "string"); -}); - -app.jwt.sign({ a: "b" }, {}, (err, token) => { - if (err) { - throw err; - } - - return token; -}); - -app.jwt.sign("string", { algorithm: "some-algorithm" }, (err, token) => { - if (err) { - throw err; - } - - return token; -}); - -app.jwt.sign([], {}, (err, token) => { - if (err) { - throw err; - } - - return token; -}); - -app.jwt.sign(new Buffer("buffer"), {}, (err, token) => { - if (err) { - throw err; - } - - return token; -}); - -app.jwt.decode("some-token"); -app.jwt.decode("some-token"); -app.jwt.secret = "some-secret"; -app.jwt.verify("some-token", {}, (err) => { - if (err) { - throw err; - } - - return true; -}); diff --git a/types/fastify-jwt/index.d.ts b/types/fastify-jwt/index.d.ts deleted file mode 100644 index 94e6249a3c..0000000000 --- a/types/fastify-jwt/index.d.ts +++ /dev/null @@ -1,52 +0,0 @@ -// Type definitions for fastify-jwt 0.4 -// Project: https://github.com/fastify/fastify-jwt#readme -// Definitions by: Jannik Keye -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 -import fastify = require("fastify"); - -import { Secret, SignOptions, VerifyOptions, VerifyCallback, SignCallback, DecodeOptions } from 'jsonwebtoken'; -import { IncomingMessage, ServerResponse } from 'http'; - -declare module "fastify" { - interface FastifyInstance { - jwt: jwt; - } - - interface SignFunction { - (payload: string | Buffer | object, options?: SignOptions): string; - (payload: string | Buffer | object, options?: SignOptions, callback?: SignCallback): void; - } - - interface VerifyFunction { - (token: string, options?: VerifyOptions, callback?: VerifyCallback): void; - (token: string, options?: VerifyOptions): object | string; - } - - interface jwt { - sign: SignFunction; - verify: VerifyFunction; - decode(token: string, options?: DecodeOptions): null | { [key: string]: any } | string; - secret: Secret; - } - - interface FastifyRequest { - jwtVerify: (options?: VerifyOptions | VerifyCallback, next?: VerifyCallback) => Promise | null | { [key: string]: any } | string; - } - - interface FastifyReply { - jwtSign: (payload: string | Buffer | object, options?: SignOptions | SignCallback, next?: SignCallback) => void; - } -} - -declare function fastifyJwt(): void; - -declare namespace fastifyJwt { - type SecretCallback = (request: fastify.FastifyRequest, reply: string | Buffer | object, callback?: VerifyCallback | SignCallback) => void; - - interface FastifyJwtOptions { - secret: string | SecretCallback; - } -} - -export = fastifyJwt; diff --git a/types/fastify-rate-limit/fastify-rate-limit-tests.ts b/types/fastify-rate-limit/fastify-rate-limit-tests.ts new file mode 100644 index 0000000000..ee79951f48 --- /dev/null +++ b/types/fastify-rate-limit/fastify-rate-limit-tests.ts @@ -0,0 +1,22 @@ +import fastifyRateLimit = require("fastify-rate-limit"); +import * as IORedis from 'ioredis'; +import { FastifyRequest, DefaultQuery } from "fastify"; +import { IncomingMessage } from "http"; + +fastifyRateLimit(); + +const fastifyRateLimitOptions: fastifyRateLimit.FastifyRateLimitOptions> = { + max: 3, + timeWindow: 5000, + cache: 10000, + whitelist: ['127.0.0.1'], + redis: new IORedis({ host: '127.0.0.1' }), + skipOnError: true, // default false + keyGenerator: (req) => { + return req.headers['x-real-ip'] + || req.headers['x-client-ip'] + || req.headers['x-forwarded-for'] + || req.params.test + || req.ip; + }, +}; diff --git a/types/fastify-rate-limit/index.d.ts b/types/fastify-rate-limit/index.d.ts new file mode 100644 index 0000000000..888611ad72 --- /dev/null +++ b/types/fastify-rate-limit/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for fastify-rate-limit 2.0 +// Project: https://github.com/fastify/fastify-rate-limit#readme +// Definitions by: Christian D +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Redis } from "ioredis"; +import { FastifyRequest } from "fastify"; +import { IncomingMessage } from "http"; + +declare function fastifyRateLimit(): void; + +declare namespace fastifyRateLimit { + interface FastifyRateLimitOptions> { + /** + * Is the maximum number of requests a single client can perform inside a + * timeWindow. + * + * default: 1000 + */ + max?: number; + + /** + * The duration of the time window, can be expressed in milliseconds (as a + * number) or as a string, see ms too see the supported formats + * + * default: 1000 * 60 + */ + timeWindow?: number; + + /** + * This plugin internally uses a lru cache to handle the clients, you can + * change the size of the cache with this option. + * + * default: 5000 + */ + cache?: number; + + /** + * Array of string of ips to exclude from rate limiting. + * + * default: [] + */ + whitelist?: string[]; + + /** + * By default this plugins uses an in-memory store, which is fast but if + * you application works on more than one server it is useless, since the + * data is store locally. You can pass a Redis client here and magically + * the issue is solved. To achieve the maximum speed, this plugins requires + * the use of ioredis. + * + * default: null + */ + redis?: Redis; + + /** + * If `true` it will skip errors generated by the storage (eg, redis not + * reachable). + * + * default: false + */ + skipOnError?: boolean; + + /** + * Function to generate a unique identifier for each incoming request. + * + * default: (req) => req.ip + */ + keyGenerator?: (req: T) => string; + } +} + +export = fastifyRateLimit; diff --git a/types/fastify-rate-limit/package.json b/types/fastify-rate-limit/package.json new file mode 100644 index 0000000000..e8c68ab969 --- /dev/null +++ b/types/fastify-rate-limit/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "fastify": "^1.11.2" + } +} diff --git a/types/fastify-rate-limit/tsconfig.json b/types/fastify-rate-limit/tsconfig.json new file mode 100644 index 0000000000..5dc0e91ea2 --- /dev/null +++ b/types/fastify-rate-limit/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "fastify-rate-limit-tests.ts"], + "exclude": ["node-modules"] +} diff --git a/types/fastify-rate-limit/tslint.json b/types/fastify-rate-limit/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fastify-rate-limit/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/feathersjs__authentication-jwt/index.d.ts b/types/feathersjs__authentication-jwt/index.d.ts index 7a555071d9..16d79bb885 100644 --- a/types/feathersjs__authentication-jwt/index.d.ts +++ b/types/feathersjs__authentication-jwt/index.d.ts @@ -52,9 +52,9 @@ export class Verifier { verify(req: Request, payload: any, done: (error: any, user?: any, info?: any) => void): void; } -export type JwtFromRequestFunction = (req: Request) => string; +export type JwtFromRequestFunction = (req: Request) => string | null; -export const ExtractJWT: { +export const ExtractJwt: { fromHeader(header_name: string): JwtFromRequestFunction; fromBodyField(field_name: string): JwtFromRequestFunction; fromUrlQueryParameter(param_name: string): JwtFromRequestFunction; diff --git a/types/feathersjs__authentication-oauth2/feathersjs__authentication-oauth2-tests.ts b/types/feathersjs__authentication-oauth2/feathersjs__authentication-oauth2-tests.ts index 34dba17062..4784a885b5 100644 --- a/types/feathersjs__authentication-oauth2/feathersjs__authentication-oauth2-tests.ts +++ b/types/feathersjs__authentication-oauth2/feathersjs__authentication-oauth2-tests.ts @@ -1,5 +1,10 @@ import feathers, { Application } from '@feathersjs/feathers'; -import feathersAuthenticationOAuth2, { Verifier } from '@feathersjs/authentication-oauth2'; +import feathersAuthenticationOAuth2, { Verifier, FeathersAuthenticationOAuth2Options } from '@feathersjs/authentication-oauth2'; +import { RequestHandler, Response, NextFunction } from 'express'; +import { Request } from 'express-serve-static-core'; +import { Strategy } from 'passport'; +import { Profile as GithubProfile } from 'passport-github'; +import { Profile as FacebookProfile } from 'passport-facebook'; const app: Application<{}> = feathers().configure(feathersAuthenticationOAuth2()); @@ -8,3 +13,79 @@ class CustomVerifier extends Verifier { super(app, options); } } + +const handler: RequestHandler = (req: Request, res: Response, next: NextFunction) => { }; + +class someStrategy extends Strategy { + something = "foo"; +} +/** + * Strongly Typed Verifier + */ + +interface User { + name?: string; + email?: string; + facebookId?: string; + orSomeOtherProviderId?: string; +} + +interface VerifierOptions extends FeathersAuthenticationOAuth2Options { + foo?: boolean; +} + +type IProfileType = GithubProfile | FacebookProfile; + +export default class TestVerifier extends Verifier { } + +const testVerifier = new TestVerifier(app, { + name: "test", + foo: false, + successRedirect: "foo", + failureRedirect: "bar", + service: 'Users', + Strategy: someStrategy, + passReqToCallback: false, + session: false +}); + +testVerifier._createEntity({ + profile: { + id: "", + displayName: "", + birthday: "", + _raw: "", + _json: "", + provider: "" + }, + accessToken: "", + refreshToken: "" +}); + +/** + * Options + */ + +const coreOptions: FeathersAuthenticationOAuth2Options = { + name: "foo", + Strategy: someStrategy, + successRedirect: "foo", + failureRedirect: "foo", + service: "foo", + passReqToCallback: true, + session: true +}; + +const options: FeathersAuthenticationOAuth2Options = { + ...coreOptions, + idField: "foo", + path: "foo", + callbackPath: "foo", + callbackURL: "foo", + entity: "foo", + service: "foo", + handler, + errorHandler: handler, + formatter: handler, + Verifier: TestVerifier +}; diff --git a/types/feathersjs__authentication-oauth2/index.d.ts b/types/feathersjs__authentication-oauth2/index.d.ts index b2bf133c68..65e8989ae9 100644 --- a/types/feathersjs__authentication-oauth2/index.d.ts +++ b/types/feathersjs__authentication-oauth2/index.d.ts @@ -1,73 +1,126 @@ // Type definitions for @feathersjs/authentication-oauth2 1.0 // Project: http://feathersjs.com/ -// Definitions by: Jan Lohage +// Definitions by: Jan Lohage +// Nick Bolles // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 -import { - Application, - Paginated -} from '@feathersjs/feathers'; -import { Request } from 'express'; import * as self from '@feathersjs/authentication-oauth2'; +import { Application, Paginated, Service } from '@feathersjs/feathers'; +import { Request, RequestHandler } from 'express'; +import { Profile, Strategy } from 'passport'; declare const feathersAuthenticationOAuth2: ((options?: FeathersAuthenticationOAuth2Options) => () => void) & typeof self; export default feathersAuthenticationOAuth2; -export interface FeathersAuthenticationOAuth2Options { +// todo: make a base options interface in feathers/authentication that we can extend here +export interface FeathersAuthenticationOAuth2Options { /** - * The field to look up the entity by when logging in with the provider. Defaults to 'Id' (ie. 'facebookId'). + * The name of the OAuth2 provider */ - idField: string; + name: string; /** - * The route to register the middleware + * The OAuth strategy to use */ - path: string; + Strategy: string | typeof Strategy; /** - * The route to register the callback handler + * The route to register the callback handler, defaults to `${path}/callback` */ - callbackPath: string; + callbackPath?: string; /** - * The callback url. + * The callback url. Defaults to @feathersjs/common's makeUrl + callbackPath */ - callbackURL: string; + callbackURL?: string; successRedirect: string; failureRedirect: string; /** - * the entity that you are looking up + * Express middleware for handling the oauth callback. Defaults to the built in middleware. todo: needs a proper type */ - entity: string; + handler?: RequestHandler; + /** + * Express middleware for handling the oauth error callback. Defaults to the built in middleware. todo: needs a proper type + */ + errorHandler?: RequestHandler; + /** + * The response formatter. Defaults the the built in feathers-rest formatter, which returns JSON. todo: needs a proper type + */ + formatter?: RequestHandler; + /** + * A Verifier class. Defaults to the built-in one but can be a custom one. See below for details. + */ + Verifier?: VerifierType; + // todo: some of these options are actually @feathersjs/authentication options, + /** + * The field to look up the entity by when logging in with the provider. Defaults to 'Id' (ie. 'facebookId'). + * This can also be set on app.get('auth') or app.get('authentication') + */ + idField?: string; + /** + * The route to register the middleware on. Defaults to `/auth/${name}` + * This can also be set on app.get('auth') or app.get('authentication') + */ + path?: string; + /** + * the entity that you are looking up. + * This can also be set on app.get('auth') or app.get('authentication') + */ + entity?: string; /** * the service to look up the entity + * This can also be set on app.get('auth') or app.get('authentication') */ - service: string; + service: string | Service; /** * whether the request object should be passed to `verify` + * This can also be set on app.get('auth') or app.get('authentication') */ passReqToCallback: boolean; /** * whether to use sessions, + * This can also be set on app.get('auth') or app.get('authentication') */ session: boolean; /** - * Express middleware for handling the oauth callback. Defaults to the built in middleware. todo: needs a proper type + * Oauth flag to tell @feathersjs/authentication that this is an oauth authentication + * Set by feathersOAuth2 to pass into @feathersjs/authentication */ - handler: any; - /** - * The response formatter. Defaults the the built in feathers-rest formatter, which returns JSON. todo: needs a proper type - */ - formatter: any; - /** - * A Verifier class. Defaults to the built-in one but can be a custom one. See below for details. - */ - Verifier: Verifier; + __oath?: boolean; } -export class Verifier { - constructor(app: Application, options: any) - - _updateEntity(entity: any, data: { profile: any, accessToken: string, refreshToken: string }): Promise; // updates an existing entity - _createEntity(data: { profile: any, accessToken: string, refreshToken: string }): Promise; // creates an entity if they didn't exist already - _normalizeResult(results: T[] | Paginated): Promise; // normalizes result from service to account for pagination - verify(req: Request, accessToken: string, refreshToken: string, profile: any, done: (err: Error | null, user: object, info: object) => void): void; +interface FeathersAuthenticationOAuth2Data { + profile: T; + accessToken: string; + refreshToken: string; } + +export class Verifier< + /** + * The data type for the service object, used in _normalizeResults + */ + DataType = any, + /** + * The interface for the options that are passed into the verifier + */ + OptionType extends FeathersAuthenticationOAuth2Options = FeathersAuthenticationOAuth2Options, + /** + * The profile type for the response, 99% f use cases will be fine with passports default Profile, but you can get more specific like this + * @example + * import {Profile as GithubProfile} from 'passport-github'; + * import {Profile as FacebookProfile} from 'passport-facebook'; + * type IProfileType = GithubProfile | FacebookProfile; + * class MyVerifier extends Verifier { + constructor(app: Application, options: OptionType) + options: OptionType; + service: Service; + _updateEntity(entity: any, data: FeathersAuthenticationOAuth2Data): Promise; // updates an existing entity + _createEntity(data: FeathersAuthenticationOAuth2Data): Promise; // creates an entity if they didn't exist already + _normalizeResult(results: T[] | Paginated): Promise; // normalizes result from service to account for pagination + _setPayloadAndDone(entity: any, done: (err: Error | null, user: object, info: object) => void): Promise; + verify(req: Request, accessToken: string, refreshToken: string, profile: ProfileType, done: (err: Error | null, user: object, info: object) => void): void; +} + +export const defaultHandler: RequestHandler; +export const defaultErrorHandler: RequestHandler; diff --git a/types/feathersjs__authentication/index.d.ts b/types/feathersjs__authentication/index.d.ts index 7bb88a903d..8094c6002a 100644 --- a/types/feathersjs__authentication/index.d.ts +++ b/types/feathersjs__authentication/index.d.ts @@ -1,11 +1,15 @@ // Type definitions for @feathersjs/authentication 2.1 // Project: http://feathersjs.com/ -// Definitions by: Abraao Alves , Jan Lohage +// Definitions by: Abraao Alves +// Jan Lohage +// Nick Bolles // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript // TypeScript Version: 2.3 -import { Hook } from '@feathersjs/feathers'; +import { Hook, Params } from '@feathersjs/feathers'; import * as self from '@feathersjs/authentication'; +import { RequestHandler, Application } from 'express'; +import { create } from 'domain'; declare const feathersAuthentication: ((config?: FeathersAuthenticationOptions) => () => void) & typeof self; export default feathersAuthentication; @@ -52,6 +56,26 @@ export interface FeathersAuthenticationOptions { }; } +export namespace express { + function exposeHeaders(): RequestHandler; + function exposeCookies(): RequestHandler; + function authenticate(strategy: string | string[], options?: FeathersAuthenticationOptions): RequestHandler; + function setCookie(options?: FeathersAuthenticationOptions): RequestHandler; + function successRedirect(): RequestHandler; + function failureRedirect(options?: FeathersAuthenticationOptions): RequestHandler; + function emitEvents(): RequestHandler; +} + +export function service(options: FeathersAuthenticationOptions): (app?: Application) => void; + +export namespace service { + class Service { + constructor(app: Application) + create(data: Partial, params: Params): Promise<{ accessToken: string }>; + remove(id: null | string, params: Params): Promise<{ accessToken: string }>; + } +} + export namespace AuthHooks { interface HashPassOptions { passwordField: string; diff --git a/types/feathersjs__rest-client/index.d.ts b/types/feathersjs__rest-client/index.d.ts index 22e5f1084b..65fdc93707 100644 --- a/types/feathersjs__rest-client/index.d.ts +++ b/types/feathersjs__rest-client/index.d.ts @@ -5,7 +5,7 @@ // todo: get rid of all the anys -export default function feathersRestClient(base: string): Transport; +export default function feathersRestClient(base?: string): Transport; export interface HandlerResult extends Function { /** diff --git a/types/fetch-mock/fetch-mock-tests.ts b/types/fetch-mock/fetch-mock-tests.ts index a5dc13c348..50b4d79252 100644 --- a/types/fetch-mock/fetch-mock-tests.ts +++ b/types/fetch-mock/fetch-mock-tests.ts @@ -1,4 +1,4 @@ -import * as fetchMock from "fetch-mock"; +import fetchMock = require('fetch-mock'); fetchMock.mock("http://test.com", 200); fetchMock.mock("http://test.com", 200, { @@ -141,3 +141,16 @@ sandbox.get("http://test.com", { const response: fetchMock.MockResponseObject = { throws: new Error('error'), }; + +fetchMock.config.sendAsJson = true; +fetchMock.config.includeContentLength = true; +fetchMock.config.fallbackToNetwork = true; +fetchMock.config.fallbackToNetwork = 'always'; +fetchMock.config.overwriteRoutes = true; +fetchMock.config.overwriteRoutes = undefined; +fetchMock.config.warnOnFallback = true; +fetchMock.config.Promise = Promise; +fetchMock.config.fetch = (): Promise => new Promise(() => { }); +fetchMock.config.Headers = Headers; +fetchMock.config.Request = Request; +fetchMock.config.Response = Response; diff --git a/types/fetch-mock/index.d.ts b/types/fetch-mock/index.d.ts index a872a824d9..c9984dea89 100644 --- a/types/fetch-mock/index.d.ts +++ b/types/fetch-mock/index.d.ts @@ -523,14 +523,83 @@ declare namespace fetchMock { options?: InspectionOptions, ): MockOptions | undefined; - /** - * Set some global config options, which include - * sendAsJson [default `true`] - by default fetchMock will - * convert objects to JSON before sending. This is overrideable - * for each call but for some scenarios, e.g. when dealing with a - * lot of array buffers, it can be useful to default to `false` - */ - configure(opts: {}): void; + config: { + /** + * Convert objects into JSON before delivering as stub reponses. + * Can be useful to set to false globally if e.g. dealing with a + * lot of array buffers. If true, will also add + * content-type: application/json header. + * @default true + */ + sendAsJson?: boolean; + + /** + * Automatically sets a content-length header on each response. + * @default true + */ + includeContentLength?: boolean; + + /** + * - true: Unhandled calls fall through to the network + * - false: Unhandled calls throw an error + * - 'always': All calls fall through to the network, effectively + * disabling fetch-mock. + * @default false + */ + fallbackToNetwork?: boolean | 'always'; + + /** + * Determines behaviour if a new route has the same name (or + * inferred name) as an existing one + * - undefined: An error will be throw when routes clash + * - true: Overwrites the existing route + * - false: Appends the new route to the list of routes + * @default undefined + */ + overwriteRoutes?: boolean; + + /** + * Print a warning if any call is caught by a fallback handler (set + * using the fallbackToNetwork option or catch()) + * @default true + */ + warnOnFallback?: boolean; + + /** + * Reference to the Promise constructor of a custom Promise + * implementation. + */ + Promise?: new (executor: ( + resolve: () => void, + reject: () => void, + ) => void) => Promise; + + /** + * Reference to a custom fetch implementation. + */ + fetch?: ( + input?: string | Request, + init?: RequestInit, + ) => Promise; + + /** + * Reference to the Headers constructor of a custom fetch + * implementation. + */ + Headers?: new () => Headers; + + /** + * Reference to the Request constructor of a custom fetch + * implementation. + */ + Request?: new (input: string | Request, init?: RequestInit) => Request; + + /** + * Reference to the Response constructor of a custom fetch + * implementation. + */ + Response?: new () => Response; + }; } interface FetchMockSandbox extends FetchMockStatic { diff --git a/types/filesize/index.d.ts b/types/filesize/index.d.ts index 511e2373af..e8905d906d 100644 --- a/types/filesize/index.d.ts +++ b/types/filesize/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for filesize 3.6 +// Type definitions for filesize 4.0 // Project: https://github.com/avoidwork/filesize.js // Definitions by: Giedrius Grabauskas // Renaud Chaput +// Roman Nuritdinov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var fileSize: Filesize.Filesize; @@ -80,11 +81,6 @@ declare namespace Filesize { * Dictionary of SI/JEDEC symbols to replace for localization, defaults to english if no match is found */ symbols?: SiJedec; - /** - * Dictionary of SI/JEDEC symbols to replace for localization, defaults to english if no match is found - * @deprecated: use `symbols` - */ - suffixes?: SiJedec; /** * Enables unix style human readable output, e.g ls -lh, default is false */ diff --git a/types/filter-console/filter-console-tests.ts b/types/filter-console/filter-console-tests.ts new file mode 100644 index 0000000000..18bb766d32 --- /dev/null +++ b/types/filter-console/filter-console-tests.ts @@ -0,0 +1,8 @@ +import filterConsole = require('filter-console'); + +const disableFilter = filterConsole(['🐼']); +disableFilter; // $ExpectType () => void +filterConsole([/🐼/]); +filterConsole([input => input === '🐼']); + +disableFilter(); diff --git a/types/filter-console/index.d.ts b/types/filter-console/index.d.ts new file mode 100644 index 0000000000..58ee621211 --- /dev/null +++ b/types/filter-console/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for filter-console 0.1 +// Project: https://github.com/sindresorhus/filter-console#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +export = filterConsole; + +/** + * Filter out unwanted `console.log()` output. + * Can be useful when you don't control the output, for example, filtering out PropType warnings from a + * third-party React component. + * + * @param excludePatterns Console output that matches any of the given patterns are filtered from being logged. + * The patterns are matched against what would be logged and not the `console` method input arguments directly. + * Meaning an exclude pattern of `'foo bar'` will match `console.log('foo %s', 'bar')`. + * @returns A function, which when called, disables the filter. + */ +declare function filterConsole( + excludePatterns: Array boolean)>, + options?: filterConsole.Options +): () => void; + +declare namespace filterConsole { + interface Options { + /** + * Console methods to filter. + * @default ['log', 'debug', 'info', 'warn', 'error'] + */ + methods?: Array<'log' | 'debug' | 'info' | 'warn' | 'error'>; + + /** + * Use a custom `console` object. Can be useful for testing or mocking. + */ + console?: Console; + } + + type Console = Record< + 'log' | 'debug' | 'info' | 'warn' | 'error', + (message?: any, ...optionalParams: any[]) => void + >; +} diff --git a/types/filter-console/tsconfig.json b/types/filter-console/tsconfig.json new file mode 100644 index 0000000000..34ed881aab --- /dev/null +++ b/types/filter-console/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", + "filter-console-tests.ts" + ] +} diff --git a/types/filter-console/tslint.json b/types/filter-console/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/filter-console/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/first-run/first-run-tests.ts b/types/first-run/first-run-tests.ts new file mode 100644 index 0000000000..5451c7c88c --- /dev/null +++ b/types/first-run/first-run-tests.ts @@ -0,0 +1,6 @@ +import firstRun = require('first-run'); + +firstRun(); // $ExpectType boolean +firstRun({ name: 'foo' }); // $ExpectType boolean + +firstRun.clear(); diff --git a/types/first-run/index.d.ts b/types/first-run/index.d.ts new file mode 100644 index 0000000000..dc92053d03 --- /dev/null +++ b/types/first-run/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for first-run 1.2 +// Project: https://github.com/sindresorhus/first-run +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = firstRun; + +/** + * Check if it's the first time the process is run. + */ +declare function firstRun(options?: firstRun.Options): boolean; + +declare namespace firstRun { + /** + * Clear the state. + */ + function clear(): void; + + interface Options { + /** + * The name used to identify it. + * @default name field in your package.json + */ + name: string; + } +} diff --git a/types/first-run/tsconfig.json b/types/first-run/tsconfig.json new file mode 100644 index 0000000000..6a4ce007ab --- /dev/null +++ b/types/first-run/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", + "first-run-tests.ts" + ] +} diff --git a/types/first-run/tslint.json b/types/first-run/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/first-run/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fkill/fkill-tests.ts b/types/fkill/fkill-tests.ts new file mode 100644 index 0000000000..6e2b380a16 --- /dev/null +++ b/types/fkill/fkill-tests.ts @@ -0,0 +1,5 @@ +import fkill = require('fkill'); + +fkill(1337); // $ExpectType Promise +fkill('Safari'); // $ExpectType Promise +fkill([1337, 'Safari', ':8080']); // $ExpectType Promise diff --git a/types/fkill/index.d.ts b/types/fkill/index.d.ts new file mode 100644 index 0000000000..4b6663a10c --- /dev/null +++ b/types/fkill/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for fkill 5.3 +// Project: https://github.com/sindresorhus/fkill#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = fkill; + +/** + * Fabulously kill processes. Cross-platform. + * + * @param input One or more process IDs/names/ports to kill. + * To kill a port, prefix it with a colon. For example: `:8080`. + */ +declare function fkill( + input: number | string | Array, + options?: fkill.Options +): Promise; + +declare namespace fkill { + interface Options { + /** + * Force kill the process. + * @default false + */ + force?: boolean; + + /** + * Kill all child processes along with the parent process. *(Windows only)* + * @default true + */ + tree?: boolean; + + /** + * Ignore capitalization when killing a process. + * Note that the case is always ignored on Windows. + * @default false + */ + ignoreCase?: boolean; + } +} diff --git a/types/fkill/tsconfig.json b/types/fkill/tsconfig.json new file mode 100644 index 0000000000..2e36e29395 --- /dev/null +++ b/types/fkill/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", + "fkill-tests.ts" + ] +} diff --git a/types/fkill/tslint.json b/types/fkill/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fkill/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/flatbuffers/flatbuffers-tests.ts b/types/flatbuffers/flatbuffers-tests.ts index 13f8453224..030835c2c9 100644 --- a/types/flatbuffers/flatbuffers-tests.ts +++ b/types/flatbuffers/flatbuffers-tests.ts @@ -86,6 +86,27 @@ class Test { builder.writeInt16(a); return builder.offset(); } + + static testClear(builder: flatbuffers.Builder, a: number, b: number) { + const offsets: number[] = []; + const iterations = 100; + for (let i = 0; i < iterations; i++) { + const offset = Test.createTest(builder, a, b); + offsets.push(offset); + builder.clear(); + } + + let lastOffsetValue = offsets[0]; + let sameValue = true; + for (let i = 1; i < offsets.length; i++) { + if (lastOffsetValue !== offsets[i]) { + sameValue = false; + return sameValue; + } + lastOffsetValue = offsets[i]; + } + return sameValue; + } } class TestSimpleTableWithEnum { diff --git a/types/flatbuffers/index.d.ts b/types/flatbuffers/index.d.ts index bd74387bf2..03f3d952f3 100644 --- a/types/flatbuffers/index.d.ts +++ b/types/flatbuffers/index.d.ts @@ -42,6 +42,12 @@ declare global { class Builder { constructor(initial_size?: number); + /** + * Reset all the state in this FlatBufferBuilder + * so it can be reused to construct another buffer. + */ + clear(): void; + /** * In order to save space, fields that are set to their default value * don't get serialized into the buffer. Forcing defaults provides a @@ -211,6 +217,8 @@ declare global { static allocate(byte_size: number): ByteBuffer; + clear(): void; + bytes(): Uint8Array; position(): number; diff --git a/types/flexmonster/flexmonster-tests.ts b/types/flexmonster/flexmonster-tests.ts new file mode 100644 index 0000000000..fb9840c6cb --- /dev/null +++ b/types/flexmonster/flexmonster-tests.ts @@ -0,0 +1,7 @@ +import Flexmonster = require('flexmonster'); + +new Flexmonster({ + container: 'pivot-container', + height: '550px', + width: '100%' +}); diff --git a/types/flexmonster/index.d.ts b/types/flexmonster/index.d.ts new file mode 100644 index 0000000000..00a6c49bcb --- /dev/null +++ b/types/flexmonster/index.d.ts @@ -0,0 +1,479 @@ +// Type definitions for flexmonster 2.6 +// Project: https://www.flexmonster.com/ +// Definitions by: Flexmonster +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export as namespace Flexmonster; + +declare const Flexmonster: FlexmonsterConstructor; +export = Flexmonster; + +interface FlexmonsterConstructor { + new (params: Flexmonster.Params): Flexmonster.Pivot; + (params: Flexmonster.Params): Flexmonster.Pivot; +} + +declare namespace Flexmonster { + interface Params { + // params + toolbar?: boolean; + licenseKey?: string; + width?: string | number; + height?: string | number; + componentFolder?: string; + report?: Report | string; + global?: Report; + customizeCell?: (cell: CellBuilder, data: CellData) => void; + customizeContextMenu?: (items: ContextMenuItem[], data: CellData | ChartData, viewType: string) => ContextMenuItem[]; + // events + afterchartdraw?: () => void; + aftergriddraw?: (param: object) => void; + beforegriddraw?: (param: object) => void; + beforetoolbarcreated?: (toolbar: Toolbar) => void; + cellclick?: (cell: CellData) => void; + celldoubleclick?: (cell: CellData) => void; + datachanged?: (param: object) => void; + dataerror?: (param: object) => void; + datafilecancelled?: () => void; + dataloaded?: () => void; + exportcomplete?: () => void; + exportstart?: () => void; + fieldslistclose?: () => void; + fieldslistopen?: () => void; + filterclose?: () => void; + filteropen?: () => void; + loadingdata?: () => void; + loadinglocalization?: () => void; + loadingolapstructure?: () => void; + loadingreportfile?: () => void; + localizationerror?: () => void; + localizationloaded?: () => void; + olapstructureerror?: () => void; + olapstructureloaded?: () => void; + openingreportfile?: () => void; + printcomplete?: () => void; + printstart?: () => void; + querycomplete?: () => void; + queryerror?: () => void; + ready?: () => void; + reportchange?: () => void; + reportcomplete?: () => void; + reportfilecancelled?: () => void; + reportfileerror?: () => void; + runningquery?: () => void; + update?: () => void; + // other + container?: string; + } + + interface Pivot { + addCalculatedMeasure(measure: Measure): void; + addCondition(condition: ConditionalFormat): void; + addJSON(json: object[]): void; + alert(options: { title?: string; message?: string; type?: string; buttons?: Array<{ label: string; handler?: () => void; }>; blocking?: boolean; }): void; + clear(): void; + clearFilter(hierarchyName: string): void; + clearXMLACache(proxyUrl: string, databaseId: string, callbackHandler: ((reponse: object) => void) | string, cubeId: string, measuresGroupId: string, + username?: string, password?: string): void; + closeFieldsList(): void; + collapseAllData(): void; + collapseData(hierarchyName: string): void; + connectTo(object: DataSource): void; + customizeCell(customizeCellFunction: (cell: CellBuilder, data: CellData) => void): void; + customizeContextMenu(customizeFunction: (items: ContextMenuItem[], data: CellData | ChartData, viewType: string) => ContextMenuItem[]): void; + dispose(): void; + expandAllData(withAllChildren?: boolean): void; + expandData(hierarchyName: string): void; + exportTo(type: string, exportOptions?: ExportOptions, callbackHandler?: ((result: object) => void) | string): void; + getAllConditions(): ConditionalFormat[]; + getAllHierarchies(): Hierarchy[]; + getAllMeasures(): Measure[]; + getCell(rowIdx: number, colIdx: number): CellData; + getColumns(): Hierarchy[]; + getCondition(id: string): ConditionalFormat; + getData(options: { slice?: Slice }, callbackHandler: ((rawData: any) => void) | string, updateHandler?: ((rawData: any) => void) | string): void; + getFilter(hierarchyName: string): FilterItem[]; + getFilterProperties(hierarchyName: string): FilterProperties; + getFormat(measureName: string): Format; + getMeasures(): Measure[]; + getMembers(hierarchyName: string, memberName: string, callbackHandler: ((members: Member[]) => void) | string): Member[]; + getOptions(): Options; + getReport(format?: string): Report | string; + getReportFilters(): Hierarchy[]; + getRows(): Hierarchy[]; + getSelectedCell(): CellData | CellData[]; + getSort(hierarchyName: string): string; + getXMLACatalogs(proxyURL: string, dataSource: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): void; + getXMLACubes(proxyURL: string, dataSource: string, catalog: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): void; + getXMLADataSources(proxyURL: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): void; + getXMLAProviderName(proxyURL: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): string; + load(url: string, componentFolder?: string): void; + off(eventType: string, handler?: ((...args: any[]) => any) | string): void; + on(eventType: string, handler: ((...args: any[]) => any) | string): void; + open(): void; + openFieldsList(): void; + openFilter(hierarchyName: string): void; + print(options?: PrintOptions): void; + refresh(): void; + removeAllCalculatedMeasures(): void; + removeAllConditions(): void; + removeCalculatedMeasure(uniqueName: string): void; + removeCondition(id: string): void; + removeSelection(): void; + runQuery(slice: Slice): void; + save(filename: string, destination: string, callbackHandler?: (() => void) | string, url?: string, embedData?: boolean): string; + setBottomX(hierarchyName: string, num: number, measure: MeasureObject): void; + setFilter(hierarchyName: string, items: string[], negation?: boolean): void; + setFormat(format: Format, measureName: string): void; + setOptions(options: Options): void; + setReport(report: Report): void; + setSort(hierarchyName: string, sortName: string, customSorting?: string[]): void; + setTopX(hierarchyName: string, num: number, measure: MeasureObject): void; + showCharts(type?: string, multiple?: boolean): void; + showGrid(): void; + showGridAndCharts(type?: string, position?: string, multiple?: boolean): void; + sortingMethod(hierarchyName: string, compareFunction: (a: string, b: string) => boolean): void; + sortValues(axisName: string, type: string, tuple: number[], measure: MeasureObject): void; + updateData(object: DataSource | object[]): void; + version: string; + fusioncharts?: { + getData(options: { type: string; slice?: Slice; prepareDataFunction?: (rawData: any) => any }, callbackHandler: ((rawData: any) => void) | string, + updateHandler?: ((rawData: any) => void) | string): void; + getNumberFormat(format: object): object; + }; + googlecharts?: { + getData(options: { type?: string; slice?: Slice; prepareDataFunction?: (rawData: any) => any }, callbackHandler: ((rawData: any) => void) | string, + updateHandler?: ((rawData: any) => void) | string): void; + getNumberFormat(format: object): object; + getNumberFormatPattern(format: object): string; + }; + highcharts?: { + getData(options: { type?: string; slice?: Slice; xAxisType?: string; valuesOnly?: boolean, withDrilldown?: boolean, prepareDataFunction?: (rawData: any) => any }, + callbackHandler: ((rawData: any) => void) | string, updateHandler?: ((rawData: any) => void) | string): void; + getAxisFormat(format: object): string; + getPointXFormat(format: object): string; + getPointYFormat(format: object): string; + getPointZFormat(format: object): string; + }; + } + + interface Report { + dataSource?: DataSource; + slice?: Slice; + options?: Options; + conditions?: ConditionalFormat[]; + formats?: Format[]; + tableSizes?: { + columns?: ColumnSize[]; + rows?: RowSize[]; + }; + localization?: object | string; + } + + interface DataSource { + browseForFile?: boolean; + catalog?: string; + cube?: string; + data?: object[]; + dataSourceInfo?: string; + dataSourceType?: string; + fieldSeparator?: string; + filename?: string; + ignoreQuotedLineBreaks?: boolean; + proxyUrl?: string; + recordsetDelimiter?: string; + binary?: boolean; + roles?: string; + localeIdentifier?: string; + effectiveUserName?: string; + customData?: string; + hash?: string; + username?: string; + password?: string; + } + + interface Slice { + columns?: Hierarchy[]; + measures?: Measure[]; + reportFilters?: Hierarchy[]; + rows?: Hierarchy[]; + drills?: { + drillAll?: boolean; + columns?: Array<{ tuple: string[]; measure?: MeasureObject; }>; + rows?: Array<{ tuple: string[]; measure?: MeasureObject; }>; + }; + expands?: { + expandAll?: boolean; + columns?: Array<{ tuple: string[]; measure?: MeasureObject; }>; + rows?: Array<{ tuple: string[]; measure?: MeasureObject; }>; + }; + sorting?: { + column?: Array<{ type: string; tuple: string[]; measure: MeasureObject; }>; + row?: Array<{ type: string; tuple: string[]; measure: MeasureObject; }>; + }; + drillThrough?: string[]; + } + + interface Options { + chart?: { + activeMeasure?: MeasureObject; + activeTupleIndex?: number; + autoRange?: boolean; + labelsHierarchy?: string; + multipleMeasures?: boolean; + oneLevel?: boolean; + showFilter?: boolean; + showLegend?: boolean; + showLegendButton?: boolean; + showMeasures?: boolean; + showWarning?: boolean; + title?: string; + type?: string; + showDataLabels?: boolean; + reversedAxes?: boolean; + showAllLabels?: boolean; + showOneMeasureSelection?: boolean; + position?: string; + pieDataIndex?: string; + }; + grid?: { + showFilter?: boolean; + showGrandTotals?: string; + showHeaders?: boolean; + showHierarchies?: boolean; + showHierarchyCaptions?: boolean; + showReportFiltersArea?: boolean; + showTotals?: boolean; + title?: string; + type?: string; + showAutoCalculationBar?: boolean; + dragging?: boolean; + grandTotalsPosition?: string; + drillThroughMaxRows?: number; + }; + configuratorActive?: boolean; + configuratorButton?: boolean; + dateTimezoneOffset?: number; + datePattern?: string; + dateTimePattern?: string; + defaultHierarchySortName?: string; + drillThrough?: boolean; + editing?: boolean; + selectEmptyCells?: boolean; + showAggregations?: boolean; + showCalculatedValuesButton?: boolean; + showDefaultSlice?: boolean; + showMemberProperties?: boolean; + sorting?: string; + viewType?: string; + showAggregationLabels?: boolean; + useOlapFormatting?: boolean; + defaultDateType?: string; + timePattern?: string; + showOutdatedDataAlert?: boolean; + showEmptyData?: boolean; + saveAllFormats?: boolean; + showDrillThroughConfigurator?: boolean; + grouping?: boolean; + } + + interface PrintOptions { + header?: string; + footer?: string; + } + + interface Member { + caption?: string; + uniqueName?: string; + hierarchyName?: string; + children?: Member[]; + isLeaf?: boolean; + parentMember?: string; + } + + interface FilterProperties { + type: string; + members?: FilterItem[]; + quantity?: number; + measure?: MeasureObject; + } + + interface FilterItem { + caption?: string; + uniqueName?: string; + hierarchyName?: string; + } + + interface CellData { + columnIndex?: number; + columns?: object[]; + escapedLabel?: string; + height?: number; + hierarchy?: Hierarchy; + isClassicTotalRow?: boolean; + isDrillThrough?: boolean; + isGrandTotal?: boolean; + isGrandTotalColumn?: boolean; + isGrandTotalRow?: boolean; + isTotal?: boolean; + isTotalColumn?: boolean; + isTotalRow?: boolean; + member?: Member; + width?: number; + x?: number; + y?: number; + label?: string; + measure?: MeasureObject; + rowIndex?: number; + rows?: object[]; + type?: string; + value?: number; + } + + interface ExportOptions { + filename?: string; + destinationType?: string; + excelSheetName?: string; + footer?: string; + header?: string; + pageOrientation?: string; + showFilters?: boolean; + url?: string; + useOlapFormattingInExcel?: boolean; + useCustomizeCellForData?: boolean; + excelExportAll?: boolean; + } + + interface Hierarchy { + caption?: string; + dimensionName?: string; + filter?: { + members?: string[]; + negation?: boolean; + measure?: MeasureObject; + quantity?: number; + type?: string; + }; + sortName?: string; + sortOrder?: string[]; + uniqueName?: string; + } + + interface Measure { + uniqueName?: string; + active?: boolean; + aggregation?: string; + availableAggregations?: string[]; + caption?: string; + formula?: string; + format?: string; + grandTotalCaption?: string; + } + + interface MeasureObject { + uniqueName: string; + aggregation?: string; + } + + interface ConditionalFormat { + formula?: string; + format?: Style; + formatCSS?: string; + row?: number; + column?: number; + measureName?: string; + hierarchy?: string; + member?: string; + isTotal?: number; + } + + interface Style { + color?: string; + backgroundColor?: string; + backgroundImage?: string; + borderColor?: string; + fontSize?: string; + fontWeight?: string; + fill?: string; + textAlign?: string; + fontFamily?: string; + width?: number; + maxWidth?: number; + height?: number; + maxHeight?: number; + } + + interface Format { + name?: string; + thousandsSeparator?: string; + decimalSeparator?: string; + decimalPlaces?: number; + maxDecimalPlaces?: number; + maxSymbols?: number; + currencySymbol?: string; + currencySymbolAlign?: string; + nullValue?: string; + infinityValue?: string; + divideByZeroValue?: string; + textAlign?: string; + isPercent?: boolean; + beautifyFloatingPoint?: boolean; + } + + interface ColumnSize { + width?: number; + idx?: number; + tuple?: string[]; + measure?: MeasureObject; + } + + interface RowSize { + height?: number; + idx?: number; + tuple?: string[]; + measure?: MeasureObject; + } + + interface CellBuilder { + attr?: object; + classes?: string[]; + style?: object; + tag?: string; + text?: string; + addClass(value?: string): void; + toHtml(): string; + } + + interface ContextMenuItem { + label?: string; + handler?: (() => void) | string; + submenu?: ContextMenuItem[]; + isSelected?: boolean; + } + + interface ChartData { + columnTuple?: number[]; + id?: string; + label?: string; + measure?: MeasureObject; + rawTuple?: number[]; + value?: number; + } + + interface Toolbar { + getTabs: () => ToolbarTab[]; + } + + interface ToolbarTab { + android: boolean; + args: any; + handler: (() => void) | string; + icon: string; + id: string; + ios: boolean; + mobile: boolean; + menu: ToolbarTab[]; + title: string; + } +} diff --git a/types/flexmonster/tsconfig.json b/types/flexmonster/tsconfig.json new file mode 100644 index 0000000000..9e3ef7747b --- /dev/null +++ b/types/flexmonster/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", + "flexmonster-tests.ts" + ] +} \ No newline at end of file diff --git a/types/flexmonster/tslint.json b/types/flexmonster/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/flexmonster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fluent-langneg/fluent-langneg-tests.ts b/types/fluent-langneg/fluent-langneg-tests.ts new file mode 100644 index 0000000000..45eaa22ee8 --- /dev/null +++ b/types/fluent-langneg/fluent-langneg-tests.ts @@ -0,0 +1,7 @@ +import { negotiateLanguages } from 'fluent-langneg'; + +const supportedLocales = negotiateLanguages( + ['en-US', 'pl'], // requested locales + ['de', 'en-US', 'pl'], // available locales + { defaultLocale: 'en-US' } +); diff --git a/types/fluent-langneg/index.d.ts b/types/fluent-langneg/index.d.ts new file mode 100644 index 0000000000..28abe2c2d9 --- /dev/null +++ b/types/fluent-langneg/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for fluent-langneg 0.1 +// Project: http://projectfluent.io +// Definitions by: Huy Nguyen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface LanguageNegotiationOptions { + strategy?: 'filtering' | 'matching' | 'lookup'; + defaultLocale?: string; +} + +export function negotiateLanguages(requestedLocales: ReadonlyArray, availableLocales: ReadonlyArray, options?: LanguageNegotiationOptions): string[]; diff --git a/types/fluent-langneg/tsconfig.json b/types/fluent-langneg/tsconfig.json new file mode 100644 index 0000000000..665c5dc082 --- /dev/null +++ b/types/fluent-langneg/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", + "fluent-langneg-tests.ts" + ] +} diff --git a/types/fluent-langneg/tslint.json b/types/fluent-langneg/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fluent-langneg/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fluent-react/fluent-react-tests.tsx b/types/fluent-react/fluent-react-tests.tsx new file mode 100644 index 0000000000..225749d64e --- /dev/null +++ b/types/fluent-react/fluent-react-tests.tsx @@ -0,0 +1,60 @@ +import { Localized, LocalizationProvider, withLocalization, GetString } from 'fluent-react'; +import { FluentBundle, ftl } from 'fluent'; +import * as ReactDOM from 'react-dom'; + +// Localized examples: +const Test = () => ( + +

Hello, world!

+ +); + +// LocalizationProvider examples: +function* generateBundles(currentLocales: string[]) { + for (const locale of currentLocales) { + const bundle = new FluentBundle(locale); + bundle.addMessages(ftl`some-message = Hello`); + yield bundle; + } +} + +ReactDOM.render( + + Content + , + document.getElementById('root') +); + +// withLocalization examples: +interface Props { + getString: GetString; + otherProp: number; + someOtherProp: string; +} +function HelloButton(props: Props) { + const { getString } = props; + + return ( + + ); +} + +const LocalizedHelloButton = withLocalization(HelloButton); + +// Remove `getString` from list of required props: +const Test2 = () => ( + +); +// Should not allow `getString` prop: +const Test3 = () => ( + // $ExpectError + {}}/> +); + +// Should not allow any other props to be omitted: +const Test4 = () => ( + // $ExpectError + +); diff --git a/types/fluent-react/index.d.ts b/types/fluent-react/index.d.ts new file mode 100644 index 0000000000..5ffc93d874 --- /dev/null +++ b/types/fluent-react/index.d.ts @@ -0,0 +1,101 @@ +// Type definitions for fluent-react 0.8 +// Project: http://projectfluent.org +// Definitions by: Huy Nguyen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import { + FluentBundle, +} from 'fluent'; + +export interface Node { + TEXT_NODE: 3; + nodeType: number; + localName?: string; + textContext: string; +} + +export type MarkupParser = (str: string) => Node[]; + +export interface Context { + l10n: ReactLocalization; + parseMarkup: MarkupParser; +} +export interface LocalizationProviderProps { + bundles: IterableIterator; + parseMarkup?: MarkupParser; +} +export class LocalizationProvider extends React.Component { +} + +export class ReactLocalization { + constructor(bundles: IterableIterator); + getString(id: string, args?: object, fallback?: string): string; +} + +export interface LocalizedProps { + id: string; + attrs?: object; + [key: string]: any; +} + +export class Localized extends React.Component { +} + +// Inspired by react-redux's type definition: +/** + * A property P will be present if: + * - it is present in DecorationTargetProps + * + * Its value will be dependent on the following conditions + * - if property P is present in InjectedProps and its definition extends the definition + * in DecorationTargetProps, then its definition will be that of DecorationTargetProps[P] + * - if property P is not present in InjectedProps then its definition will be that of + * DecorationTargetProps[P] + * - if property P is present in InjectedProps but does not extend the + * DecorationTargetProps[P] definition, its definition will be that of InjectedProps[P] + */ +export type Matching = { + [P in keyof DecorationTargetProps]: P extends keyof InjectedProps + ? InjectedProps[P] extends DecorationTargetProps[P] + ? DecorationTargetProps[P] + : InjectedProps[P] + : DecorationTargetProps[P]; +}; + +/** + * a property P will be present if : + * - it is present in both DecorationTargetProps and InjectedProps + * - InjectedProps[P] can satisfy DecorationTargetProps[P] + * ie: decorated component can accept more types than decorator is injecting + * + * For decoration, inject props or ownProps are all optionally + * required by the decorated (right hand side) component. + * But any property required by the decorated component must be satisfied by the injected property. + */ +export type Shared< + InjectedProps, + DecorationTargetProps extends Shared + > = { + [P in Extract]?: InjectedProps[P] extends DecorationTargetProps[P] ? DecorationTargetProps[P] : never; + }; + +// Infers prop type from component C +export type GetProps = C extends React.ComponentType ? P : never; + +export type GetString = (id: string, args?: object) => string; + +export interface InjectedProps { + getString: GetString; +} + +// Taken from +// https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#predefined-conditional-types +export type Omit = Pick>; + +// Injects `getString` and removes it from the prop requirements. Will not pass +// through `getString` if it's passed in during render. +export function withLocalization>>>( + component: C +): React.ComponentType, keyof Shared>>>; diff --git a/types/react-bootstrap-typeahead/package.json b/types/fluent-react/package.json similarity index 100% rename from types/react-bootstrap-typeahead/package.json rename to types/fluent-react/package.json diff --git a/types/fluent-react/tsconfig.json b/types/fluent-react/tsconfig.json new file mode 100644 index 0000000000..5a962376b4 --- /dev/null +++ b/types/fluent-react/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "jsx": "preserve", + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fluent-react-tests.tsx" + ] +} diff --git a/types/fluent-react/tslint.json b/types/fluent-react/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/fluent-react/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fluent/fluent-tests.ts b/types/fluent/fluent-tests.ts new file mode 100644 index 0000000000..d2fcd4a6c4 --- /dev/null +++ b/types/fluent/fluent-tests.ts @@ -0,0 +1,44 @@ +import { FluentBundle, ftl, FluentResource } from 'fluent'; + +const bundle1 = new FluentBundle('en-US'); + +const errors1 = bundle1.addMessages(ftl` + -brand-name = Foo 3000 + welcome = Welcome, { $name }, to { -brand-name }! +`); + +if (errors1.length) { + // syntax errors are per-message and don't break the whole resource +} + +const welcome = bundle1.getMessage('welcome'); + +bundle1.format(welcome, { name: 'Anna' }); + +// FluentBundle constructor examples: +const bundle2 = new FluentBundle(['en-US']); + +const bundle3 = new FluentBundle(['en-US'], { useIsolating: false }); + +const bundle4 = new FluentBundle(['en-US'], { + useIsolating: true, + functions: { + NODE_ENV: () => 'production' + } +}); + +// FluentBundle addMessages examples: +bundle1.addMessages('foo = Foo'); +bundle2.getMessage('foo'); + +// FluentBundle addResource examples: +const a = FluentResource.fromString('foo'); +bundle1.addResource(a); +bundle2.getMessage('foo'); + +// FluentBundle format examples: +const errors2: any[] = []; +bundle1.addMessages('hello = Hello, { $name }!'); +const hello = bundle2.getMessage('hello'); +bundle3.format(hello, { name: 'Jane' }, errors2); +bundle3.format(hello, undefined, errors2); diff --git a/types/fluent/index.d.ts b/types/fluent/index.d.ts new file mode 100644 index 0000000000..56014044ab --- /dev/null +++ b/types/fluent/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for fluent 0.10 +// Project: http://projectfluent.org +// Definitions by: Huy Nguyen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export interface FluentBundleContructorOptions { + functions?: object; + useIsolating?: boolean; + transform?: (...args: any[]) => any; +} + +export class FluentType { + constructor(value: any, opts: object); + toString(bundle: FluentBundle): string; + valueOf(): any; +} + +export class FluentNone extends FluentType {} +export class FluentNumber extends FluentType {} +export class FluentDateTime extends FluentType {} + +export type FluentNode = FluentType | string; + +export class FluentResource extends Map { + static fromString(source: string): FluentResource; +} + +export class FluentBundle { + constructor(locales: string | string[], options?: FluentBundleContructorOptions); + addMessages(source: string): string[]; + getMessage(id: string): FluentNode[]; + format(message: FluentNode[], args?: object, errors?: string[]): string; + addResource(res: FluentResource): string[]; +} + +export function ftl(strings: TemplateStringsArray): string; diff --git a/types/fluent/tsconfig.json b/types/fluent/tsconfig.json new file mode 100644 index 0000000000..64e2460dcd --- /dev/null +++ b/types/fluent/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", + "fluent-tests.ts" + ] +} diff --git a/types/fluent/tslint.json b/types/fluent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fluent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/force-graph/force-graph-tests.ts b/types/force-graph/force-graph-tests.ts new file mode 100644 index 0000000000..a47b551e11 --- /dev/null +++ b/types/force-graph/force-graph-tests.ts @@ -0,0 +1,92 @@ +import ForceGraph from 'force-graph'; + +const graph = ForceGraph(); +graph(new HTMLElement()); + +graph + .graphData({nodes: [], links: []}) + .nodeId('testNode') + .linkSource('source') + .linkTarget('target') + .width(100) + .height(100) + .backgroundColor('#FFF') + .nodeRelSize(4) + .nodeVal(1) + .nodeVal('val') + .nodeVal((node) => node.val) + .nodeLabel('name') + .nodeLabel((node) => node.name) + .nodeColor('color') + .nodeColor((node) => node.val) + .nodeAutoColorBy('color') + .nodeAutoColorBy((node) => node.val) + .nodeCanvasObject((node, ctx, scale) => {}) + .linkLabel('name') + .linkLabel((link) => link.type) + .linkVisibility(true) + .linkVisibility((link) => true) + .linkColor('color') + .linkColor((link) => link.type) + .linkAutoColorBy('type') + .linkAutoColorBy((link) => link.type) + .linkWidth(1) + .linkWidth((link) => 1) + .linkCurvature(ForceGraph.LinkCurvatureType.Straight) + .linkCurvature('curvature') + .linkCurvature((link) => ForceGraph.LinkCurvatureType.Straight) + .linkCanvasObject((link, ctx, scale) => {}) + .linkDirectionalArrowLength(0) + .linkDirectionalArrowLength('length') + .linkDirectionalArrowLength((link) => 0) + .linkDirectionalArrowColor('color') + .linkDirectionalArrowColor((link) => link.type) + .linkDirectionalArrowRelPos(0.5) + .linkDirectionalArrowRelPos('pos') + .linkDirectionalArrowRelPos((link) => 0.5) + .linkDirectionalParticles(0) + .linkDirectionalParticles('particles') + .linkDirectionalParticles((link) => 0) + .linkDirectionalParticleSpeed(0.01) + .linkDirectionalParticleSpeed('speed') + .linkDirectionalParticleSpeed((link) => 0.01) + .linkDirectionalParticleWidth(4) + .linkDirectionalParticleWidth('width') + .linkDirectionalParticleWidth((link) => 4) + .linkDirectionalParticleColor('color') + .linkDirectionalParticleColor((link) => link.type); + +graph.pauseAnimation(); +graph.resumeAnimation(); +graph.centerAt(0, 0, 0); +graph.zoom(1.0, 0); + +graph + .dagMode('td') + .dagLevelDistance(1) + .d3AlphaDecay(0.0228) + .d3VelocityDecay(0.4) + .d3Force('link') + .d3Force('custom', (node) => 1) + .warmupTicks(0) + .cooldownTicks(Infinity) + .cooldownTime(15000) + .onEngineTick(() => {}) + .onEngineStop(() => {}); + +graph + .onNodeClick(() => {}) + .onNodeRightClick(() => {}) + .onNodeHover(() => {}) + .onNodeDrag(() => {}) + .onNodeDragEnd(() => {}) + .onLinkClick(() => {}) + .onLinkRightClick(() => {}) + .onLinkHover(() => {}) + .linkHoverPrecision(4) + .enableNodeDrag(true) + .enableZoomPanInteraction(true) + .enablePointerInteraction(true); + +// Test a property getter +const nodeDraggingEnabled: boolean = graph.enableNodeDrag(); diff --git a/types/force-graph/index.d.ts b/types/force-graph/index.d.ts new file mode 100644 index 0000000000..b9b056ce04 --- /dev/null +++ b/types/force-graph/index.d.ts @@ -0,0 +1,149 @@ +// Type definitions for force-graph >= 1.14 +// Project: https://github.com/vasturiano/force-graph +// Definitions by: Peter Kimberley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function ForceGraph(): ForceGraph.ForceGraphInstance; + +declare namespace ForceGraph { + /** + * Interfaces + */ + + interface GraphData { + nodes: GraphNode[]; + links: GraphLink[]; + } + + interface GraphEntity { + id: string; + } + + interface GraphNode extends GraphEntity { + name: string; + val: any; + } + + interface GraphNodeObject extends GraphNode { + x: number; + y: number; + index: number; + } + + interface GraphLink extends GraphEntity { + type: string; + source: string | GraphNode; + target: string | GraphNode; + } + + interface GraphLinkObject extends GraphLink { + source: GraphNode; + target: GraphNode; + } + + /** + * Enums + */ + + enum LinkCurvatureType { + Straight = 0, + HalfLineLength = 1 + } + + /** + * Types + */ + + type NodeAccessorFn = (node: GraphNodeObject) => T; + type NodeCanvasCallbackFn = (node: GraphNodeObject, canvasContext: CanvasRenderingContext2D, globalScale: number) => void; + type NodeEventCallback = (node: GraphNodeObject) => void; + + type LinkAccessorFn = (link: GraphLinkObject) => T; + type LinkCanvasCallbackFn = (link: GraphLinkObject, canvasContext: CanvasRenderingContext2D, globalScale: number) => void; + type LinkEventCallback = (link: GraphLinkObject) => void; + + type DagMode = 'td' | 'bu' | 'lr' | 'rl' | 'radialout' | 'radialin'; + type ForceFn = (node: { x: number, y: number }) => number; + + /** + * Represents ForceGraph runtime object + * @example: + * let forceGraph = ForceGraph(); + * forceGraph(myHtmlElement); + * forceGraph.graphData([]) + */ + + interface ForceGraphInstance { + (element: HTMLElement): ForceGraphInstance; + + // Data input + graphData(data?: GraphData): ForceGraphInstance & GraphData; + nodeId(id?: string): ForceGraphInstance & string; + linkSource(source?: string): ForceGraphInstance & string; + linkTarget(target?: string): ForceGraphInstance & string; + + // Container layout + width(width?: number): ForceGraphInstance & number; + height(height?: number): ForceGraphInstance & number; + backgroundColor(color?: string): ForceGraphInstance & string; + + // Node styling + nodeRelSize(size?: number): ForceGraphInstance & number; + nodeVal(val?: number | string | NodeAccessorFn): ForceGraphInstance & (number | string | NodeAccessorFn); + nodeLabel(label?: string | NodeAccessorFn): ForceGraphInstance & (string | NodeAccessorFn); + nodeColor(color?: string | NodeAccessorFn): ForceGraphInstance & (string | NodeAccessorFn); + nodeAutoColorBy(attribute?: string | NodeAccessorFn): ForceGraphInstance & (string | NodeAccessorFn); + nodeCanvasObject(callback?: NodeCanvasCallbackFn): ForceGraphInstance & NodeCanvasCallbackFn; + + // Link styling + linkLabel(label?: string | LinkAccessorFn): ForceGraphInstance & (string | LinkAccessorFn); + linkVisibility(visible?: boolean | string | LinkAccessorFn): ForceGraphInstance & (boolean | string | LinkAccessorFn); + linkColor(color?: string | LinkAccessorFn): ForceGraphInstance & (string | LinkAccessorFn); + linkAutoColorBy(attribute?: string | LinkAccessorFn): ForceGraphInstance & (string | LinkAccessorFn); + linkWidth(width?: number | string | LinkAccessorFn): ForceGraphInstance & (number | string | LinkAccessorFn); + linkCurvature(curvature?: LinkCurvatureType | string | LinkAccessorFn): ForceGraphInstance; + linkCanvasObject(callback?: LinkCanvasCallbackFn): ForceGraphInstance & LinkCanvasCallbackFn; + linkDirectionalArrowLength(length?: number | string | LinkAccessorFn): ForceGraphInstance & (number | string | LinkAccessorFn); + linkDirectionalArrowColor(color?: string | LinkAccessorFn): ForceGraphInstance & (string | LinkAccessorFn); + linkDirectionalArrowRelPos(ratio?: number | string | LinkAccessorFn): ForceGraphInstance & (number | string | LinkAccessorFn); + linkDirectionalParticles(particleCount?: number | string | LinkAccessorFn): ForceGraphInstance & (number | string | LinkAccessorFn); + linkDirectionalParticleSpeed(speed?: number | string | LinkAccessorFn): ForceGraphInstance & (number | string | LinkAccessorFn); + linkDirectionalParticleWidth(width?: number | string | LinkAccessorFn): ForceGraphInstance & (number | string | LinkAccessorFn); + linkDirectionalParticleColor(color?: string | LinkAccessorFn): ForceGraphInstance & (string | LinkAccessorFn); + + // Render control + pauseAnimation(): ForceGraphInstance; + stopAnimation(): ForceGraphInstance; // Alias for pauseAnimation() + resumeAnimation(): ForceGraphInstance; + centerAt(x?: number, y?: number, milliseconds?: number): ForceGraphInstance & {x: number, y: number}; + zoom(zoomLevel?: number, duration?: number): ForceGraphInstance & number; + + // Force engine configuration + dagMode(mode?: DagMode): ForceGraphInstance & DagMode; + dagLevelDistance(distance?: number): ForceGraphInstance & number; + d3AlphaDecay(decay?: number): ForceGraphInstance & number; + d3VelocityDecay(decay?: number): ForceGraphInstance & number; + d3Force(force: 'link' | 'charge' | 'center' | string, forceFn?: ForceFn): ForceGraphInstance & ForceFn; + warmupTicks(ticks?: number): ForceGraphInstance & number; + cooldownTicks(ticks?: number): ForceGraphInstance & number; + cooldownTime(milliseconds?: number): ForceGraphInstance & number; + onEngineTick(callback: () => void): ForceGraphInstance; + onEngineStop(callback: () => void): ForceGraphInstance; + + // Interaction + onNodeClick(callback: NodeEventCallback): ForceGraphInstance; + onNodeRightClick(callback: NodeEventCallback): ForceGraphInstance; + onNodeHover(callback: (node?: GraphNodeObject, previousNode?: GraphNodeObject) => void): ForceGraphInstance; + onNodeDrag(callback: NodeEventCallback): ForceGraphInstance; + onNodeDragEnd(callback: NodeEventCallback): ForceGraphInstance; + onLinkClick(callback: LinkEventCallback): ForceGraphInstance; + onLinkRightClick(callback: LinkEventCallback): ForceGraphInstance; + onLinkHover(callback: (link?: GraphLinkObject, previousLink?: GraphLinkObject) => void): ForceGraphInstance; + linkHoverPrecision(precision?: number): ForceGraphInstance & number; + enableNodeDrag(enable?: boolean): ForceGraphInstance & boolean; + enableZoomPanInteraction(enable?: boolean): ForceGraphInstance & boolean; + enablePointerInteraction(enable?: boolean): ForceGraphInstance & boolean; + } +} + +export default ForceGraph; diff --git a/types/force-graph/tsconfig.json b/types/force-graph/tsconfig.json new file mode 100644 index 0000000000..280a78f67a --- /dev/null +++ b/types/force-graph/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "exclude": [ + "node_modules" + ], + "files": [ + "index.d.ts", + "force-graph-tests.ts" + ] +} diff --git a/types/force-graph/tslint.json b/types/force-graph/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/force-graph/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/forever-monitor/index.d.ts b/types/forever-monitor/index.d.ts index c9de58e7cc..cc666b65c0 100644 --- a/types/forever-monitor/index.d.ts +++ b/types/forever-monitor/index.d.ts @@ -25,7 +25,7 @@ export interface Options { sourceDir?: string; watch?: boolean; watchIgnoreDotFiles?: boolean; - watchIgnorePatters?: string[]; + watchIgnorePatterns?: string[]; watchDirectory?: string; spawnWith?: SpawnWith; env?: NodeJS.ProcessEnv; diff --git a/types/forge-apis/README.md b/types/forge-apis/README.md new file mode 100644 index 0000000000..9da41d3d61 --- /dev/null +++ b/types/forge-apis/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/forge-apis` + +# Summary +This package contains type definitions for Forge Node.js SDK (https://github.com/Autodesk-Forge/forge-api-nodejs-client). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/forge-apis + +Additional Details + * Last updated: Fri, 11 Jan 2019 10:39:13 GMT + * Dependencies: @types/three + * Global values: none + +# Credits +
Forge Partner Development diff --git a/types/forge-apis/forge-apis-tests.ts b/types/forge-apis/forge-apis-tests.ts new file mode 100644 index 0000000000..d7031facb9 --- /dev/null +++ b/types/forge-apis/forge-apis-tests.ts @@ -0,0 +1,13 @@ +import { AuthClientTwoLegged, AuthClientThreeLegged, BucketsApi, HubsApi, FoldersApi, DerivativesApi } from 'forge-apis'; + +const authClientTwoLegged: AuthClientTwoLegged = new AuthClientTwoLegged("", "", []); + +const authClientThreeLegged: AuthClientThreeLegged = new AuthClientThreeLegged("", "", "", []); + +const bucketsApi: BucketsApi = new BucketsApi(); + +const hubsApi: HubsApi = new HubsApi(); + +const foldersApi: FoldersApi = new FoldersApi(); + +const derivativesApi: DerivativesApi = new DerivativesApi(); diff --git a/types/forge-apis/index.d.ts b/types/forge-apis/index.d.ts new file mode 100644 index 0000000000..07dca58812 --- /dev/null +++ b/types/forge-apis/index.d.ts @@ -0,0 +1,193 @@ +// Type definitions for Forge-apis 0.4 +// Project: https://github.com/Autodesk-Forge/forge-api-nodejs-client +// Definitions by: Autodesk Forge Partner Development +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +// Copyright (c) Autodesk, Inc. All rights reserved +// +// Permission to use, copy, modify, and distribute this software in +// object code form for any purpose and without fee is hereby granted, +// provided that the above copyright notice appears in all copies and +// that both that copyright notice and the limited warranty and +// restricted rights notice below appear in all supporting +// documentation. +// +// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. +// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF +// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. +// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE +// UNINTERRUPTED OR ERROR FREE. +// + +export class AuthClientTwoLegged { + constructor(clientId: string, clientSecret: string, scope: string[]); + + authenticate(): Promise; + getCredentials(): AuthToken; + setCredentials(credentials: AuthToken): void; + isAuthorized(): boolean; +} + +export class AuthClientThreeLegged { + constructor(clientId: string, clientSecret: string, redirectUri: string, scope: string[]); + + generateAuthUrl(): string; + getToken(code: string): Promise; + refreshToken(credentials: AuthToken): Promise; +} + +export interface ApiResponse { + body: any; + headers: any; + statusCode: number; +} + +export interface ApiError { + statusCode: number; + statusMessage: string; +} + +export class BucketsApi { + constructor(); + + createBucket(postBuckets: object, opts: object, credentials: AuthToken): Promise; + deleteBucket(bucketKey: string, credentials: AuthToken): Promise; + getBucketDetails(bucketKey: string, credentials: AuthToken): Promise; + getBuckets(options: object, credentials: AuthToken): Promise; +} + +export class HubsApi { + constructor(); + + getHub(hubId: string, opts: object, credentials: AuthToken): Promise; + getHubs(opts: object, credentials: AuthToken): Promise; + getHubProjects(hubId: string, opts: object, credentials: AuthToken): Promise; +} + +export class FoldersApi { + constructor(); + + getFolderContents(projectId: string, folderId: string, opts: object, credentials: AuthToken): Promise; +} + +export interface JobPayload { + input: JobPayloadInput; + output: JobPayloadOutput; +} + +export interface JobPayloadInput { + urn: string; + compressedUrn?: boolean; + rootFilename?: string; +} + +export interface JobPayloadOutput { + formats: JobPayloadItem[]; +} + +export interface JobPayloadItem { + type: string; + views?: string[]; + advanced?: { + applicationProtocol: string; + tolerance: number; + }; + format?: string; + exportColor?: boolean; + exportFileStructure?: string; +} + +export class DerivativesApi { + constructor(); + + deleteManifest(urn: string, credentials: AuthToken): Promise; + getDerivativeManifest(urn: string, derivativeUrn: string, opts: object, credentials: AuthToken): Promise; + getFormats(opts: object, credentials: AuthToken): Promise; + getManifest(urn: string, opts: object, credentials: AuthToken): Promise; + getMetadata(urn: string, opts: object, credentials: AuthToken): Promise; + getModelviewMetadata(urn: string, guid: string, opts: object, credentials: AuthToken): Promise; + getModelviewProperties(urn: string, guid: string, opts: object, credentials: AuthToken): Promise; + getThumbnail(urn: string, opts: object, credentials: AuthToken): Promise; + translate(job: JobPayload, opts: { xAdsForce?: boolean }, credentials: AuthToken): Promise; +} + +export interface Credentials { + client_id: string; + client_secret: string; + grant_type: string; + scope?: string; +} + +export interface AuthToken { + access_token: string; + expires_in: number; + token_type: string; + refresh_token?: string; +} + +export namespace Dm { + interface BucketResponse { + bucketKey: string; + bucketOwner: string; + createdDate: number; + permissions: Array<{ + access: string; + authId: string; + }>; + policyKey: string; + } + + interface ItemResponse { + data: any[]; + included: Item[]; + jsonapi: { + version: string; + }; + links: any; + } + + interface Item { + attributes: { + createTime: string; + createUserId: string; + displayName: string; + extension: object; + fileType: string; + lastModifiedTime: string; + lastModifiedUserId: string; + mimeType: string; + name: string; + storageSize: number; + versionNumber: number; + }; + id: string; + links: { + self: { + href: string; + }; + }; + relationships: { + derivatives: { + data: { + id: string; + }, + meta: { + link: { + href: string; + } + } + }, + item: any; + refs: any; + storage: { + data: { + id: string; + type: string; + } + }; + thumbnail: any; + }; + type: string; + } +} diff --git a/types/forge-apis/tsconfig.json b/types/forge-apis/tsconfig.json new file mode 100644 index 0000000000..3e026ae2b1 --- /dev/null +++ b/types/forge-apis/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", + "forge-apis-tests.ts" + ] +} diff --git a/types/forge-apis/tslint.json b/types/forge-apis/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/forge-apis/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/forge-viewer/README.md b/types/forge-viewer/README.md new file mode 100644 index 0000000000..005bd5f19e --- /dev/null +++ b/types/forge-viewer/README.md @@ -0,0 +1,17 @@ +# Installation +> `npm install --save @types/forge-viewer` + +# Summary +This package contains type definitions for Autodesk Forge Viewer.js Library (https://forge.autodesk.com/en/docs/viewer/v6/reference/javascript/viewer3d/). + +# Details +These are for our Model Visualization library Viewer.js which at the moment can only be loaded externally from our CDN via script tags so the library itself is not a NPM package at the moment. + +Additional Details + * Last updated: Wed, 23 Jan 2019 10:39:13 GMT + * Dependencies: @types/three + * Global values: none + +# Credits +- Forge Partner Development +- Alan Smith [@alansmithnbs](https://github.com/alansmithnbs) diff --git a/types/forge-viewer/index.d.ts b/types/forge-viewer/index.d.ts new file mode 100644 index 0000000000..bff0c637a0 --- /dev/null +++ b/types/forge-viewer/index.d.ts @@ -0,0 +1,1149 @@ +// Type definitions for Forge Viewer 6.3 +// Project: https://forge.autodesk.com/en/docs/viewer/v6/reference/javascript/viewer3d/ +// Definitions by: Autodesk Forge Partner Development , Alan Smith +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +// Copyright (c) Autodesk, Inc. All rights reserved +// +// Permission to use, copy, modify, and distribute this software in +// object code form for any purpose and without fee is hereby granted, +// provided that the above copyright notice appears in all copies and +// that both that copyright notice and the limited warranty and +// restricted rights notice below appear in all supporting +// documentation. +// +// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. +// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF +// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. +// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE +// UNINTERRUPTED OR ERROR FREE. +// +/// + +declare namespace Autodesk { + namespace Viewing { + enum ErrorCodes { + UNKNOWN_FAILURE = 1, + BAD_DATA = 2, + NETWORK_FAILURE = 3, + NETWORK_ACCESS_DENIED = 4, + NETWORK_FILE_NOT_FOUND = 5, + NETWORK_SERVER_ERROR = 6, + NETWORK_UNHANDLED_RESPONSE_CODE = 7, + BROWSER_WEBGL_NOT_SUPPORTED = 8, + BAD_DATA_NO_VIEWABLE_CONTENT = 9, + BROWSER_WEBGL_DISABLED = 10, + BAD_DATA_MODEL_IS_EMPTY = 11, + RTC_ERROR = 12, + UNSUPORTED_FILE_EXTENSION = 13, + VIEWER_INTERNAL_ERROR = 14, + } + + enum SelectionMode { + MIXED, + REGULAR, + OVERLAYED, + LEAF_OBJECT, + FIRST_OBJECT, + LAST_OBJECT, + } + + enum ProgressState { + ROOT_LOADED, + LOADING, + RENDERING, + } + + enum KeyCode { + BACKSPACE = 8, + TAB = 9, + ENTER = 13, + SHIFT = 16, + CONTROL = 17, + ALT = 18, + ESCAPE = 27, + SPACE = 32, + PAGEUP = 33, + PAGEDOWN = 34, + END = 35, + HOME = 36, + LEFT = 37, + UP = 38, + RIGHT = 39, + DOWN = 40, + INSERT = 45, + DELETE = 46, + ZERO = 48, + SEMICOLONMOZ = 59, + EQUALSMOZ = 61, + a = 65, + b = 66, + c = 67, + d = 68, + e = 69, + f = 70, + g = 71, + h = 72, + i = 73, + j = 74, + k = 75, + l = 76, + m = 77, + n = 78, + o = 79, + p = 80, + q = 81, + r = 82, + s = 83, + t = 84, + u = 85, + v = 86, + w = 87, + x = 88, + y = 89, + z = 90, + LCOMMAND = 91, + RCOMMAND = 93, + PLUS = 107, + PLUSMOZ = 171, + DASHMOZ = 109, + F1 = 112, + F2 = 113, + F3 = 114, + F4 = 115, + F5 = 116, + F6 = 117, + F7 = 118, + F8 = 119, + F9 = 120, + F10 = 121, + F11 = 122, + F12 = 123, + DASHMOZNEW = 173, + SEMICOLON = 186, + EQUALS = 187, + COMMA = 188, + DASH = 189, + PERIOD = 190, + SLASH = 191, + LBRACKET = 219, + RBRACKET = 221, + SINGLEQUOTE = 222, + COMMANDMOZ = 224, + } + + interface ViewerEvent { + (event: any): void; + } + + interface Viewer3DConfig { + startOnInitialize?: boolean; + theme?: 'dark-theme'|'light-theme'|string; + [key: string]: any; + } + + interface ViewingApplicationOptions { + disableBrowserContextMenu?: boolean; + [key: string]: any; + } + + interface ViewerConfig { + disableBrowserContextMenu?: boolean; + extensions?: string[]; + useConsolidation?: boolean; + consolidationMemoryLimit?: number; + sharedPropertyDbPath?: string; + bubbleNode?: BubbleNode; + canvasConfig?: any; + startOnInitialize?: boolean; + experimental?: any[]; + theme?: 'dark-theme'|'light-theme'|string; + [key: string]: any; + } + + interface ItemSelectedObserver { + onItemSelected(viewer: Viewer3D): void; + } + + interface SelectionVisibility { + hasVisible: boolean; + hasHidden: boolean; + } + + interface ThumbnailOptions { + urn: string; + width: number; + height: number; + guid: string; + acmsession: (string); + } + + interface FileLoaderOptions { + ids?: string; + sharedPropertyDbPath?: string; + [key: string]: any; + } + + interface LoadModelOptions { + fileLoader?: FileLoader; + loadOptions?: object; + sharedPropertyDbPath?: string; + ids?: string; + [key: string]: any; + } + + interface PropertyOptions { + propFilter?: string[]; + ignoreHidden?: boolean; + [key: string]: any; + } + + interface ResizePanelOptions { + dockingPanels?: UI.DockingPanel[]; + viewer?: Viewer3D; + dimensions?: { + width: number; + height: number; + }; + } + + class FileLoader { + constructor(viewer: Viewer3D); + + is3d(): boolean; + loadFile(url: string, options: FileLoaderOptions, onSuccess: () => void, onError: () => void): void; + } + + interface ViewerItem { + children?: ViewerItem[]; + guid: string; + hasThumbnail: boolean; + name: string; + parent: ViewerItem; + progress: string; + role: '3d'|'2d'|string; + size: number; + status: string; + success: string; + type: 'view'|'geometry'|string; + viewableID: string; + } + + interface ExtensionOptions { + defaultModelStructureTitle: string; + extensions: string[]; + startOnInitialize: boolean; + viewableName: string; + [key: string]: any; + } + + const AGGREGATE_SELECTION_CHANGED_EVENT = 'aggregateSelection'; + const ANIMATION_READY_EVENT = 'animationReady'; + const CAMERA_CHANGE_EVENT = 'cameraChanged'; + const CUTPLANES_CHANGE_EVENT = 'cutplanesChanged'; + const ESCAPE_EVENT = 'escape'; + const EXPLODE_CHANGE_EVENT = 'explodeChanged'; + const EXTENSION_LOADED_EVENT = 'extensionLoaded'; + const EXTENSION_UNLOADED_EVENT = 'extensionUnloaded'; + const FINAL_FRAME_RENDERED_CHANGED_EVENT = 'finalFrameRenderedChanged'; + const FIT_TO_VIEW_EVENT = 'fitToView'; + const FRAGMENTS_LOADED_EVENT = 'fragmentsLoaded'; + const FULLSCREEN_MODE_EVENT = 'fullscreenMode'; + const GEOMETRY_LOADED_EVENT = 'geometryLoaded'; + const HIDE_EVENT = 'hide'; + const HYPERLINK_EVENT = 'hyperlink'; + const ISOLATE_EVENT = 'isolate'; + const LAYER_VISIBILITY_CHANGED_EVENT = 'layerVisibilityChanged'; + const LOAD_MISSING_GEOMETRY = 'loadMissingGeometry'; + const MODEL_ROOT_LOADED_EVENT = 'modelRootLoaded'; + const MODEL_UNLOADED_EVENT = 'modelUnloaded'; + const NAVIGATION_MODE_CHANGED_EVENT = 'navigationModeChanged'; + const OBJECT_TREE_CREATED_EVENT = 'objectTreeCreated'; + const OBJECT_TREE_UNAVAILABLE_EVENT = 'objectTreeUnavailable'; + const PREF_CHANGED_EVENT = 'prefChanged'; + const PREF_RESET_EVENT = 'prefReset'; + const PROGRESS_UPDATE_EVENT = 'progressUpdate'; + const RENDER_OPTION_CHANGED_EVENT = 'renderOptionChanged'; + const RENDER_PRESENTED_EVENT = 'renderPresented'; + const RESET_EVENT = 'reset'; + const RESTORE_DEFAULT_SETTINGS_EVENT = 'restoreDefaultSettings'; + const SELECTION_CHANGED_EVENT = 'selection'; + const SHOW_EVENT = 'show'; + const TEXTURES_LOADED_EVENT = 'texturesLoaded'; + const TOOL_CHANGE_EVENT = 'toolChanged'; + const TOOLBAR_CREATED_EVENT = 'toolbarCreated'; + const VIEWER_INITIALIZED = 'viewerInitialized'; + const VIEWER_RESIZE_EVENT = 'viewerResize'; + const VIEWER_STATE_RESTORED_EVENT = 'viewerStateRestored'; + const VIEWER_UNINITIALIZED = 'viewerUninitialized'; + + interface ViewerEventArgs { + target?: Viewer3D; + model?: ViewerItem; + type: string; + [key: string]: any; + } + + interface BubbleNodeSearchProps { + role?: '3d'|'2d'|string; + type?: 'view'|'geometry'|string; + mime?: string; + } + + class BubbleNode { + static MODEL_NODE: BubbleNodeSearchProps; + static GEOMETRY_SVF_NODE: BubbleNodeSearchProps; + static SHEET_NODE: BubbleNodeSearchProps; + static GEOMETRY_F2D_NODE: BubbleNodeSearchProps; + static VIEWABLE_NODE: BubbleNodeSearchProps; + + parent: BubbleNode; + id: number; + data: ViewerItem; + isLeaf: boolean; + sharedPropertyDbPath: string; + lodNode: object; + children: BubbleNode[]; + + constructor(rawNode: object, parent?: BubbleNode); + + findByGuid(guid: string): BubbleNode; + findParentGeom2Dor3D(): BubbleNode; + findPropertyDbPath(): string; + findViewableParent(): BubbleNode; + getLodNode(): boolean; + getNamedViews(): string[]; + getPlacementTransform(): object; + getRootNode(): BubbleNode; + getTag(tag: string): any; + getViewableRootPath(): string; + guid(): string; + is2D(): boolean; + is2DGeom(): boolean; + is3D(): boolean; + is3DGeom(): boolean; + isGeometry(): boolean; + isGeomLeaf(): boolean; + isMetadata(): boolean; + isViewable(): boolean; + name(): string; + search(propsToMatch: BubbleNodeSearchProps): BubbleNode[]; + searchByTag(tagsToMatch: object): BubbleNode[]; + setTag(tag: string, value: any): void; + traverse(cb: () => void): boolean; + urn(searchParent: boolean): string; + } + + let theExtensionManager: ExtensionManager; + + interface InitializerOptions { + env?: string; + webGLHelpLink?: string; + getAccessToken?(callback?: (accessToken: string, expires: number) => void): void; + refreshToken?(callback?: (accessToken: string, expires: number) => void): void; + language?: string; + accessToken?: string; + useADP?: boolean; + [key: string]: any; + } + + function Initializer(options: InitializerOptions, callback?: () => void): void; + + class Document { + constructor(dataJSON: object, path: string, acmsession: string); + static load(documentId: string, successCallback: (doc: Document) => void, + errorCallback: (errorCode: ErrorCodes, errorMsg: string, messages: any[]) => void, accessControlProperties?: any): void; + static getSubItemsWithProperties(item: object, properties: Properties, recursive: boolean): object[]; + + acmSessionId: string; + + getFullPath(urn: string): string; + getItemById(id: string): object; + getMessages(itemId: string, excludeGlobal: boolean): object; + getNumViews(item: object): number; + getParentId(item: string): string; + getPath(): string; + getPropertyDbPath(): string; + getRoot(): BubbleNode; + getRootItem(): object; + getSubItemsWithProperties(item: object, properties: object, recursive: boolean): object; + getThumbnailOptions(item: object, width: number, height: number): ThumbnailOptions; + getThumbnailPath(item: string, width: number, height: number): string; + getViewableItems(document: Document): void; + getViewablePath(item: object, outLoadOptions?: object): string; + getViewGeometry(item: object): object; + load(documentId: string, onSuccessCallback: () => void, onErrorCallback: () => void, accessControlProperties?: object): void; + requestThumbnailWithSecurity(data: string, onComplete: (err: Error, response: any) => void): void; + } + + class Extension { + viewer: Private.GuiViewer3D; + options: any; + constructor(viewer: Private.GuiViewer3D, options: any); + + load(): boolean; + unload(): boolean; + } + + class ExtensionManager { + extensions: { [key: string]: Extension }; + extensionsAsync: { [key: string]: Extension }; + + registerExtension(extensionId: string, extension: object): boolean; + getExtension(extensionId: string): Extension|null; + unregisterExtension(extensionId: string): boolean; + registerExternalExtension(extensionId: string, urlPath: string): boolean; + getExternalPath(extensionId: string): string|null; + unregisterExternalExtension(extensionId: string): boolean; + getRegisteredExtensions(): Array<{ id: string, inMemory: boolean, isAsync: boolean}>; + popuplateOptions(options: any): void; + } + + class InstanceTree { + maxDepth: number; + nodeAccess: InstanceTreeAccess; + numHidden: number; + numOff: number; + objectCount: number; + + enumNodeChildren(node: any, callback: (dbId: number) => void, recursive?: boolean): void; + enumNodeFragments(node: any, callback: (fragId: number) => void, recursive?: boolean): void; + getChildCount(dbId: number): number; + getNodeBox(dbId: number, nodeBox: Float32Array): void; + getNodeParentId(dbId: number): number; + getRootId(): number; + setFlagGlobal(flag: any, value: any): void; + setFlagNode(dbId: number, flag: any, value: any): boolean; + } + + class InstanceTreeAccess { + children: any; + dbIdToIndex: any; + nameSuffixes: any; + names: any; + nodeBoxes: any; + nodes: any; + numNodes: number; + rootId: number; + strings: string[]; + visibleIds: number; + } + + interface InstanceTreeNode { + dbId: number; + name: string; + fragments: number[]; + children: InstanceTreeNode[]; + } + + class Model { + getBoundingBox(): THREE.Box3; + getBulkProperties(dbIds: number[], propFilter?: string[], successCallback?: (r: any) => void, errorCallback?: (err: any) => void): void; + getData(): any; + getFragmentList(): any; + getObjectTree(successCallback?: (result: InstanceTree) => void, errorCallback?: (err: any) => void): void; + getProperties(dbId: number, successCallback?: (r: PropertyResult) => void, errorCallback?: (err: any) => void): void; + getUnitScale(): number; + getUnitString(): number; + + search(text: string, successCallback: (r: number[]) => void, errorCallback?: (err: any) => void, attributeNames?: string[]): void; + clearThemingColors(): void; + + getInstanceTree(): InstanceTree; + visibilityManager: Private.VisibilityManager; + } + + interface PropertyResult { + dbId: number; + externalId?: string; + name?: string; + properties: Property[]; + } + + interface Property { + displayCategory: string; + displayName: string; + displayValue: string; + hidden: boolean; + type: number; + units: string; + } + + class Navigation { + getCamera(): any; + getEyeVector(): THREE.Vector3; + getFovMin(): number; + getFovMax(): number; + getPivotPoint(): THREE.Vector3; + setPivotPoint(pivot: THREE.Vector3): void; + getPosition(): THREE.Vector3; + setPosition(pos: THREE.Vector3): void; + getTarget(): THREE.Vector3; + setTarget(target: THREE.Vector3): void; + getScreenViewport(): ClientRect; + setScreenViewport(viewport: ClientRect): void; + setView(position: THREE.Vector3, target: THREE.Vector3): void; + setCameraUpVector(up: THREE.Vector): void; + } + + interface Properties { + type: string; + role: string; + } + + class ToolController { + activateTool(name: string): boolean; + deactivateTool(name: string): boolean; + registerTool(tool: any): boolean; + deregisterTool(tool: any): boolean; + getToolNames(): string[]; + getActiveToolName(): string; + } + + interface ToolInterface { + getCursor?(): string; + getName(): string; + getNames(): string[]; + register(): void; + deregister(): void; + activate(name: string, viewerApi?: Private.GuiViewer3D): void; + deactivate(name: string): void; + update(): boolean; + handleSingleClick?(event: MouseEvent, button: number): boolean; + handleDoubleClick?(event: MouseEvent, button: number): boolean; + handleSingleTap?(event: Event): boolean; + handleDoubleTap?(event: Event): boolean; + handleKeyDown?(event: KeyboardEvent, keyCode: number): boolean; + handleKeyUp?(event: KeyboardEvent, keyCode: number): boolean; + handleWheelInput?(delta: number): boolean; + handleButtonDown?(event: MouseEvent, button: number): boolean; + handleButtonUp?(event: MouseEvent, button: number): boolean; + handleMouseMove?(event: MouseEvent): boolean; + handleGesture?(event: Event): boolean; + handleBlur?(event: Event): boolean; + handleResize?(): void; + } + + class UnifiedCamera { + } + + interface ContextMenuCallbackStatus { + hasHidden: boolean; + hasSelected: boolean; + hasVisible: boolean; + numSelected: number; + } + + interface ContextMenuItem { + target: () => void; + title: string; + } + + class ScreenMode { + } + + abstract class ScreenModeDelegate { + constructor(viewer: Viewer3D); + + doScreenModeChange(oldMode: ScreenMode, newMode: ScreenMode): void; + fullscreenEventListener(): void; + getEscapeMode(): ScreenMode | undefined; + getMode(): ScreenMode; + getNextMode(): ScreenMode | undefined; + isModeSupported(mode: ScreenMode): boolean; + onScreenModeChanged(oldMode: ScreenMode, newMode: ScreenMode): void; + setMode(mode: ScreenMode): boolean; + uninitialize(): void; + } + + class AppScreenModeDelegate extends ScreenModeDelegate { + constructor(viewer: Viewer3D); + } + + class NullScreenModeDelegate extends ScreenModeDelegate { + constructor(viewer: Viewer3D); + } + + class Viewer3D { + constructor(container: HTMLElement, config?: Viewer3DConfig); + + id: number; + activateLayerState(stateName: string): void; + activateExtension(extensionID: string, mode: string): boolean; + anyLayerHidden(): boolean; + applyCamera(camera: THREE.Camera, fit?: boolean): void; + areAllVisible(): boolean; + clearSelection(): void; + clearThemingColors(model: any): void; + clientToWorld(point: THREE.Vector3): THREE.Vector3; + container: Element; + createViewCube(): void; + deactivateExtension(extensionID: string): boolean; + displayViewCube(display: boolean): void; + displayViewCubeUI(display: boolean): void; + explode(scale: number): void; + finish(): void; + fitToView(objectIds?: number[], model?: Model): boolean; + getActiveNavigationTool(): string; + getAggregateSelection(callback?: () => void): object[]; + getBimWalkToolPopup(): boolean; + getCamera(): any; + getClickConfig(what: string, where: string): string[] | null; + getCutPlanes(): object[]; + getDefaultNavigationToolName(): object; + getDimensions(): object; + getExplodeScale(): number; + getExtensionModes(extensionID: string): string[]; + getFirstPersonToolPopup(): boolean; + getFocalLength(): number; + getFOV(): number; + getVisibleModels(): Model[]; + getHiddenModels(): any[]; // Array; + getHiddenNodes(): any[]; // Array of nodes + getHotkeyManager(): any; + getIsolatedNodes(): number[]; + getLayerStates(): any[]; + getLoadedExtensions(): any[]; + getMemoryInfo(): any; + getNavigationLock(): boolean; + getNavigationLockSettings(): object; + getObjectTree(onSuccessCallback?: () => void, onErrorCallback?: () => void): void; + getProperties(dbid: number, onSuccessCallback?: () => void, onErrorCallback?: () => void): void; + getScreenShot(w?: number, h?: number, cb?: () => void): any; // DOMString + getSelection(): number[]; + getSelectionCount(): number; + getSelectionVisibility(): { hasVisible: boolean, hasHidden: boolean }; + getState(filter?: any): any; + hide(node: number | number[]): void; + hideLines(hide: boolean): void; + hideModel(modelId: number): boolean; + hidePoints(hide: boolean): void; + hideById(node: number): void; + isolate(node: number | number[]): void; + isolateById(dbIds: number | number[]): void; + initialize(): number | ErrorCodes; + initSettings(): void; + isExtensionActive(extensionID: string): boolean; + isExtensionLoaded(extensionID: string): boolean; + isLayerVisible(node: object): boolean; + isNodeVisible(nodeId: number, model?: Model): boolean; + joinLiveReview(sessionId: string): void; + leaveLiveReview(): void; + load(urn: string, sharedPropertyDbPath?: string, onSuccesfullCallback?: () => void, + onErrorCallback?: (errorCode: ErrorCodes, errorMessage: string, statusCode: number, statusText: string) => void): any; + loadModel(urn: string, options?: any, onSuccesfullCallback?: () => void, + onErrorCallback?: (errorCode: ErrorCodes, errorMessage: string, statusCode: number, statusText: string) => void): any; + loadDocumentNode(lmvDocument: Document, bubbleNode: BubbleNode, options?: object): void; + localize(): void; + modelHasTopology(): boolean; + playAnimation(callback?: () => void): void; + registerContextMenuCallback(id: string, callback: (menu: ContextMenuItem[], status: ContextMenuCallbackStatus) => void): void; + resize(): void; + restoreState(state: any, filter?: any, immediate?: boolean): boolean; + search(text: string, successCallback: (r: number[]) => void, errorCallback: (err: any) => void, attributeNames?: string[]): void; + select(dbIds: number | number[]): void; + setActiveNavigationTool(toolName?: string): boolean; + setBackgroundColor(red: number, green: number, blue: number, red2: number, green2: number, blue2: number): void; + setBimWalkToolPopup(value: boolean): void; + setCanvasClickBehavior(config: object): void; + setClickConfig(what: string, where: string, newAction: string|string[]): boolean; + setClickToSetCOI(state: boolean, updatePrefs?: boolean): void; + setContextMenu(contextMenu: any): void; // ObjectContextMenu) + setCutPlanes(planes: THREE.Vector4[]): void; + setDefaultContextMenu(): boolean; + setDefaultNavigationTool(toolName: string): void; + setDisplayEdges(show: boolean): void; + setEnvMapBackground(value: boolean): void; + setFirstPersonToolPopup(value: boolean): void; + setFocalLength(mm: number): void; + setFOV(degrees: number): void; + setGhosting(value: boolean): void; + setGrayscale(value: boolean): void; + setGroundReflection(value: boolean): void; + setGroundReflectionAlpha(alpha: number): void; + setGroundReflectionColor(color: THREE.Color): void; + setGroundShadow(value: boolean): void; + setGroundShadowAlpha(alpha: number): void; + setGroundShadowColor(color: THREE.Color): void; + setLayerVisible(nodes: any[], visible: boolean, isolate?: boolean): void; + setLightPreset(index: number): void; + setModelUnits(model: Model): void; + setNavigationLock(value: boolean): void; + setNavigationLockSettings(settings: { [key: string]: boolean }): void; + setOptimizeNavigation(value: boolean): void; + setOrbitPastWorldPoles(value: boolean): void; + setProgressiveRendering(value: boolean): void; + setQualityLevel(useSAO: boolean, useFXAA: boolean): void; + setRenderCache(value: boolean): void; + setReverseHorizontalLookDirection(value: boolean): void; + setReverseVerticalLookDirection(value: boolean): void; + setReverseZoomDirection(value: boolean): void; + setSelectionColor(color: THREE.Color, selectionType: SelectionMode): void; + setSelectionMode(mode: SelectionMode): void; + setSwapBlackAndWhite(value: boolean): void; + setTheme(name: 'dark-theme'|'light-theme'|string): void; + setThemingColor(dbId: number, color: THREE.Vector4, model?: any): void; + setUp(config?: any): void; + setUseLeftHandedInput(value: boolean): void; + setUsePivotAlways(value: boolean): void; + setViewCube(face: string): void; + setViewFromArray(params: any[]): void; + setViewFromFile(): void; + setViewFromViewBox(viewbox: any[], name?: string): void; + setZoomTowardsPivot(value: boolean): void; + show(node: number | number[]): void; + showAll(): void; + showModel(modelId: number): boolean; + start(url?: string, options?: LoadModelOptions, + onSuccessCallback?: () => void, + onErrorCallback?: () => void): number|ErrorCodes; + tearDown(): void; + toggleSelect(dbid: number, selectionType: SelectionMode): void; + toggleVisibility(node: number): void; + toolbar: UI.ToolBar; + trackADPSettingsOptions(): void; + transferModel(): void; + uninitialize(): void; + unregisterContextMenuCallback(id: string): void; + worldToClient(point: THREE.Vector3): THREE.Vector3; + + addEventListener(type: string, + listener?: ViewerEvent, + options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, + listener?: ViewerEvent, + options?: boolean | EventListenerOptions): void; + } + + class ViewingApplication { + k3D: '3D'; + bubble: BubbleNode; + appContainerId: string; + container: HTMLElement; + options: ViewingApplicationOptions; + myRegisteredViewers: any; + myDocument: Document; + myCurrentViewer: Viewer3D; + urn: string; + selectedItem: ViewerItem|null; + extensionCache: object; + + constructor(containerId: string, options?: ViewingApplicationOptions); + + addItemSelectedObserver(observer: ItemSelectedObserver): void; + finish(): void; + getCurrentViewer(): Viewer3D; + getDefaultGeometry(geometryItems: any[]): object; + getNamedViews(item: object): any[]; + getSelectedItem(): object|null; + getViewer(config: Viewer3DConfig): Viewer3D; + getViewerContainer(): HTMLElement; + loadDocument(documentId: any, + onDocumentLoad?: (document: Document) => void, + onLoadFailed?: (errorCode: string, errorMsg: string, errors: any[]) => void, + accessControlProperties?: object): void; + registerViewer(viewableType: string, viewerClass: any, config?: ViewerConfig): void; + selectItem(item: ViewerItem|BubbleNode, + onSuccessCallback: (viewer: Viewer3D, item: ViewerItem) => void, + onErrorCallback: (errorCode: ErrorCodes, errorMsg: string, + statusCode: string, statusText: string, messages: string) => void): boolean; + selectItemById(itemId: number, + onItemSelectedCallback: (item: object, viewGeometryItem: object) => void, + onItemFailedToSelectCallback: () => void): boolean; + setCurrentViewer(viewer: Viewer3D): void; + setDocument(docManifest: object): boolean; + } + + class ViewingUtilities { + getHitPoint(x: number, y: number): THREE.Vector3; + } + + namespace Private { + function getHtmlTemplate(url: string, callback: (error: string, content: string) => void): void; + + const env: string; + + function formatValueWithUnits(value: number, units: string, type: number, precision: number): string; + function convertUnits(fromUnits: string, toUnits: string, calibrationFactor: number, + d: number, type: string): number; + function calculatePrecision(value: string|number): number; + + interface PreferencesOptions { + localStorage?: boolean; + prefix?: string; + } + + class Preferences { + constructor(viewer: Viewer3D, options: PreferencesOptions); + + add(name: string, defaultValue: any, tags?: string[]|string): boolean; + addListeners(name: string, onChangedCallback: () => void, onResetCallback: () => void): void; + get(): any; + hasTag(name: string, tag: string): boolean; + load(defaultValues: object): void; + remove(name: string, removeFromWebStorage?: boolean): boolean; + removeListeners(name: string): void; + reset(tag?: string, include?: boolean): void; + set(name: string, value: any, notify?: boolean): boolean; + tag(tag: string, names?: string[]|string): void; + untag(tag: string, names?: string[]|string): void; + } + + class ViewerState { + constructor(viewer: Viewer3D); + + areEqual(viewerStateA: object, viewerStateB: object, filter?: object): boolean; + getSeedUrn(): string; + getState(filter?: object): object; + restoreState(viewerState: object, filter?: object, immediate?: boolean): boolean; + } + + class GuiViewer3D extends Viewer3D { + canvas: HTMLCanvasElement; + + toolController: ToolController; + impl: Viewer3DImpl; + model: Model; + navigation: Navigation; + + addPanel(panel: UI.PropertyPanel): boolean; + getToolbar(create: boolean): UI.ToolBar; + removePanel(panel: UI.PropertyPanel): boolean; + resizePanels(options?: ResizePanelOptions): void; + setLayersPanel(layersPanel: UI.LayersPanel): boolean; + setModelStructurePanel(modelStructurePanel: UI.ModelStructurePanel): boolean; + setPropertyPanel(propertyPanel: UI.PropertyPanel): boolean; + setSettingsPanel(settingsPanel: UI.SettingsPanel): boolean; + updateToolbarButtons(): void; + } + + interface HitTestResult { + dbId: number; + face: THREE.Face3; + fragId: number; + intersectPoint: THREE.Vector3; + model: Model; + } + + namespace HudMessage { + function displayMessage(container: Element, messageSpec: { + msgTitleKey: string, + msgTitleDefault?: string, + messageKey: string, + messageDefaultValue?: string, + buttonText?: string, + checkboxChecked?: boolean + }, closeCallback?: (event: any) => void, buttonCallback?: (event: any) => void, checkboxCallback?: (event: any) => void): void; + + function dismiss(): boolean; + } + + class Viewer3DImpl { + constructor(thecanvas: any, theapi: any); + + visibilityManager: VisibilityManager; + + clientToViewport(clientX: number, clientY: number): THREE.Vector3; + hitTest(clientX: number, clientY: number, ignoreTransparent: boolean): HitTestResult; + hitTestViewport(vpVec: THREE.Vector3, ignoreTransparent: boolean): HitTestResult; + initialize(): void; + setLightPreset(index: number, force?: boolean): void; + viewportToClient(viewportX: number, viewportY: number): THREE.Vector3; + + getMaterials(): any; + getRenderProxy(model: Model, fragId: number): any; + sceneUpdated(param: boolean): void; + } + + class VisibilityManager { + constructor(viewerImpl: any, model: any); + + getHiddenNodes(): any; + getInstanceTree(): InstanceTree; + getIsolatedNodes(): any; + hide(node: number | object): void; + isNodeVisible(dbId: number): boolean; + isolate(node: number | object): void; + isolateMultiple(nodeList: any[]): void; + isolateNone(): void; + setAllVisibility(visible: boolean): void; + setVisibilityOnNode(node: number | object, visible: boolean): void; + setNodeOff(node: number | object, isOff: boolean): void; + show(node: number | object): void; + toggleVisibility(node: number | object): void; + updateNodeVisibilityTracking(node: number | object, visible: boolean): void; + } + } + + namespace UI { + interface DockingPanelOptions { + localizeTitle?: boolean; + [key: string]: any; + } + + interface ScrollContainerOptions { + left: boolean; + heightAdjustment: number; + marginTop: number; + [key: string]: any; + } + + interface ContentSize { + height: number; + width: number; + } + + interface ResizeOptions { + maxHeight: number; + [key: string]: any; + } + + interface AddPropertyOptions { + localizeCategory: boolean; + localizeProperty: boolean; + [key: string]: any; + } + + interface ControlOptions { + collapsible?: boolean; + [key: string]: any; + } + + interface AddControlOptions { + index?: object; + [key: string]: any; + } + + interface DisplayCategoryOptions { + localize?: boolean; + [key: string]: any; + } + + interface MenuItem { + title: string; + target: () => void | MenuItem[]; + } + + const COLLAPSED_CHANGED = 'Control.VisibilityChanged'; + const VISIBILITY_CHANGED = 'Control.CollapsedChanged'; + const CONTROL_ADDED = 'ControlGroup.ControlAdded'; + const CONTROL_REMOVED = 'ControlGroup.ControlRemoved'; + const SIZE_CHANGED = 'ControlGroup.SizeChanged'; + + class DockingPanel { + constructor(parentContainer: HTMLElement, id: string, title: string, options?: DockingPanelOptions); + + closer: HTMLElement; + container: HTMLElement; + content: Node; + title: HTMLElement; + titleLabel: string; + + addEventListener(target: object, eventId: string, callback: () => void): void; + addVisibilityListener(callback: () => void): void; + createCloseButton(): HTMLElement; + createScrollContainer(options: ScrollContainerOptions): void; + createTitleBar(title: string): HTMLElement; + getContainerBoundingRect(): ClientRect; + getContentSize(): ContentSize; + initialize(): void; + initializeCloseHandler(closer: HTMLElement): void; + initializeMoveHandlers(mover: HTMLElement): void; + isVisible(): boolean; + onEndMove(event: MouseEvent, endX: number, endY: number): void; + onMove(event: MouseEvent, currentX: number, currentY: number): void; + onStartMove(event: MouseEvent, startX: number, startY: number): void; + onTitleClick(event: Event): void; + onTitleDoubleClick(event: Event): void; + removeEventListener(target: object, eventId: string, callback: () => void): boolean; + resizeToContent(options: ResizeOptions): void; + setTitle(text: string, options: DockingPanelOptions): void; + setVisible(show: boolean): void; + uninitialize(): void; + visibilityChanged(): void; + } + + class LayersPanel extends DockingPanel { + build(): void; + createNode(node: object, parent: HTMLElement): void; + getNodeClass(node: object): string; + getNodeLabel(node: object): string; + isGroupCollapsed(node: object): boolean; + isGroupNode(node: object): boolean; + onClick(node: object, event: Event): void; + onDoubleClick(node: object, event: Event): void; + onIconClick(node: object, event: Event): void; + onImageClick(node: object, event: Event): void; + onRightClick(node: object, event: Event): void; + setGroupCollapsed(node: object, collapse: boolean): void; + setLayerVisible(node: object, collapse: boolean): void; + shouldInclude(node: object): boolean; + update(): void; + } + + class PropertyPanel extends DockingPanel { + addProperty(name: string, value: string, category: string, options?: AddPropertyOptions): boolean; + areDefaultPropertiesShown(): void; + displayCategory(category: object, parent: HTMLElement, options: DisplayCategoryOptions): HTMLElement[]; + displayProperty(property: object, parent: HTMLElement, options: DisplayCategoryOptions): HTMLElement[]; + getCategoryClass(category: object): string; + getPropertyClass(property: object): string; + hasProperties(): boolean; + highlight(text: string, options: object): void; + isCategoryCollapsed(category: object): boolean; + onCategoryClick(category: object, event: Event): void; + onCategoryDoubleClick(category: object, event: Event): void; + onCategoryIconClick(category: object, event: Event): void; + onCategoryRightClick(category: object, event: Event): void; + onPropertyClick(property: object, event: Event): void; + onPropertyDoubleClick(property: object, event: Event): void; + onPropertyIconClick(property: object, event: Event): void; + onPropertyRightClick(property: object, event: Event): void; + removeAllProperties(): void; + removeProperty(name: string, value: string, category: string, options?: object): boolean; + setCategoryCollapsed(category: object, collapsed: boolean): void; + setProperties(properties: Array<{displayName: string, displayValue: any}>, options?: object): void; + showDefaultProperties(): void; + showNoProperties(): void; + } + + class SettingsPanel extends DockingPanel { + addCheckbox(tabId: string, caption: string, initialState: boolean, + onchange: () => void, options?: object): string; + addControl(tabId: string, control: object|HTMLElement, options: object|undefined): string; + addDropDownMenu(tabId: string, caption: string, items: MenuItem[], + initialItemIndex: number, onchange: () => void, options: object|undefined): string; + addSlider(tabId: string, caption: string, min: number, max: number, initialValue: number, + onchange: () => void, options: object|undefined): string; + addTab(tabId: string, tabTitle: string, options: object|undefined): boolean; + getControl(controlId: string): object; + hasTab(tabId: string): boolean; + isTabSelected(tabId: string): boolean; + removeCheckbox(checkboxId: string|Control): boolean; + removeControl(controlId: string|Control): boolean; + removeDropdownMenu(dropdownMenuId: string|Control): boolean; + removeSlider(sliderId: string|Control): boolean; + removeTab(tabId: string): boolean; + selectTab(tabId: string): boolean; + setVisible(show: boolean, skipTransition?: boolean): void; + } + + class ModelStructurePanel extends DockingPanel { + addClass(id: string, className: string): boolean; + getNodeClass(node: object): string; + getNodeLabel(node: object): string; + isGroupCollapsed(node: object): boolean; + isGroupNode(node: object): boolean; + onClick(node: object, event: Event): void; + onDoubleClick(node: object, event: Event): void; + onHover(node: object, event: Event): void; + onIconClick(node: object, event: Event): void; + onRightClick(node: object, event: Event): void; + removeClass(id: string, className: string): boolean; + setGroupCollapsed(node: object, collapsed: boolean): void; + setModel(instanceTree: object, modelTitle: string): void; // InstanceTree? + setSelection(nodes: Model[]): void; + shouldInclude(node: Model): boolean; + } + + class ObjectContextMenu { + constructor(viewer: Viewer3D); + + buildMenu(event: Event, status: object): MenuItem[]; + hide(): boolean; + show(event: Event): void; + } + + class ControlEventArgs { + VISIBILITY_CHANGED: 'Control.VisibilityChanged'; + COLLAPSED_CHANGED: 'Control.CollapsedChanged'; + ACTIVE_BUTTON_CHANGED: 'RadioButtonGroup.ActiveButtonChanged'; + STATE_CHANGED: 'Button.StateChanged'; + CLICK: 'click'; + } + + class Control { + constructor(id?: string, options?: ControlOptions); + + Event: ControlEventArgs; + addClass(cssClass: string): void; + getDimensions(): object; + getId(): string; + getPosition(): object; + getToolTip(): string; + isCollapsed(): boolean; + isCollapsible(): boolean; + isVisible(): boolean; + removeClass(cssClass: string): void; + setCollapsed(collapsed: boolean): boolean; + setToolTip(toolTipText: string): boolean; + setVisible(visible: boolean): boolean; + + // Events + addEventListener(type: string, + listener?: ViewerEvent, + options?: boolean | AddEventListenerOptions): void; + dispatchEvent(evt: Event): boolean; + removeEventListener(type: string, + listener?: ViewerEvent, + options?: boolean | EventListenerOptions): void; + } + + class ControlGroup extends Control { + container: HTMLElement; + + addControl(control: Control, options?: AddControlOptions): boolean; + getControl(controlId: string): Control; + getControlId(index: number): string; + getNumberOfControls(): number; + indexOf(control: string|Control): number; + removeControl(control: string|Control): boolean; + setCollapsed(collapsed: boolean): boolean; + } + + class ToolBar extends ControlGroup { + constructor(id: string, options?: object); + } + + class RadioButtonGroup extends ControlGroup { + constructor(id: string, options?: object); + + Event: ControlEventArgs; + + addControl(control: Control, options: object): boolean; + getActiveButton(): Button; + removeControl(control: string | Control): boolean; + } + + enum ControlStates { + ACTIVE = 0, + INACTIVE = 1, + DISABLED = 2 + } + + class Button extends Control { + constructor(id: string, options?: object); + + State: ControlStates; + Event: ControlEventArgs; + + getState(): ControlStates; + onClick: (event: Event) => void; + onMouseOut: (event: Event) => void; + onMouseOver: (event: Event) => void; + setIcon(iconClass: string): void; + setState(state: ControlStates): boolean; + } + + class ComboButton extends Button { + constructor(id: string, options?: object); + + addControl(): void; + restoreDefault(): void; + saveAsDefault(): void; + } + } + } +} diff --git a/types/forge-viewer/tsconfig.json b/types/forge-viewer/tsconfig.json new file mode 100644 index 0000000000..fe1ad377b9 --- /dev/null +++ b/types/forge-viewer/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" + ] +} diff --git a/types/forge-viewer/tslint.json b/types/forge-viewer/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/forge-viewer/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/frisby/frisby-tests.ts b/types/frisby/frisby-tests.ts index d0bb27ff20..65a7315790 100644 --- a/types/frisby/frisby-tests.ts +++ b/types/frisby/frisby-tests.ts @@ -18,4 +18,9 @@ describe('Test Suite 1', () => { .expect('status', 418) .done(done); }); + + it('should handle jest matchers', () => { + const str = 'bar'; + expect(str).toHaveLength(3); + }); }); diff --git a/types/frisby/index.d.ts b/types/frisby/index.d.ts index 1bcd6fdabb..3d132bdc91 100644 --- a/types/frisby/index.d.ts +++ b/types/frisby/index.d.ts @@ -3,9 +3,9 @@ // Definitions by: Christopher E. Woodland // Johnny Li // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 -/// +/// // #region Imports export import nodeFetch = require('node-fetch'); // Import all definitions from node-fetch. diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index bd40ce9650..6db3755cc7 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -101,6 +101,16 @@ declare namespace gapi.auth2 { * Optional if fetch_basic_profile is not set to false. */ scope?: string; + /** + * The UX mode to use for the sign-in flow. + * By default, it will open the consent flow in a popup. + */ + ux_mode?: "popup" | "redirect"; + /** + * If using ux_mode='redirect', this parameter allows you to override the default redirect_uri that will be used at the end of the consent flow. + * The default redirect_uri is the current URL stripped of query parameters and hash fragment. + */ + redirect_uri?: string; } /** diff --git a/types/gapi.client.drive/index.d.ts b/types/gapi.client.drive/index.d.ts index 1b2a939a7d..ca28f228e7 100644 --- a/types/gapi.client.drive/index.d.ts +++ b/types/gapi.client.drive/index.d.ts @@ -1042,6 +1042,8 @@ declare namespace gapi.client { }): Request; /** Creates a new file. */ create(request: { + /** Resource Parameter for folder creation */ + resource?: any; /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 4b8a69aa93..28590def30 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -34,7 +34,7 @@ const opts = { priorityRange: 5, autostart: false, evictionRunIntervalMillis: 200, - numTestsPerRun: 3, + numTestsPerEvictionRun: 3, softIdleTimeoutMillis: 100, idleTimeoutMillis: 5000 }; diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index 80a3c0e9df..6bb537e9ba 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -43,7 +43,7 @@ export interface Options { priorityRange?: number; autostart?: boolean; evictionRunIntervalMillis?: number; - numTestsPerRun?: number; + numTestsPerEvictionRun?: number; softIdleTimeoutMillis?: number; idleTimeoutMillis?: number; } diff --git a/types/geojson/geojson-tests.ts b/types/geojson/geojson-tests.ts index 4ea0f57a6f..82787c8c36 100644 --- a/types/geojson/geojson-tests.ts +++ b/types/geojson/geojson-tests.ts @@ -1,10 +1,10 @@ import { - BBox, Feature, FeatureCollection, GeometryCollection, LineString, - MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, GeometryObject + MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, GeoJsonGeometryTypes, + GeoJsonTypes, GeometryObject } from "geojson"; -let featureCollection: FeatureCollection = { +let featureCollection: FeatureCollection = { type: "FeatureCollection", features: [ { @@ -53,6 +53,17 @@ let featureCollection: FeatureCollection = { type: "Feature", bbox: [-180.0, -90.0, 180.0, 90.0], @@ -65,6 +76,11 @@ const featureWithPolygon: Feature = { properties: null }; +featureWithPolygon.type; // $ExpectType "Feature" +featureWithPolygon.geometry; // $ExpectType Polygon +featureWithPolygon.geometry.type; // $ExpectType "Polygon" +featureWithPolygon.geometry.coordinates; // $ExpectType number[][][] + const point: Point = { type: "Point", coordinates: [100.0, 0.0] @@ -135,6 +151,8 @@ let feature: Feature = { properties: null }; +feature.properties; // $ExpectType GeoJsonProperties + feature = { type: "Feature", geometry: polygon, @@ -275,12 +293,16 @@ const featureGeometryNull: Feature = { geometry: null }; +featureGeometryNull.properties.foo; // $ExpectType "bar" | "baz" + const featureNoNull: Feature = { type: "Feature", properties: testProps, geometry: point }; +featureNoNull.geometry.type; // $ExpectType "Point" + const collectionAllNull: FeatureCollection = { type: "FeatureCollection", features: [featureAllNull], @@ -301,6 +323,8 @@ const collectionGeometryMaybeNull: FeatureCollection features: [featureGeometryNull, featureNoNull], }; +collectionGeometryMaybeNull.features[0].geometry; // $ExpectType Point | null + const collectionNoNull: FeatureCollection = { type: "FeatureCollection", features: [featureNoNull], @@ -311,6 +335,9 @@ const collectionDefault: FeatureCollection = { features: [] }; +collectionDefault.features[0].geometry; // $ExpectType Geometry +collectionDefault.features[0].properties!.foo; // $ExpectType any + isNull = featureAllNull.geometry; isPoint = featurePropertyNull.geometry; isNull = featureAllNull.properties; diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index 93f66d3f27..db8074e242 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -4,6 +4,7 @@ // Arne Schubert // Jeff Jacobson // Ilia Choly +// Dan Vanderkam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -16,14 +17,13 @@ export as namespace GeoJSON; * The valid values for the "type" property of GeoJSON geometry objects. * https://tools.ietf.org/html/rfc7946#section-1.4 */ -export type GeoJsonGeometryTypes = "Point" | "LineString" | "MultiPoint" | "Polygon" | "MultiLineString" | - "MultiPolygon" | "GeometryCollection"; +export type GeoJsonGeometryTypes = Geometry['type']; /** * The value values for the "type" property of GeoJSON Objects. * https://tools.ietf.org/html/rfc7946#section-1.4 */ -export type GeoJsonTypes = "FeatureCollection" | "Feature" | GeoJsonGeometryTypes; +export type GeoJsonTypes = GeoJSON['type']; /** * Bounding box @@ -58,6 +58,10 @@ export interface GeoJsonObject { type: GeoJsonTypes; /** * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. + * The value of the bbox member is an array of length 2*n where n is the number of dimensions + * represented in the contained geometries, with all axes of the most southwesterly point + * followed by all axes of the more northeasterly point. + * The axes order of a bbox follows the axes order of geometries. * https://tools.ietf.org/html/rfc7946#section-5 */ bbox?: BBox; @@ -69,24 +73,17 @@ export interface GeoJsonObject { export type GeoJSON = Geometry | Feature | FeatureCollection; /** - * A geometry object. - * https://tools.ietf.org/html/rfc7946#section-3 - */ -export interface GeometryObject extends GeoJsonObject { - type: GeoJsonGeometryTypes; -} - -/** - * Union of geometry objects. + * Geometry object. * https://tools.ietf.org/html/rfc7946#section-3 */ export type Geometry = Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon | GeometryCollection; +export type GeometryObject = Geometry; /** * Point geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.2 */ -export interface Point extends GeometryObject { +export interface Point extends GeoJsonObject { type: "Point"; coordinates: Position; } @@ -95,7 +92,7 @@ export interface Point extends GeometryObject { * MultiPoint geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.3 */ -export interface MultiPoint extends GeometryObject { +export interface MultiPoint extends GeoJsonObject { type: "MultiPoint"; coordinates: Position[]; } @@ -104,7 +101,7 @@ export interface MultiPoint extends GeometryObject { * LineString geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.4 */ -export interface LineString extends GeometryObject { +export interface LineString extends GeoJsonObject { type: "LineString"; coordinates: Position[]; } @@ -113,7 +110,7 @@ export interface LineString extends GeometryObject { * MultiLineString geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.5 */ -export interface MultiLineString extends GeometryObject { +export interface MultiLineString extends GeoJsonObject { type: "MultiLineString"; coordinates: Position[][]; } @@ -122,7 +119,7 @@ export interface MultiLineString extends GeometryObject { * Polygon geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.6 */ -export interface Polygon extends GeometryObject { +export interface Polygon extends GeoJsonObject { type: "Polygon"; coordinates: Position[][]; } @@ -131,7 +128,7 @@ export interface Polygon extends GeometryObject { * MultiPolygon geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.7 */ -export interface MultiPolygon extends GeometryObject { +export interface MultiPolygon extends GeoJsonObject { type: "MultiPolygon"; coordinates: Position[][][]; } @@ -140,7 +137,7 @@ export interface MultiPolygon extends GeometryObject { * Geometry Collection * https://tools.ietf.org/html/rfc7946#section-3.1.8 */ -export interface GeometryCollection extends GeometryObject { +export interface GeometryCollection extends GeoJsonObject { type: "GeometryCollection"; geometries: Geometry[]; } @@ -151,7 +148,7 @@ export type GeoJsonProperties = { [name: string]: any; } | null; * A feature object which contains a geometry and associated properties. * https://tools.ietf.org/html/rfc7946#section-3.2 */ -export interface Feature extends GeoJsonObject { +export interface Feature extends GeoJsonObject { type: "Feature"; /** * The feature's geometry @@ -172,7 +169,7 @@ export interface Feature extends GeoJsonObject { +export interface FeatureCollection extends GeoJsonObject { type: "FeatureCollection"; features: Array>; } diff --git a/types/gestalt/index.d.ts b/types/gestalt/index.d.ts index 162d61dd52..dd9ff81e41 100644 --- a/types/gestalt/index.d.ts +++ b/types/gestalt/index.d.ts @@ -359,7 +359,15 @@ export type Icons = | "sound" | "speech" | "speech-ellipsis" - | "tag"; + | "tag" + | "terms" + | "text-align-left" + | "text-align-center" + | "text-align-right" + | "twitter" + | "view-type-default" + | "view-type-dense" + | "view-type-list"; export interface IconProps { accessibilityLabel: string; diff --git a/types/gl-matrix/gl-matrix-tests.ts b/types/gl-matrix/gl-matrix-tests.ts index 36700536cd..5f165e9ced 100644 --- a/types/gl-matrix/gl-matrix-tests.ts +++ b/types/gl-matrix/gl-matrix-tests.ts @@ -308,6 +308,7 @@ outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1); outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A); +outMat4 = mat4.targetTo(outMat4, vec3A, vec3B, vec3A); outStr = mat4.str(mat4A); outVal = mat4.frob(mat4A); outMat4 = mat4.add(outMat4, mat4A, mat4B); @@ -670,6 +671,7 @@ outMat4 = _mat4.perspective(outMat4, Math.PI, 1, 0, 1); outMat4 = _mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); outMat4 = _mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); outMat4 = _mat4.lookAt(outMat4, vec3A, vec3B, vec3A); +outMat4 = _mat4.targetTo(outMat4, vec3A, vec3B, vec3A); outStr = _mat4.str(mat4A); outVal = _mat4.frob(mat4A); outMat4 = _mat4.add(outMat4, mat4A, mat4B); diff --git a/types/gl-matrix/index.d.ts b/types/gl-matrix/index.d.ts index 8d2d522ddc..750eb73509 100644 --- a/types/gl-matrix/index.d.ts +++ b/types/gl-matrix/index.d.ts @@ -2662,6 +2662,17 @@ declare module 'gl-matrix' { */ public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; + /** + * Generates a matrix that makes something look at something else. + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param target Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + public static targetTo(out: mat4, eye: vec3 | number[], target: vec3 | number[], up: vec3 | number[]): mat4; + /** * Returns a string representation of a mat4 * diff --git a/types/google-apps-script/google-apps-script.base.d.ts b/types/google-apps-script/google-apps-script.base.d.ts index 0b5236af0f..9f7153a6bb 100644 --- a/types/google-apps-script/google-apps-script.base.d.ts +++ b/types/google-apps-script/google-apps-script.base.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-12-26 +// Type definitions for Google Apps Script 2019-01-23 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -284,15 +284,13 @@ declare namespace GoogleAppsScript { * // A simple INFO log message, using sprintf() formatting. * console.info('Timing the %s function (%d arguments)', 'myFunction', 1); * - * // Log a JSON object at a DEBUG level. The log is labeled - * // with the message string in the log viewer, and the JSON content - * // is displayed in the expanded log structure under "structPayload". + * // Log a JSON object at a DEBUG level. Writes the stringified object to the log. * var parameters = { * isValid: true, * content: 'some string', * timestamp: new Date() * }; - * console.log({message: 'Function Input', initialData: parameters}); + * console.log(parameters); * * var label = 'myFunction() time'; // Labels the timing log entry. * console.time(label); // Starts the timer. @@ -326,4 +324,3 @@ declare var Logger: GoogleAppsScript.Base.Logger; // conflicts with MimeType in lib.d.ts // declare var MimeType: GoogleAppsScript.Base.MimeType; declare var Session: GoogleAppsScript.Base.Session; -declare var console: GoogleAppsScript.Base.console; diff --git a/types/google-apps-script/google-apps-script.cache.d.ts b/types/google-apps-script/google-apps-script.cache.d.ts index 7056dc0b08..c1e72c3f64 100644 --- a/types/google-apps-script/google-apps-script.cache.d.ts +++ b/types/google-apps-script/google-apps-script.cache.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2019-01-23 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -44,6 +44,9 @@ declare namespace GoogleAppsScript { * This class lets you get a specific cache instance. Public caches are for things that are not * dependent on which user is accessing your script. Private caches are for things which are * user-specific, like settings or recent activity. + * + * The data you write to the cache is not guaranteed to persist until its expiration time. You + * must be prepared to get back null from all reads. */ export interface CacheService { getDocumentCache(): Cache; diff --git a/types/google-apps-script/google-apps-script.data-studio.d.ts b/types/google-apps-script/google-apps-script.data-studio.d.ts index d4c9d15cde..332dff6dbc 100644 --- a/types/google-apps-script/google-apps-script.data-studio.d.ts +++ b/types/google-apps-script/google-apps-script.data-studio.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2019-01-06 +// Type definitions for Google Apps Script 2019-01-23 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,6 +12,11 @@ declare namespace GoogleAppsScript { */ export enum AggregationType { NO_AGGREGATION, AVG, COUNT, COUNT_DISTINCT, MAX, MIN, SUM } + /** + * An enum that defines the authentication types that can be set for a connector. + */ + export enum AuthType { NONE, OAUTH2, USER_PASS, KEY, USER_TOKEN } + /** * Contains checkbox information for the config. Its properties determine how the checkbox is * displayed in Data Studio. @@ -47,9 +52,11 @@ declare namespace GoogleAppsScript { */ export interface CommunityConnector { AggregationType: typeof AggregationType; + AuthType: typeof AuthType; FieldType: typeof FieldType; getConfig(): Config; getFields(): Fields; + newAuthTypeResponse(): GetAuthTypeResponse; newDebugError(): DebugError; newUserError(): UserError; } @@ -166,6 +173,26 @@ declare namespace GoogleAppsScript { setDefaultMetric(fieldId: string): void; } + /** + * Builder to create a getAuthType() response for your script project. + * + * function getAuthType() { + * var cc = DataStudioApp.createCommunityConnector(); + * var authTypes = cc.AuthType; + * + * return cc.newGetAuthTypeResponse() + * .setAuthType(authTypes.USER_PASS) + * .setHelpUrl("https://www.example.org/connector-auth-help") + * .build(); + * } + */ + export interface GetAuthTypeResponse { + build(): Object; + printJson(): string; + setAuthType(authType: AuthType): GetAuthTypeResponse; + setHelpUrl(helpUrl: string): GetAuthTypeResponse; + } + /** * Contains info data for the config. Its properties determine how the info is displayed in Data * Studio. @@ -174,7 +201,7 @@ declare namespace GoogleAppsScript { * var config = cc.getConfig(); * * var info1 = config.newInfo() - * .setName("info1") + * .setId("info1") * .setText("This text gives some context on the configuration."); */ export interface Info { diff --git a/types/google-apps-script/google-apps-script.sites.d.ts b/types/google-apps-script/google-apps-script.sites.d.ts index b8e7fff5f0..6ca13e808a 100644 --- a/types/google-apps-script/google-apps-script.sites.d.ts +++ b/types/google-apps-script/google-apps-script.sites.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-07-11 +// Type definitions for Google Apps Script 2019-01-23 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -11,7 +11,8 @@ declare namespace GoogleAppsScript { /** * A Sites Attachment such as a file attached to a page. * - * Note that an Attachment is a Blob and can be used anywhere Blob input is expected. A rebuilt + * Note that an Attachment is a Blob and can be used anywhere Blob input is expected. + * A rebuilt * version of Sites was launched on November 22, 2016. Apps Script cannot currently access or * modify Sites made with this version, but script can still access * classic Sites. @@ -44,7 +45,8 @@ declare namespace GoogleAppsScript { } /** - * A typesafe enum for sites attachment type. A rebuilt + * A typesafe enum for sites attachment type. + * A rebuilt * version of Sites was launched on November 22, 2016. Apps Script cannot currently access or * modify Sites made with this version, but script can still access * classic Sites. @@ -52,7 +54,8 @@ declare namespace GoogleAppsScript { export enum AttachmentType { WEB, HOSTED } /** - * A Sites Column - a column from a Sites List page. A rebuilt + * A Sites Column - a column from a Sites List page. + * A rebuilt * version of Sites was launched on November 22, 2016. Apps Script cannot currently access or * modify Sites made with this version, but script can still access * classic Sites. @@ -65,7 +68,8 @@ declare namespace GoogleAppsScript { } /** - * A Comment attached to any Sites page. A rebuilt + * A Comment attached to any Sites page. + * A rebuilt * version of Sites was launched on November 22, 2016. Apps Script cannot currently access or * modify Sites made with this version, but script can still access * classic Sites. @@ -83,7 +87,8 @@ declare namespace GoogleAppsScript { } /** - * A Sites ListItem - a list element from a Sites List page. A rebuilt + * A Sites ListItem - a list element from a Sites List page. + * A rebuilt * version of Sites was launched on November 22, 2016. Apps Script cannot currently access or * modify Sites made with this version, but script can still access * classic Sites. @@ -101,7 +106,8 @@ declare namespace GoogleAppsScript { } /** - * A Page on a Google Site. A rebuilt + * A Page on a Google Site. + * A rebuilt * version of Sites was launched on November 22, 2016. Apps Script cannot currently access or * modify Sites made with this version, but script can still access * classic Sites. @@ -162,7 +168,8 @@ declare namespace GoogleAppsScript { } /** - * A typesafe enum for sites page type. A rebuilt + * A typesafe enum for sites page type. + * A rebuilt * version of Sites was launched on November 22, 2016. Apps Script cannot currently access or * modify Sites made with this version, but script can still access * classic Sites. @@ -170,7 +177,8 @@ declare namespace GoogleAppsScript { export enum PageType { WEB_PAGE, LIST_PAGE, ANNOUNCEMENT, ANNOUNCEMENTS_PAGE, FILE_CABINET_PAGE } /** - * An object representing a Google Site. A rebuilt + * An object representing a Google Site. + * A rebuilt * version of Sites was launched on November 22, 2016. Apps Script cannot currently access or * modify Sites made with this version, but script can still access * classic Sites. @@ -238,7 +246,8 @@ declare namespace GoogleAppsScript { } /** - * Create and access Google Sites. A rebuilt + * Create and access Google Sites. + * A rebuilt * version of Sites was launched on November 22, 2016. Apps Script cannot currently access or * modify Sites made with this version, but script can still access * classic Sites. diff --git a/types/google-apps-script/google-apps-script.spreadsheet.d.ts b/types/google-apps-script/google-apps-script.spreadsheet.d.ts index 76a5bd5f22..d8dc3bc4d0 100644 --- a/types/google-apps-script/google-apps-script.spreadsheet.d.ts +++ b/types/google-apps-script/google-apps-script.spreadsheet.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-12-26 +// Type definitions for Google Apps Script 2019-01-23 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -1254,6 +1254,8 @@ declare namespace GoogleAppsScript { getNumRows(): Integer; getNumberFormat(): string; getNumberFormats(): string[][]; + getRichTextValue(): RichTextValue; + getRichTextValues(): RichTextValue[][]; getRow(): Integer; getRowIndex(): Integer; getSheet(): Sheet; @@ -1261,6 +1263,8 @@ declare namespace GoogleAppsScript { getTextDirections(): TextDirection[][]; getTextRotation(): TextRotation; getTextRotations(): TextRotation[][]; + getTextStyle(): TextStyle; + getTextStyles(): TextStyle[][]; getValue(): Object; getValues(): Object[][]; getVerticalAlignment(): string; @@ -1315,12 +1319,16 @@ declare namespace GoogleAppsScript { setNotes(notes: Object[][]): Range; setNumberFormat(numberFormat: string): Range; setNumberFormats(numberFormats: Object[][]): Range; + setRichTextValue(value: RichTextValue): Range; + setRichTextValues(values: RichTextValue[][]): Range; setShowHyperlink(showHyperlink: boolean): Range; setTextDirection(direction: TextDirection): Range; setTextDirections(directions: TextDirection[][]): Range; setTextRotation(degrees: Integer): Range; setTextRotation(rotation: TextRotation): Range; setTextRotations(rotations: TextRotation[][]): Range; + setTextStyle(style: TextStyle): Range; + setTextStyles(styles: TextStyle[][]): Range; setValue(value: Object): Range; setValues(values: Object[][]): Range; setVerticalAlignment(alignment: string): Range; @@ -1383,6 +1391,34 @@ declare namespace GoogleAppsScript { */ export enum RelativeDate { TODAY, TOMORROW, YESTERDAY, PAST_WEEK, PAST_MONTH, PAST_YEAR } + /** + * A stylized text string used to represent cell text. Substrings of the text can have different + * text styles. + * + * A run is the longest unbroken substring having the same text style. For example, the + * sentence "This kid has two apples." has four runs: ["This ", "kid ", "has two ", + * "apples."]. + */ + export interface RichTextValue { + copy(): RichTextValueBuilder; + getEndIndex(): Integer; + getRuns(): RichTextValue[]; + getStartIndex(): Integer; + getText(): string; + getTextStyle(): TextStyle; + getTextStyle(startOffset: Integer, endOffset: Integer): TextStyle; + } + + /** + * A builder for Rich Text values. + */ + export interface RichTextValueBuilder { + build(): RichTextValue; + setText(text: string): RichTextValueBuilder; + setTextStyle(startOffset: Integer, endOffset: Integer, textStyle: TextStyle): RichTextValueBuilder; + setTextStyle(textStyle: TextStyle): RichTextValueBuilder; + } + /** * Access the current active selection in the active sheet. A selection is the set of cells the user * has highlighted in the sheet, which can be non-adjacent ranges. One cell in the selection is the @@ -1720,6 +1756,8 @@ declare namespace GoogleAppsScript { newConditionalFormatRule(): ConditionalFormatRuleBuilder; newDataValidation(): DataValidationBuilder; newFilterCriteria(): FilterCriteriaBuilder; + newRichTextValue(): RichTextValueBuilder; + newTextStyle(): TextStyleBuilder; open(file: Drive.File): Spreadsheet; openById(id: string): Spreadsheet; openByUrl(url: string): Spreadsheet; @@ -1744,6 +1782,38 @@ declare namespace GoogleAppsScript { isVertical(): boolean; } + /** + * The rendered style of text in a cell. + * + * Text styles can have a corresponding RichTextValue. If the RichTextValue spans multiple text runs that have different values for a given text style read + * method, the method returns null. To avoid this, query for text styles using the Rich Text + * values returned by the RichTextValue.getRuns() method. + */ + export interface TextStyle { + copy(): TextStyleBuilder; + getFontFamily(): string; + getFontSize(): Integer; + getForegroundColor(): string; + isBold(): boolean; + isItalic(): boolean; + isStrikethrough(): boolean; + isUnderline(): boolean; + } + + /** + * A builder for text styles. + */ + export interface TextStyleBuilder { + build(): TextStyle; + setBold(bold: boolean): TextStyleBuilder; + setFontFamily(fontFamily: string): TextStyleBuilder; + setFontSize(fontSize: Integer): TextStyleBuilder; + setForegroundColor(cssString: string): TextStyleBuilder; + setItalic(italic: boolean): TextStyleBuilder; + setStrikethrough(strikethrough: boolean): TextStyleBuilder; + setUnderline(underline: boolean): TextStyleBuilder; + } + /** * An enumeration of the types of preset delimiters that can split a column of text into multiple * columns. diff --git a/types/google-cloud__tasks/google-cloud__tasks-tests.ts b/types/google-cloud__tasks/google-cloud__tasks-tests.ts new file mode 100644 index 0000000000..4539f345ff --- /dev/null +++ b/types/google-cloud__tasks/google-cloud__tasks-tests.ts @@ -0,0 +1,18 @@ +import Tasks, { Queue } from "@google-cloud/tasks"; + +const client = new Tasks({}); + +const formattedParent = client.locationPath("[PROJECT]", "[LOCATION]"); +const queue: Partial = {}; +const request = { + parent: formattedParent, + queue +}; +client + .createQueue(request) + .then(([queue]) => { + const q = queue; + }) + .catch(err => { + console.error(err); + }); diff --git a/types/google-cloud__tasks/index.d.ts b/types/google-cloud__tasks/index.d.ts new file mode 100644 index 0000000000..c3347c8ea4 --- /dev/null +++ b/types/google-cloud__tasks/index.d.ts @@ -0,0 +1,1627 @@ +// Type definitions for @google-cloud/tasks 0.2 +// Project: https://github.com/googleapis/nodejs-tasks +// Definitions by: Ifiok Jr. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.8 + +/// + +import { Transform } from "stream"; +export type GoogleError = any; +export type GoogleAuthOptions = any; +export type CallOptions = any; +export type GoogleAuth = any; + +export interface CloudTasksConfig extends GoogleAuthOptions { + key?: string; + autoRetry?: boolean; + maxRetries?: number; + libName?: string; + libVersion?: string; + promise?: PromiseConstructor; +} + +export interface AppEngineHttpQueue { + appEngineRoutingOverride: AppEngineRouting; +} + +export interface AppEngineHttpRequest { + appEngineRouting: AppEngineRouting; + body: string; + headers: { + [key: string]: string; + }; + httpMethod: string; + relativeUri: string; +} + +export interface AppEngineRouting { + host: string; + instance: string; + service: string; + version: string; +} + +export interface Attempt { + dispatchTime: string; + responseStatus: Status; + responseTime: string; + scheduleTime: string; +} + +export interface Binding { + condition: Expr; + members: string[]; + role: string; +} + +export interface CreateTaskRequest { + responseView: View; + task: Partial; +} + +export interface Expr { + description: string; + expression: string; + location: string; + title: string; +} + +export interface ListLocationsResponse { + locations: Location[]; + nextPageToken?: string; +} + +export interface ListQueuesResponse { + nextPageToken?: string; + queues: Queue[]; +} + +export interface ListTasksResponse { + nextPageToken?: string; + tasks: Task[]; +} + +export interface Location { + displayName: string; + labels: { + [key: string]: string; + }; + locationId: string; + metadata: object; + name: string; +} + +export interface Policy { + bindings: Binding[]; + etag: string; + version: number; +} + +export interface Queue { + appEngineHttpQueue: AppEngineHttpQueue; + name: string; + purgeTime: string; + rateLimits: RateLimits; + retryConfig: RetryConfig; + state: string; +} + +export interface RateLimits { + maxBurstSize: number; + maxConcurrentDispatches: number; + maxDispatchesPerSecond: number; +} + +export interface RetryConfig { + maxAttempts: number; + maxBackoff: string; + maxDoublings: number; + maxRetryDuration: string; + minBackoff: string; +} + +export interface RunTaskRequest { + responseView?: View; +} + +export interface SetIamPolicyRequest { + policy: Partial; +} + +export interface Status { + code: number; + details: object[]; + message: string; +} + +/** + * `VIEW_UNSPECIFIED = 0;` + * When Unspecified. Defaults to the behaviour of BASIC. + * + * `BASIC = 1;` + * The basic view omits fields which can be large or can contain + * sensitive data. + * This view does not include the + * ([payload in AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] and + * [payload in PullMessage][google.cloud.tasks.v2beta2.PullMessage.payload]). These payloads are + * desirable to return only when needed, because they can be large + * and because of the sensitivity of the data that you choose to + * store in it. + * + * `FULL = 2;` + * All information is returned. + * + * Authorization for [FULL][google.cloud.tasks.v2beta2.Task.View.FULL] requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the [Queue][google.cloud.tasks.v2beta2.Queue] resource. + */ +export type View = 0 | 1 | 2; + +export interface Task { + appEngineHttpRequest: AppEngineHttpRequest; + createTime: string; + dispatchCount: number; + firstAttempt: Attempt; + lastAttempt: Attempt; + name: string; + responseCount: number; + scheduleTime: string; + view: View; +} + +export interface TestIamPermissionsRequest { + permissions?: string[]; +} + +export interface TestIamPermissionsResponse { + permissions?: string[]; +} + +export interface PromiseLike extends Promise { + /** + * Cancel the ongoing promise + */ + cancel(): void; +} + +export type Keys = keyof T; + +export type EnhancedPick< + T, + Req extends keyof T, + Opt extends keyof T +> = Required> & Partial>; + +export type ProjectIdCallback = ( + err?: Error | null, + projectId?: string | null +) => void; + +export type APICallback = ( + err: GoogleError | null, + response?: T +) => void; + +export type APIPaginatedCallback = ( + err: GoogleError | null, + response?: T, + next?: U | null, + rawResponse?: V +) => void; + +export interface CallOptionsWithPagination extends CallOptions { + autoPaginate: false; +} + +export interface MethodOverload { + (data: T, options?: CallOptions): PromiseLike<[R]>; + (data: T, options: CallOptions, callback: APICallback): void; + (data: T, callback: APICallback): void; +} + +export interface PaginatedMethodOverload { + (data: T, options: CallOptionsWithPagination): PromiseLike<[R, V, U]>; + (data: T, options?: CallOptions): PromiseLike<[R]>; + (data: T, options: CallOptions, callback: APICallback): void; + ( + data: T, + options: CallOptionsWithPagination, + callback: APIPaginatedCallback + ): void; + (data: T, callback: APICallback): void; +} + +export interface ParentRequest { + /** + * The location name. For example: projects/PROJECT_ID/locations/LOCATION_ID + */ + parent: string; +} + +export interface ResourceRequest { + /** + * The resource for which the policy is being requested. resource is usually specified as a path. For example, a Project resource is specified as projects/{project}. + */ + resource: string; +} + +export interface ListRequestObject extends ParentRequest { + /** + * `filter` can be used to specify a subset of queues. Any Queue field can be used as a filter and several operators as supported. + * For example: <=, <, >=, >, !=, =, :. The filter syntax is the same as described in Stackdriver's Advanced Logs Filters. + * Sample filter "state: PAUSED". + * Note that using filters might cause fewer queues than the requested page_size to be returned. + */ + filter?: string; + + /** + * The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, + * this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. + */ + pageSize?: number; +} + +export interface NamedRequest { + /** + * The resource name of the queue. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID + */ + name: string; +} + +export type CreateNamedRequest = ParentRequest & + { [P in N]: T }; +export type UpdateNamedRequest = ParentRequest & + { [P in N]: T }; + +/** + * Cloud Tasks allows developers to manage the execution of background + * work in their applications. + */ +export default class CloudTasksClient { + /** + * The DNS address for this API service. + * @default 'cloudtasks.googleapis.com' + */ + static readonly servicePath: string; + + /** + * The port for this API service. + * @default 443 + */ + static readonly port: number; + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @default ["https://www.googleapis.com/auth/cloud-platform"] + */ + static readonlyscopes: string; + + auth: GoogleAuth; + + /** + * Construct an instance of CloudTasksClient. + * + * @param [options] - The configuration object. See the subsequent + * parameters for more details. + * @param [options.credentials] - Credentials object. + * @param [options.credentials.client_email] + * @param [options.credentials.private_key] + * @param [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param [options.port] - The port on which to connect to + * the remote host. + * @param [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param [options.promise] - Custom promise module to use instead + * of native Promises. + * @param [options.servicePath] - The domain name of the + * API remote host. + */ + constructor(config: CloudTasksConfig); + + /** + * Return the project ID used by this class. + * @param callback - the callback to + * be called with the current project Id. + */ + getProjectId(): PromiseLike; + getProjectId(callback: ProjectIdCallback): void; + + // ------------------- + // -- Service calls -- + // ------------------- + + /** + * Lists queues. + * + * Queues are returned in lexicographical order. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param [request.filter] + * `filter` can be used to specify a subset of queues. Any Queue + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * + * When autoPaginate: false is specified through options, it contains the result + * in a single response. If the response indicates the next page exists, the third + * parameter is set to be used for the next request object. The fourth parameter keeps + * the raw response object of an object representing [ListQueuesResponse]{@link google.cloud.tasks.v2beta3.ListQueuesResponse}. + * The first element of the array is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * + * When autoPaginate: false is specified through options, the array has three elements. + * The first element is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue} in a single response. + * The second element is the next request object if the response + * indicates the next page exists, or null. The third element is + * an object representing [ListQueuesResponse]{@link google.cloud.tasks.v2beta3.ListQueuesResponse}. + * + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * // Iterate over all elements. + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * + * client.listQueues({parent: formattedParent}) + * .then(responses => { + * const resources = responses[0]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]) + * } + * }) + * .catch(err => { + * console.error(err); + * }); + * + * // Or obtain the paged response. + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * + * + * const options = {autoPaginate: false}; + * const callback = responses => { + * // The actual resources in a response. + * const resources = responses[0]; + * // The next request if the response shows that there are more responses. + * const nextRequest = responses[1]; + * // The actual response object, if necessary. + * // const rawResponse = responses[2]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]); + * } + * if (nextRequest) { + * // Fetch the next page. + * return client.listQueues(nextRequest, options).then(callback); + * } + * } + * client.listQueues({parent: formattedParent}, options) + * .then(callback) + * .catch(err => { + * console.error(err); + * }); + */ + listQueues: PaginatedMethodOverload< + ListRequestObject, + Queue[], + ListQueuesResponse + >; + + /** + * Equivalent to {@link listQueues}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listQueues} continuously + * and invokes the callback registered for 'data' event for each element in the + * responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param [request.filter] + * `filter` can be used to specify a subset of queues. Any Queue + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * An object stream which emits an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue} on 'data' event. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * client.listQueuesStream({parent: formattedParent}) + * .on('data', element => { + * // doThingsWith(element) + * }).on('error', err => { + * console.log(err); + * }); + */ + listQueuesStream( + request: ListRequestObject, + options?: CallOptions + ): Transform; + + /** + * Gets a queue. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The resource name of the queue. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.getQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getQueue: MethodOverload; + + /** + * Creates a queue. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name in which the queue will be created. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * + * The list of allowed locations can be obtained by calling Cloud + * Tasks' implementation of + * ListLocations. + * @param request.queue + * Required. + * + * The queue to create. + * + * Queue's name cannot be the same as an existing queue. + * + * This object should have the same structure as [Queue]{@link google.cloud.tasks.v2beta3.Queue} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * const queue = {}; + * const request = { + * parent: formattedParent, + * queue: queue, + * }; + * client.createQueue(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + createQueue: MethodOverload< + CreateNamedRequest<"queue", Partial>, + Queue + >; + + /** + * Updates a queue. + * + * This method creates the queue if it does not exist and updates + * the queue if it does exist. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.queue + * Required. + * + * The queue to create or update. + * + * The queue's name must be specified. + * + * Output only fields cannot be modified using UpdateQueue. + * Any value specified for an output only field will be ignored. + * The queue's name cannot be changed. + * + * This object should have the same structure as [Queue]{@link google.cloud.tasks.v2beta3.Queue} + * @param [request.updateMask] + * A mask used to specify which fields of the queue are being updated. + * + * If empty, then all fields will be updated. + * + * This object should have the same structure as [FieldMask]{@link google.protobuf.FieldMask} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const queue = {}; + * client.updateQueue({queue: queue}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + updateQueue: MethodOverload< + UpdateNamedRequest< + "queue", + EnhancedPick< + Queue, + "name", + "appEngineHttpQueue" | "rateLimits" | "retryConfig" + > + >, + Queue + >; + + /** + * Deletes a queue. + * + * This command will delete the queue even if it has tasks in it. + * + * Note: If you delete a queue, a queue with the same name can't be created + * for 7 days. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.deleteQueue({name: formattedName}).catch(err => { + * console.error(err); + * }); + */ + deleteQueue: MethodOverload; + + /** + * Purges a queue by deleting all of its tasks. + * + * All tasks created before this method is called are permanently deleted. + * + * Purge operations can take up to one minute to take effect. Tasks + * might be dispatched before the purge takes effect. A purge is irreversible. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.purgeQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + purgeQueue: MethodOverload; + + /** + * Pauses the queue. + * + * If a queue is paused then the system will stop dispatching tasks + * until the queue is resumed via + * ResumeQueue. Tasks can still be added + * when the queue is paused. A queue is paused if its + * state is PAUSED. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.pauseQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + pauseQueue: MethodOverload; + + /** + * Resume a queue. + * + * This method resumes a queue after it has been + * PAUSED or + * DISABLED. The state of a queue is stored + * in the queue's state; after calling this method it + * will be set to RUNNING. + * + * WARNING: Resuming many high-QPS queues at the same time can + * lead to target overloading. If you are resuming high-QPS + * queues, follow the 500/50/5 pattern described in + * [Managing Cloud Tasks Scaling Risks](https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.resumeQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + resumeQueue: MethodOverload; + + /** + * Gets the access control policy for a Queue. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.getIamPolicy` + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Policy]{@link google.iam.v1.Policy}. + * The first element of the array is an object representing [Policy]{@link google.iam.v1.Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.getIamPolicy({resource: formattedResource}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getIamPolicy: MethodOverload; + + /** + * Sets the access control policy for a Queue. Replaces any existing + * policy. + * + * Note: The Cloud Console does not check queue-level IAM permissions yet. + * Project-level permissions are required to use the Cloud Console. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.setIamPolicy` + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param request.policy + * REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * + * This object should have the same structure as [Policy]{@link google.iam.v1.Policy} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Policy]{@link google.iam.v1.Policy}. + * The first element of the array is an object representing [Policy]{@link google.iam.v1.Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const policy = {}; + * const request = { + * resource: formattedResource, + * policy: policy, + * }; + * client.setIamPolicy(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + setIamPolicy: MethodOverload; + + /** + * Returns permissions that a caller has on a Queue. + * If the resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building permission-aware + * UIs and command-line tools, not for authorization checking. This operation + * may "fail open" without warning. + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [TestIamPermissionsResponse]{@link google.iam.v1.TestIamPermissionsResponse}. + * The first element of the array is an object representing [TestIamPermissionsResponse]{@link google.iam.v1.TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const permissions = []; + * const request = { + * resource: formattedResource, + * permissions: permissions, + * }; + * client.testIamPermissions(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + testIamPermissions: MethodOverload< + ResourceRequest & TestIamPermissionsRequest, + TestIamPermissionsResponse + >; + + /** + * Lists the tasks in a queue. + * + * By default, only the BASIC view is retrieved + * due to performance considerations; + * response_view controls the + * subset of information which is returned. + * + * The tasks may be returned in any order. The ordering may change at any + * time. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of [Task]{@link google.cloud.tasks.v2beta3.Task}. + * + * When autoPaginate: false is specified through options, it contains the result + * in a single response. If the response indicates the next page exists, the third + * parameter is set to be used for the next request object. The fourth parameter keeps + * the raw response object of an object representing [ListTasksResponse]{@link google.cloud.tasks.v2beta3.ListTasksResponse}. + * The first element of the array is Array of [Task]{@link google.cloud.tasks.v2beta3.Task}. + * + * When autoPaginate: false is specified through options, the array has three elements. + * The first element is Array of [Task]{@link google.cloud.tasks.v2beta3.Task} in a single response. + * The second element is the next request object if the response + * indicates the next page exists, or null. The third element is + * an object representing [ListTasksResponse]{@link google.cloud.tasks.v2beta3.ListTasksResponse}. + * + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * // Iterate over all elements. + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * + * client.listTasks({parent: formattedParent}) + * .then(responses => { + * const resources = responses[0]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]) + * } + * }) + * .catch(err => { + * console.error(err); + * }); + * + * // Or obtain the paged response. + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * + * + * const options = {autoPaginate: false}; + * const callback = responses => { + * // The actual resources in a response. + * const resources = responses[0]; + * // The next request if the response shows that there are more responses. + * const nextRequest = responses[1]; + * // The actual response object, if necessary. + * // const rawResponse = responses[2]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]); + * } + * if (nextRequest) { + * // Fetch the next page. + * return client.listTasks(nextRequest, options).then(callback); + * } + * } + * client.listTasks({parent: formattedParent}, options) + * .then(callback) + * .catch(err => { + * console.error(err); + * }); + */ + listTasks: PaginatedMethodOverload< + ListRequestObject & RunTaskRequest, + Task[], + ListTasksResponse + >; + + /** + * Equivalent to {@link listTasks}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listTasks} continuously + * and invokes the callback registered for 'data' event for each element in the + * responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * An object stream which emits an object representing [Task]{@link google.cloud.tasks.v2beta3.Task} on 'data' event. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.listTasksStream({parent: formattedParent}) + * .on('data', element => { + * // doThingsWith(element) + * }).on('error', err => { + * console.log(err); + * }); + */ + listTasksStream( + request: ListRequestObject & RunTaskRequest, + options?: CallOptions + ): Transform; + + /** + * Gets a task. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.getTask({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getTask: MethodOverload; + /** + * Creates a task and adds it to a queue. + * + * Tasks cannot be updated after creation; there is no UpdateTask command. + * + * * For App Engine queues, the maximum task size is + * 100KB. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * + * The queue must already exist. + * @param request.task + * Required. + * + * The task to add. + * + * Task names have the following format: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`. + * The user can optionally specify a task name. If a + * name is not specified then the system will generate a random + * unique task id, which will be set in the task returned in the + * response. + * + * If schedule_time is not set or is in the + * past then Cloud Tasks will set it to the current time. + * + * Task De-duplication: + * + * Explicitly specifying a task ID enables task de-duplication. If + * a task's ID is identical to that of an existing task or a task + * that was deleted or executed recently then the call will fail + * with ALREADY_EXISTS. + * If the task's queue was created using Cloud Tasks, then another task with + * the same name can't be created for ~1hour after the original task was + * deleted or executed. If the task's queue was created using queue.yaml or + * queue.xml, then another task with the same name can't be created + * for ~9days after the original task was deleted or executed. + * + * Because there is an extra lookup cost to identify duplicate task + * names, these CreateTask calls have significantly + * increased latency. Using hashed strings for the task id or for + * the prefix of the task id is recommended. Choosing task ids that + * are sequential or have sequential prefixes, for example using a + * timestamp, causes an increase in latency and error rates in all + * task commands. The infrastructure relies on an approximately + * uniform distribution of task ids to store and serve tasks + * efficiently. + * + * This object should have the same structure as [Task]{@link google.cloud.tasks.v2beta3.Task} + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const task = {}; + * const request = { + * parent: formattedParent, + * task: task, + * }; + * client.createTask(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + createTask: MethodOverload; + + /** + * Deletes a task. + * + * A task can be deleted if it is scheduled or dispatched. A task + * cannot be deleted if it has executed successfully or permanently + * failed. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.deleteTask({name: formattedName}).catch(err => { + * console.error(err); + * }); + */ + deleteTask: MethodOverload; + + /** + * Forces a task to run now. + * + * When this method is called, Cloud Tasks will dispatch the task, even if + * the task is already running, the queue has reached its RateLimits or + * is PAUSED. + * + * This command is meant to be used for manual debugging. For + * example, RunTask can be used to retry a failed + * task after a fix has been made or to manually force a task to be + * dispatched now. + * + * The dispatched task is returned. That is, the task that is returned + * contains the status after the task is dispatched but + * before the task is received by its target. + * + * If Cloud Tasks receives a successful response from the task's + * target, then the task will be deleted; otherwise the task's + * schedule_time will be reset to the time that + * RunTask was called plus the retry delay specified + * in the queue's RetryConfig. + * + * RunTask returns + * NOT_FOUND when it is called on a + * task that has already succeeded or permanently failed. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.runTask({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + runTask: MethodOverload; + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified project resource name string. + * + * @param project + */ + projectPath(project: string): string; + + /** + * Return a fully-qualified location resource name string. + * + * @param project + * @param location + */ + locationPath(project: string, location: string): string; + + /** + * Return a fully-qualified queue resource name string. + * + * @param project + * @param location + * @param queue + */ + queuePath(project: string, location: string, queue: string): string; + + /** + * Return a fully-qualified task resource name string. + * + * @param project + * @param location + * @param queue + * @param task + */ + taskPath( + project: string, + location: string, + queue: string, + task: string + ): string; + + /** + * Parse the projectName from a project resource. + * + * @param projectName + * A fully-qualified path representing a project resources. + */ + matchProjectFromProjectName(projectName: string): string; + + /** + * Parse the locationName from a location resource. + * + * @param locationName + * A fully-qualified path representing a location resources. + */ + matchProjectFromLocationName(locationName: string): string; + + /** + * Parse the locationName from a location resource. + * + * @param locationName + * A fully-qualified path representing a location resources. + */ + matchLocationFromLocationName(locationName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchProjectFromQueueName(queueName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchLocationFromQueueName(queueName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchQueueFromQueueName(queueName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchProjectFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchLocationFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchQueueFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchTaskFromTaskName(taskName: string): string; +} diff --git a/types/google-cloud__tasks/package.json b/types/google-cloud__tasks/package.json new file mode 100644 index 0000000000..c4a850824a --- /dev/null +++ b/types/google-cloud__tasks/package.json @@ -0,0 +1,14 @@ +{ + "private": true, + "dependencies": { + "google-gax": "^0.22.1" + }, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + } +} diff --git a/types/google-cloud__tasks/ts3.1/google-cloud__tasks-tests.ts b/types/google-cloud__tasks/ts3.1/google-cloud__tasks-tests.ts new file mode 100644 index 0000000000..94a7ebcfa4 --- /dev/null +++ b/types/google-cloud__tasks/ts3.1/google-cloud__tasks-tests.ts @@ -0,0 +1,21 @@ +import Tasks, { Queue } from "@google-cloud/tasks"; + +const client = new Tasks({}); + +// $ExpectError +const failedClient = new Tasks({ unrecognized: "" }); + +const formattedParent = client.locationPath("[PROJECT]", "[LOCATION]"); +const queue: Partial = {}; +const request = { + parent: formattedParent, + queue +}; +client + .createQueue(request) + .then(([queue]) => { + const q = queue; + }) + .catch(err => { + console.error(err); + }); diff --git a/types/google-cloud__tasks/ts3.1/index.d.ts b/types/google-cloud__tasks/ts3.1/index.d.ts new file mode 100644 index 0000000000..6b09fdd06d --- /dev/null +++ b/types/google-cloud__tasks/ts3.1/index.d.ts @@ -0,0 +1,1622 @@ +/// + +import { Transform } from "stream"; +import { + GoogleAuthOptions, + GoogleError, + CallOptions, + GoogleAuth +} from "google-gax"; + +export interface CloudTasksConfig extends GoogleAuthOptions { + key?: string; + autoRetry?: boolean; + maxRetries?: number; + libName?: string; + libVersion?: string; + promise?: PromiseConstructor; +} + +export interface AppEngineHttpQueue { + appEngineRoutingOverride: AppEngineRouting; +} + +export interface AppEngineHttpRequest { + appEngineRouting: AppEngineRouting; + body: string; + headers: { + [key: string]: string; + }; + httpMethod: string; + relativeUri: string; +} + +export interface AppEngineRouting { + host: string; + instance: string; + service: string; + version: string; +} + +export interface Attempt { + dispatchTime: string; + responseStatus: Status; + responseTime: string; + scheduleTime: string; +} + +export interface Binding { + condition: Expr; + members: string[]; + role: string; +} + +export interface CreateTaskRequest { + responseView: View; + task: Partial; +} + +export interface Expr { + description: string; + expression: string; + location: string; + title: string; +} + +export interface ListLocationsResponse { + locations: Location[]; + nextPageToken?: string; +} + +export interface ListQueuesResponse { + nextPageToken?: string; + queues: Queue[]; +} + +export interface ListTasksResponse { + nextPageToken?: string; + tasks: Task[]; +} + +export interface Location { + displayName: string; + labels: { + [key: string]: string; + }; + locationId: string; + metadata: object; + name: string; +} + +export interface Policy { + bindings: Binding[]; + etag: string; + version: number; +} + +export interface Queue { + appEngineHttpQueue: AppEngineHttpQueue; + name: string; + purgeTime: string; + rateLimits: RateLimits; + retryConfig: RetryConfig; + state: string; +} + +export interface RateLimits { + maxBurstSize: number; + maxConcurrentDispatches: number; + maxDispatchesPerSecond: number; +} + +export interface RetryConfig { + maxAttempts: number; + maxBackoff: string; + maxDoublings: number; + maxRetryDuration: string; + minBackoff: string; +} + +export interface RunTaskRequest { + responseView?: View; +} + +export interface SetIamPolicyRequest { + policy: Partial; +} + +export interface Status { + code: number; + details: object[]; + message: string; +} + +/** + * `VIEW_UNSPECIFIED = 0;` + * When Unspecified. Defaults to the behaviour of BASIC. + * + * `BASIC = 1;` + * The basic view omits fields which can be large or can contain + * sensitive data. + * This view does not include the + * ([payload in AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] and + * [payload in PullMessage][google.cloud.tasks.v2beta2.PullMessage.payload]). These payloads are + * desirable to return only when needed, because they can be large + * and because of the sensitivity of the data that you choose to + * store in it. + * + * `FULL = 2;` + * All information is returned. + * + * Authorization for [FULL][google.cloud.tasks.v2beta2.Task.View.FULL] requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the [Queue][google.cloud.tasks.v2beta2.Queue] resource. + */ +export type View = 0 | 1 | 2; + +export interface Task { + appEngineHttpRequest: AppEngineHttpRequest; + createTime: string; + dispatchCount: number; + firstAttempt: Attempt; + lastAttempt: Attempt; + name: string; + responseCount: number; + scheduleTime: string; + view: View; +} + +export interface TestIamPermissionsRequest { + permissions?: string[]; +} + +export interface TestIamPermissionsResponse { + permissions?: string[]; +} + +export interface PromiseLike extends Promise { + /** + * Cancel the ongoing promise + */ + cancel(): void; +} + +export type Keys = keyof T; + +export type EnhancedPick< + T, + Req extends keyof T, + Opt extends keyof T +> = Required> & Partial>; + +export type ProjectIdCallback = ( + err?: Error | null, + projectId?: string | null +) => void; + +export type APICallback = ( + err: GoogleError | null, + response?: T +) => void; + +export type APIPaginatedCallback = ( + err: GoogleError | null, + response?: T, + next?: U | null, + rawResponse?: V +) => void; + +export interface CallOptionsWithPagination extends CallOptions { + autoPaginate: false; +} + +export interface MethodOverload { + (data: T, options?: CallOptions): PromiseLike<[R]>; + (data: T, options: CallOptions, callback: APICallback): void; + (data: T, callback: APICallback): void; +} + +export interface PaginatedMethodOverload { + (data: T, options: CallOptionsWithPagination): PromiseLike<[R, V, U]>; + (data: T, options?: CallOptions): PromiseLike<[R]>; + (data: T, options: CallOptions, callback: APICallback): void; + ( + data: T, + options: CallOptionsWithPagination, + callback: APIPaginatedCallback + ): void; + (data: T, callback: APICallback): void; +} + +export interface ParentRequest { + /** + * The location name. For example: projects/PROJECT_ID/locations/LOCATION_ID + */ + parent: string; +} + +export interface ResourceRequest { + /** + * The resource for which the policy is being requested. resource is usually specified as a path. For example, a Project resource is specified as projects/{project}. + */ + resource: string; +} + +export interface ListRequestObject extends ParentRequest { + /** + * `filter` can be used to specify a subset of queues. Any Queue field can be used as a filter and several operators as supported. + * For example: <=, <, >=, >, !=, =, :. The filter syntax is the same as described in Stackdriver's Advanced Logs Filters. + * Sample filter "state: PAUSED". + * Note that using filters might cause fewer queues than the requested page_size to be returned. + */ + filter?: string; + + /** + * The maximum number of resources contained in the underlying API response. If page streaming is performed per-resource, + * this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. + */ + pageSize?: number; +} + +export interface NamedRequest { + /** + * The resource name of the queue. For example: projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID + */ + name: string; +} + +export type CreateNamedRequest = ParentRequest & + { [P in N]: T }; +export type UpdateNamedRequest = ParentRequest & + { [P in N]: T }; + +/** + * Cloud Tasks allows developers to manage the execution of background + * work in their applications. + */ +export default class CloudTasksClient { + /** + * The DNS address for this API service. + * @default 'cloudtasks.googleapis.com' + */ + static readonly servicePath: string; + + /** + * The port for this API service. + * @default 443 + */ + static readonly port: number; + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @default ["https://www.googleapis.com/auth/cloud-platform"] + */ + static readonlyscopes: string; + + auth: GoogleAuth; + + /** + * Construct an instance of CloudTasksClient. + * + * @param [options] - The configuration object. See the subsequent + * parameters for more details. + * @param [options.credentials] - Credentials object. + * @param [options.credentials.client_email] + * @param [options.credentials.private_key] + * @param [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param [options.port] - The port on which to connect to + * the remote host. + * @param [options.projectId] - The project ID from the Google + * Developer's Console, e.g. 'grape-spaceship-123'. We will also check + * the environment variable GCLOUD_PROJECT for your project ID. If your + * app is running in an environment which supports + * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * your project ID will be detected automatically. + * @param [options.promise] - Custom promise module to use instead + * of native Promises. + * @param [options.servicePath] - The domain name of the + * API remote host. + */ + constructor(config: CloudTasksConfig); + + /** + * Return the project ID used by this class. + * @param callback - the callback to + * be called with the current project Id. + */ + getProjectId(): PromiseLike; + getProjectId(callback: ProjectIdCallback): void; + + // ------------------- + // -- Service calls -- + // ------------------- + + /** + * Lists queues. + * + * Queues are returned in lexicographical order. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param [request.filter] + * `filter` can be used to specify a subset of queues. Any Queue + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * + * When autoPaginate: false is specified through options, it contains the result + * in a single response. If the response indicates the next page exists, the third + * parameter is set to be used for the next request object. The fourth parameter keeps + * the raw response object of an object representing [ListQueuesResponse]{@link google.cloud.tasks.v2beta3.ListQueuesResponse}. + * The first element of the array is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * + * When autoPaginate: false is specified through options, the array has three elements. + * The first element is Array of [Queue]{@link google.cloud.tasks.v2beta3.Queue} in a single response. + * The second element is the next request object if the response + * indicates the next page exists, or null. The third element is + * an object representing [ListQueuesResponse]{@link google.cloud.tasks.v2beta3.ListQueuesResponse}. + * + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * // Iterate over all elements. + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * + * client.listQueues({parent: formattedParent}) + * .then(responses => { + * const resources = responses[0]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]) + * } + * }) + * .catch(err => { + * console.error(err); + * }); + * + * // Or obtain the paged response. + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * + * + * const options = {autoPaginate: false}; + * const callback = responses => { + * // The actual resources in a response. + * const resources = responses[0]; + * // The next request if the response shows that there are more responses. + * const nextRequest = responses[1]; + * // The actual response object, if necessary. + * // const rawResponse = responses[2]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]); + * } + * if (nextRequest) { + * // Fetch the next page. + * return client.listQueues(nextRequest, options).then(callback); + * } + * } + * client.listQueues({parent: formattedParent}, options) + * .then(callback) + * .catch(err => { + * console.error(err); + * }); + */ + listQueues: PaginatedMethodOverload< + ListRequestObject, + Queue[], + ListQueuesResponse + >; + + /** + * Equivalent to {@link listQueues}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listQueues} continuously + * and invokes the callback registered for 'data' event for each element in the + * responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * @param [request.filter] + * `filter` can be used to specify a subset of queues. Any Queue + * field can be used as a filter and several operators as supported. + * For example: `<=, <, >=, >, !=, =, :`. The filter syntax is the same as + * described in + * [Stackdriver's Advanced Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). + * + * Sample filter "state: PAUSED". + * + * Note that using filters might cause fewer queues than the + * requested page_size to be returned. + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * An object stream which emits an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue} on 'data' event. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * client.listQueuesStream({parent: formattedParent}) + * .on('data', element => { + * // doThingsWith(element) + * }).on('error', err => { + * console.log(err); + * }); + */ + listQueuesStream( + request: ListRequestObject, + options?: CallOptions + ): Transform; + + /** + * Gets a queue. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The resource name of the queue. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.getQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getQueue: MethodOverload; + + /** + * Creates a queue. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The location name in which the queue will be created. + * For example: `projects/PROJECT_ID/locations/LOCATION_ID` + * + * The list of allowed locations can be obtained by calling Cloud + * Tasks' implementation of + * ListLocations. + * @param request.queue + * Required. + * + * The queue to create. + * + * Queue's name cannot be the same as an existing queue. + * + * This object should have the same structure as [Queue]{@link google.cloud.tasks.v2beta3.Queue} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); + * const queue = {}; + * const request = { + * parent: formattedParent, + * queue: queue, + * }; + * client.createQueue(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + createQueue: MethodOverload< + CreateNamedRequest<"queue", Partial>, + Queue + >; + + /** + * Updates a queue. + * + * This method creates the queue if it does not exist and updates + * the queue if it does exist. + * + * Queues created with this method allow tasks to live for a maximum of 31 + * days. After a task is 31 days old, the task will be deleted regardless of whether + * it was dispatched or not. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.queue + * Required. + * + * The queue to create or update. + * + * The queue's name must be specified. + * + * Output only fields cannot be modified using UpdateQueue. + * Any value specified for an output only field will be ignored. + * The queue's name cannot be changed. + * + * This object should have the same structure as [Queue]{@link google.cloud.tasks.v2beta3.Queue} + * @param [request.updateMask] + * A mask used to specify which fields of the queue are being updated. + * + * If empty, then all fields will be updated. + * + * This object should have the same structure as [FieldMask]{@link google.protobuf.FieldMask} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const queue = {}; + * client.updateQueue({queue: queue}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + updateQueue: MethodOverload< + UpdateNamedRequest< + "queue", + EnhancedPick< + Queue, + "name", + "appEngineHttpQueue" | "rateLimits" | "retryConfig" + > + >, + Queue + >; + + /** + * Deletes a queue. + * + * This command will delete the queue even if it has tasks in it. + * + * Note: If you delete a queue, a queue with the same name can't be created + * for 7 days. + * + * WARNING: Using this method may have unintended side effects if you are + * using an App Engine `queue.yaml` or `queue.xml` file to manage your queues. + * Read + * [Overview of Queue Management and queue.yaml](https://cloud.google.com/tasks/docs/queue-yaml) + * before using this method. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.deleteQueue({name: formattedName}).catch(err => { + * console.error(err); + * }); + */ + deleteQueue: MethodOverload; + + /** + * Purges a queue by deleting all of its tasks. + * + * All tasks created before this method is called are permanently deleted. + * + * Purge operations can take up to one minute to take effect. Tasks + * might be dispatched before the purge takes effect. A purge is irreversible. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.purgeQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + purgeQueue: MethodOverload; + + /** + * Pauses the queue. + * + * If a queue is paused then the system will stop dispatching tasks + * until the queue is resumed via + * ResumeQueue. Tasks can still be added + * when the queue is paused. A queue is paused if its + * state is PAUSED. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.pauseQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + pauseQueue: MethodOverload; + + /** + * Resume a queue. + * + * This method resumes a queue after it has been + * PAUSED or + * DISABLED. The state of a queue is stored + * in the queue's state; after calling this method it + * will be set to RUNNING. + * + * WARNING: Resuming many high-QPS queues at the same time can + * lead to target overloading. If you are resuming high-QPS + * queues, follow the 500/50/5 pattern described in + * [Managing Cloud Tasks Scaling Risks](https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/location/LOCATION_ID/queues/QUEUE_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The first element of the array is an object representing [Queue]{@link google.cloud.tasks.v2beta3.Queue}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.resumeQueue({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + resumeQueue: MethodOverload; + + /** + * Gets the access control policy for a Queue. + * Returns an empty policy if the resource exists and does not have a policy + * set. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.getIamPolicy` + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Policy]{@link google.iam.v1.Policy}. + * The first element of the array is an object representing [Policy]{@link google.iam.v1.Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.getIamPolicy({resource: formattedResource}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getIamPolicy: MethodOverload; + + /** + * Sets the access control policy for a Queue. Replaces any existing + * policy. + * + * Note: The Cloud Console does not check queue-level IAM permissions yet. + * Project-level permissions are required to use the Cloud Console. + * + * Authorization requires the following + * [Google IAM](https://cloud.google.com/iam) permission on the specified + * resource parent: + * + * * `cloudtasks.queues.setIamPolicy` + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy is being specified. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param request.policy + * REQUIRED: The complete policy to be applied to the `resource`. The size of + * the policy is limited to a few 10s of KB. An empty policy is a + * valid policy but certain Cloud Platform services (such as Projects) + * might reject them. + * + * This object should have the same structure as [Policy]{@link google.iam.v1.Policy} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Policy]{@link google.iam.v1.Policy}. + * The first element of the array is an object representing [Policy]{@link google.iam.v1.Policy}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const policy = {}; + * const request = { + * resource: formattedResource, + * policy: policy, + * }; + * client.setIamPolicy(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + setIamPolicy: MethodOverload; + + /** + * Returns permissions that a caller has on a Queue. + * If the resource does not exist, this will return an empty set of + * permissions, not a NOT_FOUND error. + * + * Note: This operation is designed to be used for building permission-aware + * UIs and command-line tools, not for authorization checking. This operation + * may "fail open" without warning. + * + * @param request + * The request object that will be sent. + * @param request.resource + * REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project + * resource is specified as `projects/{project}`. + * @param request.permissions + * The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more + * information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [TestIamPermissionsResponse]{@link google.iam.v1.TestIamPermissionsResponse}. + * The first element of the array is an object representing [TestIamPermissionsResponse]{@link google.iam.v1.TestIamPermissionsResponse}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedResource = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const permissions = []; + * const request = { + * resource: formattedResource, + * permissions: permissions, + * }; + * client.testIamPermissions(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + testIamPermissions: MethodOverload< + ResourceRequest & TestIamPermissionsRequest, + TestIamPermissionsResponse + >; + + /** + * Lists the tasks in a queue. + * + * By default, only the BASIC view is retrieved + * due to performance considerations; + * response_view controls the + * subset of information which is returned. + * + * The tasks may be returned in any order. The ordering may change at any + * time. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is Array of [Task]{@link google.cloud.tasks.v2beta3.Task}. + * + * When autoPaginate: false is specified through options, it contains the result + * in a single response. If the response indicates the next page exists, the third + * parameter is set to be used for the next request object. The fourth parameter keeps + * the raw response object of an object representing [ListTasksResponse]{@link google.cloud.tasks.v2beta3.ListTasksResponse}. + * The first element of the array is Array of [Task]{@link google.cloud.tasks.v2beta3.Task}. + * + * When autoPaginate: false is specified through options, the array has three elements. + * The first element is Array of [Task]{@link google.cloud.tasks.v2beta3.Task} in a single response. + * The second element is the next request object if the response + * indicates the next page exists, or null. The third element is + * an object representing [ListTasksResponse]{@link google.cloud.tasks.v2beta3.ListTasksResponse}. + * + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * // Iterate over all elements. + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * + * client.listTasks({parent: formattedParent}) + * .then(responses => { + * const resources = responses[0]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]) + * } + * }) + * .catch(err => { + * console.error(err); + * }); + * + * // Or obtain the paged response. + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * + * + * const options = {autoPaginate: false}; + * const callback = responses => { + * // The actual resources in a response. + * const resources = responses[0]; + * // The next request if the response shows that there are more responses. + * const nextRequest = responses[1]; + * // The actual response object, if necessary. + * // const rawResponse = responses[2]; + * for (let i = 0; i < resources.length; i += 1) { + * // doThingsWith(resources[i]); + * } + * if (nextRequest) { + * // Fetch the next page. + * return client.listTasks(nextRequest, options).then(callback); + * } + * } + * client.listTasks({parent: formattedParent}, options) + * .then(callback) + * .catch(err => { + * console.error(err); + * }); + */ + listTasks: PaginatedMethodOverload< + ListRequestObject & RunTaskRequest, + Task[], + ListTasksResponse + >; + + /** + * Equivalent to {@link listTasks}, but returns a NodeJS Stream object. + * + * This fetches the paged responses for {@link listTasks} continuously + * and invokes the callback registered for 'data' event for each element in the + * responses. + * + * The returned object has 'end' method when no more elements are required. + * + * autoPaginate option will be ignored. + * + * @see {@link https://nodejs.org/api/stream.html} + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [request.pageSize] + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * An object stream which emits an object representing [Task]{@link google.cloud.tasks.v2beta3.Task} on 'data' event. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * client.listTasksStream({parent: formattedParent}) + * .on('data', element => { + * // doThingsWith(element) + * }).on('error', err => { + * console.log(err); + * }); + */ + listTasksStream( + request: ListRequestObject & RunTaskRequest, + options?: CallOptions + ): Transform; + + /** + * Gets a task. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.getTask({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + getTask: MethodOverload; + /** + * Creates a task and adds it to a queue. + * + * Tasks cannot be updated after creation; there is no UpdateTask command. + * + * * For App Engine queues, the maximum task size is + * 100KB. + * + * @param request + * The request object that will be sent. + * @param request.parent + * Required. + * + * The queue name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` + * + * The queue must already exist. + * @param request.task + * Required. + * + * The task to add. + * + * Task names have the following format: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID`. + * The user can optionally specify a task name. If a + * name is not specified then the system will generate a random + * unique task id, which will be set in the task returned in the + * response. + * + * If schedule_time is not set or is in the + * past then Cloud Tasks will set it to the current time. + * + * Task De-duplication: + * + * Explicitly specifying a task ID enables task de-duplication. If + * a task's ID is identical to that of an existing task or a task + * that was deleted or executed recently then the call will fail + * with ALREADY_EXISTS. + * If the task's queue was created using Cloud Tasks, then another task with + * the same name can't be created for ~1hour after the original task was + * deleted or executed. If the task's queue was created using queue.yaml or + * queue.xml, then another task with the same name can't be created + * for ~9days after the original task was deleted or executed. + * + * Because there is an extra lookup cost to identify duplicate task + * names, these CreateTask calls have significantly + * increased latency. Using hashed strings for the task id or for + * the prefix of the task id is recommended. Choosing task ids that + * are sequential or have sequential prefixes, for example using a + * timestamp, causes an increase in latency and error rates in all + * task commands. The infrastructure relies on an approximately + * uniform distribution of task ids to store and serve tasks + * efficiently. + * + * This object should have the same structure as [Task]{@link google.cloud.tasks.v2beta3.Task} + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedParent = client.queuePath('[PROJECT]', '[LOCATION]', '[QUEUE]'); + * const task = {}; + * const request = { + * parent: formattedParent, + * task: task, + * }; + * client.createTask(request) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + createTask: MethodOverload; + + /** + * Deletes a task. + * + * A task can be deleted if it is scheduled or dispatched. A task + * cannot be deleted if it has executed successfully or permanently + * failed. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.deleteTask({name: formattedName}).catch(err => { + * console.error(err); + * }); + */ + deleteTask: MethodOverload; + + /** + * Forces a task to run now. + * + * When this method is called, Cloud Tasks will dispatch the task, even if + * the task is already running, the queue has reached its RateLimits or + * is PAUSED. + * + * This command is meant to be used for manual debugging. For + * example, RunTask can be used to retry a failed + * task after a fix has been made or to manually force a task to be + * dispatched now. + * + * The dispatched task is returned. That is, the task that is returned + * contains the status after the task is dispatched but + * before the task is received by its target. + * + * If Cloud Tasks receives a successful response from the task's + * target, then the task will be deleted; otherwise the task's + * schedule_time will be reset to the time that + * RunTask was called plus the retry delay specified + * in the queue's RetryConfig. + * + * RunTask returns + * NOT_FOUND when it is called on a + * task that has already succeeded or permanently failed. + * + * @param request + * The request object that will be sent. + * @param request.name + * Required. + * + * The task name. For example: + * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` + * @param [request.responseView] + * The response_view specifies which subset of the Task will be + * returned. + * + * By default response_view is BASIC; not all + * information is retrieved by default because some data, such as + * payloads, might be desirable to return only when needed because + * of its large size or because of the sensitivity of data that it + * contains. + * + * Authorization for FULL requires + * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) + * permission on the Task resource. + * + * The number should be among the values of [View]{@link google.cloud.tasks.v2beta3.View} + * @param [options] + * Optional parameters. You can override the default settings for this call, e.g, timeout, + * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. + * @param [callback] + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The first element of the array is an object representing [Task]{@link google.cloud.tasks.v2beta3.Task}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * + * import CloudTasks from '@google-cloud/tasks'; + * + * const client = new tasks.v2beta3.CloudTasksClient({ + * // optional auth parameters. + * }); + * + * const formattedName = client.taskPath('[PROJECT]', '[LOCATION]', '[QUEUE]', '[TASK]'); + * client.runTask({name: formattedName}) + * .then(responses => { + * const response = responses[0]; + * // doThingsWith(response) + * }) + * .catch(err => { + * console.error(err); + * }); + */ + runTask: MethodOverload; + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified project resource name string. + * + * @param project + */ + projectPath(project: string): string; + + /** + * Return a fully-qualified location resource name string. + * + * @param project + * @param location + */ + locationPath(project: string, location: string): string; + + /** + * Return a fully-qualified queue resource name string. + * + * @param project + * @param location + * @param queue + */ + queuePath(project: string, location: string, queue: string): string; + + /** + * Return a fully-qualified task resource name string. + * + * @param project + * @param location + * @param queue + * @param task + */ + taskPath( + project: string, + location: string, + queue: string, + task: string + ): string; + + /** + * Parse the projectName from a project resource. + * + * @param projectName + * A fully-qualified path representing a project resources. + */ + matchProjectFromProjectName(projectName: string): string; + + /** + * Parse the locationName from a location resource. + * + * @param locationName + * A fully-qualified path representing a location resources. + */ + matchProjectFromLocationName(locationName: string): string; + + /** + * Parse the locationName from a location resource. + * + * @param locationName + * A fully-qualified path representing a location resources. + */ + matchLocationFromLocationName(locationName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchProjectFromQueueName(queueName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchLocationFromQueueName(queueName: string): string; + + /** + * Parse the queueName from a queue resource. + * + * @param queueName + * A fully-qualified path representing a queue resources. + */ + matchQueueFromQueueName(queueName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchProjectFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchLocationFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchQueueFromTaskName(taskName: string): string; + + /** + * Parse the taskName from a task resource. + * + * @param taskName + * A fully-qualified path representing a task resources. + */ + matchTaskFromTaskName(taskName: string): string; +} diff --git a/types/google-cloud__tasks/ts3.1/tsconfig.json b/types/google-cloud__tasks/ts3.1/tsconfig.json new file mode 100644 index 0000000000..08ba955879 --- /dev/null +++ b/types/google-cloud__tasks/ts3.1/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "paths": { + "@google-cloud/tasks": ["google-cloud__tasks"] + }, + "baseUrl": "../../", + "typeRoots": ["../../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "google-cloud__tasks-tests.ts"] +} diff --git a/types/google-cloud__tasks/ts3.1/tslint.json b/types/google-cloud__tasks/ts3.1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/google-cloud__tasks/ts3.1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google-cloud__tasks/tsconfig.json b/types/google-cloud__tasks/tsconfig.json new file mode 100644 index 0000000000..498e1217fc --- /dev/null +++ b/types/google-cloud__tasks/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "paths": { + "@google-cloud/tasks": ["google-cloud__tasks"] + }, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "google-cloud__tasks-tests.ts"] +} diff --git a/types/google-cloud__tasks/tslint.json b/types/google-cloud__tasks/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/google-cloud__tasks/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/google__maps/index.d.ts b/types/google__maps/index.d.ts index 4759d412dd..f1df5d8f38 100644 --- a/types/google__maps/index.d.ts +++ b/types/google__maps/index.d.ts @@ -907,7 +907,9 @@ export interface DirectionsRoute { * contains a single `points` object that holds an encoded polyline representation of the route. * This polyline is an approximate (smoothed) path of the resulting directions. */ - overview_polyline: string; + overview_polyline: { + points: string; + }; /** contains the viewport bounding box of the `overview_polyline`. */ bounds: LatLngBounds; /** contains the copyrights text to be displayed for this route. You must handle and display this information yourself. */ @@ -2005,7 +2007,7 @@ export interface GeocodingResponse { * When the geocoder returns a status code other than `OK`, there may be an additional `error_message` field * within the Geocoding response object. This field contains more detailed information about the reasons behind the given status code. */ - error_meesage: string; + error_message: string; /** * contains an array of geocoded address information and geometry information. * @@ -3105,7 +3107,7 @@ export interface QueryAutocompleteResult { * contains an `offset` value and a `length`. * These describe the location of the entered term in the prediction result text, so that the term can be highlighted if desired. */ - matched_substring: PredictionSubstring[]; + matched_substrings: PredictionSubstring[]; } /** A Radar Search request must include at least one of `keyword`, `name`, or `type`. */ diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index d80d0aadcf..afaac89ba4 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -265,10 +265,28 @@ got('https://todomvc.com', { rejectUnauthorized: false }); got('/examples/angularjs', { baseUrl: 'http://todomvc.com' }); got('http://todomvc.com', { headers: { foo: 'bar'} }); got('http://todomvc.com', { cookieJar: new tough.CookieJar() }); + +// Test retry options. got('http://todomvc.com', { retry: 2 }); -got('http://todomvc.com', { retry: { retries: 2, methods: ['GET'], statusCodes: [408, 504], maxRetryAfter: 1 } }); +got('http://todomvc.com', { + retry: { + retries: 2, + methods: ['GET'], + statusCodes: [408, 504], + maxRetryAfter: 1, + errorCodes: ['ETIMEDOUT'] + } +}); +// Test custom retry error code. See https://github.com/sindresorhus/got/blob/9f3a09948ff80057b12af0af60846cc5b8f0372d/test/retry.js#L155 +got('http://todomvc.com', { + retry: { + retries: 1, + methods: ['GET'], + errorCodes: ['OH_SNAP'] + } +}); + got('http://todomvc.com', { throwHttpErrors: false }); -got('http://todomvc.com', { hooks: { beforeRequest: [ () => 'foo']} }); // Test timeout options. got('http://todomvc.com', {timeout: 1}); @@ -288,6 +306,15 @@ got('http://todomvc.com', { got('http://todomvc.com', {timeout: 1}).catch((err) => err instanceof got.TimeoutError); // Test hooks. +got('example.com', { + hooks: { + beforeRequest: [ + options => { + options.headers!['x-foo'] = 'bar'; + } + ] + } +}); got('example.com', { hooks: { beforeRedirect: [ @@ -339,6 +366,11 @@ got('example.com', { got('example.com', { hooks: { + beforeRequest: [ + async () => { + await doSomethingAsync(); + } + ], beforeRedirect: [ async () => { await doSomethingAsync(); diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 09b451f4bb..0c847d6489 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for got 9.3 +// Type definitions for got 9.4 // Project: https://github.com/sindresorhus/got#readme // Definitions by: BendingBender // Linus Unnebäck @@ -226,6 +226,10 @@ declare namespace got { methods?: Array<'GET' | 'PUT' | 'HEAD' | 'DELETE' | 'OPTIONS' | 'TRACE'>; statusCodes?: Array<408 | 413 | 429 | 500 | 502 | 503 | 504>; maxRetryAfter?: number; + /** + * Allowed error codes. + */ + errorCodes?: string[]; } interface AgentOptions { diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index 1df7c85690..97c16f305c 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -342,15 +342,15 @@ export interface GraphQLScalarTypeConfig { * }); * */ -export class GraphQLObjectType { +export class GraphQLObjectType { name: string; description: Maybe; astNode: Maybe; extensionASTNodes: Maybe>; - isTypeOf: Maybe>; + isTypeOf: Maybe>; - constructor(config: GraphQLObjectTypeConfig); - getFields(): GraphQLFieldMap; + constructor(config: GraphQLObjectTypeConfig); + getFields(): GraphQLFieldMap; getInterfaces(): GraphQLInterfaceType[]; toString(): string; toJSON(): string; @@ -371,7 +371,7 @@ export type GraphQLTypeResolver = ( value: TSource, context: TContext, info: GraphQLResolveInfo -) => MaybePromise>; +) => MaybePromise | string>>; export type GraphQLIsTypeOfFn = ( source: TSource, diff --git a/types/gsap/Timeline.d.ts b/types/gsap/Timeline.d.ts index 60292e354d..232d2ed9a3 100644 --- a/types/gsap/Timeline.d.ts +++ b/types/gsap/Timeline.d.ts @@ -85,7 +85,7 @@ declare namespace gsap { removeLabel(label: string): any; /** Jumps to a specific time (or label) without affecting whether or not the instance is paused or reversed. */ - seek(position: string | number, supressEvents: boolean): TimelineLite; + seek(position: string | number, supressEvents?: boolean): TimelineLite; /** * Adds a zero-duration tween to the end of the timeline (or elsewhere using the "position" parameter) that sets values immediately (when the virtual playhead reaches that diff --git a/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts b/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts index 6a31efb820..38398d9830 100644 --- a/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts +++ b/types/guardian__prosemirror-invisibles/guardian__prosemirror-invisibles-tests.ts @@ -1,3 +1,8 @@ -import invisibles, { hardBreak, paragraph, space } from 'guardian__prosemirror-invisibles'; +import { Node } from 'prosemirror-model'; +import { Plugin } from 'prosemirror-state'; -const plugin = invisibles([hardBreak, paragraph, space]); +import invisibles, { hardBreak, paragraph, space, Builder } from 'guardian__prosemirror-invisibles'; + +const plugin1: Plugin = invisibles([hardBreak((node: Node) => true), paragraph(), space((char: string) => false)]); + +const plugin2: Plugin = invisibles([hardBreak(), paragraph((node: Node) => false), space()]); diff --git a/types/guardian__prosemirror-invisibles/index.d.ts b/types/guardian__prosemirror-invisibles/index.d.ts index b2e2434662..f3453cd6ec 100644 --- a/types/guardian__prosemirror-invisibles/index.d.ts +++ b/types/guardian__prosemirror-invisibles/index.d.ts @@ -1,17 +1,25 @@ -// Type definitions for @guardian/prosemirror-invisibles 0.1 +// Type definitions for @guardian/prosemirror-invisibles 1.0 // Project: https://github.com/guardian/prosemirror-invisibles // Definitions by: Daniil Dotsev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { Node } from 'prosemirror-model'; -import { DecorationSet } from "prosemirror-view"; +import { Decoration, DecorationSet } from "prosemirror-view"; import { Plugin } from 'prosemirror-state'; export type Builder = (from: number, to: number, doc: Node, decos: DecorationSet) => DecorationSet; +export interface TextBetweenPosition { + pos: number; + text: string; +} + export default function(builders: Builder[]): Plugin; -export const hardBreak: Builder; -export const paragraph: Builder; -export const space: Builder; +export function hardBreak(predicate?: (node: Node) => boolean): Builder; +export function paragraph(predicate?: (node: Node) => boolean): Builder; +export function space(predicate?: (char: string) => boolean): Builder; + +export function createDeco(pos: number, type: string): Decoration; +export function textBetween(from: number, to: number, doc: Node): TextBetweenPosition[]; diff --git a/types/gulp-minify-css/tsconfig.json b/types/gulp-minify-css/tsconfig.json index ccb2e4b319..0742a43568 100644 --- a/types/gulp-minify-css/tsconfig.json +++ b/types/gulp-minify-css/tsconfig.json @@ -12,6 +12,14 @@ "typeRoots": [ "../" ], + "paths": { + "clean-css": [ + "clean-css/v3" + ], + "clean-css/*": [ + "clean-css/v3/*" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-rev-replace/tsconfig.json b/types/gulp-rev-replace/tsconfig.json index d6b9abe0ba..736d44e64d 100644 --- a/types/gulp-rev-replace/tsconfig.json +++ b/types/gulp-rev-replace/tsconfig.json @@ -12,6 +12,14 @@ "typeRoots": [ "../" ], + "paths": { + "clean-css": [ + "clean-css/v3" + ], + "clean-css/*": [ + "clean-css/v3/*" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/gulp-useref/tsconfig.json b/types/gulp-useref/tsconfig.json index b8a3dc7bba..4dc6f70464 100644 --- a/types/gulp-useref/tsconfig.json +++ b/types/gulp-useref/tsconfig.json @@ -12,6 +12,14 @@ "typeRoots": [ "../" ], + "paths": { + "clean-css": [ + "clean-css/v3" + ], + "clean-css/*": [ + "clean-css/v3/*" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/h2o2/h2o2-tests.ts b/types/h2o2/h2o2-tests.ts index 9d0a590fa8..9da2899258 100644 --- a/types/h2o2/h2o2-tests.ts +++ b/types/h2o2/h2o2-tests.ts @@ -140,6 +140,18 @@ const badProtocolDemo: hapi.ServerRoute = { } }; +const replyViaToolkit: hapi.ServerRoute = { + method: 'GET', + path: '/', + async handler(req, h): Promise { + return h.proxy({ + host: '10.33.33.1', + port: '443', + protocol: 'https' + }); + } +}; + if (!module.parent) { main().then(() => console.log('done'), err => console.error(err.stack)); } diff --git a/types/h2o2/index.d.ts b/types/h2o2/index.d.ts index b6e5145eb6..58be5eb271 100644 --- a/types/h2o2/index.d.ts +++ b/types/h2o2/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for h2o2 8.1 // Project: https://github.com/hapijs/h2o2 -// Definitions by: Jason Swearingen , AJP +// Definitions by: Jason Swearingen , AJP , Garth Kidd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -83,13 +83,17 @@ declare namespace h2o2 { declare module 'hapi' { interface HandlerDecorations { - /** Proxies the request to an upstream endpoint */ + /** + * Proxies the request to an upstream endpoint. + */ proxy?: h2o2.ProxyHandlerOptions; } interface ResponseToolkit { - /** Proxies the request to an upstream endpoint */ - proxy(options: h2o2.ProxyHandlerOptions): void; + /** + * Proxies the request to an upstream endpoint. `async`, so you'll need to `await` the `ResponseObject` to work on it before returning it. + */ + proxy(options: h2o2.ProxyHandlerOptions): Promise; } } diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 65ce60be85..f66ae5a8ea 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hapi 17.8 +// Type definitions for hapi 18.0 // Project: https://github.com/hapijs/hapi // Definitions by: Rafael Souza Fijalkowski // Justin Simms @@ -29,9 +29,9 @@ import * as zlib from 'zlib'; import { MimosOptions } from 'mimos'; import { SealOptions, SealOptionsSub } from 'iron'; -import { AnySchema, ValidationOptions } from 'joi'; +import { ValidationOptions, SchemaMap, Schema } from 'joi'; import Podium = require('podium'); -import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePrototype, Policy } from 'catbox'; +import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePrototype, Policy, ClientApi, ClientOptions } from 'catbox'; /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -318,6 +318,8 @@ export interface RequestInfo { remotePort: string; /** request response timestamp (0 is not responded yet). */ responded: number; + /** request processing completion timestamp (0 is still processing). */ + completed: number; } /** @@ -503,9 +505,10 @@ export interface Request extends Podium { /** * Access: read / write (see limitations below). * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to - * override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). + * override with a different response. + * In case of an aborted request the status code will be set to `disconnectStatusCode`. */ - response: ResponseObject | Boom | null; + response: ResponseObject | Boom; /** * Same as pre but represented as the response object created by the pre method. @@ -513,10 +516,9 @@ export interface Request extends Podium { readonly preResponses: Util.Dictionary; /** - * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query - * attribute as an unparsed string). + * By default the object outputted from node's URL parse() method. */ - readonly query: RequestQuery | string; + readonly query: RequestQuery; /** * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. @@ -549,7 +551,7 @@ export interface Request extends Podium { /** * The parsed request URI. */ - readonly url: url.Url; + readonly url: url.URL; /** * Returns `true` when the request is active and processing should continue and `false` when the @@ -599,7 +601,7 @@ export interface Request extends Podium { * @return void * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) */ - setUrl(url: string | url.Url, stripTrailingSlash?: boolean): void; + setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; } /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1436,14 +1438,19 @@ export interface RouteOptionsPreObject { failAction?: Lifecycle.FailAction; } -export interface ValidationObject { - [key: string]: AnySchema; -} +export type ValidationObject = SchemaMap; +/** + * * true - any query parameter value allowed (no validation performed). false - no parameter value allowed. + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.* object containing the request parameters. + * * * options - options. + */ export type RouteOptionsResponseSchema = boolean | ValidationObject - | AnySchema + | Schema | ((value: object | Buffer | string, options: ValidationOptions) => Promise); /** @@ -1517,6 +1524,16 @@ export interface RouteOptionsResponse { * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) */ status?: Util.Dictionary; + + /** + * The default HTTP status code used to set a response error when the request is closed or aborted before the + * response is fully transmitted. + * Value can be any integer greater or equal to 400. + * The default value 499 is based on the non-standard nginx "CLIENT CLOSED REQUEST" error. + * The value is only used for logging as the request has already ended. + * @default 499 + */ + disconnectStatusCode?: number; } /** @@ -1630,21 +1647,15 @@ export interface RouteOptionsValidate { failAction?: Lifecycle.FailAction; /** - * Default value: true (no validation). * Validation rules for incoming request headers: - * * true - any headers allowed (no validation performed). - * * a joi validation object. - * * a validation function using the signature async function(value, options) where: - * * * value - the request.headers object containing the request headers. - * * * options - options. - * * * if a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error + * * If a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error * is thrown, the error is handled according to failAction. Note that all header field names must be in lowercase to match the headers normalized by node. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) + * @default true */ headers?: RouteOptionsResponseSchema; /** - * Default value: none. * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here). * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter. * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as @@ -1653,11 +1664,11 @@ export interface RouteOptionsValidate { * will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the * individual route settings override the routes defaults (the rules are not merged). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + * @default true */ options?: ValidationOptions | object; /** - * Default value: true (no validation). * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where: * * true - any path parameter value allowed (no validation performed). * * a joi validation object. @@ -1667,39 +1678,37 @@ export interface RouteOptionsValidate { * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an * error is thrown, the error is handled according to failAction. Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + * @default true */ params?: RouteOptionsResponseSchema; /** - * Default value: true (no validation). * Validation rules for incoming request payload (request body), where: - * * true - any payload allowed (no validation performed). false - no payload allowed. - * * a joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are allowed, the schema must be explicitly defined by - * setting the rule to a joi schema with null allowed (e.g. Joi.object({ keys here }).allow(null)). - * * a validation function using the signature async function(value, options) where: - * * * value - the request.query object containing the request query parameters. - * * * options - options. - * if a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is + * * If a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is * thrown, the error is handled according to failAction. Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well * as the significant performance cost of validating large amounts of data. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) + * @default true */ payload?: RouteOptionsResponseSchema; /** - * Default value: true (no validation). * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in * request.query prior to validation. Where: - * * true - any query parameter value allowed (no validation performed). false - no query parameter value allowed. - * * a joi validation object. - * * a validation function using the signature async function(value, options) where: - * * * value - the request.query object containing the request query parameters. - * * * options - options. - * if a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. If an error + * * If a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. + * If an error * is thrown, the error is handled according to failAction. Note that changes to the query parameters will not be reflected in request.url. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) + * @default true */ query?: RouteOptionsResponseSchema; + + /** + * Validation rules for incoming cookies. + * The cookie header is parsed and decoded into the request.state prior to validation. + * @default true + */ + state?: RouteOptionsResponseSchema; } /** @@ -2125,13 +2134,13 @@ export interface ServerAuth { * Tests a request against an authentication strategy where: * @param strategy - the strategy name registered with server.auth.strategy(). * @param request - the request object. - * @return Return value: the authentication credentials object if authentication was successful, otherwise throws an error. + * @return an object containing the authentication credentials and artifacts if authentication was successful, otherwise throws an error. * Note that the test() method does not take into account the route authentication configuration. It also does not * perform payload authentication. It is limited to the basic strategy authentication execution. It does not * include verifying scope, entity, or other route properties. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) */ - test(strategy: string, request: Request): Promise; + test(strategy: string, request: Request): Promise; /** * Verify a request's authentication credentials against an authentication strategy. @@ -2647,15 +2656,24 @@ export interface ServerInfo { */ export interface ServerInjectOptions extends Shot.RequestOptions { /** - * an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via - * an authentication scheme. Defaults to no credentials. + * Authentication bypass options. */ - credentials?: AuthCredentials; - /** - * (an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received - * via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. - */ - artifacts?: object; + auth?: { + /** + * The authentication strategy name matching the provided credentials. + */ + strategy: string; + /** + * The credentials are used to bypass the default authentication strategies, + * and are validated directly as if they were received via an authentication scheme. + */ + credentials: AuthCredentials; + /** + * The artifacts are used to bypass the default authentication strategies, + * and are validated directly as if they were received via an authentication scheme. Defaults to no artifacts. + */ + artifacts?: object; + }; /** * sets the initial value of request.app, defaults to {}. */ @@ -2704,7 +2722,7 @@ export interface ServerInjectResponse extends Shot.ResponseObject { * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ -export type ServerMethod = (...args: any[]) => Promise; +export type ServerMethod = (...args: any[]) => any; /** * The same cache configuration used in server.cache(). @@ -2766,14 +2784,24 @@ export interface ServerMethodConfigurationObject { options?: ServerMethodOptions; } +export type CacheProvider = EnginePrototype | { + constructor: EnginePrototype; + options?: T; +}; + /** * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache) */ export interface ServerOptionsCache extends PolicyOptions { - /** a class, a prototype function, or a catbox engine object. */ - engine?: EnginePrototypeOrObject; + /** catbox engine object. */ + engine?: ClientApi; + + /** + * a class or a prototype function + */ + provider?: CacheProvider; /** * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines @@ -2851,7 +2879,7 @@ export interface ServerOptions { * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache) */ - cache?: EnginePrototype | ServerOptionsCache | ServerOptionsCache[]; + cache?: CacheProvider | ServerOptionsCache | ServerOptionsCache[]; /** * Default value: { minBytes: 1024 }. @@ -2996,6 +3024,17 @@ export interface ServerOptions { * The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server server.info.uri, otherwise constructed from the server settings. */ uri?: string; + + /** + * Query parameter configuration. + */ + query?: { + /** + * the method must return an object where each key is a parameter and matching value is the parameter value. + * If the method throws, the error is used as the response or returned when `request.setUrl` is called. + */ + parser(raw: Util.Dictionary): Util.Dictionary; + }; } /** diff --git a/types/hapi/test/request/info.ts b/types/hapi/test/request/info.ts new file mode 100644 index 0000000000..eae9d67d5f --- /dev/null +++ b/types/hapi/test/request/info.ts @@ -0,0 +1,4 @@ +import { Request } from "hapi"; + +const req: Request = {} as any; +const { completed, responded } = req.info; diff --git a/types/hapi/test/request/query.ts b/types/hapi/test/request/query.ts index 090ab3ae8d..26a886aa5f 100644 --- a/types/hapi/test/request/query.ts +++ b/types/hapi/test/request/query.ts @@ -6,10 +6,10 @@ const options: ServerOptions = { }; const handlerFn: Lifecycle.Method = (request, h) => { - const query1 = request.query as string; + const query1 = request.query; console.log(query1); - const query2 = request.query as RequestQuery; + const query2 = request.query; // http://localhost:8000/?name=test return `You asked for ${query2.name}`; }; diff --git a/types/hapi/test/response/response-events.ts b/types/hapi/test/response/response-events.ts index ec1b070b18..c78611cd2a 100644 --- a/types/hapi/test/response/response-events.ts +++ b/types/hapi/test/response/response-events.ts @@ -4,7 +4,7 @@ import * as Crypto from "crypto"; const preResponse: Lifecycle.Method = (request, h) => { // In onPreResponse, the response object will be defined. - const response = request.response!; + const response = request.response; const hash = Crypto.createHash('sha1'); response.events.on('peek', (chunk, encoding) => { diff --git a/types/hapi/test/route/route-options.ts b/types/hapi/test/route/route-options.ts index 438ef77d62..5f718a9c68 100644 --- a/types/hapi/test/route/route-options.ts +++ b/types/hapi/test/route/route-options.ts @@ -89,6 +89,7 @@ const routeOptionsResponse: RouteOptionsResponse = { 302: true, 404: false, }, + disconnectStatusCode: 123, }; const routeOptionSecure: RouteOptionsSecureObject = { diff --git a/types/hapi/test/route/validation.ts b/types/hapi/test/route/validation.ts index 6cc4ed186d..79b8effbb1 100644 --- a/types/hapi/test/route/validation.ts +++ b/types/hapi/test/route/validation.ts @@ -8,12 +8,30 @@ const options: ServerOptions = { const routeOptions: RouteOptions = { validate: { + payload: { + id: Joi.string().uuid().required(), + name: Joi.object({ + firstName: Joi.string().required(), + lastName: Joi.string().allow(null) + }), + firstName: Joi.ref("name.firstName") + }, params: { - name: Joi.string().min(3).max(10) - } + name: Joi.string().min(3).max(10), + nameRef: Joi.ref("name") + }, + state: { + woop: Joi.string().allow('doop'), + }, }, response: { - schema: Joi.string() + schema: Joi.object({ + a: Joi.string(), + b: Joi.object({ + c: Joi.number() + }), + d: Joi.ref("b.c") + }) } }; diff --git a/types/hapi/test/server/server-auth-test.ts b/types/hapi/test/server/server-auth-test.ts index 4e2a175e1a..c9f25fdfac 100644 --- a/types/hapi/test/server/server-auth-test.ts +++ b/types/hapi/test/server/server-auth-test.ts @@ -34,7 +34,7 @@ server.route({ path: '/', handler: async (request: Request, h: ResponseToolkit) => { try { - const credentials = await request.server.auth.test('default', request); + const { credentials } = await request.server.auth.test('default', request); return { status: true, user: credentials.name }; } catch (err) { return { status: false }; diff --git a/types/hapi/test/server/server-inject.ts b/types/hapi/test/server/server-inject.ts index a2ae777a71..c7c7565ccf 100644 --- a/types/hapi/test/server/server-inject.ts +++ b/types/hapi/test/server/server-inject.ts @@ -25,6 +25,14 @@ declare module 'hapi' { } server.inject({ + auth: { + strategy: 'test', + credentials: { + user: { + a: 1, + }, + }, + }, url: "test", app: { injectState: 1 diff --git a/types/hapi/test/server/server-method.ts b/types/hapi/test/server/server-method.ts index bb729516b7..39c3fdb9d7 100644 --- a/types/hapi/test/server/server-method.ts +++ b/types/hapi/test/server/server-method.ts @@ -6,7 +6,7 @@ const server = new Server({ }); server.start(); -const add = (a: any, b: any) => { +const add = (a: any, b: any): number => { return a + b; }; diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index 9df329c575..f47f0d8dfb 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -22,6 +22,7 @@ "test/request/catch-all.ts", "test/request/event-types.ts", "test/request/get-log.ts", + "test/request/info.ts", "test/request/methods.ts", "test/request/parameters.ts", "test/request/query.ts", diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts new file mode 100644 index 0000000000..d3262f5285 --- /dev/null +++ b/types/hapi/v17/index.d.ts @@ -0,0 +1,4005 @@ +// Type definitions for hapi 17.8 +// Project: https://github.com/hapijs/hapi +// Definitions by: Rafael Souza Fijalkowski +// Justin Simms +// Simon Schick +// Rodrigo Saboya +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WARNING: BACKWARDS INCOMPATIBLE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/// + +import * as Boom from 'boom'; +import * as http from 'http'; +import * as https from 'https'; +import * as Shot from 'shot'; +import * as stream from 'stream'; +import * as url from 'url'; +import * as zlib from 'zlib'; + +import { MimosOptions } from 'mimos'; +import { SealOptions, SealOptionsSub } from 'iron'; +import { ValidationOptions, SchemaMap, Schema } from 'joi'; +import Podium = require('podium'); +import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePrototype, Policy } from 'catbox'; + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Plugin + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * one of + * a single plugin name string. + * an array of plugin name strings. + * an object where each key is a plugin name and each matching value is a + * {@link https://www.npmjs.com/package/semver version range string} which must match the registered + * plugin version. + */ +export type Dependencies = string | string[] | { + [key: string]: string; +}; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ + +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginsListRegistered { +} + +/** + * An object of the currently registered plugins where each key is a registered plugin name and the value is an + * object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ +export interface PluginRegistered { + /** + * the plugin version. + */ + version: string; + + /** + * the plugin name. + */ + name: string; + + /** + * options used to register the plugin. + */ + options: object; +} + +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginsStates { +} + +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginSpecificConfiguration { +} + +export interface PluginNameVersion { + /** + * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm + * registry) should use the same name as the name field in their 'package.json' file. Names must be + * unique within each application. + */ + name: string; + + /** + * optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's + * 'package.json' file. + */ + version?: string; +} + +export interface PluginPackage { + /** + * Alternatively, the name and version can be included via the pkg property containing the 'package.json' file for the module which already has the name and version included + */ + pkg: any; +} + +/** + * Plugins provide a way to organize application code by splitting the server logic into smaller components. Each + * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox + * certain properties. For example, setting a file path in one plugin doesn't affect the file path set + * in another plugin. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins) + * + * The type T is the type of the plugin options. + */ +export interface PluginBase { + /** + * (required) the registration function with the signature async function(server, options) where: + * * server - the server object with a plugin-specific server.realm. + * * options - any options passed to the plugin during registration via server.register(). + */ + register: (server: Server, options: T) => void | Promise; + + /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ + multiple?: boolean; + + /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ + dependencies?: Dependencies; + + /** + * Allows defining semver requirements for node and hapi. + * @default Allows all. + */ + requirements?: { + node?: string; + hapi?: string; + }; + + /** once - (optional) if true, will only register the plugin once per server. If set, overrides the once option passed to server.register(). Defaults to no override. */ + once?: boolean; +} + +export type Plugin = PluginBase & (PluginNameVersion | PluginPackage); + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Request + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * User extensible types user credentials. + */ +// tslint:disable-next-line:no-empty-interface +export interface UserCredentials { +} + +/** + * User extensible types app credentials. + */ +// tslint:disable-next-line:no-empty-interface +export interface AppCredentials { +} + +/** + * User-extensible type for request.auth credentials. + */ +export interface AuthCredentials { + /** + * The application scopes to be granted. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) + */ + scope?: string[]; + /** + * If set, will only work with routes that set `access.entity` to `user`. + */ + user?: UserCredentials; + + /** + * If set, will only work with routes that set `access.entity` to `app`. + */ + app?: AppCredentials; +} + +/** + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed + * authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + */ +export interface RequestAuth { + /** an artifact object received from the authentication strategy and used in authentication-related actions. */ + artifacts: object; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: AuthCredentials; + /** the authentication error is failed and mode set to 'try'. */ + error: Error; + /** true if the request has been successfully authenticated, otherwise false. */ + isAuthenticated: boolean; + /** + * true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, + * set to false. + */ + isAuthorized: boolean; + /** the route authentication mode. */ + mode: string; + /** the name of the strategy used. */ + strategy: string; +} + +/** + * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export type RequestEventType = 'peek' | 'finish' | 'disconnect'; + +/** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export interface RequestEvents extends Podium { + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + on(criteria: 'peek', listener: PeekListener): void; + + on(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void; + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + once(criteria: 'peek', listener: PeekListener): void; + + once(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): void; +} + +/** + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only + * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) + */ +export interface RequestInfo { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + /** + * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after + * the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + */ + isOriginMatch?: boolean; + }; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com'). */ + hostname: string; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}') */ + id: string; + /** request reception timestamp. */ + received: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** remote client IP address. */ + remoteAddress: string; + /** remote client port. */ + remotePort: string; + /** request response timestamp (0 is not responded yet). */ + responded: number; +} + +/** + * The request route information object, where: + * * method - the route HTTP method. + * * path - the route path. + * * vhost - the route vhost option if configured. + * * realm - the active realm associated with the route. + * * settings - the route options object with all defaults applied. + * * fingerprint - the route internal normalized string representing the normalized path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + */ +export interface RequestRoute { + /** the route HTTP method. */ + method: Util.HTTP_METHODS_PARTIAL; + + /** the route path. */ + path: string; + + /** the route vhost option if configured. */ + vhost?: string | string[]; + + /** the active realm associated with the route. */ + realm: ServerRealm; + + /** the route options object with all defaults applied. */ + settings: RouteOptions; + + /** the route internal normalized string representing the normalized path. */ + fingerprint: string; + + auth: { + /** + * Validates a request against the route's authentication access configuration, where: + * @param request - the request object. + * @return Return value: true if the request would have passed the route's access requirements. + * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access + * configuration. If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may + * not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route + * requires any authentication. + * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) + */ + access(request: Request): boolean; + }; +} + +/** + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig) + */ +export interface RequestOrig { + params: object; + query: object; + payload: object; +} + +export interface RequestLog { + request: string; + timestamp: number; + tags: string[]; + data: string | object; + channel: string; +} + +export interface RequestQuery { + [key: string]: string | string[]; +} + +/** + * The request object is created internally for each incoming request. It is not the same object received from the node + * HTTP server callback (which is available via [request.raw.req](https://github.com/hapijs/hapi/blob/master/API.md#request.raw)). The request properties change throughout + * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle). + */ +export interface Request extends Podium { + /** + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp) + */ + app: ApplicationState; + + /** + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed + * authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + */ + readonly auth: RequestAuth; + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + events: RequestEvents; + + /** + * The raw request headers (references request.raw.req.headers). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) + */ + readonly headers: Util.Dictionary; + + /** + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only + * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) + */ + readonly info: RequestInfo; + + /** + * An array containing the logged request events. + * Note that this array will be empty if route log.collect is set to false. + */ + readonly logs: RequestLog[]; + + /** + * The request method in lower case (e.g. 'get', 'post'). + */ + readonly method: Util.HTTP_METHODS_PARTIAL_LOWERCASE; + + /** + * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. + */ + readonly mime: string; + + /** + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + */ + readonly orig: RequestOrig; + + /** + * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). + */ + readonly params: Util.Dictionary; + + /** + * An array containing all the path params values in the order they appeared in the path. + */ + readonly paramsArray: string[]; + + /** + * The request URI's pathname component. + */ + readonly path: string; + + /** + * The request payload based on the route payload.output and payload.parse settings. + * TODO check this typing and add references / links. + */ + readonly payload: stream.Readable | Buffer | string | object; + + /** + * Plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. + */ + plugins: PluginsStates; + + /** + * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response + * object, use responses. + */ + readonly pre: Util.Dictionary; + + /** + * Access: read / write (see limitations below). + * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to + * override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). + */ + response: ResponseObject | Boom | null; + + /** + * Same as pre but represented as the response object created by the pre method. + */ + readonly preResponses: Util.Dictionary; + + /** + * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query + * attribute as an unparsed string). + */ + readonly query: RequestQuery | string; + + /** + * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. + * * req - the node request object. + * * res - the node response object. + */ + readonly raw: { + req: http.IncomingMessage; + res: http.ServerResponse; + }; + + /** + * The request route information object and method + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest) + */ + readonly route: RequestRoute; + + /** + * Access: read only and the public server interface. + * The server object. + */ + server: Server; + + /** + * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. + */ + readonly state: Util.Dictionary; + + /** + * The parsed request URI. + */ + readonly url: url.Url; + + /** + * Returns `true` when the request is active and processing should continue and `false` when the + * request terminated early or completed its lifecycle. Useful when request processing is a + * resource-intensive operation and should be terminated early if the request is no longer active + * (e.g. client disconnected or aborted early). + */ + active(): boolean; + + /** + * Returns a response which you can pass into the reply interface where: + * @param source - the value to set as the source of the reply interface, optional. + * @param options - options for the method, optional. + * @return ResponseObject + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options) + */ + /* tslint:disable-next-line:max-line-length */ + generateResponse(source: string | object | null, options?: { variety?: string; prepare?: (response: ResponseObject) => Promise; marshal?: (response: ResponseObject) => Promise; close?: (response: ResponseObject) => void; }): ResponseObject; + + /** + * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: + * @param tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism + * for describing and filtering events. + * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return + * value) the actual data emitted to the listeners. Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag + * set to true. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data) + */ + log(tags: string | string[], data?: string | object | (() => string | object)): void; + + /** + * Changes the request method before the router begins processing the request where: + * @param method - is the request HTTP method (e.g. 'GET'). + * @return void + * Can only be called from an 'onRequest' extension method. + * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod) + */ + setMethod(method: Util.HTTP_METHODS_PARTIAL): void; + + /** + * Changes the request URI before the router begins processing the request where: + * Can only be called from an 'onRequest' extension method. + * @param url - the new request URI. If url is a string, it is parsed with node's URL parse() method with parseQueryString set to true. url can also be set to an object compatible with node's URL + * parse() method output. + * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false. + * @return void + * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) + */ + setUrl(url: string | url.Url, stripTrailingSlash?: boolean): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Response + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * Access: read only and the public podium interface. + * The response.events object supports the following events: + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ +export interface ResponseEvents extends Podium { + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ + on(criteria: 'peek', listener: PeekListener): void; + + on(criteria: 'finish', listener: (data: undefined) => void): void; + + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ + once(criteria: 'peek', listener: PeekListener): void; + + once(criteria: 'finish', listener: (data: undefined) => void): void; +} + +/** + * Object where: + * * append - if true, the value is appended to any existing header value using separator. Defaults to false. + * * separator - string used as separator when appending to an existing value. Defaults to ','. + * * override - if false, the header value is not set if an existing value present. Defaults to true. + * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + */ +export interface ResponseObjectHeaderOptions { + append?: boolean; + separator?: string; + override?: boolean; + duplicate?: boolean; +} + +/** + * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle + * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status + * code). In order to customize a response before it is returned, the h.response() method is provided. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ +export interface ResponseObject extends Podium { + /** + * Default value: {}. + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp) + */ + app: ApplicationState; + + /** + * Access: read only and the public podium interface. + * The response.events object supports the following events: + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ + readonly events: ResponseEvents; + + /** + * Default value: {}. + * An object containing the response headers where each key is a header field name and the value is the string header value or array of string. + * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) + */ + readonly headers: Util.Dictionary; + + /** + * Default value: {}. + * Plugin-specific state. Provides a place to store and pass request-level plugin data. plugins is an object where each key is a plugin name and the value is the state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins) + */ + plugins: PluginsStates; + + /** + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) + */ + readonly settings: ResponseSettings; + + /** + * The raw value returned by the lifecycle method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource) + */ + readonly source: Lifecycle.ReturnValue; + + /** + * Default value: 200. + * The HTTP response status code. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode) + */ + readonly statusCode: number; + + /** + * A string indicating the type of source with available values: + * * 'plain' - a plain response such as string, number, null, or simple object. + * * 'buffer' - a Buffer. + * * 'stream' - a Stream. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety) + */ + readonly variety: 'plain' | 'buffer' | 'stream'; + + /** + * Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: + * @param length - the header value. Must match the actual payload size. + * @return Return value: the current response object. + * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength) + */ + bytes(length: number): ResponseObject; + + /** + * Sets the 'Content-Type' HTTP header 'charset' property where: + * @param charset - the charset property value. + * @return Return value: the current response object. + * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset) + */ + charset(charset: string): ResponseObject; + + /** + * Sets the 'Content-Type' HTTP header 'charset' property where: + * $param charset - the charset property value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode) + */ + code(statusCode: number): ResponseObject; + + /** + * Sets the HTTP status message where: + * @param httpMessage - the HTTP status message (e.g. 'Ok' for status code 200). + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage) + */ + message(httpMessage: string): ResponseObject; + + /** + * Sets the HTTP status code to Created (201) and the HTTP 'Location' header where: + * @param uri - an absolute or relative URI used as the 'Location' header value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri) + */ + created(uri: string): ResponseObject; + + /** + * Sets the string encoding scheme used to serial data into the HTTP payload where: + * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). + * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. + * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. + * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. + * * 'ucs2' - Alias of 'utf16le'. + * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. + * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). + * * 'binary' - Alias for 'latin1'. + * * 'hex' - Encode each byte as two hexadecimal characters. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding) + */ + encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject; + + /** + * Sets the representation entity tag where: + * @param tag - the entity tag string without the double-quote. + * @param options - (optional) settings where: + * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by + * a '-' character). Ignored when weak is true. Defaults to true. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options) + */ + etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject; + + /** + * Sets an HTTP header where: + * @param name - the header name. + * @param value - the header value. + * @param options - (optional) object where: + * * append - if true, the value is appended to any existing header value using separator. Defaults to false. + * * separator - string used as separator when appending to an existing value. Defaults to ','. + * * override - if false, the header value is not set if an existing value present. Defaults to true. + * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) + */ + header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject; + + /** + * Sets the HTTP 'Location' header where: + * @param uri - an absolute or relative URI used as the 'Location' header value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri) + */ + location(uri: string): ResponseObject; + + /** + * Sets an HTTP redirection response (302) and decorates the response with additional methods, where: + * @param uri - an absolute or relative URI used to redirect the client to another resource. + * @return Return value: the current response object. + * Decorates the response object with the response.temporary(), response.permanent(), and response.rewritable() methods to easily change the default redirection code (302). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi) + */ + redirect(uri: string): ResponseObject; + + /** + * Sets the JSON.stringify() replacer argument where: + * @param method - the replacer function or array. Defaults to none. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod) + */ + replacer(method: Json.StringifyReplacer): ResponseObject; + + /** + * Sets the JSON.stringify() space argument where: + * @param count - the number of spaces to indent nested object keys. Defaults to no indentation. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount) + */ + spaces(count: number): ResponseObject; + + /** + * Sets an HTTP cookie where: + * @param name - the cookie name. + * @param value - the cookie value. If no options.encoding is defined, must be a string. See server.state() for supported encoding values. + * @param options - (optional) configuration. If the state was previously registered with the server using server.state(), the specified keys in options are merged with the default server + * definition. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) + */ + state(name: string, value: object | string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * Sets a string suffix when the response is process via JSON.stringify() where: + * @param suffix - the string suffix. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix) + */ + suffix(suffix: string): ResponseObject; + + /** + * Overrides the default route cache expiration rule for this response instance where: + * @param msec - the time-to-live value in milliseconds. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec) + */ + ttl(msec: number): ResponseObject; + + /** + * Sets the HTTP 'Content-Type' header where: + * @param mimeType - is the mime type. + * @return Return value: the current response object. + * Should only be used to override the built-in default for each response type. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype) + */ + type(mimeType: string): ResponseObject; + + /** + * Clears the HTTP cookie by setting an expired value where: + * @param name - the cookie name. + * @param options - (optional) configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified options are merged with the server + * definition. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options) + */ + unstate(name: string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: + * @param header - the HTTP request header name. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader) + */ + vary(header: string): ResponseObject; + + /** + * Marks the response object as a takeover response. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover) + */ + takeover(): ResponseObject; + + /** + * Sets the status code to 302 or 307 (based on the response.rewritable() setting) where: + * @param isTemporary - if false, sets status to permanent. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary) + */ + temporary(isTemporary: boolean): ResponseObject; + + /** + * Sets the status code to 301 or 308 (based on the response.rewritable() setting) where: + * @param isPermanent - if false, sets status to temporary. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent) + */ + permanent(isPermanent: boolean): ResponseObject; + + /** + * Sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' + * to 'GET'). Exact code based on the response.temporary() or response.permanent() setting. Arguments: + * @param isRewritable - if false, sets to non-rewritable. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable) + */ + rewritable(isRewritable: boolean): ResponseObject; +} + +/** + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) + */ +export interface ResponseSettings { + /** + * Defaults value: true. + * If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response. + */ + readonly passThrough: boolean; + + /** + * Default value: null (use route defaults). + * Override the route json options used when source value requires stringification. + */ + readonly stringify: Json.StringifyArguments; + + /** + * Default value: null (use route defaults). + * If set, overrides the route cache with an expiration value in milliseconds. + */ + readonly ttl: number; + + /** + * Default value: false. + * If true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. + */ + varyEtag: boolean; +} + +/** + * See more about Lifecycle + * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle + * + */ + +export type ResponseValue = string | object; + +export interface AuthenticationData { + credentials: AuthCredentials; + artifacts?: object; +} + +export interface Auth { + readonly isAuth: true; + readonly error?: Error | null; + readonly data?: AuthenticationData; +} + +/** + * The response toolkit is a collection of properties and utilities passed to every [lifecycle method](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the + * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this + * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) + */ +export interface ResponseToolkit { + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step + * without further interaction with the node response stream. It is the developer's responsibility to write + * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw). + */ + readonly abandon: symbol; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after + * calling request.raw.res.end()) to close the the node response stream. + */ + readonly close: symbol; + + /** + * A response symbol. Provides access to the route or server context set via the route [bind](https://github.com/hapijs/hapi/blob/master/API.md#route.options.bind) + * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()). + */ + readonly context: any; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response. + */ + readonly continue: symbol; + + /** + * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching + * route. Defaults to the root server realm in the onRequest step. + */ + readonly realm: ServerRealm; + + /** + * Access: read only and public request interface. + * The [request] object. This is a duplication of the request lifecycle method argument used by + * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request. + */ + readonly request: Readonly; + + /** + * Used by the [authentication] method to pass back valid credentials where: + * @param data - an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return Return value: an internal authentication object. + */ + authenticated(data: AuthenticationData): Auth; + + /** + * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if + * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request + * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will + * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined. + * The method argumetns are: + * @param options - a required configuration object with: + * * etag - the ETag string. Required if modified is not present. Defaults to no header. + * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. + * * vary - same as the response.etag() option. Defaults to true. + * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed. + * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned, + * it should be used as the return value (but may be customize using the response methods). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions) + */ + entity(options?: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined; + + /** + * Redirects the client to the specified uri. Same as calling h.response().redirect(uri). + * @param url + * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi) + */ + redirect(uri?: string): ResponseObject; + + /** + * Wraps the provided value and returns a response object which allows customizing the response + * (e.g. setting the HTTP status code, custom headers, etc.), where: + * @param value - (optional) return value. Defaults to null. + * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue) + */ + response(value?: ResponseValue): ResponseObject; + + /** + * Sets a response cookie using the same arguments as response.state(). + * @param name of the cookie + * @param value of the cookie + * @param (optional) ServerStateCookieOptions object. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options) + */ + state(name: string, value: string | object, options?: ServerStateCookieOptions): void; + + /** + * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: + * @param error - (required) the authentication error. + * @param data - (optional) an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return void. + * The method is used to pass both the authentication error and the credentials. For example, if a request included + * expired credentials, it allows the method to pass back the user information (combined with a 'try' + * authentication mode) for error customization. + * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data) + */ + unauthenticated(error: Error, data?: AuthenticationData): void; + + /** + * Clears a response cookie using the same arguments as + * @param name of the cookie + * @param options (optional) ServerStateCookieOptions object. + * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options) + */ + unstate(name: string, options?: ServerStateCookieOptions): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Route + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +export type RouteOptionsAccessScope = false | string | string[]; + +export type RouteOptionsAccessEntity = 'any' | 'user' | 'app'; + +export interface RouteOptionsAccessScopeObject { + scope: RouteOptionsAccessScope; +} + +export interface RouteOptionsAccessEntityObject { + entity: RouteOptionsAccessEntity; +} + +export type RouteOptionsAccessObject = + RouteOptionsAccessScopeObject + | RouteOptionsAccessEntityObject + | (RouteOptionsAccessScopeObject & RouteOptionsAccessEntityObject); + +/** + * Route Authentication Options + */ +export interface RouteOptionsAccess { + /** + * Default value: none. + * An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object + * must include at least one of scope or entity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess) + */ + access?: RouteOptionsAccessObject | RouteOptionsAccessObject[]; + + /** + * Default value: false (no scope requirements). + * The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least + * one of the scopes defined to access the route. If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For + * example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. You may also access + * properties on the request object (query, params, payload, and credentials) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as 'user-{params.id}'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) + */ + scope?: RouteOptionsAccessScope; + + /** + * Default value: 'any'. + * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values: + * * 'any' - the authentication can be on behalf of a user or application. + * * 'user' - the authentication must be on behalf of a user which is identified by the presence of a 'user' attribute in the credentials object returned by the authentication strategy. + * * 'app' - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication + * strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity) + */ + entity?: RouteOptionsAccessEntity; + + /** + * Default value: 'required'. + * The authentication mode. Available values: + * * 'required' - authentication is required. + * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all. + * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode) + */ + mode?: 'required' | 'optional' | 'try'; + + /** + * Default value: false, unless the scheme requires payload authentication. + * If set, the incoming request payload is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' + * when the scheme sets the authentication options.payload to true. Available values: + * * false - no payload authentication. + * * 'required' - payload authentication required. + * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload) + */ + payload?: false | 'required' | 'optional'; + + /** + * Default value: the default strategy set via server.auth.default(). + * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies) + */ + strategies?: string[]; + + /** + * Default value: the default strategy set via server.auth.default(). + * A string strategy names. Cannot be used together with strategies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy) + */ + strategy?: string; +} + +/** + * Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) + */ +export type RouteOptionsCache = { + privacy?: 'default' | 'public' | 'private'; + statuses?: number[]; + otherwise?: string; +} & ( + { + expiresIn?: number; + expiresAt?: undefined; + } | { + expiresIn?: undefined; + expiresAt?: string; +} | { + expiresIn?: undefined; + expiresAt?: undefined; +} + ); + +/** + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain + * than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a + * wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. + * Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. + * Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) + */ +export interface RouteOptionsCors { + /** + * an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' + * character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any + * origin ['*']. + */ + origin?: string[] | '*' | 'ignore'; + /** + * number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. + * Defaults to 86400 (one day). + */ + maxAge?: number; + /** + * a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + */ + headers?: string[]; + /** + * a strings array of additional headers to headers. Use this to keep the default headers in place. + */ + additionalHeaders?: string[]; + /** + * a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + */ + exposedHeaders?: string[]; + /** + * a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + */ + additionalExposedHeaders?: string[]; + /** + * if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + */ + credentials?: boolean; +} + +/** + * The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw + * Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are + * provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart + * payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the + * multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are + * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of + * which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. For context [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) + */ +export type PayloadOutput = 'data' | 'stream' | 'file'; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) + */ +export type PayloadCompressionDecoderSettings = object; + +/** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ +export interface RouteOptionsPayload { + /** + * Default value: allows parsing of the following mime types: + * * application/json + * * application/*+json + * * application/octet-stream + * * application/x-www-form-urlencoded + * * multipart/form-data + * * text/* + * A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed + * above will not enable them to be parsed, and if parse is true, the request will result in an error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow) + */ + allow?: string | string[]; + + /** + * Default value: none. + * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) + */ + compression?: Util.Dictionary; + + /** + * Default value: 'application/json'. + * The default content type if the 'Content-Type' request header is missing. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype) + */ + defaultContentType?: string; + + /** + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle payload parsing errors. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: 1048576 (1MB). + * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes) + */ + maxBytes?: number; + + /** + * Default value: none. + * Overrides payload processing for multipart requests. Value can be one of: + * * false - disable multipart processing. + * an object with the following required options: + * * output - same as the output option with an additional value option: + * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? + * * * * headers - the part headers. + * * * * filename - the part file name. + * * * * payload - the processed part payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart) + */ + multipart?: false | { + output: PayloadOutput | 'annotated'; + }; + + /** + * Default value: 'data'. + * The processed payload format. The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw + * Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files + * are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart + * payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the + * multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are + * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track + * of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) + */ + output?: PayloadOutput; + + /** + * Default value: none. + * A mime type string overriding the 'Content-Type' header value received. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride) + */ + override?: string; + + /** + * Default value: true. + * Determines if the incoming payload is processed or presented raw. Available values: + * * true - if the request 'Content-Type' matches the allowed mime types set by allow (for the whole payload as well as parts), the payload is converted into an object when possible. If the + * format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded. + * * false - the raw payload is returned unmodified. + * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse) + */ + parse?: boolean | 'gunzip'; + + /** + * Default value: to 10000 (10 seconds). + * Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) + * error response. Set to false to disable. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout) + */ + timeout?: false | number; + + /** + * Default value: os.tmpdir(). + * The directory used for writing file uploads. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads) + */ + uploads?: string; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreArray = RouteOptionsPreAllOptions[]; + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.Method; + +/** + * An object with: + * * method - a lifecycle method. + * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export interface RouteOptionsPreObject { + /** + * a lifecycle method. + */ + method: Lifecycle.Method; + /** + * key name used to assign the response of the method to in request.pre and request.preResponses. + */ + assign?: string; + /** + * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + */ + failAction?: Lifecycle.FailAction; +} + +export type ValidationObject = SchemaMap; + +export type RouteOptionsResponseSchema = + boolean + | ValidationObject + | Schema + | ((value: object | Buffer | string, options: ValidationOptions) => Promise); + +/** + * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) + */ +export interface RouteOptionsResponse { + /** + * Default value: 200. + * The default HTTP status code when the payload is considered empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time of response transmission (the + * response status code will remain 200 throughout the request lifecycle unless manually set). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode) + */ + emptyStatusCode?: 200 | 204; + + /** + * Default value: 'error' (return an Internal Server Error (500) error response). + * A failAction value which defines what to do when a response fails payload validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: false. + * If true, applies the validation rule changes to the response payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify) + */ + modify?: boolean; + + /** + * Default value: none. + * [joi](http://github.com/hapijs/joi) options object pass to the validation function. Useful to set global options such as stripUnknown or abortEarly (the complete list is available here). If a + * custom validation function is defined via schema or status then options can an arbitrary object that will be passed to this function as the second argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions) + */ + options?: ValidationOptions; // TODO needs validation + + /** + * Default value: true. + * If false, payload range support is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges) + */ + ranges?: boolean; + + /** + * Default value: 100 (all responses). + * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample) + */ + sample?: number; + + /** + * Default value: true (no validation). + * The default response payload validation rules (for all non-error responses) expressed as one of: + * * true - any payload allowed (no validation). + * * false - no payload allowed. + * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function. + * * a validation function using the signature async function(value, options) where: + * * * value - the pending response payload. + * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }). + * * * if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error + * output.payload. If an error is thrown, the error is processed according to failAction. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema) + */ + schema?: RouteOptionsResponseSchema; + + /** + * Default value: none. + * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema. + * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) + */ + status?: Util.Dictionary; +} + +/** + * @see https://www.w3.org/TR/referrer-policy/ + */ +export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'unsafe-url' | + 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin'; + +/** + * Default value: false (security headers disabled). + * Sets common security headers. To enable, set security to true or to an object with the following options: + * * hsts - controls the 'Strict-Transport-Security' header, where: + * * * true - the header will be set to max-age=15768000. This is the default value. + * * * a number - the maxAge parameter will be set to the provided value. + * * * an object with the following fields: + * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. + * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. + * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + * * xframe - controls the 'X-Frame-Options' header, where: + * * * true - the header will be set to 'DENY'. This is the default value. + * * * 'deny' - the headers will be set to 'DENY'. + * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. + * * * an object for specifying the 'allow-from' rule, where: + * * * * rule - one of: + * * * * * 'deny' + * * * * * 'sameorigin' + * * * * * 'allow-from' + * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically + * changed to 'sameorigin'. + * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively + * support old versions of IE, it may be wise to explicitly set this flag to false. + * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) + */ +export interface RouteOptionsSecureObject { + /** + * hsts - controls the 'Strict-Transport-Security' header + */ + hsts?: boolean | number | { + /** + * the max-age portion of the header, as a number. Default is 15768000. + */ + maxAge: number; + /** + * a boolean specifying whether to add the includeSubDomains flag to the header. + */ + includeSubdomains: boolean; + /** + * a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + */ + preload: boolean; + }; + /** + * controls the 'X-Frame-Options' header + */ + xframe?: true | 'deny' | 'sameorigin' | { + /** + * an object for specifying the 'allow-from' rule, + */ + rule: 'deny' | 'sameorigin' | 'allow-from'; + /** + * when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed + * to 'sameorigin'. + */ + source: string; + }; + /** + * boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively + * support old versions of IE, it may be wise to explicitly set this flag to false. + */ + xss: boolean; + /** + * boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + */ + noOpen?: boolean; + /** + * boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + */ + noSniff?: boolean; + + /** + * Controls the `Referrer-Policy` header, which has the following possible values. + * @default false Header will not be send. + */ + referrer?: false | ReferrerPolicy; +} + +export type RouteOptionsSecure = boolean | RouteOptionsSecureObject; + +/** + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) + */ +export interface RouteOptionsValidate { + /** + * Default value: none. + * An optional object with error fields copied into every validation error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields) + */ + errorFields?: object; + + /** + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle failed validations. When set to a function, the err argument includes the type of validation error under err.output.payload.validation.source. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatefailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: true (no validation). + * Validation rules for incoming request headers: + * * true - any headers allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.headers object containing the request headers. + * * * options - options. + * * * if a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error + * is thrown, the error is handled according to failAction. Note that all header field names must be in lowercase to match the headers normalized by node. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) + */ + headers?: RouteOptionsResponseSchema; + + /** + * Default value: none. + * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here). + * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter. + * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as + * Joi.ref('$query.key')). + * Note that validation is performed in order (i.e. headers, params, query, and payload) and if type casting is used (e.g. converting a string to a number), the value of inputs not yet validated + * will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the + * individual route settings override the routes defaults (the rules are not merged). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + */ + options?: ValidationOptions | object; + + /** + * Default value: true (no validation). + * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where: + * * true - any path parameter value allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.params object containing the request path parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an + * error is thrown, the error is handled according to failAction. Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + */ + params?: RouteOptionsResponseSchema; + + /** + * Default value: true (no validation). + * Validation rules for incoming request payload (request body), where: + * * true - any payload allowed (no validation performed). false - no payload allowed. + * * a joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are allowed, the schema must be explicitly defined by + * setting the rule to a joi schema with null allowed (e.g. Joi.object({ keys here }).allow(null)). + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is + * thrown, the error is handled according to failAction. Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well + * as the significant performance cost of validating large amounts of data. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) + */ + payload?: RouteOptionsResponseSchema; + + /** + * Default value: true (no validation). + * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in + * request.query prior to validation. Where: + * * true - any query parameter value allowed (no validation performed). false - no query parameter value allowed. + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. If an error + * is thrown, the error is handled according to failAction. Note that changes to the query parameters will not be reflected in request.url. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) + */ + query?: RouteOptionsResponseSchema; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + */ +export type RouteCompressionEncoderSettings = object; + +/** + * Empty interface to allow for user-defined augmentations. + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface RouteOptionsApp { +} + +/** + * Each route can be customized to change the default behavior of the request lifecycle. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options) + */ +export interface RouteOptions { + /** + * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) + */ + app?: RouteOptionsApp; + + /** + * Route authentication configuration. Value can be: + * false to disable authentication if a default strategy is set. + * a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode. + * an authentication configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) + */ + auth?: false | string | RouteOptionsAccess; + + /** + * Default value: null. + * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind) + */ + bind?: object | null; + + /** + * Default value: { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. + * If the route method is 'GET', the route can be configured to include HTTP caching directives in the response. Caching can be customized using an object with the following options: + * privacy - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * The default Cache-Control: no-cache header can be disabled by setting cache to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) + */ + cache?: false | RouteOptionsCache; + + /** + * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) + */ + compression?: Util.Dictionary; + + /** + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different + * domain than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a + * wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. + * Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in + * policy. Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) + */ + cors?: boolean | RouteOptionsCors; + + /** + * Default value: none. + * Route description used for generating documentation (string). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsdescription) + */ + description?: string; + + /** + * Default value: none. + * Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the + * server.ext(events) event argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ + ext?: { + [key in RouteRequestExtType]?: RouteExtObject | RouteExtObject[]; + }; + + /** + * Default value: { relativeTo: '.' }. + * Defines the behavior for accessing files: + * * relativeTo - determines the folder relative paths are resolved against. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsfiles) + */ + files?: { + relativeTo: string; + }; + + /** + * Default value: none. + * The route handler function performs the main business logic of the route and sets the response. handler can be assigned: + * * a lifecycle method. + * * an object with a single property using the name of a handler type registred with the server.handler() method. The matching property value is passed as options to the registered handler + * generator. Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler) + */ + handler?: Lifecycle.Method | object; + + /** + * Default value: none. + * An optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes added with an array of methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsid) + */ + id?: string; + + /** + * Default value: false. + * If true, the route cannot be accessed through the HTTP listener but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should + * not be accessible to the outside world. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsisinternal) + */ + isInternal?: boolean; + + /** + * Default value: none. + * Optional arguments passed to JSON.stringify() when converting an object or error response to a string payload or escaping it after stringification. Supports the following: + * * replacer - the replacer function or array. Defaults to no action. + * * space - number of spaces to indent nested object keys. Defaults to no indentation. + * * suffix - string suffix added after conversion to JSON string. Defaults to no suffix. + * * escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + json?: Json.StringifyArguments; + + /** + * Default value: none. + * Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. + * For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Cannot be used with stream + * responses. The 'Content-Type' response header is set to 'text/javascript' and the 'X-Content-Type-Options' response header is set to 'nosniff', and will override those headers even if + * explicitly set by response.type(). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjsonp) + */ + jsonp?: string; + + /** + * Default value: { collect: false }. + * Request logging options: + * collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionslog) + */ + log?: { + collect: boolean; + }; + + /** + * Default value: none. + * Route notes used for generating documentation (string or array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsnotes) + */ + notes?: string | string[]; + + /** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ + payload?: RouteOptionsPayload; + + /** + * Default value: {}. + * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) + */ + plugins?: PluginSpecificConfiguration; + + /** + * Default value: none. + * The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared + * ascross routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). pre is assigned an ordered array of methods which + * are called serially in order. If the pre array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of + * the methods error, return a takeover response, or abort signal, the other parallel methods will continue to execute but will be ignored once completed. pre can be assigned a mixed array of: + * * an array containing the elements listed below, which are executed in parallel. + * * an object with: + * * * method - a lifecycle method. + * * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be + * assigned. + * * a method function - same as including an object with a single method key. + * Note that pre-handler methods do not behave the same way other lifecycle methods do when a value is returned. Instead of the return value becoming the new response payload, the value is used + * to assign the corresponding request.pre and request.preResponses properties. Otherwise, the handling of errors, takeover response response, or abort signal behave the same as any other + * lifecycle methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ + pre?: RouteOptionsPreArray; + + /** + * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) + */ + response?: RouteOptionsResponse; + + /** + * Default value: false (security headers disabled). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) + */ + security?: RouteOptionsSecure; + + /** + * Default value: { parse: true, failAction: 'error' }. + * HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following + * options: parse - determines if incoming 'Cookie' headers are parsed and stored in the request.state object. failAction - A failAction value which determines how to handle cookie parsing + * errors. Defaults to 'error' (return a Bad Request (400) error response). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsstate) + */ + state?: { + parse?: boolean; + failAction?: Lifecycle.FailAction; + }; + + /** + * Default value: none. + * Route tags used for generating documentation (array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstags) + */ + tags?: string[]; + + /** + * Default value: { server: false }. + * Timeouts for processing durations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstimeout) + */ + timeout?: { + /** + * Response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming request before giving up and responding with a Service Unavailable (503) error + * response. + */ + server?: boolean | number; + + /** + * Default value: none (use node default of 2 minutes). + * By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to false to disable socket timeouts. + */ + socket?: boolean | number; + }; + + /** + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) + */ + validate?: RouteOptionsValidate; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Server + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + */ +export type ServerAuthSchemeOptions = object; + +/** + * the method implementing the scheme with signature function(server, options) where: + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + * @param server - a reference to the server object the scheme is added to. + * @param options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + */ +export type ServerAuthScheme = (server: Server, options?: ServerAuthSchemeOptions) => ServerAuthSchemeObject; + +/* tslint:disable-next-line:no-empty-interface */ +export interface ServerAuthSchemeObjectApi { +} + +/** + * The scheme method must return an object with the following + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#authentication-scheme) + */ +export interface ServerAuthSchemeObject { + /** + * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object. + */ + api?: ServerAuthSchemeObjectApi; + + /** + * A lifecycle method function called for each incoming request configured with the authentication scheme. The + * method is provided with two special toolkit methods for returning an authenticated or an unauthenticate result: + * * h.authenticated() - indicate request authenticated successfully. + * * h.unauthenticated() - indicate request failed to authenticate. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + authenticate(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * A lifecycle method to authenticate the request payload. + * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad + * payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), + * authentication may still be successful if the route auth.payload configuration is set to 'optional'. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + payload?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * a method used to verify the authentication credentials provided + * are still valid (e.g. not expired or revoked after the initial authentication). + * the method throws an `Error` when the credentials passed are no longer valid (e.g. expired or + * revoked). Note that the method does not have access to the original request, only to the + * credentials and artifacts produced by the `authenticate()` method. + */ + verify?(auth: RequestAuth): Promise; + + /** + * An object with the following keys: + * * payload + */ + options?: { + /** + * if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. + */ + payload?: boolean; + }; +} + +/** + * An authentication configuration object using the same format as the route auth handler options. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface ServerAuthConfig extends RouteOptionsAccess { +} + +export interface ServerAuth { + /** + * An object where each key is an authentication strategy name and the value is the exposed strategy API. + * Available only when the authentication scheme exposes an API by returning an api key in the object + * returned from its implementation function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) + */ + api: Util.Dictionary; + + /** + * Contains the default authentication configuration is a default strategy was set via + * [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). + */ + readonly settings: { + default: ServerAuthConfig; + }; + + /** + * Sets a default strategy which is applied to every route where: + * @param options - one of: + * * a string with the default strategy name + * * an authentication configuration object using the same format as the route auth handler options. + * @return void. + * The default does not apply when a route config specifies auth as false, or has an authentication strategy + * configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication + * config is applied to the defaults. + * Note that if the route has authentication configured, the default only applies at the time of adding the route, + * not at runtime. This means that calling server.auth.default() after adding a route with some authentication + * config will have no impact on the routes added prior. However, the default will apply to routes added + * before server.auth.default() is called if those routes lack any authentication config. + * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active + * authentication configuration of a route, use server.auth.lookup(request.route). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + */ + default(options: string | ServerAuthConfig): void; + + /** + * Registers an authentication scheme where: + * @param name the scheme name. + * @param scheme - the method implementing the scheme with signature function(server, options) where: + * * server - a reference to the server object the scheme is added to. + * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + */ + scheme(name: string, scheme: ServerAuthScheme): void; + + /** + * Registers an authentication strategy where: + * @param name - the strategy name. + * @param scheme - the scheme name (must be previously registered using server.auth.scheme()). + * @param options - scheme options based on the scheme requirements. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) + */ + strategy(name: string, scheme: string, options?: object): void; + + /** + * Tests a request against an authentication strategy where: + * @param strategy - the strategy name registered with server.auth.strategy(). + * @param request - the request object. + * @return Return value: the authentication credentials object if authentication was successful, otherwise throws an error. + * Note that the test() method does not take into account the route authentication configuration. It also does not + * perform payload authentication. It is limited to the basic strategy authentication execution. It does not + * include verifying scope, entity, or other route properties. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) + */ + test(strategy: string, request: Request): Promise; + + /** + * Verify a request's authentication credentials against an authentication strategy. + * Returns nothing if verification was successful, otherwise throws an error. + * + * Note that the `verify()` method does not take into account the route authentication configuration + * or any other information from the request other than the `request.auth` object. It also does not + * perform payload authentication. It is limited to verifying that the previously valid credentials + * are still valid (e.g. have not been revoked or expired). It does not include verifying scope, + * entity, or other route properties. + */ + verify(request: Request): Promise; +} + +export type CachePolicyOptions = PolicyOptionVariants & { + /** + * @default '_default' + */ + cache?: string; + segment?: string; +}; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerCache { + /** + * Provisions a cache segment within the server cache facility where: + * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: + * - `id` - the `id` string or object provided to the `get()` method. + * - `flags` - an object used to pass back additional flags to the cache where: + * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. + * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + * * staleTimeout - number of milliseconds to wait before checking if an item is stale. + * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it + * is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. + * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. + * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. + * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. + * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of + * concurrent generateFunc calls beyond staleTimeout). + * * cache - the cache name configured in server.cache. Defaults to the default cache. + * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a + * server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. + * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. + * @return Catbox Policy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + = CachePolicyOptions>(options: O): Policy; + + /** + * Provisions a server cache as described in server.cache where: + * @param options - same as the server cache configuration options. + * @return Return value: none. + * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) + */ + provision(options: ServerOptionsCache): Promise; +} + +/** + * an event name string. + * an event options object. + * a podium emitter object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) + */ +export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium; + +/** + * Object that it will be used in Event + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) + */ +export interface ServerEventsApplicationObject { + /** the event name string (required). */ + name: string; + /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ + channels?: string | string[]; + /** + * if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). + */ + clone?: boolean; + /** + * if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified + * by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). + */ + spread?: boolean; + /** + * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to + * the arguments list at the end. A configuration override can be set by each listener. Defaults to false. + */ + tags?: boolean; + /** + * if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first + * configuration is used. Defaults to false (a duplicate registration will throw an error). + */ + shared?: boolean; +} + +/** + * A criteria object with the following optional keys (unless noted otherwise): + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * + * The type parameter T is the type of the name of the event. + */ +export interface ServerEventCriteria { + /** (required) the event name string. */ + name: T; + /** + * a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed + * channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. + */ + channels?: string | string[]; + /** if true, the data object passed to server.event.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ + clone?: boolean; + /** + * a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.events.once(). + * Defaults to no limit. + */ + count?: number; + /** + * filter - the event tags (if present) to subscribe to which can be one of: + * * a tag string. + * * an array of tag strings. + * * an object with the following: + * * * tags - a tag string or array of tag strings. + * * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). + */ + filter?: string | string[] | {tags: string | string[], all?: boolean}; + /** + * if true, and the data object passed to server.event.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used + * when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). + */ + spread?: boolean; + /** + * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended + * to the arguments list at the end. Defaults to the event registration option (which defaults to false). + */ + tags?: boolean; +} + +export interface LogEvent { + /** the event timestamp. */ + timestamp: string; + /** an array of tags identifying the event (e.g. ['error', 'http']) */ + tags: string[]; + /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */ + channel: 'internal' | 'app'; + /** the request identifier. */ + request: string; + /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */ + data: object; + /** the error object related to the event if applicable. Cannot appear together with data */ + error: object; +} + +export interface RequestEvent { + /** the event timestamp. */ + timestamp: string; + /** an array of tags identifying the event (e.g. ['error', 'http']) */ + tags: string[]; + /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */ + channel: 'internal' | 'app' | 'error'; + /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */ + data: object; + /** the error object related to the event if applicable. Cannot appear together with data */ + error: object; +} + +export type LogEventHandler = (event: LogEvent, tags: { [key: string]: true }) => void; +export type RequestEventHandler = (request: Request, event: RequestEvent, tags: { [key: string]: true }) => void; +export type ResponseEventHandler = (request: Request) => void; +export type RouteEventHandler = (route: RequestRoute) => void; +export type StartEventHandler = () => void; +export type StopEventHandler = () => void; + +export interface PodiumEvent { + emit(criteria: K, listener: (value: T) => void): void; + + on(criteria: K, listener: (value: T) => void): void; + + once(criteria: K, listener: (value: T) => void): void; + + once(criteria: K): Promise; + + removeListener(criteria: K, listener: Podium.Listener): this; + + removeAllListeners(criteria: K): this; + + hasListeners(criteria: K): this; +} + +/** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.event(events)](https://github.com/hapijs/hapi/blob/master/API.md#server.event()) - register application events. + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ +export interface ServerEvents extends Podium { + /** + * Subscribe to an event where: + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event) + * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event) + * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event) + * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event) + * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) + * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) + */ + on(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): void; + + on(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): void; + + on(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): void; + + on(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): void; + + on(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): void; + + on(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): void; + + /** + * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) + */ + once(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): void; + + once(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): void; + + once(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): void; + + once(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): void; + + once(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): void; + + once(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): void; + + /** + * Same as calling server.events.on() with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @return Return value: a promise that resolves when the event is emitted. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) + */ + once(criteria: string | ServerEventCriteria): Promise; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeListener(name: string, listener: Podium.Listener): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeAllListeners(name: string): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + hasListeners(name: string): boolean; +} + +/** + * The extension point event name. The available extension points include the request extension points as well as the following server extension points: + * 'onPreStart' - called before the connection listeners are started. + * 'onPostStart' - called after the connection listeners are started. + * 'onPreStop' - called before the connection listeners are stopped. + * 'onPostStop' - called after the connection listeners are stopped. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ +export type ServerExtType = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'; +export type RouteRequestExtType = 'onPreAuth' + | 'onCredentials' + | 'onPostAuth' + | 'onPreHandler' + | 'onPostHandler' + | 'onPreResponse'; + +export type ServerRequestExtType = + RouteRequestExtType + | 'onRequest'; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or + * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsObject { + /** + * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + */ + type: ServerExtType; + /** + * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * server extension points: async function(server) where: + * * * server - the server object. + * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * request extension points: a lifecycle method. + */ + method: ServerExtPointFunction | ServerExtPointFunction[]; + options?: ServerExtOptions; +} + +export interface RouteExtObject { + method: Lifecycle.Method; + options?: ServerExtOptions; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or + * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsRequestObject { + /** + * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + * * 'onPostStop' - called after the connection listeners are stopped. + */ + type: ServerRequestExtType; + /** + * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * server extension points: async function(server) where: + * * * server - the server object. + * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * request extension points: a lifecycle method. + */ + method: Lifecycle.Method | Lifecycle.Method[]; + /** + * (optional) an object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, + * or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + options?: ServerExtOptions; +} + +export type ServerExtPointFunction = (server: Server) => void; + +/** + * An object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or + * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. For context [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + */ +export interface ServerExtOptions { + /** + * a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + */ + before?: string | string[]; + /** + * a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + */ + after?: string | string[]; + /** + * a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + */ + bind?: object; + /** + * if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when + * adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + sandbox?: 'server' | 'plugin'; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + * An object containing information about the server where: + */ +export interface ServerInfo { + /** + * a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + */ + id: string; + + /** + * server creation timestamp. + */ + created: number; + + /** + * server start timestamp (0 when stopped). + */ + started: number; + + /** + * the connection [port](https://github.com/hapijs/hapi/blob/master/API.md#server.options.port) based on the following rules: + * * before the server has been started: the configured port value. + * * after the server has been started: the actual port assigned when no port is configured or was set to 0. + */ + port: number | string; + + /** + * The [host](https://github.com/hapijs/hapi/blob/master/API.md#server.options.host) configuration value. + */ + host: string; + + /** + * the active IP address the connection was bound to after starting. Set to undefined until the server has been + * started or when using a non TCP port (e.g. UNIX domain socket). + */ + address: undefined | string; + + /** + * the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + */ + protocol: 'http' | 'https' | 'socket'; + + /** + * a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains + * the uri value if set, otherwise constructed from the available settings. If no port is configured or is set + * to 0, the uri will not include a port component until the server is started. + */ + uri: string; +} + +/** + * An object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload + * processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if + * they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as + * if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested + * separately. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectOptions extends Shot.RequestOptions { + /** + * an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via + * an authentication scheme. Defaults to no credentials. + */ + credentials?: AuthCredentials; + /** + * (an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received + * via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + */ + artifacts?: object; + /** + * sets the initial value of request.app, defaults to {}. + */ + app?: ApplicationState; + /** + * sets the initial value of request.plugins, defaults to {}. + */ + plugins?: PluginsStates; + /** + * allows access to routes with config.isInternal set to true. Defaults to false. + */ + allowInternals?: boolean; +} + +/** + * A response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of + * the internal objects returned (instead of parsing the response string). + * * request - the request object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectResponse extends Shot.ResponseObject { + /** + * the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the + * internal objects returned (instead of parsing the response string). + */ + result: object | undefined; + /** + * the request object. + */ + request: Request; +} + +/** + * The method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export type ServerMethod = (...args: any[]) => any; + +/** + * The same cache configuration used in server.cache(). + * The generateTimeout option is required. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerMethodCache extends PolicyOptions { + generateTimeout: number | false; +} + +/** + * Configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an + * arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically + * generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided + * which takes the same arguments as the function and returns a unique string (or null if no key can be generated). For reference [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export interface ServerMethodOptions { + /** + * a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow + * function. + */ + bind?: object; + /** + * the same cache configuration used in server.cache(). The generateTimeout option is required. + */ + cache?: ServerMethodCache; + /** + * a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a + * unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which + * takes the same arguments as the function and returns a unique string (or null if no key can be generated). + */ + generateKey?(...args: any[]): string | null; +} + +/** + * An object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ +export interface ServerMethodConfigurationObject { + /** + * the method name. + */ + name: string; + /** + * the method function. + */ + method: ServerMethod; + /** + * (optional) settings. + */ + options?: ServerMethodOptions; +} + +/** + * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, + * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache) + */ +export interface ServerOptionsCache extends PolicyOptions { + /** a class, a prototype function, or a catbox engine object. */ + engine?: EnginePrototypeOrObject; + + /** + * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines + * the default cache. If every cache includes a name, a default memory cache is provisioned as well. + */ + name?: string; + + /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ + shared?: boolean; + + /** (optional) string used to isolate cached data. Defaults to 'hapi-cache'. */ + partition?: string; + + /** other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). */ + [s: string]: any; +} + +export interface ServerOptionsCompression { + minBytes: number; +} + +/** + * Empty interface to allow for custom augmentation. + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface ServerOptionsApp { +} + +/** + * The server options control the behavior of the server object. Note that the options object is deeply cloned + * (with the exception of listener which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on. + * All options are optionals. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-server-options) + */ +export interface ServerOptions { + /** + * Default value: '0.0.0.0' (all available network interfaces). + * Sets the hostname or IP address the server will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces. Set to '127.0.0.1' or 'localhost' to + * restrict the server to only those coming from the same host. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsaddress) + */ + address?: string; + + /** + * Default value: {}. + * Provides application-specific configuration which can later be accessed via server.settings.app. The framework does not interact with this object. It is simply a reference made available + * anywhere a server reference is provided. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time + * state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) + */ + app?: ServerOptionsApp; + + /** + * Default value: true. + * Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework. + * Cannot be set to true along with a port value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsautolisten) + */ + autoListen?: boolean; + + /** + * Default value: { engine: require('catbox-memory' }. + * Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and + * capabilities. hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized + * if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. The configuration can be assigned one or more + * (array): + * * a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this + * function. + * * a configuration object with the following: + * * * engine - a class, a prototype function, or a catbox engine object. + * * * name - an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines + * the default cache. If every cache includes a name, a default memory cache is provisioned as well. + * * * shared - if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + * * * partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'. + * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache) + */ + cache?: EnginePrototype | ServerOptionsCache | ServerOptionsCache[]; + + /** + * Default value: { minBytes: 1024 }. + * Defines server handling of content encoding requests. If false, response content encoding is disabled and no compression is performed by the server. + */ + compression?: boolean | ServerOptionsCompression; + + /** + * Default value: { request: ['implementation'] }. + * Determines which logged events are sent to the console. This should only be used for development and does not affect which events are actually logged internally and recorded. Set to false to + * disable all console logging, or to an object with: + * * log - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. Defaults to no output. + * * request - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to + * display all errors, set the option to ['error']. To turn off all console debug messages set it to false. To display all request logs, set it to '*'. Defaults to uncaught errors thrown in + * external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. For example, to display all errors, set the log + * or request to ['error']. To turn off all output set the log or request to false. To display all server logs, set the log or request to '*'. To disable all debug information, set debug to + * false. + */ + debug?: false | { + log?: string[] | false; + request?: string[] | false; + }; + + /** + * Default value: the operating system hostname and if not available, to 'localhost'. + * The public hostname or IP address. Used to set server.info.host and server.info.uri and as address is none provided. + */ + host?: string; + + /** + * Default value: none. + * An optional node HTTP (or HTTPS) http.Server object (or an object with a compatible interface). + * If the listener needs to be manually started, set autoListen to false. + * If the listener uses TLS, set tls to true. + */ + listener?: http.Server; + + /** + * Default value: { sampleInterval: 0 }. + * Server excessive load handling limits where: + * * sampleInterval - the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). + * * maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + * * maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + * * maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + */ + load?: { + /** the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). */ + sampleInterval?: number; + + /** + * Max concurrent requests. + */ + concurrent?: number; + + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes?: number; + /** + * maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + */ + maxRssBytes?: number; + /** + * maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. + * Defaults to 0 (no limit). + */ + maxEventLoopDelay?: number; + }; + + /** + * Default value: none. + * Options passed to the mimos module when generating the mime database used by the server (and accessed via server.mime): + * * override - an object hash that is merged into the built in mime information specified here. Each key value pair represents a single mime object. Each override value must contain: + * * key - the lower-cased mime-type string (e.g. 'application/javascript'). + * * value - an object following the specifications outlined here. Additional values include: + * * * type - specify the type value of result objects, defaults to key. + * * * predicate - method with signature function(mime) when this mime type is found in the database, this function will execute to allows customizations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsmime) + */ + mime?: MimosOptions; + + /** + * Default value: {}. + * Plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the + * difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. + */ + plugins?: PluginSpecificConfiguration; + + /** + * Default value: 0 (an ephemeral port). + * The TCP port the server will listen to. Defaults the next available port when the server is started (and assigned to server.info.port). + * If port is a string containing a '/' character, it is used as a UNIX domain socket path. If it starts with '\.\pipe', it is used as a Windows named pipe. + */ + port?: number | string; + + /** + * Default value: { isCaseSensitive: true, stripTrailingSlash: false }. + * Controls how incoming request URIs are matched against the routing table: + * * isCaseSensitive - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. + * * stripTrailingSlash - removes trailing slashes on incoming paths. Defaults to false. + */ + router?: { + isCaseSensitive?: boolean; + stripTrailingSlash?: boolean; + }; + + /** + * Default value: none. + * A route options object used as the default configuration for every route. + */ + routes?: RouteOptions; + + /** + * Default value: + * { + * strictHeader: true, + * ignoreErrors: false, + * isSecure: true, + * isHttpOnly: true, + * isSameSite: 'Strict', + * encoding: 'none' + * } + * Sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the state configuration object. + */ + // TODO I am not sure if I need to use all the server.state() definition (like the default value) OR only the options below. The v16 use "any" here. + // state?: ServerStateCookieOptions; + state?: { + strictHeader?: boolean, + ignoreErrors?: boolean, + isSecure?: boolean, + isHttpOnly?: boolean, + isSameSite?: false | 'Strict' | 'Lax', + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron' + }; + + /** + * Default value: none. + * Used to create an HTTPS connection. The tls object is passed unchanged to the node HTTPS server as described in the node HTTPS documentation. + */ + tls?: boolean | https.ServerOptions; + + /** + * Default value: constructed from runtime server information. + * The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server server.info.uri, otherwise constructed from the server settings. + */ + uri?: string; +} + +/** + * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When registering a plugin or an authentication scheme, a server object reference is provided + * with a new server.realm container specific to that registration. It allows each plugin to maintain its own settings without leaking and affecting other plugins. For example, a plugin can set a + * default file path for local resources without breaking other plugins' configured paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by routes + * and extensions added at the same level (server root or plugin). + * + * https://github.com/hapijs/hapi/blob/master/API.md#server.realm + */ +export interface ServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */ + modifiers: { + /** routes preferences: */ + route: { + /** + * the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include + * the trailing slash. + */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + } + }; + /** the realm of the parent server object, or null for the root server. */ + parent: ServerRealm | null; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** the plugin options object passed at registration. */ + pluginOptions: object; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: PluginsStates; + /** settings overrides */ + settings: { + files: { + relativeTo: string; + }; + bind: object; + }; +} + +/** + * Registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the + * second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific + * prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ +export interface ServerRegisterOptions { + /** + * if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second + * time a plugin is registered on the server. + */ + once?: boolean; + /** + * modifiers applied to each route added by the plugin: + */ + routes?: { + /** + * string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + */ + prefix: string; + /** + * virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + */ + vhost?: string | string[]; + }; +} + +/** + * An object with the following: + * * plugin - a plugin object. + * * options - (optional) options passed to the plugin during registration. + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the + * second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific + * prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + * + * The type parameter T is the type of the plugin configuration options. + */ +export interface ServerRegisterPluginObject extends ServerRegisterOptions { + /** + * a plugin object. + */ + plugin: Plugin; + /** + * options passed to the plugin during registration. + */ + options?: T; +} + +export interface ServerRegisterPluginObjectArray extends Array + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | ServerRegisterPluginObject + | undefined> { + 0: ServerRegisterPluginObject; + 1?: ServerRegisterPluginObject; + 2?: ServerRegisterPluginObject; + 3?: ServerRegisterPluginObject; + 4?: ServerRegisterPluginObject; + 5?: ServerRegisterPluginObject; + 6?: ServerRegisterPluginObject; +} + +/* tslint:disable-next-line:no-empty-interface */ +export interface HandlerDecorations { +} + +/** + * A route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The + * path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP + * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same + * result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the + * header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being + * added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ +export interface ServerRoute { + /** + * (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path + * can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. For context [See + * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters) + */ + path: string; + + /** + * (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method + * (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same + * result as adding the same route with different methods manually. + */ + method: Util.HTTP_METHODS_PARTIAL | Util.HTTP_METHODS_PARTIAL[] | string | string[]; + + /** + * (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header + * only (excluding the port). Defaults to all hosts. + */ + vhost?: string | string[]; + + /** + * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + */ + handler?: Lifecycle.Method | HandlerDecorations; + + /** + * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to + * and this is bound to the current realm's bind option. + */ + options?: RouteOptions | ((server: Server) => RouteOptions); + + /** + * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + */ + rules?: object; +} + +/** + * Optional cookie settings + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + */ +export interface ServerStateCookieOptions { + /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */ + ttl?: number | null; + /** sets the 'Secure' flag. Defaults to true. */ + isSecure?: boolean; + /** sets the 'HttpOnly' flag. Defaults to true. */ + isHttpOnly?: boolean; + /** + * sets the 'SameSite' flag. The value must be one of: + * * false - no flag. + * * 'Strict' - sets the value to 'Strict' (this is the default value). + * * 'Lax' - sets the value to 'Lax'. + */ + isSameSite?: false | 'Strict' | 'Lax'; + /** the path scope. Defaults to null (no path). */ + path?: string | null; + /** the domain scope. Defaults to null (no domain). */ + domain?: string | null; + + /** + * if present and the cookie was not received from the client or explicitly set by the route handler, the + * cookie is automatically added to the response with the provided value. The value can be + * a function with signature async function(request) where: + */ + autoValue?(request: Request): void; + + /** + * encoding performs on the provided value before serialization. Options are: + * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + * * 'base64' - string value is encoded using Base64. + * * 'base64json' - object value is JSON-stringified then encoded using Base64. + * * 'form' - object value is encoded using the x-www-form-urlencoded method. + * * 'iron' - Encrypts and sign the value using iron. + */ + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron'; + /** + * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean + * to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are: + * * integrity - algorithm options. Defaults to require('iron').defaults.integrity. + * * password - password used for HMAC key generation (must be at least 32 characters long). + */ + sign?: { + integrity?: SealOptionsSub; + password: string; + }; + /** password used for 'iron' encoding (must be at least 32 characters long). */ + password?: string; + /** options for 'iron' encoding. Defaults to require('iron').defaults. */ + iron?: SealOptions; + /** if true, errors are ignored and treated as missing cookies. */ + ignoreErrors?: boolean; + /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */ + clearInvalid?: boolean; + /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */ + strictHeader?: boolean; + /** used by proxy plugins (e.g. h2o2). */ + passThrough?: any; +} + +/** + * A single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + */ +export interface ServerStateFormat { + name: string; + value: string; + options: ServerStateCookieOptions; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsstate) + */ +export interface ServerState { + /** + * The server cookies manager. + * Access: read only and statehood public interface. + */ + readonly states: object; + + /** + * The server cookies manager settings. The settings are based on the values configured in [server.options.state](https://github.com/hapijs/hapi/blob/master/API.md#server.options.state). + */ + readonly settings: ServerStateCookieOptions; + + /** + * An object containing the configuration of each cookie added via [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()) where each key is the + * cookie name and value is the configuration object. + */ + readonly cookies: { + [key: string]: ServerStateCookieOptions; + }; + + /** + * An array containing the names of all configued cookies. + */ + readonly names: string[]; + + /** + * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). + */ + add(name: string, options?: ServerStateCookieOptions): void; + + /** + * Formats an HTTP 'Set-Cookie' header based on the server.options.state where: + * @param cookies - a single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + * @return Return value: a header string. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formating (e.g. when headers are set manually). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies) + */ + format(cookies: ServerStateFormat | ServerStateFormat[]): Promise; + + /** + * Parses an HTTP 'Cookies' header based on the server.options.state where: + * @param header - the HTTP header. + * @return Return value: an object where each key is a cookie name and value is the parsed cookie. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) + */ + parse(header: string): Promise>; +} + +/** + * The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. + * If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + */ +export interface HandlerDecorationMethod { + (route: RouteOptions, options: any): Lifecycle.Method; + defaults?: RouteOptions | ((method: any) => RouteOptions); +} + +/** + * The general case for decorators added via server.decorate. + */ +export type DecorationMethod = (this: T, ...args: any[]) => any; + +/** + * An empty interface to allow typings of custom plugin properties. + */ +/* tslint:disable-next-line:no-empty-interface */ +export interface PluginProperties { +} + +export type DecorateName = string | symbol; + +/** + * The server object is the main application container. The server manages all incoming requests along with all + * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server) + */ +export class Server { + /** + * Creates a new server object + * @param options server configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions) + */ + constructor(options?: ServerOptions); + + /** + * Provides a safe place to store server-specific run-time application data without potential conflicts with + * the framework internals. The data can be accessed whenever the server is accessible. + * Initialized with an empty object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp) + */ + app: ApplicationState; + + /** + * Server Auth: properties and methods + */ + readonly auth: ServerAuth; + + /** + * Links another server to the initialize/start/stop state of the current server by calling the + * controlled server `initialize()`/`start()`/`stop()` methods whenever the current server methods + * are called, where: + */ + control(server: Server): void; + + /** + * Provides access to the decorations already applied to various framework interfaces. The object must not be + * modified directly, but only through server.decorate. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecorations) + */ + readonly decorations: { + /** + * decorations on the request object. + */ + request: string[], + /** + * decorations on the response toolkit. + */ + toolkit: string[], + /** + * decorations on the server object. + */ + server: string[] + }; + + /** + * Register custom application events where: + * @param events must be one of: + * * an event name string. + * * an event options object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). + * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is + * passed as-is). + * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override + * specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its + * type). + * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is + * appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. + * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only + * the first configuration is used. Defaults to false (a duplicate registration will throw an error). + * * a podium emitter object. + * * an array containing any of the above. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + event(events: ServerEventsApplication | ServerEventsApplication[]): void; + + /** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + events: ServerEvents; + + /** + * An object containing information about the server where: + * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + * * created - server creation timestamp. + * * started - server start timestamp (0 when stopped). + * * port - the connection port based on the following rules: + * * host - The host configuration value. + * * address - the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). + * * protocol - the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available + * settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + */ + readonly info: ServerInfo; + + /** + * Access: read only and listener public interface. + * The node HTTP server object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener) + */ + listener: http.Server; + + /** + * An object containing the process load metrics (when load.sampleInterval is enabled): + * * eventLoopDelay - event loop delay milliseconds. + * * heapUsed - V8 heap usage. + * * rss - RSS memory usage. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverload) + */ + readonly load: { + /** + * event loop delay milliseconds. + */ + eventLoopDelay: number; + + /** + * Max concurrent requests. + */ + concurrent: number + /** + * V8 heap usage. + */ + heapUsed: number; + /** + * RSS memory usage. + */ + rss: number; + }; + + /** + * Server methods are functions registered with the server and used throughout the application as a common utility. + * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request + * handlers without having to create a common module. + * sever.methods is an object which provides access to the methods registered via server.method() where each + * server method name is an object property. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods + */ + readonly methods: Util.Dictionary; + + /** + * Provides access to the server MIME database used for setting content-type information. The object must not be + * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime) + */ + mime: any; + + /** + * An object containing the values exposed by each registered plugin where each key is a plugin name and the values + * are the exposed properties by each plugin using server.expose(). Plugins may set the value of + * the server.plugins[name] object directly or via the server.expose() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) + */ + plugins: PluginProperties; + + /** + * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When + * registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm + * container specific to that registration. It allows each plugin to maintain its own settings without leaking + * and affecting other plugins. + * For example, a plugin can set a default file path for local resources without breaking other plugins' configured + * paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by + * routes and extensions added at the same level (server root or plugin). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm) + */ + readonly realm: ServerRealm; + + /** + * An object of the currently registered plugins where each key is a registered plugin name and the value is + * an object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ + readonly registrations: PluginsListRegistered; + + /** + * The server configuration object after defaults applied. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serversettings) + */ + readonly settings: ServerOptions; + + /** + * The server cookies manager. + * Access: read only and statehood public interface. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstates) + */ + readonly states: ServerState; + + /** + * A string indicating the listener type where: + * * 'socket' - UNIX domain socket or Windows named pipe. + * * 'tcp' - an HTTP listener. + */ + readonly type: 'socket' | 'tcp'; + + /** + * The hapi module version number. + */ + readonly version: string; + + /** + * Sets a global context used as the default bind object when adding a route or an extension where: + * @param context - the object used to bind this in lifecycle methods such as the route handler and extension methods. The context is also made available as h.context. + * @return Return value: none. + * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. + * Ignored if the method being bound is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) + */ + bind(context: object): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + cache: ServerCache; + + /** + * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the decoder name string. + * @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the + * return value is an object compatible with the output of node's zlib.createGunzip(). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) + */ + decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void; + + /** + * Extends various framework interfaces with custom methods where: + * @param type - the interface being decorated. Supported types: + * 'handler' - adds a new handler type to be used in routes handlers. + * 'request' - adds methods to the Request object. + * 'server' - adds methods to the Server object. + * 'toolkit' - adds methods to the response toolkit. + * @param property - the object decoration key name. + * @param method - the extension function or other value. + * @param options - (optional) supports the following optional settings: + * apply - when the type is 'request', if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned + * as the decoration. extend - if true, overrides an existing decoration. The method must be a function with the signature function(existing) where: existing - is the previously set + * decoration method value. must return the new decoration function or value. cannot be used to extend handler decorations. + * @return void; + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) + */ + decorate(type: 'handler', property: DecorateName, method: HandlerDecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + decorate(type: 'request', property: DecorateName, method: (existing: ((...args: any[]) => any)) => (request: Request) => DecorationMethod, options: {apply: true, extend: true}): void; + decorate(type: 'request', property: DecorateName, method: (request: Request) => DecorationMethod, options: {apply: true, extend?: boolean}): void; + decorate(type: 'request', property: DecorateName, method: DecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + decorate(type: 'toolkit', property: DecorateName, method: (existing: ((...args: any[]) => any)) => DecorationMethod, options: {apply?: boolean, extend: true}): void; + decorate(type: 'toolkit', property: DecorateName, method: DecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + decorate(type: 'server', property: DecorateName, method: (existing: ((...args: any[]) => any)) => DecorationMethod, options: {apply?: boolean, extend: true}): void; + decorate(type: 'server', property: DecorateName, method: DecorationMethod, options?: {apply?: boolean, extend?: boolean}): void; + + /** + * Used within a plugin to declare a required dependency on other plugins where: + * @param dependencies - plugins which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is + * initialized or started. + * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is + * initialized or started. The function signature is async function(server) where: server - the server the dependency() method was called on. + * @return Return value: none. + * The after method is identical to setting a server extension point on 'onPreStart'. + * If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). + * The method does not provide version dependency which should be implemented using npm peer dependencies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) + */ + dependency(dependencies: Dependencies, after?: ((server: Server) => Promise)): void; + + /** + * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the encoder name string. + * @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object + * compatible with the output of node's zlib.createGzip(). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + */ + encoder(encoding: string, encoder: ((options: RouteCompressionEncoderSettings) => zlib.Gzip)): void; + + /** + * Used within a plugin to expose a property via server.plugins[name] where: + * @param key - the key assigned (server.plugins[name][key]). + * @param value - the value assigned. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) + */ + expose(key: string, value: any): void; + + /** + * Merges an object into to the existing content of server.plugins[name] where: + * @param obj - the object merged into the exposed properties container. + * @return Return value: none. + * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method + * for exposing large objects that may be expensive to clone or singleton objects such as database client + * objects. Instead favor server.expose(key, value), which only copies a reference to value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) + */ + expose(obj: object): void; + + /** + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level + * extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + */ + ext(events: ServerExtEventsObject | ServerExtEventsObject[] | ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void; + + /** + * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) + */ + ext(event: ServerExtType, method: ServerExtPointFunction, options?: ServerExtOptions): void; + ext(event: ServerRequestExtType, method: Lifecycle.Method, options?: ServerExtOptions): void; + + /** + * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and + * should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and + * other event listeners will get confused by repeated attempts to start the server or make assumptions about the + * healthy state of the environment. It is recommended to abort the process when the server fails to start properly. + * If you must try to resume after an error, call server.stop() first to reset the server state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize) + */ + initialize(): Promise; + + /** + * Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic + * internally without the overhead and limitations of the network stack. The method utilizes the shot module for performing injections, with some additional options and response properties: + * @param options - can be assigned a string with the requested URI, or an object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload + * processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as + * if they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly + * as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested + * separately. + * @return Return value: a response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse + * of the internal objects returned (instead of parsing the response string). + * * request - the request object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + */ + inject(options: string | ServerInjectOptions): Promise; + + /** + * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or + * output to the console. The arguments are: + * @param tags - (required) a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive + * mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return + * value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @param timestamp - (optional) an timestamp expressed in milliseconds. Defaults to Date.now() (now). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp) + */ + log(tags: string | string[], data?: string | object | (() => any), timestamp?: number): void; + + /** + * Looks up a route configuration where: + * @param id - the route identifier. + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid) + */ + lookup(id: string): RequestRoute | null; + + /** + * Looks up a route configuration where: + * @param method - the HTTP method (e.g. 'GET', 'POST'). + * @param path - the requested path (must begin with '/'). + * @param host - (optional) hostname (to match against routes with vhost). + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) + */ + match(method: Util.HTTP_METHODS, path: string, host?: string): RequestRoute | null; + + /** + * Registers a server method where: + * @param name - a unique method name used to invoke the method via server.methods[name]. + * @param method - the method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * @param options - (optional) configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is + * an arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will + * automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation + * function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). + * @return Return value: none. + * Method names can be nested (e.g. utils.users.get) which will automatically create the full path under server.methods (e.g. accessed via server.methods.utils.users.get). + * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear + * the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ + method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; + + /** + * Registers a server method function as described in server.method() using a configuration object where: + * @param methods - an object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ + method(methods: ServerMethodConfigurationObject | ServerMethodConfigurationObject[]): void; + + /** + * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + * @param relativeTo - the path prefix added to any relative file path starting with '.'. + * @return Return value: none. + * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default route configuration files.relativeTo settings is used. The + * path only applies to routes added after it has been set. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto) + */ + path(relativeTo: string): void; + + /** + * Registers a plugin where: + * @param plugins - one or an array of: + * * a plugin object. + * * an object with the following: + * * * plugin - a plugin object. + * * * options - (optional) options passed to the plugin during registration. + * * * once, routes - (optional) plugin-specific registration options as defined below. + * @param options - (optional) registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the + * second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the + * child-specific prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ + /* tslint:disable-next-line:no-unnecessary-generics */ + register(plugin: ServerRegisterPluginObject, options?: ServerRegisterOptions): Promise; + /* tslint:disable-next-line:no-unnecessary-generics */ + register(plugins: ServerRegisterPluginObjectArray, options?: ServerRegisterOptions): Promise; + register(plugins: Array>, options?: ServerRegisterOptions): Promise; + /* tslint:disable-next-line:unified-signatures */ + register(plugins: Plugin | Array>, options?: ServerRegisterOptions): Promise; + + /** + * Adds a route where: + * @param route - a route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. + * The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP + * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has + * the same result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the + * header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being + * added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * @return Return value: none. + * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ + route(route: ServerRoute | ServerRoute[]): void; + + /** + * Defines a route rules processor for converting route rules object into route configuration where: + * @param processor - a function using the signature function(rules, info) where: + * * rules - + * * info - an object with the following properties: + * * * method - the route method. + * * * path - the route path. + * * * vhost - the route virtual host (if any defined). + * * returns a route config object. + * @param options - optional settings: + * * validate - rules object validation: + * * * schema - joi schema. + * * * options - optional joi validation options. Defaults to { allowUnknown: true }. + * Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config. + * Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin override the config generated + * by the root processor if they overlap. The route config overrides the rules config if the overlap. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) + */ + rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object, options?: {validate: object}): void; // TODO needs implementation + + /** + * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the + * various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is + * recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. If a started server + * is started again, the second call to server.start() is ignored. No events will be emitted and no extension points invoked. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart) + */ + start(): Promise; + + /** + * HTTP state management uses client cookies to persist a state across multiple requests. + * @param name - the cookie name string. + * @param options - are the optional cookie settings + * @return Return value: none. + * State defaults can be modified via the server default state configuration option. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + */ + state(name: string, options?: ServerStateCookieOptions): void; + + /** + * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + * @param options - (optional) object with: + * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions) + */ + stop(options?: {timeout: number}): Promise; + + /** + * Returns a copy of the routing table where: + * @param host - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + * @return Return value: an array of routes where each route contains: + * * settings - the route config with defaults applied. + * * method - the HTTP method in lower case. + * * path - the route path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost) + */ + table(host?: string): RequestRoute[]; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Utils + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ + +/** + * User-extensible type for application specific state. + */ + /* tslint:disable-next-line:no-empty-interface */ +export interface ApplicationState { +} + +export type PeekListener = (chunk: string, encoding: string) => void; + +export namespace Json { + /** + * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} + */ + type StringifyReplacer = ((key: string, value: any) => any) | Array<(string | number)> | undefined; + + /** + * Any value greater than 10 is truncated. + */ + type StringifySpace = number | string; + + /** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + interface StringifyArguments { + /** the replacer function or array. Defaults to no action. */ + replacer?: StringifyReplacer; + /** number of spaces to indent nested object keys. Defaults to no indentation. */ + space?: StringifySpace; + /* string suffix added after conversion to JSON string. Defaults to no suffix. */ + suffix?: string; + /* calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. */ + escape?: boolean; + } +} + +export namespace Lifecycle { + /** + * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: + * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecyle methods + * provided by the developer and executed by the framework. + * Each lifecycle method is a function with the signature await function(request, h, [err]) where: + * * request - the request object. + * * h - the response toolkit the handler must call to set a response and return control back to the framework. + * * err - an error object availble only when the method is used as a failAction value. + */ + type Method = (request: Request, h: ResponseToolkit, err?: Error) => ReturnValue; + + /** + * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns + * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. + * The return value must be one of: + * - Plain value: null, string, number, boolean + * - Buffer object + * - Error object: plain Error OR a Boom object. + * - Stream object + * - any object or array + * - a toolkit signal: + * - a toolkit method response: + * - a promise object that resolve to any of the above values + * For more info please [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + */ + type ReturnValue = ReturnValueTypes | (Promise); + type ReturnValueTypes = + (null | string | number | boolean) | + (Buffer) | + (Error | Boom) | + (stream.Stream) | + (object | object[]) | + symbol | + ResponseToolkit; + + /** + * Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be + * configured to perform another action. When supported the failAction option supports the following values: + * * 'error' - return the error object as the response. + * * 'log' - report the error but continue processing the request. + * * 'ignore' - take no action and continue processing the request. + * * a lifecycle method with the signature async function(request, h, err) where: + * * * request - the request object. + * * * h - the response toolkit. + * * * err - the error object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration) + */ + type FailAction = 'error' | 'log' | 'ignore' | Method; +} + +export namespace Util { + interface Dictionary { + [key: string]: T; + } + + type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; + type HTTP_METHODS_PARTIAL = + 'GET' + | 'POST' + | 'PUT' + | 'PATCH' + | 'DELETE' + | 'OPTIONS' + | HTTP_METHODS_PARTIAL_LOWERCASE; + type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; +} diff --git a/types/hapi/v17/test/request/auth.ts b/types/hapi/v17/test/request/auth.ts new file mode 100644 index 0000000000..cb6c04ad28 --- /dev/null +++ b/types/hapi/v17/test/request/auth.ts @@ -0,0 +1,18 @@ +import { Request } from 'hapi'; + +declare module 'hapi' { + interface UserCredentials { + a: number; + } + + interface AppCredentials { + b: number; + } +} + +const req: Request = {} as any; +const scope: string[] | undefined = req.auth.credentials.scope; +const user = req.auth.credentials.user!; +console.log(user.a); +const app = req.auth.credentials.app!; +console.log(app.b); diff --git a/types/hapi/v17/test/request/catch-all.ts b/types/hapi/v17/test/request/catch-all.ts new file mode 100644 index 0000000000..3ee4e74c42 --- /dev/null +++ b/types/hapi/v17/test/request/catch-all.ts @@ -0,0 +1,14 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route +import { Request, ResponseToolkit, Server, ServerOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; +const server = new Server(options); + +server.route({ method: '*', path: '/{p*}', handler(request, h) { + return h.response('The page was not found').code(404); +}}); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/request/event-types.ts b/types/hapi/v17/test/request/event-types.ts new file mode 100644 index 0000000000..4d4f3f01ca --- /dev/null +++ b/types/hapi/v17/test/request/event-types.ts @@ -0,0 +1,67 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +// https://github.com/hapijs/hapi/blob/master/API.md#-requestevents +import { Lifecycle, Request, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Crypto from 'crypto'; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request) { + return 'ok: ' + request.path; + } +}; + +const onRequest: Lifecycle.Method = (request, h) => { + /* + * Server events + */ + request.server.events.on('request', (request: Request, event: any, tags: any) => { + console.log(request.paramsArray); + console.log(event); + console.log(tags); + }); + + request.server.events.on('response', (request: Request) => { + console.log('Response sent for request: ' + request.path); + }); + + request.server.events.on('start', () => { + console.log('Server started'); + }); + + request.server.events.once('stop', () => { + console.log('Server stoped'); + }); + + /* + * Request events + */ + const hash = Crypto.createHash('sha1'); + + request.events.on("peek", (chunk) => { + hash.update(chunk); + }); + + request.events.once("finish", () => { + console.log(hash.digest('hex')); + }); + + request.events.once("disconnect", () => { + console.error('request aborted'); + }); + + return h.continue; +}; + +const server = new Server(options); +server.route(serverRoute); +server.ext('onRequest', onRequest, { + before: 'test', +}); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/request/get-log.ts b/types/hapi/v17/test/request/get-log.ts new file mode 100644 index 0000000000..3ba2658136 --- /dev/null +++ b/types/hapi/v17/test/request/get-log.ts @@ -0,0 +1,29 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data +import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const handlerFn: Lifecycle.Method = (request, h) => { + request.log(['test', 'error'], 'Test event'); + return 'path: ' + request.path; +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: handlerFn +}; + +const server = new Server(options); +server.route(serverRoute); +server.start(); +console.log('Server started at: ' + server.info.uri); + +server.events.on('request', (request: Request, event: any, tags: any) => { + console.log(tags); + if (tags.error) { + console.log(event); + } +}); diff --git a/types/hapi/v17/test/request/methods.ts b/types/hapi/v17/test/request/methods.ts new file mode 100644 index 0000000000..22b58aac7f --- /dev/null +++ b/types/hapi/v17/test/request/methods.ts @@ -0,0 +1,4 @@ +import { Request } from 'hapi'; + +declare const req: Request; +const act: boolean = req.active(); diff --git a/types/hapi/v17/test/request/parameters.ts b/types/hapi/v17/test/request/parameters.ts new file mode 100644 index 0000000000..3f19a02d45 --- /dev/null +++ b/types/hapi/v17/test/request/parameters.ts @@ -0,0 +1,37 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-requestparams +import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +// Example 1 +// http://localhost:8000/album-name/song-optional +const getAlbum: Lifecycle.Method = (request, h) => { + console.log(request.params); + return 'ok: ' + request.path; +}; +const serverRoute1: ServerRoute = { + path: '/{album}/{song?}', + method: 'GET', + handler: getAlbum +}; + +// Example 2 +// http://localhost:8000/person/rafael/fijalkowski +const getPerson: Lifecycle.Method = (request, h) => { + const nameParts = request.params.name.split('/'); + return { first: nameParts[0], last: nameParts[1] }; +}; +const serverRoute2: ServerRoute = { + path: '/person/{name*2}', + method: 'GET', + handler: getPerson +}; + +const server = new Server(options); +server.route(serverRoute1); +server.route(serverRoute2); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/request/query.ts b/types/hapi/v17/test/request/query.ts new file mode 100644 index 0000000000..090ab3ae8d --- /dev/null +++ b/types/hapi/v17/test/request/query.ts @@ -0,0 +1,26 @@ +// Added test in addition to docs, for request.query +import { Lifecycle, Request, RequestQuery, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const handlerFn: Lifecycle.Method = (request, h) => { + const query1 = request.query as string; + console.log(query1); + + const query2 = request.query as RequestQuery; + // http://localhost:8000/?name=test + return `You asked for ${query2.name}`; +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: handlerFn +}; + +const server = new Server(options); +server.route(serverRoute); +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/continue.ts b/types/hapi/v17/test/response/continue.ts new file mode 100644 index 0000000000..15a0f5e35b --- /dev/null +++ b/types/hapi/v17/test/response/continue.ts @@ -0,0 +1,25 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/test', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + } +}; + +const server = new Server(options); +server.route(serverRoute); + +server.ext("onRequest", (request, h) => { + request.setUrl('/test'); + return h.continue; +}); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/error.ts b/types/hapi/v17/test/response/error.ts new file mode 100644 index 0000000000..513f5fbbe5 --- /dev/null +++ b/types/hapi/v17/test/response/error.ts @@ -0,0 +1,30 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#errors +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Boom from "boom"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoutes: ServerRoute[] = [ + { + path: '/badRequest', + method: 'GET', + handler(request, h) { + throw Boom.badRequest('Unsupported parameter'); + } + }, + { + path: '/internal', + method: 'GET', + handler(request, h) { + throw new Error('unexpect error'); + } + }, +]; + +const server = new Server(options); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/redirect.ts b/types/hapi/v17/test/response/redirect.ts new file mode 100644 index 0000000000..dc1b904ce3 --- /dev/null +++ b/types/hapi/v17/test/response/redirect.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return h.redirect('http://example.com'); + } +}; + +const server = new Server(options); +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/response-events.ts b/types/hapi/v17/test/response/response-events.ts new file mode 100644 index 0000000000..ec1b070b18 --- /dev/null +++ b/types/hapi/v17/test/response/response-events.ts @@ -0,0 +1,28 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-responseevents +import { Lifecycle, Request, ResponseObject, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Crypto from "crypto"; + +const preResponse: Lifecycle.Method = (request, h) => { + // In onPreResponse, the response object will be defined. + const response = request.response!; + + const hash = Crypto.createHash('sha1'); + response.events.on('peek', (chunk, encoding) => { + hash.update(chunk); + }); + + response.events.once('finish', () => { + console.log(hash.digest('hex')); + }); + + return h.continue; +}; + +const server = new Server({ + port: 8000, +}); + +server.ext('onPreResponse', preResponse); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/response.ts b/types/hapi/v17/test/response/response.ts new file mode 100644 index 0000000000..368b6fa80b --- /dev/null +++ b/types/hapi/v17/test/response/response.ts @@ -0,0 +1,36 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoutes: ServerRoute[] = [ + // Detailed notation + { + path: '/test1', + method: 'GET', + handler(request, h) { + const response = h.response('success'); + response.type('text/plain'); + response.header('X-Custom', 'some-value'); + return response; + } + }, + // Chained notation + { + path: '/test2', + method: 'GET', + handler(request, h) { + return h.response('success') + .type('text/plain') + .header('X-Custom', 'some-value'); + } + }, +]; + +const server = new Server(options); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/route/adding-routes.ts b/types/hapi/v17/test/route/adding-routes.ts new file mode 100644 index 0000000000..ac4c895842 --- /dev/null +++ b/types/hapi/v17/test/route/adding-routes.ts @@ -0,0 +1,38 @@ +// from https://hapijs.com/tutorials/getting-started#adding-routes +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + } +}; + +const serverRoutes: ServerRoute[] = [ + { + path: '/test1', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + } + }, + { + path: '/test2', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + } + }, +]; + +const server = new Server(options); +server.route(serverRoute); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/route/config.ts b/types/hapi/v17/test/route/config.ts new file mode 100644 index 0000000000..8cebaec269 --- /dev/null +++ b/types/hapi/v17/test/route/config.ts @@ -0,0 +1,52 @@ +import { Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +// different methods +const routeConfig: ServerRoute = { + path: '/signin', + method: 'PUT', + vhost: 'site.coms', +}; +const routeConfigTest1: ServerRoute = { + path: '/signin', + method: '*' +}; +const routeConfigTest2: ServerRoute = { + path: '/signin', + method: ['OPTIONS', '*'] +}; + +// different handlers +const routeConfigTest3: ServerRoute = { + path: '/signin', + method: 'PUT', + handler(request, h) { + return 'ok'; + } +}; +const routeConfigTest4: ServerRoute = { + path: '/signin', + method: 'PUT', + handler(request, h) { + return 'ok'; + } +}; + +const server = new Server(options); +server.route(routeConfig); + +// Handler in config +const user: RouteOptions = { + cache: { expiresIn: 5000 }, + handler(request, h) { + return { name: 'John' }; + } +}; + +server.route({method: 'GET', path: '/user', options: user }); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/route/ext.ts b/types/hapi/v17/test/route/ext.ts new file mode 100644 index 0000000000..b8dff44699 --- /dev/null +++ b/types/hapi/v17/test/route/ext.ts @@ -0,0 +1,22 @@ +import { Server } from "hapi"; + +const server = new Server(); + +server.route({ + method: 'get', + path: "/test", + options: { + ext: { + onPreResponse: { + method(_request, h) { + return h.continue; + }, + }, + onPostHandler: [{ + method(_request, h) { + return h.continue; + }, + }], + } + } +}); diff --git a/types/hapi/v17/test/route/handler.ts b/types/hapi/v17/test/route/handler.ts new file mode 100644 index 0000000000..6fced10078 --- /dev/null +++ b/types/hapi/v17/test/route/handler.ts @@ -0,0 +1,9 @@ +import { Lifecycle, Request, ResponseToolkit } from "hapi"; + +const handler: Lifecycle.Method = (request, h) => { + return 'success'; +}; + +const strictHandler: Lifecycle.Method = (request, h) => { + return 123; +}; diff --git a/types/hapi/v17/test/route/route-options-pre.ts b/types/hapi/v17/test/route/route-options-pre.ts new file mode 100644 index 0000000000..897f4a8ef5 --- /dev/null +++ b/types/hapi/v17/test/route/route-options-pre.ts @@ -0,0 +1,42 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre +import { Lifecycle, Request, ResponseToolkit, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const pre1: Lifecycle.Method = (request, h) => { + return 'Hello'; +}; + +const pre2: Lifecycle.Method = (request, h) => { + return 'World'; +}; + +const pre3: Lifecycle.Method = (request, h) => { + return `request.pre.m1 request.pre.m2`; +}; + +server.route({ + method: 'GET', + path: '/', + options: { + pre: [ + [ + // m1 and m2 executed in parallel + { method: pre1, assign: 'm1' }, + { method: pre2, assign: 'm2' } + ], + { method: pre3, assign: 'm3' }, + ], + handler(request, h) { + return request.pre.m3 + '!\n'; + } + } +}); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/route/route-options.ts b/types/hapi/v17/test/route/route-options.ts new file mode 100644 index 0000000000..438ef77d62 --- /dev/null +++ b/types/hapi/v17/test/route/route-options.ts @@ -0,0 +1,193 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#route-options +import { + Lifecycle, + Request, + ResponseToolkit, + RouteOptions, + RouteOptionsAccess, + RouteOptionsCors, + RouteOptionsPayload, + RouteOptionsResponse, + RouteOptionsValidate, + Server, + RouteOptionsSecureObject +} from "hapi"; + +const routeOptionsAccess: RouteOptionsAccess = { + access: [ + { + scope: false + }, + { + entity: 'user' + } + ], + scope: false, + entity: 'user', + mode: 'optional', + payload: 'optional', + strategies: ['', ''], + strategy: '' +}; + +const corsOption: RouteOptionsCors = { + origin: 'ignore', + maxAge: 5000, + headers: ['test', 'test', 'test'], + additionalHeaders: ['test', 'test', 'test'], + exposedHeaders: ['test', 'test', 'test'], + additionalExposedHeaders: ['test', 'test', 'test'], + credentials: false +}; + +const payloadOptions: RouteOptionsPayload = { + allow: 'string', + compression: { + test1: { + test: 2 + } + }, + defaultContentType: 'application/json', + failAction(request, h) { + return 'ok: ' + request.path; + }, + maxBytes: 1048576, + multipart: { + output: 'annotated' + }, + output: 'stream', + override: '', + parse: 'gunzip', + timeout: 5000, + uploads: 'dir/' +}; + +const pre1: Lifecycle.Method = (request, h) => { + return 'Hello'; +}; + +const pre2: Lifecycle.Method = (request, h) => { + return 'World'; +}; + +const pre3: Lifecycle.Method = (request, h) => { + return `request.pre.m1 request.pre.m2`; +}; + +const routeOptionsResponse: RouteOptionsResponse = { + emptyStatusCode: 200, + failAction(request, h) { + return 'ok: ' + request.path; + }, + modify: false, + options: undefined, + ranges: true, + sample: 100, + schema: true, + status: { + 200: true, + 302: true, + 404: false, + }, +}; + +const routeOptionSecure: RouteOptionsSecureObject = { + referrer: 'origin', + noSniff: true, + xframe: "deny", + hsts: { + includeSubdomains: true, + maxAge: 1111, + preload: false, + }, + noOpen: false, + xss: true, +}; + +const routeOptionsValidate: RouteOptionsValidate = { + errorFields: {}, + failAction(request, h) { + return 'ok: ' + request.path; + }, + headers: false, + options: {}, + params: false, + payload: true, + query: true, +}; + +declare module 'hapi' { + interface RouteOptionsApp { + one: number; + two: string; + } +} + +const routeOptions: RouteOptions = { + app: { + one: 1, + two: "2" + }, + auth: routeOptionsAccess, + bind: null, + cache: { + privacy: 'default', + statuses: [200], + otherwise: 'no-cache' + }, + compression: { + test1: { + test: 2 + } + }, + cors: corsOption, + description: 'description here', + ext: undefined, + files: { relativeTo: '.' }, + handler(request, h) { + return 'ok: ' + request.path; + }, + id: 'test', + isInternal: false, + json: undefined, + jsonp: 'callback', + log: { collect: false }, + notes: ['test', 'test', 'test'], + payload: payloadOptions, + plugins: { + plugin1: {}, + plugin2: {}, + }, + pre: [ + [ + // m1 and m2 executed in parallel + { method: pre1, assign: 'm1' }, + { method: pre2, assign: 'm2' } + ], + { method: pre3, assign: 'm3' }, + ], + response: routeOptionsResponse, + security: false, + state: { + parse: true, + failAction(request, h) { + return 'ok: ' + request.path; + }, + }, + tags: ['test', 'test', 'test'], + timeout: { + server: 10000, + socket: false + }, + validate: routeOptionsValidate +}; + +const server = new Server({ + port: 8000, + routes: routeOptions +}); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/route/validation.ts b/types/hapi/v17/test/route/validation.ts new file mode 100644 index 0000000000..2151371c5f --- /dev/null +++ b/types/hapi/v17/test/route/validation.ts @@ -0,0 +1,48 @@ +// from https://hapijs.com/tutorials/validation?lang=en_US +import { Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Joi from "joi"; + +const options: ServerOptions = { + port: 8000, +}; + +const routeOptions: RouteOptions = { + validate: { + payload: { + id: Joi.string().uuid().required(), + name: Joi.object({ + firstName: Joi.string().required(), + lastName: Joi.string().allow(null) + }), + firstName: Joi.ref("name.firstName") + }, + params: { + name: Joi.string().min(3).max(10), + nameRef: Joi.ref("name") + } + }, + response: { + schema: Joi.object({ + a: Joi.string(), + b: Joi.object({ + c: Joi.number() + }), + d: Joi.ref("b.c") + }) + } +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'ok: ' + request.path; + }, + options: routeOptions +}; + +const server = new Server(options); +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-app.ts b/types/hapi/v17/test/server/server-app.ts new file mode 100644 index 0000000000..69bac86e2f --- /dev/null +++ b/types/hapi/v17/test/server/server-app.ts @@ -0,0 +1,29 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverapp +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +declare module "hapi" { + // Demonstrate augmenting the application state. + interface ApplicationState { + key?: string; + } +} + +const server = new Server(options); +server.app.key = 'value2'; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'key: ' + request.server.app.key; + } +}; + +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-auth-api.ts b/types/hapi/v17/test/server/server-auth-api.ts new file mode 100644 index 0000000000..4508c641c9 --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-api.ts @@ -0,0 +1,40 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi +import { + Server, + ServerAuthScheme, +} from "hapi"; +import * as Boom from "boom"; + +declare module 'hapi' { + interface ServerAuthSchemeObjectApi { + settings: { + x: number; + }; + } +} + +const scheme: ServerAuthScheme = (server, options) => { + return { + api: { + settings: { + x: 5 + } + }, + authenticate(request, h) { + const authorization = request.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { user: { a: 1 } } }); + } + }; +}; + +const server = new Server({ + port: 8000, +}); +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); +server.start(); + +console.log(server.auth.api.default.settings.x); // 5 diff --git a/types/hapi/v17/test/server/server-auth-default.ts b/types/hapi/v17/test/server/server-auth-default.ts new file mode 100644 index 0000000000..0a2da56efc --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-default.ts @@ -0,0 +1,41 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme +import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "hapi"; +import * as Boom from "boom"; + +declare module 'hapi' { + interface UserCredentials { + a: number; + } +} + +const server = new Server({ + port: 8000, +}); + +const scheme: ServerAuthScheme = (server, options) => { + return { + authenticate(request, h) { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { user: { a: 1 }, scope: ['test'] } }); + } + }; +}; + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); +server.auth.default('default'); + +server.route({ + method: 'GET', + path: '/', + handler(request, h) { + return request.auth.credentials.user || 'not authed'; + } +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-auth-test.ts b/types/hapi/v17/test/server/server-auth-test.ts new file mode 100644 index 0000000000..4e2a175e1a --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-test.ts @@ -0,0 +1,45 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme +import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "hapi"; +import * as Boom from "boom"; + +declare module 'hapi' { + interface AuthCredentials { + name?: string; + } +} + +const server = new Server({ + port: 8000, +}); + +const scheme: ServerAuthScheme = (server, options) => { + return { + authenticate(request, h) { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { name: 'john', } }); + } + }; +}; + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); + +server.route({ + method: 'GET', + path: '/', + handler: async (request: Request, h: ResponseToolkit) => { + try { + const credentials = await request.server.auth.test('default', request); + return { status: true, user: credentials.name }; + } catch (err) { + return { status: false }; + } + } +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-auth-verify.ts b/types/hapi/v17/test/server/server-auth-verify.ts new file mode 100644 index 0000000000..ec788fcb59 --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-verify.ts @@ -0,0 +1,26 @@ +import { Request, Server, RequestAuth } from "hapi"; +import * as Boom from "boom"; + +const server = new Server({ + port: 8000, +}); + +server.auth.scheme('custom', () => ({ + authenticate() { + throw Boom.unauthorized(null, 'hurr'); + }, + async verify(_auth: RequestAuth) { + throw Boom.unauthorized(null, 'durr'); + } +})); +server.auth.strategy('default', 'custom'); + +server.route({ + method: 'GET', + path: '/', + async handler(request: Request) { + request.server.auth.verify(request); + } +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-bind.ts b/types/hapi/v17/test/server/server-bind.ts new file mode 100644 index 0000000000..1fbd37c4c2 --- /dev/null +++ b/types/hapi/v17/test/server/server-bind.ts @@ -0,0 +1,27 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext +import { Lifecycle, Plugin, Request, ResponseToolkit, Server, ServerRegisterOptions } from "hapi"; + +const server = new Server({ + port: 8000, +}); +const handler: Lifecycle.Method = (request, h) => { + return h.context.message; // Or h.context.message +}; + +const plugin: Plugin = { + name: 'example', + register: async (server, options) => { + const bind = { + message: 'hello' + }; + server.bind(bind); + server.route({ method: 'GET', path: '/', handler }); + } +}; + +server.start(); +server.register(plugin); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-cache-provision.ts b/types/hapi/v17/test/server/server-cache-provision.ts new file mode 100644 index 0000000000..8c28ca48de --- /dev/null +++ b/types/hapi/v17/test/server/server-cache-provision.ts @@ -0,0 +1,19 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions +import { Server } from "hapi"; +import * as catbox from "catbox"; + +const server = new Server({ + port: 8000, +}); +server.initialize(); +server.cache.provision({engine: require('catbox-memory'), name: 'countries' }); + +const cache = server.cache({segment: 'countries', cache: 'countries', expiresIn: 60 * 60 * 1000 }); +cache.set('norway', 'oslo', 10 * 1000).then(() => {}); +const value = cache.get('norway').then(() => {}); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-cache.ts b/types/hapi/v17/test/server/server-cache.ts new file mode 100644 index 0000000000..0872b287df --- /dev/null +++ b/types/hapi/v17/test/server/server-cache.ts @@ -0,0 +1,23 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions +import { Server, ServerOptionsCache } from "hapi"; +import * as catbox from "catbox"; + +const server = new Server({ + port: 8000, +}); + +const catboxOptions: ServerOptionsCache = { + segment: 'countries', + expiresIn: 60 * 60 * 1000 +}; +const cache = server.cache(catboxOptions); +cache.set('norway', 'oslo', 10 * 1000).then(() => {}); + +const value = cache.get('norway').then(() => {}); +console.log("Value: " + value); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-control.ts b/types/hapi/v17/test/server/server-control.ts new file mode 100644 index 0000000000..8b145f1388 --- /dev/null +++ b/types/hapi/v17/test/server/server-control.ts @@ -0,0 +1,3 @@ +import { Server } from "hapi"; + +new Server().control(new Server()); diff --git a/types/hapi/v17/test/server/server-decoder.ts b/types/hapi/v17/test/server/server-decoder.ts new file mode 100644 index 0000000000..965745ee7c --- /dev/null +++ b/types/hapi/v17/test/server/server-decoder.ts @@ -0,0 +1,8 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder +import { Server } from "hapi"; +import * as Zlib from "zlib"; + +const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); +server.decoder('special', (options) => Zlib.createGunzip(options)); + +server.start(); diff --git a/types/hapi/v17/test/server/server-decorations.ts b/types/hapi/v17/test/server/server-decorations.ts new file mode 100644 index 0000000000..7c060735a9 --- /dev/null +++ b/types/hapi/v17/test/server/server-decorations.ts @@ -0,0 +1,111 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options +import { Request, ResponseToolkit, Server } from "hapi"; + +declare module 'hapi' { + interface HandlerDecorations { + test?: { + test: number; + }; + } +} + +// Test basic types. + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.decorate('toolkit', 'success', function() { + return this.response({ status: 'ok' }); +}); +server.decorate('handler', 'test', (route, options) => (req, h) => 123); +server.route({ + method: 'GET', + path: '/', + handler: { + test: { + test: 123, + }, + asd: 1, + } +}); + +console.log(server.decorations.toolkit); + +// Test decorators with additional arguments + +declare module 'hapi' { + interface Server { + withParams(x: number, y: string): string; + } + + interface ResponseToolkit { + withParams(x: number, y: string): string; + } +} + +function decorateServerWithParams(this: Server, x: number, y: string) { + return `${x} ${y}`; +} + +server.decorate('server', 'withParams', decorateServerWithParams); +server.withParams(1, "one"); + +function decorateToolkitWithParams(this: ResponseToolkit, x: number, y: string) { + return `${x} ${y}`; +} + +server.decorate('toolkit', 'withParams', decorateToolkitWithParams); + +server.decorate('toolkit', Symbol('hi'), decorateToolkitWithParams); + +server.route({ + method: 'GET', + path: '/toolkitWithParams', + handler: (r, h) => { + return h.withParams(1, "one"); + } +}); + +// Test request + apply option types + +declare module 'hapi' { + interface Request { + withApply(x: string, y: number): string; + } +} + +function decorateRequestWithApply(request: Request) { + return (x: string, y: number) => { + return `${x} ${y}`; + }; +} + +server.decorate('request', 'withApply', decorateRequestWithApply, {apply: true}); + +server.route({ + method: 'GET', + path: '/requestWithApply', + handler: (r, h) => { + return r.withApply("one", 1); + } +}); + +// Test extend option type + +declare module 'hapi' { + interface Server { + withExtend(x: string, y: number): string; + } +} + +const decorateServerWithExtend = (existing: () => void) => { + return (x: string, y: number) => { + existing(); + return `${x} ${y}`; + }; +}; + +server.decorate('server', 'withExtend', decorateServerWithExtend, {extend: true}); +server.withExtend("one", 1); diff --git a/types/hapi/v17/test/server/server-encoder.ts b/types/hapi/v17/test/server/server-encoder.ts new file mode 100644 index 0000000000..dd9f12f4db --- /dev/null +++ b/types/hapi/v17/test/server/server-encoder.ts @@ -0,0 +1,8 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder +import { Server } from "hapi"; +import * as Zlib from "zlib"; + +const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); +server.encoder('special', (options) => Zlib.createGzip(options)); + +server.start(); diff --git a/types/hapi/v17/test/server/server-events-once.ts b/types/hapi/v17/test/server/server-events-once.ts new file mode 100644 index 0000000000..a4903ee6dc --- /dev/null +++ b/types/hapi/v17/test/server/server-events-once.ts @@ -0,0 +1,31 @@ +// from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener +import { Request, ResponseToolkit, Server, ServerRoute } from "hapi"; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'oks: ' + request.path; + } +}; + +declare module 'hapi' { + interface ServerEvents { + once(event: 'test1', listener: (update: string) => void): this; + once(event: 'test2', listener: (...updates: string[]) => void): this; + } +} + +const server = new Server({ + port: 8000, +}); +server.route(serverRoute); +server.event('test1'); +server.event('test2'); +server.events.once('test1', update => { console.log(update); }); +server.events.once('test2', (...args) => { console.log(args); }); +server.events.emit('test1', 'hello-1'); +server.events.emit('test2', 'hello-2'); // Ignored + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-events.ts b/types/hapi/v17/test/server/server-events.ts new file mode 100644 index 0000000000..4e6d8103f1 --- /dev/null +++ b/types/hapi/v17/test/server/server-events.ts @@ -0,0 +1,24 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +import { Server, ServerEvents } from "hapi"; +import Podium = require('podium'); +import 'hapi/definitions/server/server'; + +declare module 'hapi' { + interface ServerEvents { + on(event: 'test', listener: (update: string) => void): this; + } +} + +const server = new Server({ + port: 8000, +}); + +server.events.on('route', route => { + console.log(route.path, route.vhost, route.realm, route.method, route.settings, route.fingerprint); +}); + +server.event('test'); +server.events.on('test', (update: any) => console.log(update)); +server.events.emit('test', 'hello'); + +server.start(); diff --git a/types/hapi/v17/test/server/server-expose.ts b/types/hapi/v17/test/server/server-expose.ts new file mode 100644 index 0000000000..43d6cfdaa6 --- /dev/null +++ b/types/hapi/v17/test/server/server-expose.ts @@ -0,0 +1,38 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +import { Plugin, Server, ServerRegisterOptions } from "hapi"; + +declare module 'hapi' { + interface PluginProperties { + example1: { + util(): void; + }; + example2: { + util(): void; + }; + } +} + +const plugin1: Plugin = { + name: 'example1', + async register(server: Server, options: ServerRegisterOptions) { + server.expose('util', () => console.log('something')); + } +}; + +const plugin2: Plugin = { + name: 'example2', + async register(server: Server, options: ServerRegisterOptions) { + server.expose('util', () => console.log('something')); + } +}; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.register(plugin1); +server.register(plugin2); + +server.plugins.example1.util(); +server.plugins.example2.util(); diff --git a/types/hapi/v17/test/server/server-info.ts b/types/hapi/v17/test/server/server-info.ts new file mode 100644 index 0000000000..58045b19da --- /dev/null +++ b/types/hapi/v17/test/server/server-info.ts @@ -0,0 +1,10 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +console.log(server.info); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-inject.ts b/types/hapi/v17/test/server/server-inject.ts new file mode 100644 index 0000000000..a2ae777a71 --- /dev/null +++ b/types/hapi/v17/test/server/server-inject.ts @@ -0,0 +1,32 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions +import { Request, ResponseToolkit, Server, ServerRoute } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler(request, h) { + return 'Success!'; + } +}; + +server.route(serverRoute); +server.start(); + +server.inject('/').then(res => console.log(res.result)); + +declare module 'hapi' { + interface ApplicationState { + injectState?: number; + } +} + +server.inject({ + url: "test", + app: { + injectState: 1 + } +}); diff --git a/types/hapi/v17/test/server/server-listener.ts b/types/hapi/v17/test/server/server-listener.ts new file mode 100644 index 0000000000..160821f505 --- /dev/null +++ b/types/hapi/v17/test/server/server-listener.ts @@ -0,0 +1,14 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener +import { Server } from "hapi"; +import * as SocketIO from "socket.io"; + +const server = new Server({ + port: 8000, +}); + +const io = SocketIO.listen(server.listener); +io.sockets.on('connection', (socket) => { + socket.emit('welcome'); +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-load.ts b/types/hapi/v17/test/server/server-load.ts new file mode 100644 index 0000000000..8ac89fa006 --- /dev/null +++ b/types/hapi/v17/test/server/server-load.ts @@ -0,0 +1,17 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverload +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, + load: { + sampleInterval: 1000, + concurrent: 123, + } +}); +server.start(); + +setTimeout(() => { + console.log(server.load.rss); + console.log(server.load.eventLoopDelay); + console.log(server.load.heapUsed); +}, 5 * 1000); diff --git a/types/hapi/v17/test/server/server-lookup.ts b/types/hapi/v17/test/server/server-lookup.ts new file mode 100644 index 0000000000..2bbaf5713b --- /dev/null +++ b/types/hapi/v17/test/server/server-lookup.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid +import { RequestRoute, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.route({ + path: '/', + method: 'GET', + options: { + id: 'root', + handler: () => 'ok' + } +}); + +const route: RequestRoute | null = server.lookup('root'); +console.log(route); + +server.start(); diff --git a/types/hapi/v17/test/server/server-match.ts b/types/hapi/v17/test/server/server-match.ts new file mode 100644 index 0000000000..5fc8605ad4 --- /dev/null +++ b/types/hapi/v17/test/server/server-match.ts @@ -0,0 +1,23 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host +import { RequestRoute, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.route({ + path: '/', + method: 'GET', + options: { + id: 'root', + handler: () => 'ok' + } +}); + +const route: RequestRoute | null = server.match('get', '/'); + +if (route !== null) { + console.log(route.path); +} + +server.start(); diff --git a/types/hapi/v17/test/server/server-method.ts b/types/hapi/v17/test/server/server-method.ts new file mode 100644 index 0000000000..39c3fdb9d7 --- /dev/null +++ b/types/hapi/v17/test/server/server-method.ts @@ -0,0 +1,25 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods +import { Server, ServerMethodConfigurationObject } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +const add = (a: any, b: any): number => { + return a + b; +}; + +const methodObject: ServerMethodConfigurationObject = { + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000, + generateTimeout: 100 + }, + generateKey: (a: string | undefined) => a === undefined ? null : a + } +}; + +server.method(methodObject); diff --git a/types/hapi/v17/test/server/server-methods.ts b/types/hapi/v17/test/server/server-methods.ts new file mode 100644 index 0000000000..f9a2d08e6c --- /dev/null +++ b/types/hapi/v17/test/server/server-methods.ts @@ -0,0 +1,11 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethods +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +server.method('add', (a, b) => (a + b)); +const result = server.methods.add(1, 2); // 3 +console.log(result); diff --git a/types/hapi/v17/test/server/server-mime.ts b/types/hapi/v17/test/server/server-mime.ts new file mode 100644 index 0000000000..3a50da2154 --- /dev/null +++ b/types/hapi/v17/test/server/server-mime.ts @@ -0,0 +1,22 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermime +import { Server, ServerOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } +}; + +const server = new Server(options); +console.log(server.mime.path('code.js').type); // 'application/javascript' +console.log(server.mime.path('file.npm').type); // 'node/module' + +server.start(); diff --git a/types/hapi/v17/test/server/server-options.ts b/types/hapi/v17/test/server/server-options.ts new file mode 100644 index 0000000000..f72f98a55e --- /dev/null +++ b/types/hapi/v17/test/server/server-options.ts @@ -0,0 +1,114 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-server-options +import { Plugin, RouteOptions, Server, ServerOptions, ServerRegisterOptions } from "hapi"; +import { MimosOptions, MimosOptionsValue } from "mimos"; + +const mimeOptions: MimosOptions = { + override: { + 'node/module': { + source: 'iana', + compressible: true, + extensions: ['node', 'modsule', 'npm'], + type: 'node/module' + }, + 'application/javascript': { + source: 'iana', + charset: 'UTF-8', + compressible: true, + extensions: ['js', 'javascript'], + type: 'text/javascript' + }, + 'text/html': { + predicate: (mime: MimosOptionsValue) => { + if (1 === 1) { + // mime.foo = 'test'; + } else { + // mime.foo = 'bar'; + } + return mime; + } + } + } +}; + +const plugin: Plugin = { + name: 'example', + register: async (server: Server, options: ServerRegisterOptions) => { + server.expose('key', 'value'); + server.plugins.example.other = 'other'; + console.log(server.plugins.example.key); // 'value' + console.log(server.plugins.example.other); // 'other' + } +}; + +const routeOptions: RouteOptions = { + compression: { + test: { + some: 'option' + } + }, + files: { + relativeTo: __dirname + }, + cors: { + origin: ['http://test.example.com', 'http://www.example.com', 'http://*.a.com'] + }, +}; + +declare module 'hapi' { + interface ServerOptionsApp { + key1?: string; + key2?: string; + any_thing?: string; + } +} + +const options: ServerOptions = { + address: '0.0.0.0', + app: { + key1: 'value1', + key2: 'value2', + any_thing: 'any_value', + }, + autoListen: true, + cache: { + engine: require('catbox-memory'), + name: 'test', + shared: true, + partition: 'hapi-cache', + any_thing_1: 'any_thing_1', + any_thing_2: 'any_thing_2' + }, + compression: { + minBytes: 1024 + }, + debug: { + request: ['implementation'] + }, + host: 'localhost', + listener: undefined, + load: { sampleInterval: 0 }, + mime: mimeOptions, + plugins: plugin, + port: 8000, + router: { + isCaseSensitive: true, + stripTrailingSlash: false + }, + routes: routeOptions, + state: { + strictHeader: true, + ignoreErrors: false, + isSecure: true, + isHttpOnly: true, + isSameSite: 'Strict', + encoding: 'none' + }, + tls: true +}; + +const server = new Server(options); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-path.ts b/types/hapi/v17/test/server/server-path.ts new file mode 100644 index 0000000000..8a2ebf85dc --- /dev/null +++ b/types/hapi/v17/test/server/server-path.ts @@ -0,0 +1,37 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto +import { Plugin, Server, ServerRegisterOptions, ServerRoute } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +// Definition for INERT +declare module 'hapi' { + interface HandlerDecorations { + file?: string; + } +} + +const serverRouteOption: ServerRoute = { + path: '/file', + method: 'GET', + handler: { + file: './test.html' + } +}; + +const plugin: Plugin = { + name: 'example', + register: async (server: Server, options: ServerRegisterOptions) => { + // Assuming the Inert plugin was registered previously + server.path(__dirname + '../static'); + server.route(serverRouteOption); + } +}; + +server.start(); +server.register(plugin); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-plugins.ts b/types/hapi/v17/test/server/server-plugins.ts new file mode 100644 index 0000000000..03a3c76907 --- /dev/null +++ b/types/hapi/v17/test/server/server-plugins.ts @@ -0,0 +1,116 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +import { Plugin, Server, ServerRegisterOptions } from "hapi"; + +interface Plugin1 { + one: 1; +} + +interface Plugin2 { + two: 2; +} + +interface Plugin3 { + three: 3; +} + +interface Plugin4 { + four: 4; +} + +declare module 'hapi' { + interface PluginProperties { + example: { + other: string; + key: string; + }; + } +} + +const plugin1: Plugin = { + name: 'plugin1', + register: async (server: Server, options: Plugin1) => { + server.expose('key', 'value'); + server.plugins.example.other = 'other'; + console.log(server.plugins.example.key); // 'value' + console.log(server.plugins.example.other); // 'other' + }, +}; + +const plugin2: Plugin = { + name: 'plugin2', + register: async (server: Server, options: Plugin2) => {}, + dependencies: { + plugin1: '*', + }, + requirements: { + node: '>=8', + hapi: '>=1337', + }, +}; + +const plugin3: Plugin = { + name: 'plugin3', + register: async (server: Server, options: Plugin3) => {}, + dependencies: ['plugin2'], +}; + +const plugin4: Plugin = { + name: 'plugin4', + register: (server: Server, options: Plugin4) => {}, + dependencies: 'plugin3', +}; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.register(plugin1); + +server.register({ + plugin: plugin1, + options: {one: 1} +}); + +server.register([ + { + plugin: plugin2, + options: {two: 2} + }, + { + plugin: plugin3, + options: {three: 3} + }, + { + plugin: plugin1, + options: {one: 1} + }, + { + plugin: plugin2, + options: {two: 2} + }, + { + plugin: plugin3, + options: {three: 3} + }, + { + plugin: plugin1, + options: {one: 1} + }, + { + plugin: plugin2, + options: {two: 2} + }, + { + plugin: plugin3, + options: {three: 3} + }, + { + plugin: plugin1, + options: {one: 1} + }, + { + plugin: plugin4, + options: {four: 4} + } +]); diff --git a/types/hapi/v17/test/server/server-settings.ts b/types/hapi/v17/test/server/server-settings.ts new file mode 100644 index 0000000000..f0619d95da --- /dev/null +++ b/types/hapi/v17/test/server/server-settings.ts @@ -0,0 +1,18 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serversettings +import { Server } from "hapi"; + +declare module 'hapi' { + interface ServerOptionsApp { + key?: string; + } +} + +const server = new Server({ + port: 8000, + app: { + key: 'value' + } +}); +server.start(); + +console.log(server.settings.app); // { key: 'value' } diff --git a/types/hapi/v17/test/server/server-start.ts b/types/hapi/v17/test/server/server-start.ts new file mode 100644 index 0000000000..f41349e88c --- /dev/null +++ b/types/hapi/v17/test/server/server-start.ts @@ -0,0 +1,11 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-state.ts b/types/hapi/v17/test/server/server-state.ts new file mode 100644 index 0000000000..ba4ffe344c --- /dev/null +++ b/types/hapi/v17/test/server/server-state.ts @@ -0,0 +1,28 @@ +// from https://hapijs.com/tutorials/cookies?lang=en_US +import { Server, ServerOptions, ServerRoute, ServerStateCookieOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/say-hello', + method: 'GET', + handler(_request, h) { + h.state('test', { test: true }); + return h.response('Hello').state('data', { firstVisit: false }); + } +}; + +const server = new Server(options); +server.route(serverRoute); + +const stateOption: ServerStateCookieOptions = { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: false, + isHttpOnly: false, + encoding: 'base64json', +}; +server.state('data', stateOption); +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-stop.ts b/types/hapi/v17/test/server/server-stop.ts new file mode 100644 index 0000000000..7922fa944e --- /dev/null +++ b/types/hapi/v17/test/server/server-stop.ts @@ -0,0 +1,17 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); +server.events.on('stop', () => { + console.log('Server stoped.'); +}); +setTimeout(() => { + server.stop({ timeout: 10 * 1000 }); +}, 5 * 1000); diff --git a/types/hapi/v17/test/server/server-table.ts b/types/hapi/v17/test/server/server-table.ts new file mode 100644 index 0000000000..79726118b5 --- /dev/null +++ b/types/hapi/v17/test/server/server-table.ts @@ -0,0 +1,29 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost +import { Request, ResponseToolkit, Server, ServerOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const server = new Server(options); +server.app.key = 'value2'; + +server.route({ + path: '/', + method: 'GET', + handler(request, h) { + return h.response("Hello World"); + } +}); + +server.start(); +const table = server.table(); +console.log(table); +console.log(table[0].method); +console.log(table[0].path); +console.log(table[0].vhost); +console.log(table[0].realm); +console.log(table[0].settings); +console.log(table[0].fingerprint); +console.log(table[0].auth); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-version.ts b/types/hapi/v17/test/server/server-version.ts new file mode 100644 index 0000000000..b8e59497fc --- /dev/null +++ b/types/hapi/v17/test/server/server-version.ts @@ -0,0 +1,9 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverversion +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.start(); +console.log(server.version); // 17.x.x diff --git a/types/hapi/v17/tsconfig.json b/types/hapi/v17/tsconfig.json new file mode 100644 index 0000000000..c0e48eaa17 --- /dev/null +++ b/types/hapi/v17/tsconfig.json @@ -0,0 +1,79 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "hapi": [ + "hapi/v17" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/request/auth.ts", + "test/request/catch-all.ts", + "test/request/event-types.ts", + "test/request/get-log.ts", + "test/request/methods.ts", + "test/request/parameters.ts", + "test/request/query.ts", + "test/response/continue.ts", + "test/response/error.ts", + "test/response/redirect.ts", + "test/response/response-events.ts", + "test/response/response.ts", + "test/route/adding-routes.ts", + "test/route/config.ts", + "test/route/ext.ts", + "test/route/handler.ts", + "test/route/route-options-pre.ts", + "test/route/route-options.ts", + "test/route/validation.ts", + "test/server/server-app.ts", + "test/server/server-auth-api.ts", + "test/server/server-auth-default.ts", + "test/server/server-auth-test.ts", + "test/server/server-auth-verify.ts", + "test/server/server-bind.ts", + "test/server/server-cache-provision.ts", + "test/server/server-cache.ts", + "test/server/server-control.ts", + "test/server/server-decoder.ts", + "test/server/server-decorations.ts", + "test/server/server-encoder.ts", + "test/server/server-events-once.ts", + "test/server/server-events.ts", + "test/server/server-expose.ts", + "test/server/server-info.ts", + "test/server/server-inject.ts", + "test/server/server-listener.ts", + "test/server/server-load.ts", + "test/server/server-lookup.ts", + "test/server/server-match.ts", + "test/server/server-method.ts", + "test/server/server-methods.ts", + "test/server/server-mime.ts", + "test/server/server-options.ts", + "test/server/server-path.ts", + "test/server/server-plugins.ts", + "test/server/server-settings.ts", + "test/server/server-start.ts", + "test/server/server-state.ts", + "test/server/server-stop.ts", + "test/server/server-table.ts", + "test/server/server-version.ts" + ] +} diff --git a/types/hapi/v17/tslint.json b/types/hapi/v17/tslint.json new file mode 100644 index 0000000000..1c36270d47 --- /dev/null +++ b/types/hapi/v17/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} diff --git a/types/happypack/happypack-tests.ts b/types/happypack/happypack-tests.ts new file mode 100644 index 0000000000..c0ab2d77cf --- /dev/null +++ b/types/happypack/happypack-tests.ts @@ -0,0 +1,7 @@ +import * as happyPack from 'happypack'; + +const ref: happyPack = new happyPack({ + id: '1', + threads: 1, + loaders: ['ts-loader'] +}); diff --git a/types/happypack/index.d.ts b/types/happypack/index.d.ts new file mode 100644 index 0000000000..13c212a3f8 --- /dev/null +++ b/types/happypack/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for happypack 5.0 +// Project: https://github.com/amireh/happypack +// Definitions by: Akash Vishwakarma +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Plugin } from 'webpack'; + +export = happypack; + +declare namespace happypack { + interface PluginOptions { + id?: string; + threads?: number; + loaders: any; + } +} + +declare class happypack extends Plugin { + constructor(options: happypack.PluginOptions); +} diff --git a/types/happypack/tsconfig.json b/types/happypack/tsconfig.json new file mode 100644 index 0000000000..bfd5e35551 --- /dev/null +++ b/types/happypack/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", + "happypack-tests.ts" + ] +} \ No newline at end of file diff --git a/types/happypack/tslint.json b/types/happypack/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/happypack/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/hashtag-regex/hashtag-regex-tests.ts b/types/hashtag-regex/hashtag-regex-tests.ts new file mode 100644 index 0000000000..d0c9e3417d --- /dev/null +++ b/types/hashtag-regex/hashtag-regex-tests.ts @@ -0,0 +1,3 @@ +import hashtagRegex from "hashtag-regex"; + +hashtagRegex(); // $ExpectType RegExp diff --git a/types/hashtag-regex/index.d.ts b/types/hashtag-regex/index.d.ts new file mode 100644 index 0000000000..3540ce867b --- /dev/null +++ b/types/hashtag-regex/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for hashtag-regex 2.0 +// Project: https://github.com/mathiasbynens/hashtag-regex +// Definitions by: diogofcunha +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function createRegExp(): RegExp; +export = createRegExp; diff --git a/types/hashtag-regex/tsconfig.json b/types/hashtag-regex/tsconfig.json new file mode 100644 index 0000000000..5946da8371 --- /dev/null +++ b/types/hashtag-regex/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "hashtag-regex-tests.ts"] +} diff --git a/types/hashtag-regex/tslint.json b/types/hashtag-regex/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hashtag-regex/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hex-rgb/hex-rgb-tests.ts b/types/hex-rgb/hex-rgb-tests.ts new file mode 100644 index 0000000000..f9bbf5ea71 --- /dev/null +++ b/types/hex-rgb/hex-rgb-tests.ts @@ -0,0 +1,4 @@ +import hexRgb = require('hex-rgb'); + +hexRgb('#cd2222cc'); // $ExpectType RgbaObj +hexRgb('#cd2222cc', { format: 'array' }); // $ExpectType [number, number, number, number] diff --git a/types/hex-rgb/index.d.ts b/types/hex-rgb/index.d.ts new file mode 100644 index 0000000000..ab1de9bf24 --- /dev/null +++ b/types/hex-rgb/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for hex-rgb 3.0 +// Project: https://github.com/sindresorhus/hex-rgb#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = hexRgb; + +declare function hexRgb(hex: string): hexRgb.RgbaObj; +declare function hexRgb(hex: string, options: hexRgb.Options): hexRgb.RgbaArr; + +declare namespace hexRgb { + interface Options { + format: 'array'; + } + + interface RgbaObj { + red: number; + green: number; + blue: number; + alpha: number; + } + + type RgbaArr = [number, number, number, number]; +} diff --git a/types/hex-rgb/tsconfig.json b/types/hex-rgb/tsconfig.json new file mode 100644 index 0000000000..c20c71b94f --- /dev/null +++ b/types/hex-rgb/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", + "hex-rgb-tests.ts" + ] +} diff --git a/types/hex-rgb/tslint.json b/types/hex-rgb/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hex-rgb/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/highland/highland-tests.ts b/types/highland/highland-tests.ts index cc61fcf92d..07a71e22b0 100644 --- a/types/highland/highland-tests.ts +++ b/types/highland/highland-tests.ts @@ -305,7 +305,7 @@ barStream = barStreamStream.sequence(); barStream = fooStream.series(); -barStream = fooStream.through(x => bar); +bar = fooStream.through(x => bar); barStream = fooStream.through(readwritable); fooStream = fooStream.zip(fooStream); diff --git a/types/highland/index.d.ts b/types/highland/index.d.ts index b6372f799a..825c0a1a6b 100644 --- a/types/highland/index.d.ts +++ b/types/highland/index.d.ts @@ -1172,7 +1172,7 @@ declare namespace Highland { * console.log(err); // => SyntaxError: Unexpected token z * }); */ - through(f: (x: R) => U): Stream; + through(f: (x: R) => U): U; through(thru: NodeJS.ReadWriteStream): Stream; diff --git a/types/hls.js/index.d.ts b/types/hls.js/index.d.ts index 9b7986b99f..52967890bd 100644 --- a/types/hls.js/index.d.ts +++ b/types/hls.js/index.d.ts @@ -2,6 +2,8 @@ // Project: https://github.com/video-dev/hls.js // Definitions by: John G. Gainfort, Jr. // Johan Brook +// Adrián Caballero +// Alexey I. Berezin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -189,33 +191,65 @@ declare namespace Hls { */ interface Level { /** - * level url. might contain sever items if failover/redundant streams are found in the manifest + * attribute list */ - url: string[]; + attrs: LevelAttr[]; + /** + * audio codec + */ + audioCodec: string; /** * level bitrate */ bitrate: number; /** - * level name + * level details */ - name: string; + details?: LevelDetails; /** - * used codecs + * whether there is any error on the fragment */ - codecs: string; - /** - * video width - */ - width: number; + fragmentError?: boolean; /** * video height */ height: number; /** - * level details + * index of the level */ - details: LevelDetails; + level?: number; + /** + * error code + */ + loadError: number; + /** + * level name + */ + name: string; + /** + * array of unrecognized codecs + */ + unkownCodecs: string[]; + /** + * level url. might contain several items if failover/redundant streams are found in the manifest + */ + url: string[]; + /** + * index of current url from url[] array + */ + urlId: number; + /** + * video codec + */ + videoCodec: string; + /** + * video width + */ + width: number; + } + + interface LevelAttr { + [key: string]: string; } /** @@ -1701,6 +1735,11 @@ declare class Hls { * If set to false, the mode will be set to hidden. */ subtitleDisplay: boolean; + /** + * (default: NaN) + * Return current download bandwidth in bits/s if available + */ + bandwidthEstimate: number; /** * calling this method will: * bind videoElement and hls instances diff --git a/types/html-minifier/v1/tsconfig.json b/types/html-minifier/v1/tsconfig.json index 846fa3a1f6..2ea7965d25 100644 --- a/types/html-minifier/v1/tsconfig.json +++ b/types/html-minifier/v1/tsconfig.json @@ -16,11 +16,17 @@ "html-minifier": [ "html-minifier/v1" ], + "html-minifier/*": [ + "html-minifier/v1/*" + ], "uglify-js": [ "uglify-js/v2" ], - "html-minifier/*": [ - "html-minifier/v1/*" + "clean-css": [ + "clean-css/v3" + ], + "clean-css/*": [ + "clean-css/v3/*" ] }, "types": [], diff --git a/types/html-tags/html-tags-tests.ts b/types/html-tags/html-tags-tests.ts new file mode 100644 index 0000000000..802dbb665e --- /dev/null +++ b/types/html-tags/html-tags-tests.ts @@ -0,0 +1,9 @@ +import htmlTags = require('html-tags'); +import voidHtmlTags = require('html-tags/void'); +import htmlTagsJson = require('html-tags/html-tags.json'); +import voidHtmlTagsJson = require('html-tags/html-tags-void.json'); + +htmlTags; // $ExpectType string[] +voidHtmlTags; // $ExpectType string[] +htmlTagsJson; // $ExpectType string[] +voidHtmlTagsJson; // $ExpectType string[] diff --git a/types/html-tags/html-tags-void.json.d.ts b/types/html-tags/html-tags-void.json.d.ts new file mode 100644 index 0000000000..3e194ddf27 --- /dev/null +++ b/types/html-tags/html-tags-void.json.d.ts @@ -0,0 +1,3 @@ +export = voidHtmlTags; + +declare const voidHtmlTags: string[]; diff --git a/types/html-tags/html-tags.json.d.ts b/types/html-tags/html-tags.json.d.ts new file mode 100644 index 0000000000..888779dc9c --- /dev/null +++ b/types/html-tags/html-tags.json.d.ts @@ -0,0 +1,3 @@ +export = htmlTags; + +declare const htmlTags: string[]; diff --git a/types/html-tags/index.d.ts b/types/html-tags/index.d.ts new file mode 100644 index 0000000000..635ce4820f --- /dev/null +++ b/types/html-tags/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for html-tags 2.0 +// Project: https://github.com/sindresorhus/html-tags#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = htmlTags; + +declare const htmlTags: string[]; diff --git a/types/html-tags/tsconfig.json b/types/html-tags/tsconfig.json new file mode 100644 index 0000000000..971c9bb630 --- /dev/null +++ b/types/html-tags/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "void.d.ts", + "html-tags.json.d.ts", + "html-tags-void.json.d.ts", + "html-tags-tests.ts" + ] +} diff --git a/types/html-tags/tslint.json b/types/html-tags/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/html-tags/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/html-tags/void.d.ts b/types/html-tags/void.d.ts new file mode 100644 index 0000000000..3e194ddf27 --- /dev/null +++ b/types/html-tags/void.d.ts @@ -0,0 +1,3 @@ +export = voidHtmlTags; + +declare const voidHtmlTags: string[]; diff --git a/types/http-aws-es/http-aws-es-tests.ts b/types/http-aws-es/http-aws-es-tests.ts index df432dbab4..18ae2b666c 100644 --- a/types/http-aws-es/http-aws-es-tests.ts +++ b/types/http-aws-es/http-aws-es-tests.ts @@ -1,42 +1,43 @@ -import { EnvironmentCredentials } from "aws-sdk/lib/core"; +import * as AWS from "aws-sdk"; import { Client } from "elasticsearch"; import HttpAmazonESConnector = require("http-aws-es"); new Client({ - amazonES: { - accessKey: "AKID", + awsConfig: new AWS.Config({ + accessKeyId: "AKID", region: "us-east-1", - secretKey: "secret", - }, + secretAccessKey: "secret", + }), connectionClass: HttpAmazonESConnector, host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); new Client({ - amazonES: { - accessKey: "AKID", + awsConfig: new AWS.Config({ + accessKeyId: "AKID", region: "us-east-1", - secretKey: "secret", - }, + secretAccessKey: "secret", + }), connectionClass: require("http-aws-es"), host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); -const myCredentials = new EnvironmentCredentials("AWS"); +const myCredentials = new AWS.EnvironmentCredentials("AWS"); + new Client({ - amazonES: { + awsConfig: new AWS.Config({ credentials: myCredentials, region: "us-east-1", - }, + }), connectionClass: HttpAmazonESConnector, host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); new Client({ - amazonES: { + awsConfig: new AWS.Config({ credentials: myCredentials, region: "us-east-1", - }, + }), connectionClass: require("http-aws-es"), host: "https://amazon-es-host.us-east-1.es.amazonaws.com", }); diff --git a/types/http-aws-es/index.d.ts b/types/http-aws-es/index.d.ts index 91e12604f8..2a6ca11629 100644 --- a/types/http-aws-es/index.d.ts +++ b/types/http-aws-es/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for http-aws-es 1.1 +// Type definitions for http-aws-es 6.0 // Project: https://github.com/TheDeveloper/http-aws-es#readme // Definitions by: Marco Gonzalez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,18 +7,11 @@ /// import * as e from "elasticsearch"; -import { Credentials } from "aws-sdk/lib/core"; +import * as AWS from "aws-sdk"; declare module "elasticsearch" { - interface AmazonESOptions { - accessKey?: string; - credentials?: Credentials; - region: string; - secretKey?: string; - } - interface ConfigOptions { - amazonES?: AmazonESOptions; + awsConfig?: AWS.Config; } } diff --git a/types/http-cache-semantics/http-cache-semantics-tests.ts b/types/http-cache-semantics/http-cache-semantics-tests.ts new file mode 100644 index 0000000000..73de43b370 --- /dev/null +++ b/types/http-cache-semantics/http-cache-semantics-tests.ts @@ -0,0 +1,19 @@ +const req = { url: 'https://foo.bar', method: 'GET', headers: { foo: 'bar' } }; +const res = { status: 200, headers: { foo: 'bar' } }; + +import CachePolicy = require('http-cache-semantics'); + +const policy = new CachePolicy(req, res); +new CachePolicy(req, res, { shared: true }); +new CachePolicy(req, res, { cacheHeuristic: 0.1 }); +new CachePolicy(req, res, { immutableMinTimeToLive: 24 * 3600 * 1000 }); +new CachePolicy(req, res, { ignoreCargoCult: false }); +new CachePolicy(req, res, { trustServerDate: true }); + +policy.storable(); // $ExpectType boolean +policy.satisfiesWithoutRevalidation(req); // $ExpectType boolean +policy.responseHeaders(); // $ExpectType Headers +policy.timeToLive(); // $ExpectType number +CachePolicy.fromObject(policy.toObject()); // $ExpectType CachePolicy +policy.revalidationHeaders(req); // $ExpectType Headers +policy.revalidatedPolicy(req, res); // $ExpectType RevalidationPolicy diff --git a/types/http-cache-semantics/index.d.ts b/types/http-cache-semantics/index.d.ts new file mode 100644 index 0000000000..40545f3e0a --- /dev/null +++ b/types/http-cache-semantics/index.d.ts @@ -0,0 +1,170 @@ +// Type definitions for http-cache-semantics 4.0 +// Project: https://github.com/kornelski/http-cache-semantics#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = CachePolicy; + +declare class CachePolicy { + constructor(req: CachePolicy.Request, res: CachePolicy.Response, options?: CachePolicy.Options); + + /** + * Returns `true` if the response can be stored in a cache. + * If it's `false` then you MUST NOT store either the request or the response. + */ + storable(): boolean; + + /** + * This is the most important method. Use this method to check whether the cached response is still fresh + * in the context of the new request. + * + * If it returns `true`, then the given `request` matches the original response this cache policy has been + * created with, and the response can be reused without contacting the server. Note that the old response + * can't be returned without being updated, see `responseHeaders()`. + * + * If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), + * or may require to be refreshed first (see `revalidationHeaders()`). + */ + satisfiesWithoutRevalidation(newRequest: CachePolicy.Request): boolean; + + /** + * Returns updated, filtered set of response headers to return to clients receiving the cached response. + * This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) + * and update response's `Age` to avoid doubling cache time. + * + * @example + * cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse); + */ + responseHeaders(): CachePolicy.Headers; + + /** + * Returns approximate time in milliseconds until the response becomes stale (i.e. not fresh). + * + * After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, + * there are exceptions, e.g. a client can explicitly allow stale responses, so always check with + * `satisfiesWithoutRevalidation()`. + */ + timeToLive(): number; + + /** + * Chances are you'll want to store the `CachePolicy` object along with the cached response. + * `obj = policy.toObject()` gives a plain JSON-serializable object. + */ + toObject(): CachePolicy.CachePolicyObject; + + /** + * `policy = CachePolicy.fromObject(obj)` creates an instance from object created by `toObject()`. + */ + static fromObject(obj: CachePolicy.CachePolicyObject): CachePolicy; + + /** + * Returns updated, filtered set of request headers to send to the origin server to check if the cached + * response can be reused. These headers allow the origin server to return status 304 indicating the + * response is still fresh. All headers unrelated to caching are passed through as-is. + * + * Use this method when updating cache from the origin server. + * + * @example + * updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); + */ + revalidationHeaders(newRequest: CachePolicy.Request): CachePolicy.Headers; + + /** + * Use this method to update the cache after receiving a new response from the origin server. + */ + revalidatedPolicy( + revalidationRequest: CachePolicy.Request, + revalidationResponse: CachePolicy.Response + ): CachePolicy.RevalidationPolicy; +} + +declare namespace CachePolicy { + interface Request { + url?: string; + method?: string; + headers: Headers; + } + + interface Response { + status?: number; + headers: Headers; + } + + interface Options { + /** + * If `true`, then the response is evaluated from a perspective of a shared cache (i.e. `private` is not + * cacheable and `s-maxage` is respected). If `false`, then the response is evaluated from a perspective + * of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). + * `true` is recommended for HTTP clients. + * @default true + */ + shared?: boolean; + /** + * A fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), + * e.g. if a file hasn't been modified for 100 days, it'll be cached for 100*0.1 = 10 days. + * @default 0.1 + */ + cacheHeuristic?: number; + /** + * A number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. + * Note that [per RFC](https://httpwg.org/specs/rfc8246.html#the-immutable-cache-control-extension) + * these can become stale, so `max-age` still overrides the default. + * @default 24*3600*1000 (24h) + */ + immutableMinTimeToLive?: number; + /** + * If `true`, common anti-cache directives will be completely ignored if the non-standard `pre-check` + * and `post-check` directives are present. These two useless directives are most commonly found + * in bad StackOverflow answers and PHP's "session limiter" defaults. + * @default false + */ + ignoreCargoCult?: boolean; + /** + * If `false`, then server's `Date` header won't be used as the base for `max-age`. This is against the RFC, + * but it's useful if you want to cache responses with very short `max-age`, but your local clock + * is not exactly in sync with the server's. + * @default true + */ + trustServerDate?: boolean; + } + + interface CachePolicyObject { + v: number; + t: number; + sh: boolean; + ch: number; + imm: number; + st: number; + resh: Headers; + rescc: { [key: string]: string }; + m: string; + u?: string; + h?: string; + a: boolean; + reqh: Headers | null; + reqcc: { [key: string]: string }; + } + + interface Headers { + [header: string]: string | string[] | undefined; + } + + interface RevalidationPolicy { + /** + * A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace + * the old cached `CachePolicy` with the new one. + */ + policy: CachePolicy; + /** + * Boolean indicating whether the response body has changed. + * + * - If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old + * cached response body. + * - If `true`, you should use new response's body (if present), or make another request to the origin + * server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get + * the new resource. + */ + modified: boolean; + matches: boolean; + } +} diff --git a/types/http-cache-semantics/tsconfig.json b/types/http-cache-semantics/tsconfig.json new file mode 100644 index 0000000000..9940b3d2e6 --- /dev/null +++ b/types/http-cache-semantics/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", + "http-cache-semantics-tests.ts" + ] +} diff --git a/types/http-cache-semantics/tslint.json b/types/http-cache-semantics/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-cache-semantics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/http-proxy-middleware/http-proxy-middleware-tests.ts b/types/http-proxy-middleware/http-proxy-middleware-tests.ts index aae082a956..9967dedcd9 100644 --- a/types/http-proxy-middleware/http-proxy-middleware-tests.ts +++ b/types/http-proxy-middleware/http-proxy-middleware-tests.ts @@ -140,3 +140,6 @@ proxy({ proxy({ headers: {host: 'www.example.org'} }); + +// Shorthands +proxy('/'); diff --git a/types/http-proxy-middleware/index.d.ts b/types/http-proxy-middleware/index.d.ts index 09b80e21c4..13f2669e5f 100644 --- a/types/http-proxy-middleware/index.d.ts +++ b/types/http-proxy-middleware/index.d.ts @@ -15,7 +15,7 @@ import * as httpProxy from "http-proxy"; import { Readable } from 'stream'; declare function proxy(config: proxy.Config): proxy.Proxy; -declare function proxy(contextOrUri: string | string[] | proxy.Filter, config: proxy.Config): proxy.Proxy; +declare function proxy(contextOrUri: string | string[] | proxy.Filter, config?: proxy.Config): proxy.Proxy; declare namespace proxy { type Filter = (pathname: string, req: http.IncomingMessage) => boolean; diff --git a/types/http-rx/http-rx-tests.ts b/types/http-rx/http-rx-tests.ts index 082585fdf9..b76ba67832 100644 --- a/types/http-rx/http-rx-tests.ts +++ b/types/http-rx/http-rx-tests.ts @@ -1,13 +1,14 @@ import { Observable } from 'rxjs'; import httpRx = require('http-rx'); +import request = require('request'); -const httpGet: Observable = httpRx.get(''); +const httpGet: Observable<{response: request.Response}> = httpRx.get(''); -const httpHead: Observable = httpRx.head(''); +const httpHead: Observable<{body: any}> = httpRx.head(''); -const httpPatch: Observable = httpRx.patch(''); +const httpPatch: Observable<{response: request.Response, body: any}> = httpRx.patch(''); -const httpPost: Observable = httpRx.post(''); +const httpPost: Observable<{response: request.Response, body: any}> = httpRx.post('', {json: true}); const httpPut: Observable<{}> = httpRx.put(''); diff --git a/types/http-rx/index.d.ts b/types/http-rx/index.d.ts index 3b0c734fb0..c752427b8a 100644 --- a/types/http-rx/index.d.ts +++ b/types/http-rx/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for http-rx 1.1 +// Type definitions for http-rx 2.0 // Project: https://github.com/JasonRammoray/HttpRx // Definitions by: L2jLiga // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,18 +7,23 @@ import { Observable } from 'rxjs'; import request = require('request'); +interface ResponseWrapper { + response: request.Response; + body: any; +} + interface HttpRx { - get(url: string, options?: request.CoreOptions): Observable; + get(url: string, options?: request.CoreOptions): Observable; - head(url: string, options?: request.CoreOptions): Observable; + head(url: string, options?: request.CoreOptions): Observable; - patch(url: string, options?: request.CoreOptions): Observable; + patch(url: string, options?: request.CoreOptions): Observable; - post(url: string, options?: request.CoreOptions): Observable; + post(url: string, options?: request.CoreOptions): Observable; - put(url: string, options?: request.CoreOptions): Observable; + put(url: string, options?: request.CoreOptions): Observable; - 'delete'(url: string, options?: request.CoreOptions): Observable; + delete(url: string, options?: request.CoreOptions): Observable; } declare const httpRx: HttpRx; diff --git a/types/idyll-document/idyll-document-tests.ts b/types/idyll-document/idyll-document-tests.ts index 880e017013..7a08c0189d 100644 --- a/types/idyll-document/idyll-document-tests.ts +++ b/types/idyll-document/idyll-document-tests.ts @@ -1,5 +1,7 @@ import IdyllDocument, { IdyllDocumentProps } from "idyll-document"; -import { createElement } from "react"; +import { createElement, ReactElement } from "react"; -// $ExpectType ReactElement -createElement(IdyllDocument); +const doc = createElement(IdyllDocument); + +// $ExpectType true +type test = typeof doc extends ReactElement ? true : false; diff --git a/types/image-size/image-size-tests.ts b/types/image-size/image-size-tests.ts index 058ed7934f..633169105d 100644 --- a/types/image-size/image-size-tests.ts +++ b/types/image-size/image-size-tests.ts @@ -4,11 +4,11 @@ import sizeOf = require("image-size"); // Synchronous const dimensions = sizeOf("images/funny-cats.png"); -console.log(dimensions.width, dimensions.height); +console.log(dimensions.width, dimensions.height, dimensions.orientation); // Asynchronous sizeOf("images/funny-cats.png", (err, dimensions) => { - console.log(dimensions.width, dimensions.height); + console.log(dimensions.width, dimensions.height, dimensions.orientation); }); // From URL diff --git a/types/image-size/index.d.ts b/types/image-size/index.d.ts index 9e8681d514..443c319fb2 100644 --- a/types/image-size/index.d.ts +++ b/types/image-size/index.d.ts @@ -1,23 +1,20 @@ -// Type definitions for image-size +// Type definitions for image-size 0.7 // Project: https://github.com/image-size/image-size // Definitions by: Elisée MAURER // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - - interface ImageInfo { width: number; height: number; type: string; + orientation?: number; } -declare function sizeOf(path: string): ImageInfo; +declare function sizeOf(pathOrBuffer: string | Buffer): ImageInfo; declare function sizeOf(path: string, callback: (err: Error, dimensions: ImageInfo) => void): void; -declare function sizeOf(buffer: Buffer): ImageInfo; - declare namespace sizeOf { } export = sizeOf; diff --git a/types/image-size/tsconfig.json b/types/image-size/tsconfig.json index 7a864603b7..7c8d0db7d1 100644 --- a/types/image-size/tsconfig.json +++ b/types/image-size/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/image-size/tslint.json b/types/image-size/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/image-size/tslint.json +++ b/types/image-size/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/inboxsdk/inboxsdk-tests.ts b/types/inboxsdk/inboxsdk-tests.ts index 4f51bae92c..19329b9d63 100644 --- a/types/inboxsdk/inboxsdk-tests.ts +++ b/types/inboxsdk/inboxsdk-tests.ts @@ -571,6 +571,7 @@ InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { sdk.Router.createLink('1234', {p1: 1, 0: 1}).toLowerCase(); sdk.Router.goto('1234', {p1: 1, 0: 1}); + sdk.Router.goto(sdk.Router.NativeRouteIDs.ALL_MAIL, {p1: 1, 0: 1}); const unregister1 = sdk.Router.handleCustomRoute('1234', customRouteView => { customRouteView.getParams(); @@ -591,7 +592,7 @@ InboxSDK.load(1, '1234').then((sdk: InboxSDK.InboxSDKInstance) => { unregister2(); - const unregister3 = sdk.Router.handleListRoute('ALL_MAIL', listRouteView => { + const unregister3 = sdk.Router.handleListRoute(sdk.Router.NativeListRouteIDs.DRAFTS, listRouteView => { const sectionDescriptor: SectionDescriptor = { contentElement: new HTMLElement(), footerLinkText: 'text', diff --git a/types/inboxsdk/index.d.ts b/types/inboxsdk/index.d.ts index 4ced3ce6bd..abdfe413bf 100644 --- a/types/inboxsdk/index.d.ts +++ b/types/inboxsdk/index.d.ts @@ -657,6 +657,9 @@ declare namespace InboxSDK { handleCustomListRoute(routeID: string, handler: (offset: number, max: number) => CustomListDescriptor | Promise): () => void; getCurrentRouteView(): RouteView; + + NativeListRouteIDs: typeof NativeListRouteIDs; + NativeRouteIDs: typeof NativeRouteIDs; } interface CustomListDescriptor { @@ -754,43 +757,45 @@ declare namespace InboxSDK { onClick?: () => void; } - type NativeRouteIDs = - 'INBOX' | - 'ALL_MAIL' | - 'SENT' | - 'STARRED' | - 'DRAFTS' | - 'SNOOZED' | - 'DONE' | - 'REMINDERS' | - 'LABEL' | - 'TRASH' | - 'SPAM' | - 'IMPORTANT' | - 'SEARCH' | - 'THREAD' | - 'CHATS' | - 'CHAT' | - 'CONTACTS' | - 'CONTACT' | - 'SETTINGS' | - 'ANY_LIST'; + enum NativeRouteIDs { + INBOX, + ALL_MAIL, + SENT, + STARRED, + DRAFTS, + SNOOZED, + DONE, + REMINDERS, + LABEL, + TRASH, + SPAM, + IMPORTANT, + SEARCH, + THREAD, + CHATS, + CHAT, + CONTACTS, + CONTACT, + SETTINGS, + ANY_LIST + } - type NativeListRouteIDs = - 'INBOX' - | 'ALL_MAIL' - | 'SENT' - | 'STARRED' - | 'DRAFTS' - | 'SNOOZED' - | 'DONE' - | 'REMINDERS' - | 'LABEL' - | 'TRASH' - | 'SPAM' - | 'IMPORTANT' - | 'SEARCH' - | 'ANY_LIST'; + enum NativeListRouteIDs { + INBOX, + ALL_MAIL, + SENT, + STARRED, + DRAFTS, + SNOOZED, + DONE, + REMINDERS, + LABEL, + TRASH, + SPAM, + IMPORTANT, + SEARCH, + ANY_LIST + } } export namespace NavMenu { diff --git a/types/ink/index.d.ts b/types/ink/index.d.ts index f91d83df75..23f4fe5d80 100644 --- a/types/ink/index.d.ts +++ b/types/ink/index.d.ts @@ -59,7 +59,7 @@ export abstract class Component< S extends Record = {}, C extends Record = {} > { - readonly props: P; + readonly props: P & { children?: InkNode }; readonly context: C; setState( diff --git a/types/intl-tel-input/index.d.ts b/types/intl-tel-input/index.d.ts index 667a210087..f0c8407f18 100644 --- a/types/intl-tel-input/index.d.ts +++ b/types/intl-tel-input/index.d.ts @@ -1,9 +1,21 @@ // Type definitions for intl-tel-input 14.0 // Project: https://github.com/jackocnr/intl-tel-input -// Definitions by: Fidan Hakaj , Leonard Thieu , Márton Molnár +// Definitions by: Fidan Hakaj +// Leonard Thieu +// Márton Molnár // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +export as namespace intlTelInput; + +export = IntlTelInput; + +/** + * initialise the plugin with optional options. + * @param options options that can be provided during initialization. + */ +declare function IntlTelInput(node: Element, options?: IntlTelInput.Options): IntlTelInput.Plugin; + declare namespace IntlTelInput { interface Static { /** @@ -25,6 +37,8 @@ declare namespace IntlTelInput { } interface Plugin { + promise: Promise; + /** * Remove the plugin from the input, and unbind any event listeners. */ @@ -386,16 +400,50 @@ declare namespace intlTelInputUtils { | "VOIP"; } -interface Window { - intlTelInputGlobals: IntlTelInput.Static; +declare global { + namespace intlTelInputUtils { + enum numberFormat { + E164 = 0, + INTERNATIONAL = 1, + NATIONAL = 2, + RFC3966 = 3 + } - /** - * initialise the plugin with optional options. - * @param options options that can be provided during initialization. - */ - intlTelInput(node: Element, options?: IntlTelInput.Options): IntlTelInput.Plugin; -} + enum numberType { + FIXED_LINE = 0, + MOBILE = 1, + FIXED_LINE_OR_MOBILE = 2, + TOLL_FREE = 3, + PREMIUM_RATE = 4, + SHARED_COST = 5, + VOIP = 6, + PERSONAL_NUMBER = 7, + PAGER = 8, + UAN = 9, + VOICEMAIL = 10, + UNKNOWN = -1 + } -interface JQuery { - intlTelInput: IntlTelInput.JQueryPlugin; + enum validationError { + IS_POSSIBLE = 0, + INVALID_COUNTRY_CODE = 1, + TOO_SHORT = 2, + TOO_LONG = 3, + NOT_A_NUMBER = 4 + } + } + + interface Window { + intlTelInputGlobals: IntlTelInput.Static; + + /** + * initialise the plugin with optional options. + * @param options options that can be provided during initialization. + */ + intlTelInput(node: Element, options?: IntlTelInput.Options): IntlTelInput.Plugin; + } + + interface JQuery { + intlTelInput: IntlTelInput.JQueryPlugin; + } } diff --git a/types/intl-tel-input/intl-tel-input-tests.ts b/types/intl-tel-input/intl-tel-input-tests.ts index ab6808bbed..6bb705cafb 100644 --- a/types/intl-tel-input/intl-tel-input-tests.ts +++ b/types/intl-tel-input/intl-tel-input-tests.ts @@ -1,5 +1,10 @@ /// +// Global + +// $ExpectType (node: Element, options?: Options) => Plugin +intlTelInput; + // Normal version const input = document.querySelector("#phone"); diff --git a/types/intl-tel-input/test/module-tests.ts b/types/intl-tel-input/test/module-tests.ts new file mode 100644 index 0000000000..4bfdd3c6a7 --- /dev/null +++ b/types/intl-tel-input/test/module-tests.ts @@ -0,0 +1,24 @@ +import intlTelInput = require('intl-tel-input'); + +function test_import() { + // $ExpectType (node: Element, options?: Options) => Plugin + intlTelInput; +} + +function test_IntlTelInput_not_visible() { + // $ExpectError + const options: IntlTelInput.Options = { + allowDropdown: true + }; +} + +function test_intlTelInputUtils_global() { + const input = document.querySelector('#phone'); + const iti = intlTelInput(input, { + utilsScript: 'node_modules/intl-tel-input/build/js/utils.js' + }); + + iti.promise.then(() => { + console.log(intlTelInputUtils.numberFormat.E164); + }); +} diff --git a/types/intl-tel-input/tsconfig.json b/types/intl-tel-input/tsconfig.json index e067880440..302c298ef8 100644 --- a/types/intl-tel-input/tsconfig.json +++ b/types/intl-tel-input/tsconfig.json @@ -19,6 +19,7 @@ }, "files": [ "index.d.ts", - "intl-tel-input-tests.ts" + "intl-tel-input-tests.ts", + "test/module-tests.ts" ] } diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 81381d801d..6beeccb08f 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -1081,12 +1081,12 @@ declare global { setObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; setObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; /** Creates or overwrites an object in the object db */ - setObjectAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise>; + setObjectAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise>; /** Creates an object in the object db. Existing objects are not overwritten. */ setObjectNotExists(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; setObjectNotExists(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; /** Creates an object in the object db. Existing objects are not overwritten. */ - setObjectNotExistsAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise>; + setObjectNotExistsAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise>; /** Get all states, channels and devices of this adapter */ getAdapterObjects(callback: (objects: Record) => void): void; /** Get all states, channels and devices of this adapter */ @@ -1095,7 +1095,7 @@ declare global { extendObject(id: string, objPart: PartialObject, callback?: SetObjectCallback): void; extendObject(id: string, objPart: PartialObject, options: unknown, callback?: SetObjectCallback): void; /** Extend an object and create it if it might not exist */ - extendObjectAsync(id: string, objPart: PartialObject, options?: unknown): Promise>; + extendObjectAsync(id: string, objPart: PartialObject, options?: unknown): Promise>; /** * Deletes an object from the object db * @param id - The id of the object without namespace @@ -1133,17 +1133,17 @@ declare global { setForeignObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; setForeignObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; /** Creates or overwrites an object (which might not belong to this adapter) in the object db */ - setForeignObjectAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise>; + setForeignObjectAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise>; /** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */ setForeignObjectNotExists(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; setForeignObjectNotExists(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; /** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */ - setForeignObjectNotExistsAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise>; + setForeignObjectNotExistsAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): Promise>; /** Extend an object (which might not belong to this adapter) and create it if it might not exist */ extendForeignObject(id: string, objPart: PartialObject, callback?: SetObjectCallback): void; extendForeignObject(id: string, objPart: PartialObject, options: unknown, callback?: SetObjectCallback): void; /** Extend an object (which might not belong to this adapter) and create it if it might not exist */ - extendForeignObjectAsync(id: string, objPart: PartialObject, options?: unknown): Promise>; + extendForeignObjectAsync(id: string, objPart: PartialObject, options?: unknown): Promise>; /** * Finds an object by its ID or name * @param type - common.type of the state @@ -1178,36 +1178,42 @@ declare global { setState(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateCallback): void; setState(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateCallback): void; /** Writes a value into the states DB. */ - setStateAsync(id: string, state: string | number | boolean | State | Partial, ack?: boolean): Promise>; - setStateAsync(id: string, state: string | number | boolean | State | Partial, options?: unknown): Promise>; - setStateAsync(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown): Promise>; + setStateAsync(id: string, state: string | number | boolean | State | Partial, ack?: boolean): Promise>; + setStateAsync(id: string, state: string | number | boolean | State | Partial, options?: unknown): Promise>; + setStateAsync(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown): Promise>; /** Writes a value into the states DB only if it has changed. */ setStateChanged(id: string, state: string | number | boolean | State | Partial, callback?: SetStateChangedCallback): void; setStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateChangedCallback): void; setStateChanged(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateChangedCallback): void; setStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateChangedCallback): void; /** Writes a value into the states DB only if it has changed. */ - setStateChangedAsync(id: string, state: string | number | boolean | State | Partial, ack?: boolean): Promise>; - setStateChangedAsync(id: string, state: string | number | boolean | State | Partial, options?: unknown): Promise>; - setStateChangedAsync(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown): Promise>; + setStateChangedAsync(id: string, state: string | number | boolean | State | Partial, ack?: boolean): Promise>; + setStateChangedAsync(id: string, state: string | number | boolean | State | Partial, options?: unknown): Promise>; + setStateChangedAsync(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown): Promise>; /** Writes a value (which might not belong to this adapter) into the states DB. */ setForeignState(id: string, state: string | number | boolean | State | Partial, callback?: SetStateCallback): void; setForeignState(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateCallback): void; setForeignState(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateCallback): void; setForeignState(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateCallback): void; /** Writes a value (which might not belong to this adapter) into the states DB. */ - setForeignStateAsync(id: string, state: string | number | boolean | State | Partial, ack?: boolean): Promise>; - setForeignStateAsync(id: string, state: string | number | boolean | State | Partial, options?: unknown): Promise>; - setForeignStateAsync(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown): Promise>; + setForeignStateAsync(id: string, state: string | number | boolean | State | Partial, ack?: boolean): Promise>; + setForeignStateAsync(id: string, state: string | number | boolean | State | Partial, options?: unknown): Promise>; + setForeignStateAsync(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown): Promise>; /** Writes a value (which might not belong to this adapter) into the states DB only if it has changed. */ setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, callback?: SetStateChangedCallback): void; setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateChangedCallback): void; setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateChangedCallback): void; setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateChangedCallback): void; /** Writes a value (which might not belong to this adapter) into the states DB only if it has changed. */ - setForeignStateChangedAsync(id: string, state: string | number | boolean | State | Partial, ack?: boolean): Promise>; - setForeignStateChangedAsync(id: string, state: string | number | boolean | State | Partial, options?: unknown): Promise>; - setForeignStateChangedAsync(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown): Promise>; + setForeignStateChangedAsync( + id: string, state: string | number | boolean | State | Partial, ack?: boolean + ): Promise>; + setForeignStateChangedAsync( + id: string, state: string | number | boolean | State | Partial, options?: unknown + ): Promise>; + setForeignStateChangedAsync( + id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown + ): Promise>; // tslint:enable:unified-signatures /** Read a value from the states DB. */ @@ -1266,7 +1272,7 @@ declare global { * @param binary The data to be written * @param options (optional) Some internal options. */ - setBinaryStateAsync(id: string, binary: Buffer, options?: unknown): Promise>; + setBinaryStateAsync(id: string, binary: Buffer, options?: unknown): Promise>; /** * Reads a binary state from Redis * @param id The id of the state @@ -1296,7 +1302,7 @@ declare global { getEnums(enumList: EnumList, callback: GetEnumsCallback): void; getEnums(enumList: EnumList, options: unknown, callback: GetEnumsCallback): void; /** Returns the enum tree, filtered by the optional enum name */ - getEnumsAsync(enumList: EnumList, options?: unknown): Promise>; + getEnumsAsync(enumList: EnumList, options?: unknown): Promise>; addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, callback?: ErrorCallback): void; addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, options: unknown, callback?: ErrorCallback): void; @@ -1327,19 +1333,39 @@ declare global { unsubscribeForeignObjects(pattern: string, options?: unknown, callback?: ErrorCallback): void; /** Subscribe to changes of states in this instance */ - subscribeStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; + subscribeStates(pattern: string, callback?: ErrorCallback): void; + subscribeStates(pattern: string, options: unknown, callback?: ErrorCallback): void; + /** Subscribe to changes of states in this instance */ + subscribeStatesAsync(pattern: string, options?: unknown): Promise; + /** Subscribe to changes of states (which might not belong to this adapter) */ - subscribeForeignStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; + subscribeForeignStates(pattern: string, callback?: ErrorCallback): void; + subscribeForeignStates(pattern: string, options: unknown, callback?: ErrorCallback): void; + /** Subscribe to changes of states (which might not belong to this adapter) */ + subscribeForeignStatesAsync(pattern: string, options?: unknown): Promise; + /** * Subscribe from changes of states in this instance * @param pattern - Must match the pattern used to subscribe */ - unsubscribeStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; + unsubscribeStates(pattern: string, callback?: ErrorCallback): void; + unsubscribeStates(pattern: string, options: unknown, callback?: ErrorCallback): void; + /** + * Subscribe from changes of states in this instance + * @param pattern - Must match the pattern used to subscribe + */ + unsubscribeStatesAsync(pattern: string, options?: unknown): Promise; /** * Subscribe from changes of states (which might not belong to this adapter) * @param pattern - Must match the pattern used to subscribe */ - unsubscribeForeignStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; + unsubscribeForeignStates(pattern: string, callback?: ErrorCallback): void; + unsubscribeForeignStates(pattern: string, options: unknown, callback?: ErrorCallback): void; + /** + * Subscribe from changes of states (which might not belong to this adapter) + * @param pattern - Must match the pattern used to subscribe + */ + unsubscribeForeignStatesAsync(pattern: string, options?: unknown): Promise; // ============================== // devices and channels @@ -1351,9 +1377,9 @@ declare global { createDevice(deviceName: string, common: Partial, native: Record, callback?: SetObjectCallback): void; createDevice(deviceName: string, common: Partial, native: Record, options: unknown, callback?: SetObjectCallback): void; /** creates an object with type device */ - createDeviceAsync(deviceName: string, common?: Partial): Promise>; - createDeviceAsync(deviceName: string, common: Partial, native?: Record): Promise>; - createDeviceAsync(deviceName: string, common: Partial, native: Record, options?: unknown): Promise>; + createDeviceAsync(deviceName: string, common?: Partial): Promise>; + createDeviceAsync(deviceName: string, common: Partial, native?: Record): Promise>; + createDeviceAsync(deviceName: string, common: Partial, native: Record, options?: unknown): Promise>; /** deletes a device, its channels and states */ deleteDevice(deviceName: string, callback?: ErrorCallback): void; deleteDevice(deviceName: string, options: unknown, callback?: ErrorCallback): void; @@ -1369,14 +1395,14 @@ declare global { native: Record, options: unknown, callback?: SetObjectCallback ): void; /** Creates an object with type channel. It must be located under a device */ - createChannelAsync(parentDevice: string, channelName: string, roleOrCommon?: string | Partial): Promise>; + createChannelAsync(parentDevice: string, channelName: string, roleOrCommon?: string | Partial): Promise>; createChannelAsync( parentDevice: string, channelName: string, roleOrCommon: string | Partial, native?: Record - ): Promise>; + ): Promise>; createChannelAsync( parentDevice: string, channelName: string, roleOrCommon: string | Partial, native: Record, options?: unknown - ): Promise>; + ): Promise>; /** Deletes a channel and its states. It must have been created with `createChannel` */ deleteChannel(channelName: string, options?: unknown, callback?: ErrorCallback): void; deleteChannel(parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void; @@ -1400,15 +1426,17 @@ declare global { /** * Creates a state and the corresponding object. It must be located in a channel under a device */ - createStateAsync(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | Partial): Promise>; + createStateAsync( + parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | Partial + ): Promise>; createStateAsync( parentDevice: string, parentChannel: string, stateName: string, roleOrCommon: string | Partial, native?: Record - ): Promise>; + ): Promise>; createStateAsync( parentDevice: string, parentChannel: string, stateName: string, roleOrCommon: string | Partial, native: Record, options?: unknown - ): Promise>; + ): Promise>; /** Deletes a state. It must have been created with `createState` */ deleteState(stateName: string, options?: unknown, callback?: ErrorCallback): void; deleteState(parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void; @@ -1498,7 +1526,7 @@ declare global { * @param adapterName - adapter name. If adapter name is null, default will be the name of the current adapter. * @param path - path to directory without adapter name. E.g. If you want to read "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0". */ - readDirAsync(adapterName: string | null, path: string, options?: unknown): Promise>; + readDirAsync(adapterName: string | null, path: string, options?: unknown): Promise>; mkDir(adapterName: string | null, path: string, callback: ErrorCallback): void; mkDir(adapterName: string | null, path: string, options: unknown, callback: ErrorCallback): void; @@ -1624,7 +1652,10 @@ declare global { type GetObjectsCallback3 = (err: string | null, result?: Array>) => void; type SecondParameterOf any> = T extends (arg0: any, arg1: infer R, ...args: any[]) => any ? R : never; - type CallbackReturnTypeOf any> = Exclude, null | undefined>; + /** Infers the return type from a callback-style API and strips out null and undefined */ + type NonNullCallbackReturnTypeOf any> = Exclude, null | undefined>; + /** Infers the return type from a callback-style API and and leaves null and undefined in */ + type CallbackReturnTypeOf any> = SecondParameterOf; type GetStateCallback = (err: string | null, state: State | null | undefined) => void; type GetStatesCallback = (err: string | null, states: Record) => void; /** Version of the callback used by States.getStates */ diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index f49eb34576..01ab0c6fc4 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -149,6 +149,13 @@ adapter.setForeignStateChangedAsync("state.name", "value").then(id => id.toLower adapter.setForeignStateChangedAsync("state.name", "value", true).then(id => id.toLowerCase()); adapter.setForeignStateChangedAsync("state.name", { val: "value", ack: true }).then(id => id.toLowerCase()); +adapter.getState("state.id", (err, state) => state && state.from.toLowerCase()); +adapter.getStateAsync("state.id").then(state => state && state.from.toLowerCase()); +adapter.getForeignState("state.id", (err, state) => state && state.from.toLowerCase()); +adapter.getForeignStateAsync("state.id").then(state => state && state.from.toLowerCase()); +adapter.getBinaryState("state.id", (err, state) => state && state.writeUInt16BE(0, 0)); +adapter.getBinaryStateAsync("state.id").then(state => state && state.writeUInt16BE(0, 0)); + adapter.setObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }); adapter.setObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { }); adapter.setForeignObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }); @@ -168,8 +175,8 @@ adapter.setForeignObjectNotExistsAsync("obj.id", { type: "state", common: { name adapter.getObject("obj.id", (err, obj) => { }); adapter.getForeignObject("obj.id", (err, obj) => { }); -adapter.getObjectAsync("obj.id").then(obj => obj._id.toLowerCase()); -adapter.getForeignObjectAsync("obj.id").then(obj => obj._id.toLowerCase()); +adapter.getObjectAsync("obj.id").then(obj => obj && obj._id.toLowerCase()); +adapter.getForeignObjectAsync("obj.id").then(obj => obj && obj._id.toLowerCase()); adapter.getForeignObjects("*", (err, objs) => objs["foo"]._id.toLowerCase()); adapter.getForeignObjectsAsync("*").then(objs => objs["foo"]._id.toLowerCase()); @@ -241,3 +248,14 @@ adapter.sendToHostAsync("host-foo", "command", "message").then(handleMessageResp adapter.sendToHostAsync("host-foo", "message").then(handleMessageResponse); adapter.sendToHostAsync("host-foo", "command", {msg: "message"}).then(handleMessageResponse); adapter.sendToHostAsync("host-foo", {msg: "message"}).then(handleMessageResponse); + +function handleError(err?: string) { } +adapter.subscribeStates("*", handleError); +adapter.subscribeForeignStates("*", handleError); +adapter.unsubscribeStates("*", handleError); +adapter.unsubscribeForeignStates("*", handleError); + +adapter.subscribeStatesAsync("*").catch(handleError); +adapter.subscribeForeignStatesAsync("*").catch(handleError); +adapter.unsubscribeStatesAsync("*").catch(handleError); +adapter.unsubscribeForeignStatesAsync("*").catch(handleError); diff --git a/types/iopipe__iopipe/index.d.ts b/types/iopipe__iopipe/index.d.ts new file mode 100644 index 0000000000..401e78174e --- /dev/null +++ b/types/iopipe__iopipe/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for iopipe__iopipe 1.12 +// Project: https://github.com/iopipe/iopipe (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: Javon Harper +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function iopipe(config?: iopipe.LibraryConfig): iopipe.FunctionWrapper; + +declare namespace iopipe { + function label(label: string): void; + + function metric(label: string, value: number): void; + + namespace mark { + function start(label: string): void; + function end(label: string): void; + } + + interface LibraryConfig { + debug?: boolean; + token?: string; + networkTimeout?: number; + timeoutWindow?: number; + } + + type FunctionWrapper = (handler: T) => T; +} + +export = iopipe; diff --git a/types/iopipe__iopipe/iopipe__iopipe-tests.ts b/types/iopipe__iopipe/iopipe__iopipe-tests.ts new file mode 100644 index 0000000000..0132de3e01 --- /dev/null +++ b/types/iopipe__iopipe/iopipe__iopipe-tests.ts @@ -0,0 +1,17 @@ +import iopipe = require('iopipe__iopipe'); + +const config = { + token: "ABCDEFG" +}; + +function run(event: any, context: any, callback?: any) { + iopipe.label('my label'); + + iopipe.metric("magic number", 42); + + iopipe.mark.start("my-db-call"); + // an expensive database query + iopipe.mark.end("my-db-call"); +} + +export default iopipe(config)(run); diff --git a/types/iopipe__iopipe/tsconfig.json b/types/iopipe__iopipe/tsconfig.json new file mode 100644 index 0000000000..01d23ff29d --- /dev/null +++ b/types/iopipe__iopipe/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iopipe__iopipe-tests.ts" + ], + "paths": { + "@iopipe/iopipe": ["iopipe__iopipe"] + } +} diff --git a/types/iopipe__iopipe/tslint.json b/types/iopipe__iopipe/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/iopipe__iopipe/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index acd380e7db..d5f829c8fe 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -10,6 +10,7 @@ // Dmitry Motovilov // Oleg Repin // Ting-Wai To +// Alex Petty // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -106,6 +107,7 @@ declare namespace IORedis { del(...keys: KeyType[]): Promise; exists(...keys: KeyType[]): Promise; + exists(key: KeyType, callback: (err: Error, res: number) => void): void; setbit(key: KeyType, offset: number, value: any, callback: (err: Error, res: number) => void): void; setbit(key: KeyType, offset: number, value: any): Promise; @@ -971,8 +973,13 @@ declare namespace IORedis { count?: number; } + type DNSLookupFunction = (hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; + interface NatMap { + [key: string]: {host: string, port: number}; + } + interface ClusterOptions { - clusterRetryStrategy?(times: number): number; + clusterRetryStrategy?(times: number, reason?: Error): number | null; enableOfflineQueue?: boolean; enableReadyCheck?: boolean; scaleReads?: string; @@ -980,7 +987,12 @@ declare namespace IORedis { retryDelayOnFailover?: number; retryDelayOnClusterDown?: number; retryDelayOnTryAgain?: number; + slotsRefreshTimeout?: number; + slotsRefreshInterval?: number; redisOptions?: RedisOptions; + lazyConnect?: boolean; + dnsLookup?: DNSLookupFunction; + natMap?: NatMap; } interface MultiOptions { diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index df8e37aca8..9950a8543f 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -38,6 +38,7 @@ redis.set('key', '100', ['EX', 10, 'NX'], (err, data) => {}); redis.setBuffer('key', '100', 'NX', 'EX', 10, (err, data) => {}); redis.exists('foo').then(result => result * 1); +redis.exists('foo', ((err, data) => data * 1)); // Should support usage of Buffer redis.set(Buffer.from('key'), '100'); @@ -192,3 +193,12 @@ redis.xread('STREAMS', 'streamName', '0-0'); redis.xreadgroup('GROUP', 'groupName', 'consumerName', 'STREAMS', 'streamName', '>'); redis.xrevrange('streamName', '+', '-', 'COUNT', 1); redis.xtrim('streamName', 'MAXLEN', '~', 1000); + +// ClusterRetryStrategy can return non-numbers to stop retrying +new Redis.Cluster([], { + clusterRetryStrategy: (times: number, reason?: Error) => null +}); + +new Redis.Cluster([], { + clusterRetryStrategy: (times: number, reason?: Error) => 1 +}); diff --git a/types/ioredis/v3/index.d.ts b/types/ioredis/v3/index.d.ts index ee2777c92c..b346f7cee3 100644 --- a/types/ioredis/v3/index.d.ts +++ b/types/ioredis/v3/index.d.ts @@ -7,6 +7,7 @@ // Shahar Mor // Whemoon Jang // Francis Gulotta +// Alex Petty // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -102,6 +103,7 @@ declare namespace IORedis { del(...keys: string[]): any; exists(...keys: string[]): Promise; + exists(key: string, callback: (err: Error, res: number) => void): void; setbit(key: string, offset: number, value: any, callback: (err: Error, res: number) => void): void; setbit(key: string, offset: number, value: any): Promise; @@ -894,7 +896,7 @@ declare namespace IORedis { } interface ClusterOptions { - clusterRetryStrategy?(times: number): number; + clusterRetryStrategy?(times: number): number | null; enableOfflineQueue?: boolean; enableReadyCheck?: boolean; scaleReads?: string; diff --git a/types/ioredis/v3/ioredis-tests.ts b/types/ioredis/v3/ioredis-tests.ts index b77192e3b8..6c16a338ea 100644 --- a/types/ioredis/v3/ioredis-tests.ts +++ b/types/ioredis/v3/ioredis-tests.ts @@ -32,6 +32,7 @@ redis.set('key', '100', ['EX', 10, 'NX'], (err, data) => {}); redis.setBuffer('key', '100', 'NX', 'EX', 10, (err, data) => {}); redis.exists('foo').then(result => result * 1); +redis.exists('foo', ((err, data) => data * 1)); new Redis(); // Connect to 127.0.0.1:6379 new Redis(6380); // 127.0.0.1:6380 @@ -153,3 +154,12 @@ new Redis.Cluster([{ host: 'localhost', port: 6379 }]); + +// ClusterRetryStrategy can return non-numbers to stop retrying +new Redis.Cluster([], { + clusterRetryStrategy: (times: number) => null +}); + +new Redis.Cluster([], { + clusterRetryStrategy: (times: number) => 1 +}); diff --git a/types/is-elevated/index.d.ts b/types/is-elevated/index.d.ts new file mode 100644 index 0000000000..c875437fde --- /dev/null +++ b/types/is-elevated/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-elevated 2.0 +// Project: https://github.com/sindresorhus/is-elevated#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isElevated; + +declare function isElevated(): Promise; diff --git a/types/is-elevated/is-elevated-tests.ts b/types/is-elevated/is-elevated-tests.ts new file mode 100644 index 0000000000..b2ba2f48fe --- /dev/null +++ b/types/is-elevated/is-elevated-tests.ts @@ -0,0 +1,3 @@ +import isElevated = require('is-elevated'); + +isElevated(); // $ExpectType Promise diff --git a/types/is-elevated/tsconfig.json b/types/is-elevated/tsconfig.json new file mode 100644 index 0000000000..ad48a57318 --- /dev/null +++ b/types/is-elevated/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-elevated-tests.ts" + ] +} diff --git a/types/is-elevated/tslint.json b/types/is-elevated/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-elevated/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-function/index.d.ts b/types/is-function/index.d.ts new file mode 100644 index 0000000000..841180173a --- /dev/null +++ b/types/is-function/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for is-function 1.0 +// Project: https://github.com/grncdr/js-is-function +// Definitions by: Evangelos Zotos +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isFunction; +declare function isFunction(fn: any): boolean; diff --git a/types/is-function/is-function-tests.ts b/types/is-function/is-function-tests.ts new file mode 100644 index 0000000000..d88d529710 --- /dev/null +++ b/types/is-function/is-function-tests.ts @@ -0,0 +1,9 @@ +import isFunction = require("is-function"); + +const a: boolean = isFunction("string"); +const b: boolean = isFunction(true); +const c: boolean = isFunction((x: number) => x * x); +const d: boolean = isFunction({ type: "number" }); +const e: boolean = isFunction(() => { + return "I am anounymous!"; +}); diff --git a/types/is-function/tsconfig.json b/types/is-function/tsconfig.json new file mode 100644 index 0000000000..ab7efbe2c7 --- /dev/null +++ b/types/is-function/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "is-function-tests.ts"] +} diff --git a/types/is-function/tslint.json b/types/is-function/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-function/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-online/index.d.ts b/types/is-online/index.d.ts new file mode 100644 index 0000000000..04fa123c44 --- /dev/null +++ b/types/is-online/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for is-online 8.0 +// Project: https://github.com/sindresorhus/is-online#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isOnline; + +/** + * Check if the internet connection is up. + * + * The following checks are run in parallel: + * - Retrieve [icanhazip.com](https://github.com/major/icanhaz) via HTTPS + * - Query `myip.opendns.com` on OpenDNS (Node.js only) + * - Retrieve Apple's Captive Portal test page (Node.js only) + * + * When the first check succeeds, the returned Promise is resolved to `true`. + */ +declare function isOnline(options?: isOnline.Options): Promise; + +declare namespace isOnline { + interface Options { + /** + * Milliseconds to wait for a server to respond. + * @default 5000 + */ + timeout?: number; + /** + * Internet Protocol version to use. This is an advanced option that is usually not necessary to be set, + * but it can prove useful to specifically assert IPv6 connectivity. + * @default 'v4' + */ + version?: 'v4' | 'v6'; + } +} diff --git a/types/is-online/is-online-tests.ts b/types/is-online/is-online-tests.ts new file mode 100644 index 0000000000..74dbda5efa --- /dev/null +++ b/types/is-online/is-online-tests.ts @@ -0,0 +1,6 @@ +import isOnline = require('is-online'); + +isOnline(); // $ExpectType Promise +isOnline({ timeout: 10 }); // $ExpectType Promise +isOnline({ version: 'v4' }); // $ExpectType Promise +isOnline({ version: 'v6' }); // $ExpectType Promise diff --git a/types/is-online/tsconfig.json b/types/is-online/tsconfig.json new file mode 100644 index 0000000000..7009c26024 --- /dev/null +++ b/types/is-online/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-online-tests.ts" + ] +} diff --git a/types/is-online/tslint.json b/types/is-online/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-online/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-progressive/index.d.ts b/types/is-progressive/index.d.ts new file mode 100644 index 0000000000..3c05ab6fdc --- /dev/null +++ b/types/is-progressive/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for is-progressive 3.0 +// Project: https://github.com/sindresorhus/is-progressive#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Readable } from 'stream'; + +/** + * Returns whether the `buffer` is a progressive JPEG image. + * @param buffer Buffer of a JPEG image. + * Must be at least `65535` bytes when the file is larger than that. + */ +export function buffer(buffer: Buffer): boolean; + +/** + * Returns a Promise for a boolean indicating whether the file stream is a progressive JPEG image. + * @param stream Data stream. + */ +export function stream(stream: Readable): Promise; + +/** + * Returns a Promise for a boolean indicating whether the file is a progressive JPEG image. + * @param filepath Filepath to the image. + */ +export function file(filepath: string): Promise; + +/** + * Returns whether the buffer is a progressive JPEG. + * @param filepath Filepath to the image. + */ +export function fileSync(filepath: string): boolean; diff --git a/types/is-progressive/is-progressive-tests.ts b/types/is-progressive/is-progressive-tests.ts new file mode 100644 index 0000000000..b5525962ad --- /dev/null +++ b/types/is-progressive/is-progressive-tests.ts @@ -0,0 +1,12 @@ +import https = require('https'); +import isProgressive = require('is-progressive'); + +isProgressive.file('baseline.jpg'); // $ExpectType Promise + +isProgressive.fileSync('progressive.jpg'); // $ExpectType boolean + +https.get('/', res => { + isProgressive.stream(res); // $ExpectType Promise +}); + +isProgressive.buffer(new Buffer(1)); // $ExpectType boolean diff --git a/types/is-progressive/tsconfig.json b/types/is-progressive/tsconfig.json new file mode 100644 index 0000000000..edc521b158 --- /dev/null +++ b/types/is-progressive/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-progressive-tests.ts" + ] +} diff --git a/types/is-progressive/tslint.json b/types/is-progressive/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-progressive/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/is-reachable/index.d.ts b/types/is-reachable/index.d.ts new file mode 100644 index 0000000000..6e2ea2d62f --- /dev/null +++ b/types/is-reachable/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for is-reachable 3.0 +// Project: https://github.com/sindresorhus/is-reachable#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isReachable; + +/** + * Check if servers are reachable. + * + * The Node.js version will do a TCP handshake with the target's port. It attempts to detect cases where a router + * redirects the request to itself. + * + * The browser version is limited by the fact that browsers cannot connect to arbitrary ports. It only supports + * HTTP and HTTPS and the check relies on the `/favicon.ico` path being present. + * + * @param targets One or more targets to check. Can either be a full [URL](https://nodejs.org/api/url.html) + * like `https://hostname`, `hostname:port` or just `hostname`. When the protocol is missing from a target + * `http` is assumed. + * + * [Well-known protocols](http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml) + * are supported (e.g. `ftp://`, `mysql://`, `redis://` and more). + * + * @returns A `Promise` for a `boolean` which is `true` if any of the `targets` are reachable. + */ +declare function isReachable( + targets: string | string[], + options?: isReachable.Options +): Promise; + +declare namespace isReachable { + interface Options { + /** + * Timeout in milliseconds after which a request is considered failed. + * @default 5000 + */ + timeout?: number; + } +} diff --git a/types/is-reachable/is-reachable-tests.ts b/types/is-reachable/is-reachable-tests.ts new file mode 100644 index 0000000000..d497d004f2 --- /dev/null +++ b/types/is-reachable/is-reachable-tests.ts @@ -0,0 +1,4 @@ +import isReachable = require('is-reachable'); + +isReachable('sindresorhus.com'); // $ExpectType Promise +isReachable('google.com:80', { timeout: 10 }); // $ExpectType Promise diff --git a/types/is-reachable/tsconfig.json b/types/is-reachable/tsconfig.json new file mode 100644 index 0000000000..c30236ebd5 --- /dev/null +++ b/types/is-reachable/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-reachable-tests.ts" + ] +} diff --git a/types/is-reachable/tslint.json b/types/is-reachable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-reachable/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/isotope-layout/index.d.ts b/types/isotope-layout/index.d.ts index 5e1f0623e4..66d4a21d52 100644 --- a/types/isotope-layout/index.d.ts +++ b/types/isotope-layout/index.d.ts @@ -2,6 +2,7 @@ // Project: http://isotope.metafizzy.co/ // Definitions by: Anže Videnič // Mălin Brândușe +// SPWizard01 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -30,7 +31,7 @@ declare namespace Isotope { * If set to a string, that value is used as a selector. * If filter is set to a function, that function checks each item and returns true or false if the item should be shown or hidden. */ - filter?: string | (() => boolean); + filter?: string | ((itemElement: HTMLElement) => boolean); /** * Items are arranged into rows. Rows progress vertically. Similar to what you would expect from a layout that uses CSS floats. fitRows works well for items that have the same height. */ diff --git a/types/isotope-layout/isotope-layout-tests.ts b/types/isotope-layout/isotope-layout-tests.ts index 776412b2c2..d37475cefa 100644 --- a/types/isotope-layout/isotope-layout-tests.ts +++ b/types/isotope-layout/isotope-layout-tests.ts @@ -70,8 +70,8 @@ let $grid = $('.grid').isotope({ // test the ones not used in upper test $grid = $('.grid').isotope({ - filter: (): boolean => { - return true; + filter: (itemElem): boolean => { + return itemElem ? true : false; }, sortAscending: { key: true diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index 2109645eef..f87dd67ece 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -15,13 +15,27 @@ // TypeScript Version: 2.8 // For ddescribe / iit use : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts +type ImplementationCallback = (() => Promise) | ((done: DoneFn) => void); + /** * Create a group of specs (often called a suite). * @param description Textual description of the group * @param specDefinitions Function for Jasmine to invoke that will define inner suites a specs */ declare function describe(description: string, specDefinitions: () => void): void; + +/** + * A focused `describe`. If suites or specs are focused, only those that are focused will be executed. + * @param description Textual description of the group + * @param specDefinitions Function for Jasmine to invoke that will define inner suites a specs + */ declare function fdescribe(description: string, specDefinitions: () => void): void; + +/** + * A temporarily disabled `describe`. Specs within an xdescribe will be marked pending and not executed. + * @param description Textual description of the group + * @param specDefinitions Function for Jasmine to invoke that will define inner suites a specs + */ declare function xdescribe(description: string, specDefinitions: () => void): void; /** @@ -31,23 +45,28 @@ declare function xdescribe(description: string, specDefinitions: () => void): vo * @param assertion Function that contains the code of your test. If not provided the test will be pending. * @param timeout Custom timeout for an async spec. */ -declare function it(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; +declare function it(expectation: string, assertion?: ImplementationCallback, timeout?: number): void; /** - * A focused it - * If suites or specs are focused, only those that are focused will be executed. - * @param expectation - * @param assertion - * @param timeout + * A focused `it`. If suites or specs are focused, only those that are focused will be executed. + * @param expectation Textual description of what this spec is checking + * @param assertion Function that contains the code of your test. If not provided the test will be pending. + * @param timeout Custom timeout for an async spec. */ -declare function fit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; -declare function xit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; +declare function fit(expectation: string, assertion?: ImplementationCallback, timeout?: number): void; + +/** + * A temporarily disabled `it`. The spec will report as pending and will not be executed. + * @param expectation Textual description of what this spec is checking + * @param assertion Function that contains the code of your test. If not provided the test will be pending. + * @param timeout Custom timeout for an async spec. + */ +declare function xit(expectation: string, assertion?: ImplementationCallback, timeout?: number): void; /** * Mark a spec as pending, expectation results will be ignored. * If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. - * @param reason - * @returns {} + * @param reason Reason the spec is pending. */ declare function pending(reason?: string): void; @@ -56,14 +75,14 @@ declare function pending(reason?: string): void; * @param action Function that contains the code to setup your specs. * @param timeout Custom timeout for an async beforeEach. */ -declare function beforeEach(action: (done: DoneFn) => void, timeout?: number): void; +declare function beforeEach(action: ImplementationCallback, timeout?: number): void; /** * Run some shared teardown after each of the specs in the describe in which it is called. * @param action Function that contains the code to teardown your specs. * @param timeout Custom timeout for an async afterEach. */ -declare function afterEach(action: (done: DoneFn) => void, timeout?: number): void; +declare function afterEach(action: ImplementationCallback, timeout?: number): void; /** * Run some shared setup once before all of the specs in the describe are run. @@ -71,7 +90,7 @@ declare function afterEach(action: (done: DoneFn) => void, timeout?: number): vo * @param action Function that contains the code to setup your specs. * @param timeout Custom timeout for an async beforeAll. */ -declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void; +declare function beforeAll(action: ImplementationCallback, timeout?: number): void; /** * Run some shared teardown once before all of the specs in the describe are run. @@ -79,7 +98,7 @@ declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): vo * @param action Function that contains the code to teardown your specs. * @param timeout Custom timeout for an async afterAll */ -declare function afterAll(action: (done: DoneFn) => void, timeout?: number): void; +declare function afterAll(action: ImplementationCallback, timeout?: number): void; /** * Create an expectation for a spec. @@ -119,11 +138,13 @@ declare function expectAsync(actual: Promise): jasmine.AsyncMatchers(object: T, method: keyof T): jasmine.Spy; /** - * Install a spy on a property onto an existing object. - * @param object The object upon which to install the Spy - * @param property The name of the property to replace with a Spy - * @param accessType The access type (get|set) of the property to Spy on. + * Install a spy on a property installed with `Object.defineProperty` onto an existing object. + * @param object The object upon which to install the `Spy`. + * @param property The name of the property to replace with a `Spy`. + * @param accessType The access type (get|set) of the property to `Spy` on. */ declare function spyOnProperty(object: T, property: keyof T, accessType?: 'get' | 'set'): jasmine.Spy; /** * Installs spies on all writable and configurable properties of an object. - * @param object The object upon which to install the Spies + * @param object The object upon which to install the `Spy`s. */ declare function spyOnAllFunctions(object: object): jasmine.Spy; @@ -158,9 +179,12 @@ declare function waits(timeout?: number): void; declare namespace jasmine { type Expected = T | ObjectContaining | Any | Spy; - type SpyObjMethodNames = T extends undefined ? (ReadonlyArray | {[methodName: string]: any}) : (ReadonlyArray | {[P in keyof T]?: ReturnType any ? T[P] : any>}); + type SpyObjMethodNames = + T extends undefined ? + (ReadonlyArray | {[methodName: string]: any}) : + (ReadonlyArray | {[P in keyof T]?: ReturnType any ? T[P] : any>}); - var clock: () => Clock; + function clock(): Clock; var matchersUtil: MatchersUtil; @@ -187,13 +211,12 @@ declare namespace jasmine { function addMatchers(matchers: CustomMatcherFactories): void; - function stringMatching(str: string): Any; - function stringMatching(str: RegExp): Any; + function stringMatching(str: string | RegExp): Any; function formatErrorMsg(domain: string, usage: string): (msg: string) => string; interface Any { - (...params: any[]):any; // jasmine.Any can also be a function + (...params: any[]): any; // jasmine.Any can also be a function new (expectedClass: any): any; jasmineMatches(other: any): boolean; @@ -221,7 +244,6 @@ declare namespace jasmine { } interface Block { - new (env: Env, func: SpecFunction, spec: Spec): any; execute(onComplete: () => void): void; @@ -271,12 +293,6 @@ declare namespace jasmine { } interface Env { - setTimeout: any; - clearTimeout: void; - setInterval: any; - clearInterval: void; - updateInterval: number; - currentSpec: Spec; matchersClass: Matchers; @@ -284,16 +300,15 @@ declare namespace jasmine { version(): any; versionString(): string; nextSpecId(): number; - addReporter(reporter: Reporter): void; - addReporter(reporter: CustomReporter): void; + addReporter(reporter: Reporter | CustomReporter): void; execute(): void; describe(description: string, specDefinitions: () => void): Suite; // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these - beforeEach(beforeEachFunction: (done: DoneFn) => void, timeout?: number): void; - beforeAll(beforeAllFunction: (done: DoneFn) => void, timeout?: number): void; + beforeEach(beforeEachFunction: ImplementationCallback, timeout?: number): void; + beforeAll(beforeAllFunction: ImplementationCallback, timeout?: number): void; currentRunner(): Runner; - afterEach(afterEachFunction: (done: DoneFn) => void, timeout?: number): void; - afterAll(afterAllFunction: (done: DoneFn) => void, timeout?: number): void; + afterEach(afterEachFunction: ImplementationCallback, timeout?: number): void; + afterAll(afterAllFunction: ImplementationCallback, timeout?: number): void; xdescribe(desc: string, specDefinitions: () => void): XSuite; it(description: string, func: () => void): Spec; // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these @@ -316,7 +331,6 @@ declare namespace jasmine { } interface FakeTimer { - new (): any; reset(): void; @@ -395,7 +409,6 @@ declare namespace jasmine { } interface PrettyPrinter { - new (): any; format(value: any): void; @@ -411,7 +424,6 @@ declare namespace jasmine { } interface Queue { - new (env: any): any; env: Env; @@ -432,7 +444,6 @@ declare namespace jasmine { } interface Matchers { - new (env: Env, actual: T, spec: Env, isNot?: boolean): any; env: Env; @@ -445,7 +456,6 @@ declare namespace jasmine { * * @param expected the actual value to be === to the expected value. * @param expectationFailOutput - * @returns {} */ toBe(expected: Expected, expectationFailOutput?: any): boolean; @@ -453,7 +463,6 @@ declare namespace jasmine { * * @param expected the actual value to be equal to the expected, using deep equality comparison. * @param expectationFailOutput - * @returns {} */ toEqual(expected: Expected, expectationFailOutput?: any): boolean; toMatch(expected: string | RegExp, expectationFailOutput?: any): boolean; @@ -504,7 +513,6 @@ declare namespace jasmine { } interface AsyncMatchers { - /** * Expect a promise to be resolved. * @param expectationFailOutput @@ -538,7 +546,7 @@ declare namespace jasmine { /** * Invert the matcher following this expect. */ - not: AsyncMatchers + not: AsyncMatchers; } interface Reporter { @@ -571,7 +579,6 @@ declare namespace jasmine { } interface PassedExpectation extends CustomReportExpectation { - } interface CustomReporterResult { @@ -586,7 +593,7 @@ declare namespace jasmine { interface RunDetails { failedExpectations: ExpectationResult[]; - order: jasmine.Order; + order: Order; } interface CustomReporter { @@ -599,7 +606,6 @@ declare namespace jasmine { } interface Runner { - new (env: Env): any; execute(): void; @@ -626,7 +632,6 @@ declare namespace jasmine { } interface Spec extends SuiteOrSpec { - new (env: Env, suite: Suite, description: string): any; suite: Suite; @@ -670,7 +675,6 @@ declare namespace jasmine { } interface Suite extends SuiteOrSpec { - new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; parentSuite: Suite; @@ -701,9 +705,9 @@ declare namespace jasmine { withArgs(...args: any[]): Spy; } - type SpyObj = { + type SpyObj = T & { [k in keyof T]: T[k] extends Function ? T[k] & Spy : T[k]; - } + }; interface SpyAnd { identity: string; @@ -723,21 +727,21 @@ declare namespace jasmine { } interface Calls { - /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/ + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */ any(): boolean; - /** By chaining the spy with calls.count(), will return the number of times the spy was called **/ + /** By chaining the spy with calls.count(), will return the number of times the spy was called */ count(): number; - /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/ + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */ argsFor(index: number): any[]; - /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls */ allArgs(): any[]; - /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */ all(): CallInfo[]; - /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */ mostRecent(): CallInfo; - /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */ first(): CallInfo; - /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ + /** By chaining the spy with calls.reset(), will clears all tracking for a spy */ reset(): void; } @@ -759,7 +763,6 @@ declare namespace jasmine { } interface JsApiReporter extends Reporter { - started: boolean; finished: boolean; result: any; @@ -783,10 +786,32 @@ declare namespace jasmine { util: Util; } - export var HtmlReporter: HtmlReporter; - export var HtmlSpecFilter: HtmlSpecFilter; - export var DEFAULT_TIMEOUT_INTERVAL: number; - export var MAX_PRETTY_PRINT_DEPTH: number; + var HtmlReporter: HtmlReporter; + var HtmlSpecFilter: HtmlSpecFilter; + + /** + * Default number of milliseconds Jasmine will wait for an asynchronous spec to complete. + */ + var DEFAULT_TIMEOUT_INTERVAL: number; + + /** + * Maximum number of array elements to display when pretty printing objects. + * This will also limit the number of keys and values displayed for an object. + * Elements past this number will be ellipised. + */ + var MAX_PRETTY_PRINT_ARRAY_LENGTH: number; + + /** + * Maximum number of charasters to display when pretty printing objects. + * Characters past this number will be ellipised. + */ + var MAX_PRETTY_PRINT_CHARS: number; + + /** + * Maximum object depth the pretty printer will print to. + * Set this to a lower value to speed up pretty printing if you have large objects. + */ + var MAX_PRETTY_PRINT_DEPTH: number; } declare module "jasmine" { diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index bf3598fda9..66b98c4b0d 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -16,7 +16,6 @@ describe("A suite is just a function", () => { }); describe("The 'toBe' matcher compares with ===", () => { - it("and has a positive case", () => { expect(true).toBe(true); }); @@ -27,28 +26,26 @@ describe("The 'toBe' matcher compares with ===", () => { }); describe("Included matchers:", () => { - it("The 'toBe' matcher compares with ===", () => { - var a = 12; - var b = a; + const a = 12; + const b = a; expect(a).toBe(b); expect(a).not.toBe(24); }); describe("The 'toEqual' matcher", () => { - it("works for simple literals and variables", () => { - var a = 12; + const a = 12; expect(a).toEqual(12); }); it("should work for objects", () => { - var foo = { + const foo = { a: 12, b: 34 }; - var bar = { + const bar = { a: 12, b: 34 }; @@ -56,13 +53,13 @@ describe("Included matchers:", () => { }); it("should work for optional values", () => { - var opt: string | undefined = "s"; - expect(opt as (string | undefined)).toEqual(undefined); + const opt: string | undefined = Math.random() > .5 ? "s" : undefined; + expect(opt).toEqual(undefined); }); }); it("The 'toMatch' matcher is for regular expressions", () => { - var message = "foo bar baz"; + const message = "foo bar baz"; expect(message).toMatch(/bar/); expect(message).toMatch("bar"); @@ -70,7 +67,7 @@ describe("Included matchers:", () => { }); it("The 'toBeDefined' matcher compares against `undefined`", () => { - var a = { + const a = { foo: "foo" }; @@ -79,7 +76,7 @@ describe("Included matchers:", () => { }); it("The `toBeUndefined` matcher compares against `undefined`", () => { - var a = { + const a = { foo: "foo" }; @@ -88,8 +85,8 @@ describe("Included matchers:", () => { }); it("The 'toBeNull' matcher compares against null", () => { - var a: string | null = null; - var foo = "foo"; + const a: string | null = Math.random() > 0.5 ? "s" : null; + const foo = "foo"; expect(null).toBeNull(); expect(a).toBeNull(); @@ -97,72 +94,76 @@ describe("Included matchers:", () => { }); it("The 'toBeTruthy' matcher is for boolean casting testing", () => { - var a: string | undefined, foo = "foo"; + const a: string | undefined = Math.random() > 0.5 ? "s" : undefined; + const foo = "foo"; expect(foo).toBeTruthy(); expect(a).not.toBeTruthy(); }); it("The 'toBeFalsy' matcher is for boolean casting testing", () => { - var a: string | undefined, foo = "foo"; + const a: string | undefined = Math.random() > 0.5 ? "s" : undefined; + const foo = "foo"; expect(a).toBeFalsy(); expect(foo).not.toBeFalsy(); }); it("The 'toContain' matcher is for finding an item in an Array", () => { - var a = ["foo", "bar", "baz"]; + const a = ["foo", "bar", "baz"]; expect(a).toContain('foo'); expect(a).not.toContain("quux"); }); it("The 'toContain' matcher is also for finding an object containing distinct properties in an Array", () => { - var a = [{ a: "foo" }, { a: "bar" }, { b: "baz" }]; + const a = [{ a: "foo" }, { a: "bar" }, { b: "baz" }]; expect(a).toContain(jasmine.objectContaining({ a: "foo" })); expect(a).not.toContain({ a: "quux" }); }); it("The 'toBeLessThan' matcher is for mathematical comparisons", () => { - var pi = 3.1415926, - e = 2.78; + const pi = 3.1415926; + const e = 2.78; expect(e).toBeLessThan(pi); expect(pi).not.toBeLessThan(e); }); it("The 'toBeGreaterThan' is for mathematical comparisons", () => { - var pi = 3.1415926, - e = 2.78; + const pi = 3.1415926; + const e = 2.78; expect(pi).toBeGreaterThan(e); expect(e).not.toBeGreaterThan(pi); }); it("The 'toBeCloseTo' matcher is for precision math comparison", () => { - var pi = 3.1415926, - e = 2.78; + const pi = 3.1415926; + const e = 2.78; expect(pi).not.toBeCloseTo(e, 2); expect(pi).toBeCloseTo(e, 0); }); it("The 'toThrow' matcher is for testing if a function throws an exception", () => { - var foo = () => { + const foo = () => { return 1 + 2; }; - var bar = () => { - var a: any; - return a + 1; + const bar = () => { + throw new Error("message"); }; expect(foo).not.toThrow(); + expect(foo).toThrow(); + + expect(bar).not.toThrow(); expect(bar).toThrow(); }); it("The 'toThrowError' matcher is for testing a specific thrown exception", () => { - var foo = () => { + const foo = () => { throw new TypeError("foo bar baz"); }; @@ -173,7 +174,7 @@ describe("Included matchers:", () => { }); it("async matchers", async () => { - var badness = new Error("badness"); + const badness = new Error("badness"); await expectAsync(Promise.resolve()).toBeResolved(); await expectAsync(Promise.resolve()).toBeResolved("good job"); await expectAsync(Promise.resolve(true)).toBeResolvedTo(true); @@ -184,8 +185,8 @@ describe("Included matchers:", () => { }); it("async matchers - not", async () => { - var badness = new Error("badness"); - var malady = new Error("malady"); + const badness = new Error("badness"); + const malady = new Error("malady"); await expectAsync(Promise.reject(badness)).not.toBeResolved(); await expectAsync(Promise.resolve(true)).not.toBeResolvedTo(false); await expectAsync(Promise.resolve()).not.toBeRejected(); @@ -198,7 +199,7 @@ describe("Included matchers:", () => { describe("toThrowMatching", () => { expect(() => { ({} as any).doSomething(); - }).toThrowMatching(error => error != undefined); + }).toThrowMatching(error => error !== undefined); }); describe("toBeNegativeInfinity", () => { @@ -306,7 +307,6 @@ xdescribe("A spec", () => { }); describe("Pending specs", () => { - xit("can be declared 'xit'", () => { expect(true).toBe(false); }); @@ -358,7 +358,7 @@ describe("A spy", () => { expect(bar).toBeNull(); }); - it("tracks if it was called at all", function () { + it("tracks if it was called at all", function() { foo.setBar(); expect(foo.setBar.calls.any()).toEqual(true); @@ -723,19 +723,24 @@ describe("A spy, when created manually", () => { }); describe("Multiple spies, when created manually", () => { - interface Tape { - play(): void; - pause(): void; - rewind(pos: number): void; - stop(): void; + class Tape { + private rewindTo: number; + play(): void { } + pause(): void { } + rewind(pos: number): void { + this.rewindTo = pos; + } + stop(): void { } readonly isPlaying: boolean; // spy obj makes this writable } - var tape: jasmine.SpyObj; + var tape: Tape; + var tapeSpy: jasmine.SpyObj; var el: jasmine.SpyObj; beforeEach(() => { - tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); + tapeSpy = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); + tape = tapeSpy; (tape as { isPlaying: boolean }).isPlaying = false; el = jasmine.createSpyObj('Element', ['hasAttribute']); @@ -745,6 +750,10 @@ describe("Multiple spies, when created manually", () => { tape.play(); tape.pause(); tape.rewind(0); + + tapeSpy.play.and.callThrough(); + tapeSpy.pause.and.callThrough(); + tapeSpy.rewind.and.callThrough(); }); it("creates spies for each requested function", () => { @@ -767,17 +776,15 @@ describe("Multiple spies, when created manually", () => { it("read isPlaying property", () => { expect(tape.isPlaying).toBe(false); - }) + }); }); describe("multiple spies, when created with spyOnAllFunctions", () => { - it("spies on all functions", () => { - const obj = { x: (a: number) => a, y: (a: number) => a, - } + }; spyOnAllFunctions(obj); @@ -809,7 +816,7 @@ describe("jasmine.any", () => { const a: Test = { fn1: () => { }, - fn2: (param1: number) => { return param1; }, + fn2: (param1: number) => param1, }; const expected: Test = { @@ -822,7 +829,7 @@ describe("jasmine.any", () => { describe("when used with a spy", () => { it("is useful for comparing arguments", () => { - var foo = jasmine.createSpy('foo'); + const foo = jasmine.createSpy('foo'); foo(12, () => { return true; }); @@ -867,7 +874,7 @@ describe("jasmine.objectContaining", () => { describe("when used with a spy", () => { it("is useful for comparing arguments", () => { - var callback = jasmine.createSpy('callback'); + const callback = jasmine.createSpy('callback'); callback({ bar: "baz" @@ -884,7 +891,7 @@ describe("jasmine.objectContaining", () => { }); describe("jasmine.arrayContaining", () => { - var foo: Array; + var foo: number[]; beforeEach(() => { foo = [1, 2, 3, 4]; @@ -900,7 +907,7 @@ describe("jasmine.arrayContaining", () => { describe("when used with a spy", () => { it("is useful when comparing arguments", () => { - var callback = jasmine.createSpy('callback'); + const callback = jasmine.createSpy('callback'); callback([1, 2, 3, 4]); @@ -911,7 +918,7 @@ describe("jasmine.arrayContaining", () => { }); describe("jasmine.arrayWithExactContents", () => { - var foo: Array; + var foo: number[]; beforeEach(() => { foo = [1, 2, 3, 4]; @@ -927,7 +934,7 @@ describe("jasmine.arrayWithExactContents", () => { describe("when used with a spy", () => { it("is useful when comparing arguments", () => { - var callback = jasmine.createSpy('callback'); + const callback = jasmine.createSpy('callback'); callback([1, 2, 3, 4]); @@ -980,7 +987,7 @@ describe("Manually ticking the Jasmine Clock", () => { describe("Mocking the Date object", () => { it("mocks the Date object and sets it to a given time", () => { - var baseTime = new Date(2013, 9, 23); + const baseTime = new Date(2013, 9, 23); jasmine.clock().mockDate(baseTime); @@ -1020,11 +1027,9 @@ describe("Asynchronous specs", () => { done(); }, 1000); }); - }); describe("Fail", () => { - it("should fail test when called without arguments", () => { fail(); }); @@ -1036,12 +1041,11 @@ describe("Fail", () => { it("should fail test when called an error", () => { fail(new Error("The test failed with this error")); }); - }); // test based on http://jasmine.github.io/2.2/custom_equality.html describe("custom equality", () => { - var myCustomEquality: jasmine.CustomEqualityTester = function (first: any, second: any): boolean | void { + const myCustomEquality: jasmine.CustomEqualityTester = function(first: any, second: any): boolean | void { if (typeof first === "string" && typeof second === "string") { return first[0] === second[1]; } @@ -1051,7 +1055,6 @@ describe("custom equality", () => { jasmine.addCustomEqualityTester(myCustomEquality); }); - it("should be custom equal", () => { expect("abc").toEqual("aaa"); }); @@ -1069,15 +1072,13 @@ var customMatchers: jasmine.CustomMatcherFactories = { if (expected === undefined) { expected = ''; } - var result: jasmine.CustomMatcherResult = { pass: false }; + const result: jasmine.CustomMatcherResult = { pass: false }; result.pass = util.equals(actual.hyuk, "gawrsh" + expected, customEqualityTesters); - if (result.pass) { - result.message = "Expected " + actual + " not to be quite so goofy"; - } else { - result.message = "Expected " + actual + " to be goofy, but it was not very goofy"; - } + result.message = result.pass ? + `Expected ${actual} not to be quite so goofy` : + `Expected ${actual} to be goofy, but it was not very goofy`; return result; } @@ -1110,8 +1111,8 @@ var customMatchers: jasmine.CustomMatcherFactories = { // } declare namespace jasmine { interface Matchers { - toBeGoofy(expected?: jasmine.Expected): boolean; - toBeWithinRange(expected?: jasmine.Expected, floor?: number, ceiling?: number): boolean; + toBeGoofy(expected?: Expected): boolean; + toBeWithinRange(expected?: Expected, floor?: number, ceiling?: number): boolean; } } @@ -1157,7 +1158,7 @@ describe("Custom matcher: 'toBeGoofy'", () => { const result = matcher.compare(actual, null); expect(result.pass).toBe(false); - expect(result.message).toBe("Expected " + actual + " to be goofy, but it was not very goofy"); + expect(result.message).toBe(`Expected ${actual} to be goofy, but it was not very goofy`); }); }); @@ -1168,16 +1169,16 @@ var myReporter: jasmine.CustomReporter = { }, suiteStarted: (result: jasmine.CustomReporterResult) => { - console.log("Suite started: " + result.description + " whose full description is: " + result.fullName); + console.log(`Suite started: ${result.description} whose full description is: ${result.fullName}`); }, specStarted: (result: jasmine.CustomReporterResult) => { - console.log("Spec started: " + result.description + " whose full description is: " + result.fullName); + console.log(`Spec started: ${result.description} whose full description is: ${result.fullName}`); }, specDone: (result: jasmine.CustomReporterResult) => { - console.log("Spec: " + result.description + " was " + result.status); - //tslint:disable-next-line:prefer-for-of + console.log(`Spec: ${result.description} was ${result.status}`); + // tslint:disable-next-line:prefer-for-of for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i += 1) { console.log("Failure: " + result.failedExpectations[i].message); console.log("Actual: " + result.failedExpectations[i].actual); @@ -1188,8 +1189,8 @@ var myReporter: jasmine.CustomReporter = { }, suiteDone: (result: jasmine.CustomReporterResult) => { - console.log('Suite: ' + result.description + ' was ' + result.status); - //tslint:disable-next-line:prefer-for-of + console.log(`Suite: ${result.description} was ${result.status}`); + // tslint:disable-next-line:prefer-for-of for (var i = 0; result.failedExpectations && i < result.failedExpectations.length; i += 1) { console.log('AfterAll ' + result.failedExpectations[i].message); console.log(result.failedExpectations[i].stack); @@ -1207,24 +1208,24 @@ jasmine.getEnv().addReporter(myReporter); describe("Randomize Tests", () => { it("should allow randomization of the order of tests", () => { expect(() => { - var env = jasmine.getEnv(); - return env.randomizeTests(true); + const env = jasmine.getEnv(); + env.randomizeTests(true); }).not.toThrow(); }); it("should allow a seed to be passed in for randomization", () => { expect(() => { - var env = jasmine.getEnv(); + const env = jasmine.getEnv(); env.randomizeTests(true); return env.seed(1234); }).not.toThrow(); }); }); -//dest spces copied from jasmine project (https://github.com/jasmine/jasmine/blob/master/spec/core/SpecSpec.js) -describe("createSpyObj", function () { - it("should create an object with spy methods and corresponding return values when you call jasmine.createSpyObj() with an object", function () { - var spyObj = jasmine.createSpyObj('BaseName', { 'method1': 42, 'method2': 'special sauce' }); +// Dest spces copied from jasmine project (https://github.com/jasmine/jasmine/blob/master/spec/core/SpecSpec.js) +describe("createSpyObj", function() { + it("should create an object with spy methods and corresponding return values when you call jasmine.createSpyObj() with an object", function() { + const spyObj = jasmine.createSpyObj('BaseName', {method1: 42, method2: 'special sauce'}); expect(spyObj.method1()).toEqual(42); expect(spyObj.method1.and.identity()).toEqual('BaseName.method1'); @@ -1233,17 +1234,16 @@ describe("createSpyObj", function () { expect(spyObj.method2.and.identity()).toEqual('BaseName.method2'); }); - - it("should create an object with a bunch of spy methods when you call jasmine.createSpyObj()", function () { - var spyObj = jasmine.createSpyObj('BaseName', ['method1', 'method2']); + it("should create an object with a bunch of spy methods when you call jasmine.createSpyObj()", function() { + const spyObj = jasmine.createSpyObj('BaseName', ['method1', 'method2']); expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function) }); expect(spyObj.method1.and.identity()).toEqual('BaseName.method1'); expect(spyObj.method2.and.identity()).toEqual('BaseName.method2'); }); - it("should allow you to omit the baseName and takes only an object", function () { - var spyObj = jasmine.createSpyObj({ 'method1': 42, 'method2': 'special sauce' }); + it("should allow you to omit the baseName and takes only an object", function() { + const spyObj = jasmine.createSpyObj({method1: 42, method2: 'special sauce'}); expect(spyObj.method1()).toEqual(42); expect(spyObj.method1.and.identity()).toEqual('unknown.method1'); @@ -1252,22 +1252,22 @@ describe("createSpyObj", function () { expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); }); - it("should allow you to omit the baseName and takes only a list of methods", function () { - var spyObj = jasmine.createSpyObj(['method1', 'method2']); + it("should allow you to omit the baseName and takes only a list of methods", function() { + const spyObj = jasmine.createSpyObj(['method1', 'method2']); expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function) }); expect(spyObj.method1.and.identity()).toEqual('unknown.method1'); expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); }); - it("should throw if you pass an empty array argument", function () { - expect(function () { + it("should throw if you pass an empty array argument", function() { + expect(function() { jasmine.createSpyObj('BaseName', []); }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); }); - it("should throw if you pass an empty object argument", function () { - expect(function () { + it("should throw if you pass an empty object argument", function() { + expect(function() { jasmine.createSpyObj('BaseName', {}); }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); }); @@ -1275,17 +1275,17 @@ describe("createSpyObj", function () { (() => { // from boot.js - var env = jasmine.getEnv(); + const env = jasmine.getEnv(); - var htmlReporter = new jasmine.HtmlReporter(); + const htmlReporter = new jasmine.HtmlReporter(); env.addReporter(htmlReporter); - var specFilter = new jasmine.HtmlSpecFilter(); + const specFilter = new jasmine.HtmlSpecFilter(); env.specFilter = (spec) => { return specFilter.matches(spec.getFullName()); }; - var currentWindowOnload = window.onload; + const currentWindowOnload = window.onload; window.onload = () => { if (currentWindowOnload) { (currentWindowOnload as any)(null); @@ -1293,7 +1293,6 @@ describe("createSpyObj", function () { htmlReporter.initialize(); env.execute(); }; - })(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; diff --git a/types/jasmine/tslint.json b/types/jasmine/tslint.json index 2daeb51ad8..c540ba0129 100644 --- a/types/jasmine/tslint.json +++ b/types/jasmine/tslint.json @@ -1,80 +1,13 @@ { "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": true, - "eofline": false, - "export-just-namespace": false, - "file-name-casing": [true, "kebab-case"], - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "only-arrow-functions": false } } diff --git a/types/jasmine/v2/index.d.ts b/types/jasmine/v2/index.d.ts index 4211cf2ca0..e22aca8618 100644 --- a/types/jasmine/v2/index.d.ts +++ b/types/jasmine/v2/index.d.ts @@ -13,6 +13,8 @@ // TypeScript Version: 2.8 // For ddescribe / iit use : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts +type ImplementationCallback = (() => Promise) | ((done: DoneFn) => void); + /** * Create a group of specs (often called a suite). * @param description Textual description of the group @@ -29,7 +31,7 @@ declare function xdescribe(description: string, specDefinitions: () => void): vo * @param assertion Function that contains the code of your test. If not provided the test will be pending. * @param timeout Custom timeout for an async spec. */ -declare function it(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; +declare function it(expectation: string, assertion?: ImplementationCallback, timeout?: number): void; /** * A focused it @@ -38,8 +40,8 @@ declare function it(expectation: string, assertion?: (done: DoneFn) => void, tim * @param assertion * @param timeout */ -declare function fit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; -declare function xit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void; +declare function fit(expectation: string, assertion?: ImplementationCallback, timeout?: number): void; +declare function xit(expectation: string, assertion?: ImplementationCallback, timeout?: number): void; /** * Mark a spec as pending, expectation results will be ignored. @@ -54,14 +56,14 @@ declare function pending(reason?: string): void; * @param action Function that contains the code to setup your specs. * @param timeout Custom timeout for an async beforeEach. */ -declare function beforeEach(action: (done: DoneFn) => void, timeout?: number): void; +declare function beforeEach(action: ImplementationCallback, timeout?: number): void; /** * Run some shared teardown after each of the specs in the describe in which it is called. * @param action Function that contains the code to teardown your specs. * @param timeout Custom timeout for an async afterEach. */ -declare function afterEach(action: (done: DoneFn) => void, timeout?: number): void; +declare function afterEach(action: ImplementationCallback, timeout?: number): void; /** * Run some shared setup once before all of the specs in the describe are run. @@ -69,7 +71,7 @@ declare function afterEach(action: (done: DoneFn) => void, timeout?: number): vo * @param action Function that contains the code to setup your specs. * @param timeout Custom timeout for an async beforeAll. */ -declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void; +declare function beforeAll(action: ImplementationCallback, timeout?: number): void; /** * Run some shared teardown once before all of the specs in the describe are run. @@ -77,7 +79,7 @@ declare function beforeAll(action: (done: DoneFn) => void, timeout?: number): vo * @param action Function that contains the code to teardown your specs. * @param timeout Custom timeout for an async afterAll */ -declare function afterAll(action: (done: DoneFn) => void, timeout?: number): void; +declare function afterAll(action: ImplementationCallback, timeout?: number): void; /** * Create an expectation for a spec. @@ -268,11 +270,11 @@ declare namespace jasmine { execute(): void; describe(description: string, specDefinitions: () => void): Suite; // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these - beforeEach(beforeEachFunction: (done: DoneFn) => void, timeout?: number): void; - beforeAll(beforeAllFunction: (done: DoneFn) => void, timeout?: number): void; + beforeEach(beforeEachFunction: ImplementationCallback, timeout?: number): void; + beforeAll(beforeAllFunction: ImplementationCallback, timeout?: number): void; currentRunner(): Runner; - afterEach(afterEachFunction: (done: DoneFn) => void, timeout?: number): void; - afterAll(afterAllFunction: (done: DoneFn) => void, timeout?: number): void; + afterEach(afterEachFunction: ImplementationCallback, timeout?: number): void; + afterAll(afterAllFunction: ImplementationCallback, timeout?: number): void; xdescribe(desc: string, specDefinitions: () => void): XSuite; it(description: string, func: () => void): Spec; // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these @@ -629,7 +631,7 @@ declare namespace jasmine { calls: Calls; } - type SpyObj = { + type SpyObj = T & { [k in keyof T]: T[k] extends Function ? T[k] & Spy : T[k]; } diff --git a/types/jasmine/v2/jasmine-tests.ts b/types/jasmine/v2/jasmine-tests.ts index f79c3627eb..167aca1981 100644 --- a/types/jasmine/v2/jasmine-tests.ts +++ b/types/jasmine/v2/jasmine-tests.ts @@ -643,19 +643,24 @@ describe("A spy, when created manually", () => { }); describe("Multiple spies, when created manually", () => { - interface Tape { - play(): void; - pause(): void; - rewind(pos: number): void; - stop(): void; + abstract class Tape { + private rewindTo: number; + play(): void { }; + pause(): void { }; + rewind(pos: number): void { + this.rewindTo = pos; + }; + stop(): void { }; readonly isPlaying: boolean; // spy obj makes this writable } - var tape: jasmine.SpyObj; + var tape: Tape; + var tapeSpy: jasmine.SpyObj; var el: jasmine.SpyObj; beforeEach(() => { - tape = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); + tapeSpy = jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']); + tape = tapeSpy; (tape as { isPlaying: boolean }).isPlaying = false; el = jasmine.createSpyObj('Element', ['hasAttribute']); @@ -665,6 +670,10 @@ describe("Multiple spies, when created manually", () => { tape.play(); tape.pause(); tape.rewind(0); + + tapeSpy.play.and.callThrough(); + tapeSpy.pause.and.callThrough(); + tapeSpy.rewind.and.callThrough(); }); it("creates spies for each requested function", () => { diff --git a/types/jest-axe/index.d.ts b/types/jest-axe/index.d.ts index 60375e3605..506236773f 100644 --- a/types/jest-axe/index.d.ts +++ b/types/jest-axe/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/nickcolley/jest-axe // Definitions by: Josh Goldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 3.0 /// diff --git a/types/jest-image-snapshot/index.d.ts b/types/jest-image-snapshot/index.d.ts index c15e435cc9..10d6a2a17d 100644 --- a/types/jest-image-snapshot/index.d.ts +++ b/types/jest-image-snapshot/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for jest-image-snapshot 2.4 +// Type definitions for jest-image-snapshot 2.8 // Project: https://github.com/americanexpress/jest-image-snapshot#readme // Definitions by: Janeene Beeforth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// @@ -26,10 +26,18 @@ export interface MatchImageSnapshotOptions { * Absolute path of a directory to keep the snapshot in. */ customSnapshotsDir?: string; + /** + * A custom absolute path of a directory to keep this diff in + */ + customDiffDir?: string; /** * A custom name to give this snapshot. If not provided, one is computed automatically. */ customSnapshotIdentifier?: string; + /** + * Changes diff image layout direction, default is horizontal. + */ + diffDirection?: 'horizontal' | 'vertical'; /** * Removes coloring from the console output, useful if storing the results to a file. * Defaults to false. @@ -47,6 +55,10 @@ export interface MatchImageSnapshotOptions { * Defaults to 'pixel'. */ failureThresholdType?: 'pixel' | 'percent'; + /** + * Updates a snapshot even if it passed the threshold against the existing one, defaults to false. + */ + updatePassedSnapshot?: boolean; } /** @@ -55,7 +67,7 @@ export interface MatchImageSnapshotOptions { * import { toMatchImageSnapshot } from 'jest-image-snapshot'; * expect.extend({ toMatchImageSnapshot }); */ -export function toMatchImageSnapshot(): { message(): string; pass: boolean; }; +export function toMatchImageSnapshot(options?: MatchImageSnapshotOptions): { message(): string; pass: boolean; }; /** * Configurable function that can be passed to jest's expect.extend. @@ -69,7 +81,7 @@ export function configureToMatchImageSnapshot(options: MatchImageSnapshotOptions declare global { namespace jest { interface Matchers { - toMatchImageSnapshot(): R; + toMatchImageSnapshot(options?: MatchImageSnapshotOptions): R; } } } diff --git a/types/jest-image-snapshot/jest-image-snapshot-tests.ts b/types/jest-image-snapshot/jest-image-snapshot-tests.ts index a2ccb8c777..07f6debed7 100644 --- a/types/jest-image-snapshot/jest-image-snapshot-tests.ts +++ b/types/jest-image-snapshot/jest-image-snapshot-tests.ts @@ -1,5 +1,5 @@ // Typescript Version: 2.3 -import { toMatchImageSnapshot, configureToMatchImageSnapshot } from 'jest-image-snapshot'; +import { toMatchImageSnapshot, configureToMatchImageSnapshot, MatchImageSnapshotOptions } from 'jest-image-snapshot'; it('should be able to use toMatchImageSnapshot in a test', () => { expect.extend({ toMatchImageSnapshot }); @@ -21,3 +21,22 @@ it('should be able to use configureToMatchImageSnapshot in a test', () => { expect('Me').toMatchImageSnapshot(); }); + +it('Should be able to use configuration directly in toMatchImageSnapshot', () => { + expect.extend({ toMatchImageSnapshot }); + + const options: MatchImageSnapshotOptions = { + noColors: true, + customDiffConfig: { + threshold: 5, + includeAA: false + }, + customDiffDir: './diffs', + diffDirection: 'vertical', + updatePassedSnapshot: true, + failureThreshold: 10, + failureThresholdType: 'percent' + }; + + expect('Me').toMatchImageSnapshot(options); +}); diff --git a/types/jest-in-case/index.d.ts b/types/jest-in-case/index.d.ts index 02d7d08af9..9762bc39d3 100644 --- a/types/jest-in-case/index.d.ts +++ b/types/jest-in-case/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/thinkmill/jest-in-case#readme // Definitions by: Geovani de Souza // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// /// diff --git a/types/jest-in-case/jest-in-case-tests.ts b/types/jest-in-case/jest-in-case-tests.ts index 283ade76c1..ac99bc4683 100644 --- a/types/jest-in-case/jest-in-case-tests.ts +++ b/types/jest-in-case/jest-in-case-tests.ts @@ -11,8 +11,8 @@ function subtract(minuend: number, subtrahend: number) { } beforeEach(() => { - jest.spyOn(global, 'describe').mockImplementation((title, fn) => fn()); - jest.spyOn(global, 'test').mockImplementation((name, fn) => fn()); + jest.spyOn(global, 'describe').mockImplementation((title, fn) => (fn as () => void)()); + jest.spyOn(global, 'test').mockImplementation((name, fn) => (fn as () => void)()); global.test.skip = jest.fn((name, fn) => fn()); global.test.only = jest.fn((name, fn) => fn()); }); @@ -54,8 +54,8 @@ test('array', () => { }); test('object', () => { - jest.spyOn(global, 'describe').mockImplementation((title, fn) => fn()); - jest.spyOn(global, 'test').mockImplementation((name, fn) => fn()); + jest.spyOn(global, 'describe').mockImplementation((title, fn) => (fn as () => void)()); + jest.spyOn(global, 'test').mockImplementation((name, fn) => (fn as () => void)()); const title = 'add(augend, addend)'; diff --git a/types/jest-json-schema/index.d.ts b/types/jest-json-schema/index.d.ts index 67f1c51f7e..b2133526dc 100644 --- a/types/jest-json-schema/index.d.ts +++ b/types/jest-json-schema/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/americanexpress/jest-json-schema#readme // Definitions by: Igor Korolev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// import * as ajv from "ajv"; diff --git a/types/jest-matchers/index.d.ts b/types/jest-matchers/index.d.ts index 3b028f8929..705f993ea3 100644 --- a/types/jest-matchers/index.d.ts +++ b/types/jest-matchers/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/facebook/jest#readme // Definitions by: Joscha Feth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// export = expect; diff --git a/types/jest-plugin-context/index.d.ts b/types/jest-plugin-context/index.d.ts index da2698b78e..814b334b12 100644 --- a/types/jest-plugin-context/index.d.ts +++ b/types/jest-plugin-context/index.d.ts @@ -2,7 +2,7 @@ // 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 +// TypeScript Version: 3.0 /// diff --git a/types/jest-specific-snapshot/index.d.ts b/types/jest-specific-snapshot/index.d.ts index 61a65a416a..0e0a43d895 100644 --- a/types/jest-specific-snapshot/index.d.ts +++ b/types/jest-specific-snapshot/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/igor-dv/jest-specific-snapshot#readme // Definitions by: Janeene Beeforth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 /// diff --git a/types/jest-when/index.d.ts b/types/jest-when/index.d.ts index 0579419425..386911ed7c 100644 --- a/types/jest-when/index.d.ts +++ b/types/jest-when/index.d.ts @@ -2,26 +2,21 @@ // Project: https://github.com/timkindberg/jest-when#readme // Definitions by: Alden Taylor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// -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[]): When; - - expectCalledWith(...matchers: any[]): When; - - mockReturnValue: (value: any) => jest.MockInstance['mockReturnValue'] & When; - mockReturnValueOnce: (value: any) => jest.MockInstance['mockReturnValue'] & When; - mockResolvedValue: (value: any) => jest.MockInstance['mockReturnValue'] & When; - mockResolvedValueOnce: (value: any) => jest.MockInstance['mockReturnValue'] & When; - mockRejectedValue: (value: any) => jest.MockInstance['mockReturnValue'] & When; - mockRejectedValueOnce: (value: any) => jest.MockInstance['mockReturnValue'] & When; +export interface WhenMock extends jest.Mock { + calledWith(...matchers: Y): WhenMock; + expectCalledWith(...matchers: Y): WhenMock; + mockReturnValue(value: T): WhenMock; + mockReturnValueOnce(value: T): WhenMock; + mockResolvedValue(value: T | PromiseLike): WhenMock, Y>; + mockResolvedValueOnce(value: T | PromiseLike): WhenMock, Y>; + mockRejectedValue(value: T | PromiseLike): WhenMock, Y>; + mockRejectedValueOnce(value: T | PromiseLike): WhenMock, Y>; } +export type When = (fn: jest.Mock) => WhenMock; + export const when: When; diff --git a/types/jest-when/jest-when-tests.ts b/types/jest-when/jest-when-tests.ts index 179ea2fae1..55744218ce 100644 --- a/types/jest-when/jest-when-tests.ts +++ b/types/jest-when/jest-when-tests.ts @@ -31,16 +31,20 @@ describe('mock-when test', () => { it('Supports compound declarations:', () => { const fn = jest.fn(); - when(fn).calledWith(1).mockReturnValue('no'); + when(fn).calledWith(1).mockReturnValueOnce('no').mockReturnValue('yes'); when(fn).calledWith(2).mockReturnValue('way?'); - when(fn).calledWith(3).mockReturnValue('yes'); - when(fn).calledWith(4).mockReturnValue('way!'); + when(fn).calledWith(3).mockResolvedValueOnce('no'); + when(fn).calledWith(3).mockResolvedValue('yes'); + when(fn).calledWith(4).mockRejectedValueOnce('no'); + when(fn).calledWith(4).mockRejectedValue('yes'); expect(fn(1)).toEqual('no'); + expect(fn(1)).toEqual('yes'); expect(fn(2)).toEqual('way?'); - expect(fn(3)).toEqual('yes'); - expect(fn(4)).toEqual('way!'); - expect(fn(5)).toEqual(undefined); + expect(fn(3)).resolves.toEqual('no'); + expect(fn(3)).resolves.toEqual('yes'); + expect(fn(4)).rejects.toEqual('no'); + expect(fn(4)).rejects.toEqual('yes'); }); it('Supports chained calls:', () => { diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 4073e21087..cfc9be2070 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jest 23.3 +// Type definitions for Jest 24.0 // Project: http://facebook.github.io/jest/ // Definitions by: Asana // Ivo Stratev @@ -17,8 +17,9 @@ // Martin Hochel // Sebastian Sebald // Andy +// Antoine Brault // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 declare var beforeAll: jest.Lifecycle; declare var beforeEach: jest.Lifecycle; @@ -35,6 +36,8 @@ declare var xtest: jest.It; declare const expect: jest.Expect; +type ArgsType = T extends (...args: infer A) => any ? A : never; + interface NodeRequire { /** * Returns the actual module instead of a mock, bypassing all checks on @@ -71,8 +74,8 @@ declare namespace jest { */ function clearAllMocks(): typeof jest; /** - * Clears the mock.calls and mock.instances properties of all mocks. - * Equivalent to calling .mockClear() on every mocked function. + * Resets the state of all mocks. + * Equivalent to calling .mockReset() on every mocked function. */ function resetAllMocks(): typeof jest; /** @@ -114,11 +117,11 @@ declare namespace jest { /** * Creates a mock function. Optionally takes a mock implementation. */ - function fn(implementation: (...args: any[]) => T): Mock; + function fn(): Mock; /** * Creates a mock function. Optionally takes a mock implementation. */ - function fn(implementation?: (...args: any[]) => any): Mock; + function fn(implementation: (...args: Y) => T): Mock; /** * Use the automatic mocking system to generate a mocked version of the given module. */ @@ -126,7 +129,7 @@ declare namespace jest { /** * Returns whether the given function is a mock function. */ - function isMockFunction(fn: any): fn is Mock; + function isMockFunction(fn: any): fn is Mock; /** * Mocks a module with an auto-mocked version when it is being required. */ @@ -212,7 +215,9 @@ declare namespace jest { * spy.mockRestore(); * }); */ - function spyOn(object: T, method: M, accessType?: 'get' | 'set'): SpyInstance; + function spyOn(object: T, method: M, accessType: 'get'): SpyInstance; + function spyOn(object: T, method: M, accessType: 'set'): SpyInstance; + function spyOn(object: T, method: M): T[M] extends (...args: any[]) => any ? SpyInstance, ArgsType> : never; /** * Indicates that the module system should never return a mocked version of * the specified module from require() (e.g. that it should always return the real module). @@ -274,6 +279,10 @@ declare namespace jest { * Skips running this test in the current file. */ skip: It; + /** + * Sketch out which tests to write in the future. + */ + todo: It; /** * Experimental and should be avoided. */ @@ -776,12 +785,12 @@ declare namespace jest { new (...args: any[]): any; } - interface Mock extends Function, MockInstance { - new (...args: any[]): T; - (...args: any[]): any; + interface Mock extends Function, MockInstance { + new (...args: Y): T; + (...args: Y): T; } - interface SpyInstance extends MockInstance {} + interface SpyInstance extends MockInstance {} /** * Wrap module with mock definitions @@ -795,14 +804,14 @@ declare namespace jest { * myApi.myApiMethod.mockImplementation(() => "test"); */ type Mocked = { - [P in keyof T]: T[P] & MockInstance; + [P in keyof T]: T[P] & MockInstance>; } & T; - interface MockInstance { + interface MockInstance { /** Returns the mock name string set by calling `mockFn.mockName(value)`. */ getMockName(): string; /** Provides access to the mock's metadata */ - mock: MockContext; + mock: MockContext; /** * Resets all information stored in the mockFn.mock.calls and mockFn.mock.instances arrays. * @@ -842,7 +851,7 @@ declare namespace jest { * * Note: `jest.fn(implementation)` is a shorthand for `jest.fn().mockImplementation(implementation)`. */ - mockImplementation(fn?: (...args: any[]) => any): Mock; + mockImplementation(fn?: (...args: Y) => T): Mock; /** * Accepts a function that will be used as an implementation of the mock for one call to the mocked function. * Can be chained so that multiple function calls produce different results. @@ -858,9 +867,9 @@ declare namespace jest { * * myMockFn((err, val) => console.log(val)); // false */ - mockImplementationOnce(fn: (...args: any[]) => any): Mock; + mockImplementationOnce(fn: (...args: Y) => T): Mock; /** Sets the name of the mock`. */ - mockName(name: string): Mock; + mockName(name: string): Mock; /** * Just a simple sugar function for: * @@ -870,7 +879,7 @@ declare namespace jest { * return this; * }); */ - mockReturnThis(): Mock; + mockReturnThis(): Mock; /** * Accepts a value that will be returned whenever the mock function is called. * @@ -882,7 +891,7 @@ declare namespace jest { * mock.mockReturnValue(43); * mock(); // 43 */ - mockReturnValue(value: any): Mock; + mockReturnValue(value: T): Mock; /** * Accepts a value that will be returned for one call to the mock function. Can be chained so that * successive calls to the mock function return different values. When there are no more @@ -899,11 +908,11 @@ declare namespace jest { * console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); * */ - mockReturnValueOnce(value: any): Mock; + mockReturnValueOnce(value: T): Mock; /** * Simple sugar function for: `jest.fn().mockImplementation(() => Promise.resolve(value));` */ - mockResolvedValue(value: any): Mock; + mockResolvedValue(value: T | PromiseLike): Mock, Y>; /** * Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.resolve(value));` * @@ -923,7 +932,7 @@ declare namespace jest { * }); * */ - mockResolvedValueOnce(value: any): Mock; + mockResolvedValueOnce(value: T | PromiseLike): Mock, Y>; /** * Simple sugar function for: `jest.fn().mockImplementation(() => Promise.reject(value));` * @@ -935,7 +944,7 @@ declare namespace jest { * await asyncMock(); // throws "Async error" * }); */ - mockRejectedValue(value: any): Mock; + mockRejectedValue(value: any): Mock, Y>; /** * Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.reject(value));` @@ -953,7 +962,7 @@ declare namespace jest { * }); * */ - mockRejectedValueOnce(value: any): Mock; + mockRejectedValueOnce(value: any): Mock, Y>; } /** @@ -971,8 +980,8 @@ declare namespace jest { value: any; } - interface MockContext { - calls: any[][]; + interface MockContext { + calls: Y[]; instances: T[]; invocationCallOrder: number[]; /** diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 4164e009e4..c2e930c26f 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -83,6 +83,12 @@ it.skip("name", () => {}, 9001); it.skip("name", async () => {}, 9001); it.skip("name", (callback: jest.DoneCallback) => {}, 9001); +it.todo("name", () => {}); +it.todo("name", async () => {}); +it.todo("name", () => {}, 9001); +it.todo("name", async () => {}, 9001); +it.todo("name", (callback: jest.DoneCallback) => {}, 9001); + it.concurrent("name", () => {}); it.concurrent("name", async () => {}); it.concurrent("name", () => {}, 9001); @@ -107,6 +113,12 @@ fit.skip("name", () => {}, 9001); fit.skip("name", async () => {}, 9001); fit.skip("name", (callback: jest.DoneCallback) => {}, 9001); +fit.todo("name", () => {}); +fit.todo("name", async () => {}); +fit.todo("name", () => {}, 9001); +fit.todo("name", async () => {}, 9001); +fit.todo("name", (callback: jest.DoneCallback) => {}, 9001); + fit.concurrent("name", () => {}); fit.concurrent("name", async () => {}); fit.concurrent("name", () => {}, 9001); @@ -131,6 +143,12 @@ xit.skip("name", () => {}, 9001); xit.skip("name", async () => {}, 9001); xit.skip("name", (callback: jest.DoneCallback) => {}, 9001); +xit.todo("name", () => {}); +xit.todo("name", async () => {}); +xit.todo("name", () => {}, 9001); +xit.todo("name", async () => {}, 9001); +xit.todo("name", (callback: jest.DoneCallback) => {}, 9001); + xit.concurrent("name", () => {}); xit.concurrent("name", async () => {}); xit.concurrent("name", () => {}, 9001); @@ -155,6 +173,12 @@ test.skip("name", () => {}, 9001); test.skip("name", async () => {}, 9001); test.skip("name", (callback: jest.DoneCallback) => {}, 9001); +test.todo("name", () => {}); +test.todo("name", async () => {}); +test.todo("name", () => {}, 9001); +test.todo("name", async () => {}, 9001); +test.todo("name", (callback: jest.DoneCallback) => {}, 9001); + test.concurrent("name", () => {}); test.concurrent("name", async () => {}); test.concurrent("name", () => {}, 9001); @@ -179,6 +203,12 @@ xtest.skip("name", () => {}, 9001); xtest.skip("name", async () => {}, 9001); xtest.skip("name", (callback: jest.DoneCallback) => {}, 9001); +xtest.todo("name", () => {}); +xtest.todo("name", async () => {}); +xtest.todo("name", () => {}, 9001); +xtest.todo("name", async () => {}, 9001); +xtest.todo("name", (callback: jest.DoneCallback) => {}, 9001); + xtest.concurrent("name", () => {}); xtest.concurrent("name", async () => {}); xtest.concurrent("name", () => {}, 9001); @@ -259,12 +289,43 @@ jest.requireMock("./thisAlwaysReturnsTheMock"); /* Mocks and spies */ -const mock1: jest.Mock = jest.fn(); -const mock2: jest.Mock = jest.fn(() => undefined); -const mock3: jest.Mock = jest.fn(() => "abc"); -const mock4: jest.Mock<"abc"> = jest.fn((): "abc" => "abc"); -const mock5: jest.Mock = jest.fn((...args: string[]) => args.join("")); -const mock6: jest.Mock = jest.fn((arg: {}) => arg); +// $ExpectType Mock +const mock1: jest.Mock = jest.fn(); +// $ExpectType Mock +const mock2 = jest.fn(() => undefined); +// $ExpectType Mock +const mock3 = jest.fn(() => "abc"); +// $ExpectType Mock<"abc", []> +const mock4 = jest.fn((): "abc" => "abc"); +// $ExpectType Mock +const mock5 = jest.fn((...args: string[]) => args.join("")); +// $ExpectType Mock<{}, [{}]> +const mock6 = jest.fn((arg: {}) => arg); +// $ExpectType Mock +const mock7 = jest.fn((arg: number) => arg); +// $ExpectType Mock +const mock8: jest.Mock = jest.fn((arg: number) => arg); +// $ExpectType Mock, [number, string, {}, [], boolean]> +const mock9 = jest.fn((a: number, _b: string, _c: {}, _iReallyDontCare: [], _makeItStop: boolean) => Promise.resolve(_makeItStop)); +// $ExpectType Mock +const mock10 = jest.fn((arg: never) => { throw new Error(arg); }); +// $ExpectType Mock +const mock11 = jest.fn((arg: unknown) => arg); + +// $ExpectType number +mock1('test'); + +// $ExpectError +mock7('abc'); +// $ExpectError +mock7.mockImplementation((arg: string) => 1); + +// compiles because mock8 is declared as jest.Mock<{}, any> +mock8('abc'); +mock8.mockImplementation((arg: string) => 1); + +// mockImplementation not required to declare all arguments +mock9.mockImplementation((a: number) => Promise.resolve(a === 0)); const genMockModule1: {} = jest.genMockFromModule("moduleName"); const genMockModule2: { a: "b" } = jest.genMockFromModule<{ a: "b" }>("moduleName"); @@ -278,8 +339,8 @@ if (jest.isMockFunction(maybeMock)) { } const mockName: string = jest.fn().getMockName(); -const mockContextVoid: jest.MockContext = jest.fn().mock; -const mockContextString: jest.MockContext = jest.fn(() => "").mock; +const mockContextVoid = jest.fn().mock; +const mockContextString = jest.fn(() => "").mock; jest.fn().mockClear(); @@ -289,14 +350,28 @@ jest.fn().mockRestore(); const spiedTarget = { returnsVoid(): void { }, + setValue(value: string): void { + this.value = value; + }, returnsString(): string { return ""; } }; +class SpiedTargetClass { + private _value = 3; + get value() { + return this._value; + } + set value(value) { + this._value = value; + } +} +const spiedTarget2 = new SpiedTargetClass(); + const spy1 = jest.spyOn(spiedTarget, "returnsVoid"); const spy2 = jest.spyOn(spiedTarget, "returnsVoid", "get"); -const spy3 = jest.spyOn(spiedTarget, "returnsString", "set"); +const spy3 = jest.spyOn(spiedTarget, "returnsString"); const spy1Name: string = spy1.getMockName(); const spy2Calls: any[][] = spy2.mock.calls; @@ -304,9 +379,10 @@ const spy2Calls: any[][] = spy2.mock.calls; spy2.mockClear(); spy2.mockReset(); -const spy3Mock: jest.Mock<() => string> = spy3 +const spy3Mock = spy3 .mockImplementation(() => "") .mockImplementation() + // $ExpectError .mockImplementation((arg: {}) => arg) .mockImplementation((...args: string[]) => args.join("")) .mockImplementationOnce(() => "") @@ -320,10 +396,23 @@ const spy3Mock: jest.Mock<() => string> = spy3 .mockRejectedValueOnce("value"); let spy4: jest.SpyInstance; - +// $ExpectType SpyInstance spy4 = jest.spyOn(spiedTarget, "returnsString"); +// compiles because spy4 is declared as jest.SpyInstance +spy4.mockImplementation(() => 1); spy4.mockRestore(); +// $ExpectType SpyInstance +const spy5 = jest.spyOn(spiedTarget2, "value", "get"); +// $ExpectError +spy5.mockReturnValue('5'); + +// $ExpectType SpyInstance +const spy6 = jest.spyOn(spiedTarget2, "value", "set"); + +// should compile +jest.fn().mockImplementation((test: number) => test); + /* Snapshot serialization */ const snapshotSerializerPlugin: jest.SnapshotSerializerPlugin = { diff --git a/types/jest/tsconfig.json b/types/jest/tsconfig.json index 8a02004840..20bc02a53b 100644 --- a/types/jest/tsconfig.json +++ b/types/jest/tsconfig.json @@ -13,6 +13,7 @@ "typeRoots": [ "../" ], + "target": "es5", "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/jira-client/index.d.ts b/types/jira-client/index.d.ts index e92d2a2f64..59a92a2961 100644 --- a/types/jira-client/index.d.ts +++ b/types/jira-client/index.d.ts @@ -89,7 +89,7 @@ declare class JiraApi { createCustomField(field: JiraApi.FieldObject): Promise; - listFields(): Promise; + listFields(): Promise; createFieldOption(fieldKey: string, option: JiraApi.FieldOptionObject): Promise; diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 404e0339ef..4ecf403a6f 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for joi 14.0 +// Type definitions for joi 14.3 // Project: https://github.com/hapijs/joi // Definitions by: Bart van der Schoor // Laurence Dougal Myers @@ -110,9 +110,10 @@ export interface EmailOptions { export interface HexOptions { /** - * hex decoded representation must be byte aligned + * hex decoded representation must be byte aligned. + * @default false */ - byteAligned: boolean; + byteAligned?: boolean; } export interface IpOptions { @@ -211,6 +212,16 @@ export interface JoiObject { isJoi: boolean; } +export interface ErrorOptions { + /** + * Boolean value indicating whether the error handler should be used for all errors or only for errors occurring + * on this property (`true` value). + * This concept only makes sense for `array` or `object` schemas as other values don't have children. + * @default false + */ + self?: boolean; +} + export interface ValidationError extends Error, JoiObject { details: ValidationErrorItem[]; annotate(): string; @@ -266,6 +277,14 @@ export interface AnySchema extends JoiObject { allow(...values: any[]): this; allow(values: any[]): this; + /** + * By default, some Joi methods to function properly need to rely on the Joi instance they are attached to because + * they use `this` internally. + * So `Joi.string()` works but if you extract the function from it and call `string()` it won't. + * `bind()` creates a new Joi instance where all the functions relying on `this` are bound to the Joi instance. + */ + bind(): this; + /** * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. */ @@ -412,7 +431,7 @@ export interface AnySchema extends JoiObject { * override, that error will be returned and the override will be ignored (unless the `abortEarly` * option has been set to `false`). */ - error(err: Error | ValidationErrorFunction): this; + error(err: Error | ValidationErrorFunction, options?: ErrorOptions): this; /** * Returns a plain object representing the schema's rules and properties @@ -469,7 +488,6 @@ export interface BooleanSchema extends AnySchema { /** * Allows the values provided to truthy and falsy as well as the "true" and "false" default conversion * (when not in strict() mode) to be matched in a case insensitive manner. - * @param enabled */ insensitive(enabled?: boolean): this; } @@ -681,6 +699,12 @@ export interface SymbolSchema extends AnySchema { } export interface ArraySchema extends AnySchema { + /** + * Verifies that an assertion passes for at least one item in the array, where: + * `schema` - the validation rules required to satisfy the assertion. If the `schema` includes references, they are resolved against + * the array item being tested, not the value of the `ref` target. + */ + assertItem(schema: SchemaLike): this; /** * Allow this array to be sparse. * enabled can be used with a falsy value to go back to the default behavior. @@ -767,6 +791,11 @@ export interface ObjectSchema extends AnySchema { */ length(limit: number): this; + /** + * Requires the object to be a Joi schema instance. + */ + schema(): this; + /** * Specify validation rules for unknown keys matching a pattern. * @@ -797,6 +826,13 @@ export interface ObjectSchema extends AnySchema { or(...peers: string[]): this; or(peers: string[]): this; + /** + * Defines an exclusive relationship between a set of keys where only one is allowed but none are required where: + * `peers` - the exclusive key names that must not appear together but where none are required. + */ + oxor(...peers: string[]): this; + oxor(peers: string[]): this; + /** * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where: */ diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index e21310396b..4dbc784756 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -19,28 +19,28 @@ declare const expArr: RegExp[]; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let schema: Joi.Schema = null; +let schema: Joi.Schema = Joi.any(); declare const schemaLike: Joi.SchemaLike; -let anySchema: Joi.AnySchema = null; -let numSchema: Joi.NumberSchema = null; -let strSchema: Joi.StringSchema = null; -let arrSchema: Joi.ArraySchema = null; -let boolSchema: Joi.BooleanSchema = null; -let binSchema: Joi.BinarySchema = null; -let dateSchema: Joi.DateSchema = null; -let funcSchema: Joi.FunctionSchema = null; -let objSchema: Joi.ObjectSchema = null; -let altSchema: Joi.AlternativesSchema = null; +let anySchema: Joi.AnySchema = Joi.any(); +let numSchema: Joi.NumberSchema = Joi.number(); +let strSchema: Joi.StringSchema = Joi.string(); +let arrSchema: Joi.ArraySchema = Joi.array(); +let boolSchema: Joi.BooleanSchema = Joi.boolean(); +let binSchema: Joi.BinarySchema = Joi.binary(); +let dateSchema: Joi.DateSchema = Joi.date(); +let funcSchema: Joi.FunctionSchema = Joi.func(); +let objSchema: Joi.ObjectSchema = Joi.object(); +let altSchema: Joi.AlternativesSchema = Joi.alternatives(); declare const schemaArr: Joi.Schema[]; -let ref: Joi.Reference = null; -let description: Joi.Description = null; +let ref: Joi.Reference = Joi.ref('test'); +let description: Joi.Description = {}; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let validOpts: Joi.ValidationOptions = null; +let validOpts: Joi.ValidationOptions = {}; validOpts = { abortEarly: bool }; validOpts = { convert: bool }; @@ -72,7 +72,7 @@ validOpts = { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let renOpts: Joi.RenameOptions = null; +let renOpts: Joi.RenameOptions = {}; renOpts = { alias: bool }; renOpts = { multiple: bool }; @@ -81,7 +81,7 @@ renOpts = { ignoreUndefined: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let emailOpts: Joi.EmailOptions = null; +let emailOpts: Joi.EmailOptions = {}; emailOpts = { errorLevel: num }; emailOpts = { errorLevel: bool }; @@ -91,13 +91,13 @@ emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let hexOpts: Joi.HexOptions = null; +let hexOpts: Joi.HexOptions = {}; hexOpts = { byteAligned: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let ipOpts: Joi.IpOptions = null; +let ipOpts: Joi.IpOptions = {}; ipOpts = { version: str }; ipOpts = { version: strArr }; @@ -105,7 +105,7 @@ ipOpts = { cidr: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let uriOpts: Joi.UriOptions = null; +let uriOpts: Joi.UriOptions = {}; uriOpts = { scheme: str }; uriOpts = { scheme: exp }; @@ -114,19 +114,21 @@ uriOpts = { scheme: expArr }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let base64Opts: Joi.Base64Options = null; +let base64Opts: Joi.Base64Options = {}; base64Opts = { paddingRequired: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let dataUriOpts: Joi.DataUriOptions = null; +let dataUriOpts: Joi.DataUriOptions = {}; dataUriOpts = { paddingRequired: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let whenOpts: Joi.WhenOptions = null; +let whenOpts: Joi.WhenOptions = { + is: Joi.any(), +}; whenOpts = { is: x }; whenOpts = { is: schema, then: schema }; @@ -135,7 +137,7 @@ whenOpts = { is: schemaLike, then: schemaLike, otherwise: schemaLike }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let whenSchemaOpts: Joi.WhenSchemaOptions = null; +let whenSchemaOpts: Joi.WhenSchemaOptions = {}; whenSchemaOpts = { then: schema }; whenSchemaOpts = { otherwise: schema }; @@ -143,14 +145,14 @@ whenSchemaOpts = { then: schemaLike, otherwise: schemaLike }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let refOpts: Joi.ReferenceOptions = null; +let refOpts: Joi.ReferenceOptions = {}; refOpts = { separator: str }; refOpts = { contextPrefix: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let stringRegexOpts: Joi.StringRegexOptions = null; +let stringRegexOpts: Joi.StringRegexOptions = {}; stringRegexOpts = { name: str }; stringRegexOpts = { invert: bool }; @@ -204,7 +206,7 @@ anySchema = objSchema; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -let schemaMap: Joi.SchemaMap = null; +let schemaMap: Joi.SchemaMap = {}; schemaMap = { a: numSchema, @@ -246,6 +248,7 @@ anySchema = Joi.any(); anySchema = anySchema.allow(x); anySchema = anySchema.allow(x, x); anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.bind(); anySchema = anySchema.valid(x); anySchema = anySchema.valid(x, x); anySchema = anySchema.valid([x, x, x]); @@ -302,12 +305,14 @@ anySchema = Joi.any(); anySchema = anySchema.error(err); anySchema = anySchema.error(validErrFunc); + anySchema = anySchema.error(validErrFunc, { self: true }); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- arrSchema = Joi.array(); +arrSchema = arrSchema.assertItem(Joi.any()); arrSchema = arrSchema.sparse(); arrSchema = arrSchema.sparse(bool); arrSchema = arrSchema.single(); @@ -701,11 +706,18 @@ objSchema = objSchema.nand(str, str); objSchema = objSchema.nand(str, str, str); objSchema = objSchema.nand(strArr); +objSchema = objSchema.schema(); + objSchema = objSchema.or(str); objSchema = objSchema.or(str, str); objSchema = objSchema.or(str, str, str); objSchema = objSchema.or(strArr); +objSchema = objSchema.oxor(str); +objSchema = objSchema.oxor(str, str); +objSchema = objSchema.oxor(str, str, str); +objSchema = objSchema.oxor(strArr); + objSchema = objSchema.xor(str); objSchema = objSchema.xor(str, str); objSchema = objSchema.xor(str, str, str); diff --git a/types/joi/tsconfig.json b/types/joi/tsconfig.json index 57e6c47881..09319363d5 100644 --- a/types/joi/tsconfig.json +++ b/types/joi/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/jquery.soap/index.d.ts b/types/jquery.soap/index.d.ts index 36674a677b..9a802163e4 100644 --- a/types/jquery.soap/index.d.ts +++ b/types/jquery.soap/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQuery.SOAP 1.6.7 +// Type definitions for jQuery.SOAP 1.7 // Project: https://github.com/doedje/jquery.soap // Definitions by: Roland Greim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ @@ -72,6 +72,7 @@ declare namespace JQuerySOAP { SOAPHeader?: Object; statusCode?: Object; success?: (SOAPResponse: SOAPResponse) => void; + timeout?: number; url?: string; wss?: Object; } diff --git a/types/jquery.soap/tslint.json b/types/jquery.soap/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/jquery.soap/tslint.json +++ b/types/jquery.soap/tslint.json @@ -7,7 +7,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, diff --git a/types/jquery/v2/index.d.ts b/types/jquery/v2/index.d.ts index 2643960e6d..068bbfc991 100644 --- a/types/jquery/v2/index.d.ts +++ b/types/jquery/v2/index.d.ts @@ -603,6 +603,14 @@ interface BaseJQueryEventObject extends Event { metaKey: boolean; } +interface JQueryCustomEventObject extends BaseJQueryEventObject { + /** + * @see {@link https://api.jquery.com/category/events/event-object/} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent} + */ + detail?: any; +} + interface JQueryInputEventObject extends BaseJQueryEventObject { altKey: boolean; ctrlKey: boolean; @@ -632,7 +640,7 @@ interface JQueryKeyEventObject extends JQueryInputEventObject { keyCode: number; } -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ +interface JQueryEventObject extends BaseJQueryEventObject, JQueryCustomEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { } /** diff --git a/types/jqueryui/index.d.ts b/types/jqueryui/index.d.ts index cc164360c0..c9764b8f6b 100644 --- a/types/jqueryui/index.d.ts +++ b/types/jqueryui/index.d.ts @@ -1056,6 +1056,7 @@ declare namespace JQueryUI { keyCode: KeyCode; menu: Menu; progressbar: Progressbar; + selectmenu: SelectMenu; slider: Slider; spinner: Spinner; tabs: Tabs; diff --git a/types/jqueryui/jqueryui-tests.ts b/types/jqueryui/jqueryui-tests.ts index 32712b8085..fa0f7b63a9 100644 --- a/types/jqueryui/jqueryui-tests.ts +++ b/types/jqueryui/jqueryui-tests.ts @@ -1862,6 +1862,7 @@ function test_ui() { $("aDialog").keypress(function (e) { return (e.keyCode == $.ui.keyCode.ENTER); }); + $(".selector").jQuery.ui.selectmenu({ disabled: true }); } function test_widget() { diff --git a/types/js-levenshtein/index.d.ts b/types/js-levenshtein/index.d.ts new file mode 100644 index 0000000000..5b29d11026 --- /dev/null +++ b/types/js-levenshtein/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for js-levenshtein 1.1 +// Project: https://github.com/gustf/js-levenshtein +// Definitions by: Kallu609 +// Pyry Rouvila +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Calculates Levenshtein distance between two strings + */ +declare function levenshtein(compareFrom: string, compareTo: string): number; + +export = levenshtein; diff --git a/types/js-levenshtein/js-levenshtein-tests.ts b/types/js-levenshtein/js-levenshtein-tests.ts new file mode 100644 index 0000000000..539473ccf4 --- /dev/null +++ b/types/js-levenshtein/js-levenshtein-tests.ts @@ -0,0 +1,3 @@ +import levenshtein = require('js-levenshtein'); + +levenshtein('kittens', 'mittens'); // $ExpectType number diff --git a/types/js-levenshtein/tsconfig.json b/types/js-levenshtein/tsconfig.json new file mode 100644 index 0000000000..6df128481b --- /dev/null +++ b/types/js-levenshtein/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "js-levenshtein-tests.ts"] +} diff --git a/types/js-levenshtein/tslint.json b/types/js-levenshtein/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/js-levenshtein/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/js-types/index.d.ts b/types/js-types/index.d.ts new file mode 100644 index 0000000000..756680fd04 --- /dev/null +++ b/types/js-types/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for js-types 2.0 +// Project: https://github.com/sindresorhus/js-types#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = jsTypes; + +declare const jsTypes: string[]; diff --git a/types/js-types/js-types-tests.ts b/types/js-types/js-types-tests.ts new file mode 100644 index 0000000000..b7e5a4fe8b --- /dev/null +++ b/types/js-types/js-types-tests.ts @@ -0,0 +1,5 @@ +import jsTypes = require('js-types'); +import jsTypesJson = require('js-types/js-types.json'); + +jsTypes; // $ExpectType string[] +jsTypesJson; // $ExpectType string[] diff --git a/types/js-types/js-types.json.d.ts b/types/js-types/js-types.json.d.ts new file mode 100644 index 0000000000..83565f43d1 --- /dev/null +++ b/types/js-types/js-types.json.d.ts @@ -0,0 +1,3 @@ +export = jsTypes; + +declare const jsTypes: string[]; diff --git a/types/js-types/tsconfig.json b/types/js-types/tsconfig.json new file mode 100644 index 0000000000..1b81a82e27 --- /dev/null +++ b/types/js-types/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "js-types.json.d.ts", + "js-types-tests.ts" + ] +} diff --git a/types/js-types/tslint.json b/types/js-types/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/js-types/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 49ba2807a7..b59741e74e 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-yaml 3.11 +// Type definitions for js-yaml 3.12 // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -52,6 +52,8 @@ export interface LoadOptions { export interface DumpOptions { /** indentation width to use (in spaces). */ indent?: number; + /** when true, will not add an indentation level to array elements */ + noArrayIndent?: boolean; /** do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. */ skipInvalid?: boolean; /** specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere */ diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index d3d90131d1..304da7731d 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -72,6 +72,9 @@ loadOpts = { dumpOpts = { indent: num }; +dumpOpts = { + noArrayIndent: bool +}; dumpOpts = { skipInvalid: bool }; diff --git a/types/jsdom/jsdom-tests.ts b/types/jsdom/jsdom-tests.ts index 1420723b8d..0b8be95052 100644 --- a/types/jsdom/jsdom-tests.ts +++ b/types/jsdom/jsdom-tests.ts @@ -1,4 +1,4 @@ -import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow, ResourceLoader, FetchOptions } from 'jsdom'; +import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow, ResourceLoader, FetchOptions, ConstructorOptions } from 'jsdom'; import { CookieJar as ToughCookieJar, MemoryCookieStore } from 'tough-cookie'; import { Script } from 'vm'; @@ -56,8 +56,9 @@ function test_cookieJar() { const store = {} as MemoryCookieStore; const options = {} as ToughCookieJar.Options; - const cookieJar = new CookieJar(store, options); - const dom = new JSDOM(``, { cookieJar }); + const cookieJar: CookieJar = new CookieJar(store, options); + const constructorOptions: ConstructorOptions = { cookieJar }; + const dom = new JSDOM(``, constructorOptions); } function test_beforeParse() { diff --git a/types/jsforce/api/chatter.d.ts b/types/jsforce/api/chatter.d.ts index c712187559..4b65740f36 100644 --- a/types/jsforce/api/chatter.d.ts +++ b/types/jsforce/api/chatter.d.ts @@ -27,7 +27,7 @@ interface RequestParams { export class RequestResult { } -export class Request implements Promise { +export class Request implements PromiseLike { constructor(chatter: Chatter, params: RequestParams); batchParams(): BatchRequestParams; @@ -36,16 +36,12 @@ export class Request implements Promise { stream(): Stream; - catch(onrejected?: ((reason: any) => (PromiseLike | TResult)) | null | undefined): Promise; - then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; finally(onfinally?: () => void): Promise; thenCall(callback?: (err: Error, records: T) => void): Query; - - readonly [Symbol.toStringTag]: 'Promise'; } export class Resource extends Request { diff --git a/types/jsforce/api/metadata.d.ts b/types/jsforce/api/metadata.d.ts index c6aec12e7e..88dbdaa52d 100644 --- a/types/jsforce/api/metadata.d.ts +++ b/types/jsforce/api/metadata.d.ts @@ -112,21 +112,17 @@ interface DeployOptions { singlePackage?: boolean; } -export class AsyncResultLocator extends EventEmitter implements Promise { +export class AsyncResultLocator extends EventEmitter implements PromiseLike { check(callback?: Callback): Promise complete(callback?: Callback): Promise poll(interval: number, timeout: number): void; - catch(onrejected?: ((reason: any) => (PromiseLike | TResult)) | null | undefined): Promise; - then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; finally(onfinally?: () => void): Promise; - - readonly [Symbol.toStringTag]: "Promise"; } export class DeployResultLocator extends AsyncResultLocator {} diff --git a/types/jsforce/jsforce-tests.ts b/types/jsforce/jsforce-tests.ts index 08ea888062..45442b91dc 100644 --- a/types/jsforce/jsforce-tests.ts +++ b/types/jsforce/jsforce-tests.ts @@ -615,7 +615,7 @@ async function testChatter(conn: sf.Connection): Promise { const feedResource: sf.Resource = chatter.resource('/feed-elements'); - const feedCreateRequest: any = await (feedResource.create({ + const feedCreateRequest: any = await feedResource.create({ body: { messageSegments: [{ type: 'Text', @@ -624,13 +624,13 @@ async function testChatter(conn: sf.Connection): Promise { }, feedElementType: 'FeedItem', subjectId: 'me' - }) as Promise); + }); console.log(`feedCreateRequest.id: ${feedCreateRequest.id}`); const itemLikesUrl = `/feed-elements/${feedCreateRequest.id}/capabilities/chatter-likes/items`; const itemsLikeResource: sf.Resource = chatter.resource(itemLikesUrl); - const itemsLikeCreateResult: sf.RequestResult = await (itemsLikeResource.create('') as Promise); + const itemsLikeCreateResult: sf.RequestResult = await itemsLikeResource.create(''); console.log(`itemsLikeCreateResult['likedItem']: ${itemsLikeCreateResult as any['likedItem']}`); } diff --git a/types/jsforce/tslint.json b/types/jsforce/tslint.json index 43829466b8..12201695b9 100644 --- a/types/jsforce/tslint.json +++ b/types/jsforce/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODOs "array-type": false, + "await-promise": [true, "Request"], "ban-types": false, "eofline": false, "max-line-length": false, diff --git a/types/json-schema/index.d.ts b/types/json-schema/index.d.ts index 156a86c9a5..b380b19020 100644 --- a/types/json-schema/index.d.ts +++ b/types/json-schema/index.d.ts @@ -20,6 +20,21 @@ export type JSONSchema4TypeName = 'string' | 'number' | 'integer' | 'boolean' */ export type JSONSchema4Type = any[] | boolean | number | null | object | string +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-04/schema#' + * - 'http://json-schema.org/draft-04/hyper-schema#' + * - 'http://json-schema.org/draft-03/schema#' + * - 'http://json-schema.org/draft-03/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema4Version = string; + /** * JSON Schema V4 * @see https://tools.ietf.org/html/draft-zyp-json-schema-04 @@ -27,10 +42,7 @@ export type JSONSchema4Type = any[] | boolean | number | null | object | string export interface JSONSchema4 { id?: string $ref?: string - $schema?: 'http://json-schema.org/schema#' | 'http://json-schema.org/hyper-schema#' - | 'http://json-schema.org/draft-04/schema#' | 'http://json-schema.org/draft-04/hyper-schema#' - | 'http://json-schema.org/draft-03/schema#' | 'http://json-schema.org/draft-03/hyper-schema#' - | string + $schema?: JSONSchema4Version /** * This attribute is a string that provides a short description of the @@ -210,6 +222,19 @@ export type JSONSchema6TypeName = 'string' | 'number' | 'integer' | 'boolean' | export type JSONSchema6Type = any[] | boolean | number | null | object | string +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-06/schema#' + * - 'http://json-schema.org/draft-06/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchema6Version = string; + /** * JSON Schema V6 * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01 @@ -218,8 +243,7 @@ export type JSONSchema6Definition = JSONSchema6 | boolean; export interface JSONSchema6 { $id?: string $ref?: string - $schema?: 'http://json-schema.org/schema#' | 'http://json-schema.org/hyper-schema#' | - 'http://json-schema.org/draft-06/schema#' | 'http://json-schema.org/draft-06/hyper-schema#' + $schema?: JSONSchema6Version /** * Must be strictly greater than 0. @@ -502,12 +526,16 @@ export interface JSONSchema7Array extends Array {} /** * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-07/schema#' + * - 'http://json-schema.org/draft-07/hyper-schema#' + * * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 */ -export type JSONSchema7Version = 'http://json-schema.org/schema#' - | 'http://json-schema.org/hyper-schema#' - | 'http://json-schema.org/draft-07/schema#' - | 'http://json-schema.org/draft-07/hyper-schema#'; +export type JSONSchema7Version = string; /** * JSON Schema v7 diff --git a/types/jsonabc/index.d.ts b/types/jsonabc/index.d.ts new file mode 100644 index 0000000000..41a785d015 --- /dev/null +++ b/types/jsonabc/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for jsonabc 2.3 +// Project: http://novicelab.org/jsonabc +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Sort the JSON (clean, parse, sort, stringify). + * @param noArray Sort or don't sort arrays + */ +export function sort(inputStr: string, noArray?: boolean): string; + +/** + * Sort the JSON (clean, parse, sort, stringify). + * @param noArray Sort or don't sort arrays + */ +export function sortObj(input: object, noArray?: boolean): object; + +/** Remove trailing commas */ +export function cleanJSON(input: string): string; diff --git a/types/jsonabc/jsonabc-tests.ts b/types/jsonabc/jsonabc-tests.ts new file mode 100644 index 0000000000..8d51d94bac --- /dev/null +++ b/types/jsonabc/jsonabc-tests.ts @@ -0,0 +1,9 @@ +import * as myJsonAbc from 'jsonabc'; + +myJsonAbc.sortObj({ c: 0, b: 1, a: 0 }); +myJsonAbc.sortObj({ c: 0, b: 1, a: 0 }, false); + +myJsonAbc.sort('{ c: 0, b: 1, a: 0 }'); +myJsonAbc.sort('{ c: 0, b: 1, a: 0 }', true); + +myJsonAbc.cleanJSON('{ c: 0, b: 1, a: 0 }'); diff --git a/types/jsonabc/tsconfig.json b/types/jsonabc/tsconfig.json new file mode 100644 index 0000000000..072c667a18 --- /dev/null +++ b/types/jsonabc/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jsonabc-tests.ts" + ] +} diff --git a/types/jsonabc/tslint.json b/types/jsonabc/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsonabc/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jsonapi-serializer/index.d.ts b/types/jsonapi-serializer/index.d.ts new file mode 100644 index 0000000000..4d9344bc28 --- /dev/null +++ b/types/jsonapi-serializer/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for jsonapi-serializer 3.6 +// Project: https://github.com/SeyZ/jsonapi-serializer#readme +// Definitions by: Frank Chiang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.2 + +export type RefFunction = (current: any, item: any) => string; + +export interface Relation { + ref: string | RefFunction; + attributes?: string[]; + included?: boolean; +} + +export interface SerializerOptions { + ref?: (() => void) | boolean | string; + included?: boolean; + id?: string; + attributes?: string[]; + topLevelLinks?: string[] | Array<() => void>; + dataLinks?: string[] | Array<() => void>; + dataMeta?: (() => void) | object; + relationshipLinks?: object; + relationshipMeta?: object; + ignoreRelationshipData?: boolean; + keyForAttribute?: string | KeyForAttribute; + nullIfMissing?: boolean; + pluralizeType?: boolean; + typeForAttribute?: TypeForAttribute; + meta?: object; + transform?: (() => void); +} + +export interface KeyForAttribute { + (attribute: string): string; +} + +export interface TypeForAttribute { + (attribute: string, object?: any): any; +} + +export interface Transform { + (record: any): any; +} + +export interface DeserializerOptions { + id?: string; + keyForAttribute?: + | "dash-case" + | "lisp-case" + | "spinal-case" + | "kebab-case" + | "underscore_case" + | "snake_case" + | "camelCase" + | "CamelCase"; + pluralizeType?: boolean; + typeAsAttribute?: boolean; + transform?: Transform; +} + +export interface DeserializerConstructor { + new (opts: DeserializerOptions): Deserializer; +} + +export interface SerializerConstructor { + new (collectionName: string, opts: SerializerOptions): Serializer; +} + +export interface ErrorConstructor { + new (opts: JSONAPIErrorOptions | JSONAPIErrorOptions[]): JSONAPIError; +} + +export interface JSONAPIError { + errors: any[]; +} + +export interface JSONAPIErrorOptions { + id?: string; + status?: string; + code?: string; + title?: string; + detail?: string; + source?: { + pointer?: string; + parameter?: string; + }; + links?: { + about?: string; + }; + meta?: any; +} + +export interface Serializer { + serialize(data: any): any; +} + +export interface Deserializer { + deserialize(data: any, callback: Callback): void; + + deserialize(data: any): Promise; +} + +export interface Callback { + (error: Error, response: any): any; +} + +export let Serializer: SerializerConstructor; +export let Deserializer: DeserializerConstructor; +export let Error: ErrorConstructor; diff --git a/types/jsonapi-serializer/jsonapi-serializer-tests.ts b/types/jsonapi-serializer/jsonapi-serializer-tests.ts new file mode 100644 index 0000000000..cd560cca77 --- /dev/null +++ b/types/jsonapi-serializer/jsonapi-serializer-tests.ts @@ -0,0 +1,37 @@ +import { Serializer, Deserializer, Error } from "jsonapi-serializer"; + +declare let firstName: string; +declare let lastName: string; + +const UserSerializer = new Serializer("users", { + id: "id", + attributes: ["firstName", "lastName"], + keyForAttribute: "camelCase", + pluralizeType: false +}); + +const users = UserSerializer.serialize({ firstName, lastName }); + +const UserDeserializer = new Deserializer({ + id: "id", + keyForAttribute: "camelCase", + pluralizeType: false, + typeAsAttribute: true +}); + +UserDeserializer.deserialize(users); + +new Error({ + code: "_code", + detail: "_detail", + id: "_id", + links: { + about: "_about" + }, + source: { + parameter: "_parameter", + pointer: "_pointer" + }, + status: "_status", + title: "_title" +}); diff --git a/types/jsonapi-serializer/tsconfig.json b/types/jsonapi-serializer/tsconfig.json new file mode 100644 index 0000000000..eeea88010a --- /dev/null +++ b/types/jsonapi-serializer/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "jsonapi-serializer-tests.ts"] +} diff --git a/types/jsonapi-serializer/tslint.json b/types/jsonapi-serializer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsonapi-serializer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/junk/index.d.ts b/types/junk/index.d.ts new file mode 100644 index 0000000000..390847e1c0 --- /dev/null +++ b/types/junk/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for junk 2.1 +// Project: https://github.com/sindresorhus/junk#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Returns `true` if `filename` matches a junk file. + */ +export function is(filename: string): boolean; +/** + * Returns `true` if `filename` doesn't match a junk file. + */ +export function not(filename: string): boolean; +/** + * Regex used for matching. + */ +export const regex: RegExp; diff --git a/types/junk/junk-tests.ts b/types/junk/junk-tests.ts new file mode 100644 index 0000000000..848eded660 --- /dev/null +++ b/types/junk/junk-tests.ts @@ -0,0 +1,12 @@ +/// + +import fs = require('fs'); +import * as junk from 'junk'; + +junk.is('foo'); // $ExpectType boolean +junk.not('foo'); // $ExpectType boolean +junk.regex; // $ExpectType RegExp + +fs.readdir('some/path', (err, files) => { + files.filter(junk.not); +}); diff --git a/types/junk/tsconfig.json b/types/junk/tsconfig.json new file mode 100644 index 0000000000..06710a9591 --- /dev/null +++ b/types/junk/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", + "junk-tests.ts" + ] +} diff --git a/types/junk/tslint.json b/types/junk/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/junk/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jwplayer/index.d.ts b/types/jwplayer/index.d.ts index 1d65bca261..91f0d455cc 100644 --- a/types/jwplayer/index.d.ts +++ b/types/jwplayer/index.d.ts @@ -1,509 +1,382 @@ -// Type definitions for JW Player V8.2 -// Project: https://github.com/jwplayer/jwplayer/ +// Type definitions for JW Player 8.2 +// Project: https://github.com/jwplayer/jwplayer // Definitions by: Martin Duparc // Tomer Kruvi // Philipp Gürtler // Daniel McGraw // Benjamin Dobson -// Be Birchall +// Be Birchall +// Daniel Cassidy +// Drew Wyatt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 // JW Player is the leading HTML5 & Flash video player, optimized for mobile and the desktop. Easy enough for beginners, advanced enough for pros. -interface Version { - version: string; - major: number; - minor: number +declare namespace jwplayer { + interface Version { + version: string; + major: number; + minor: number; + } + + interface Browser { + chrome: boolean; + edge: boolean; + facebook: boolean; + firefox: boolean; + ie: boolean; + msie: boolean; + safari: boolean; + version: Version; + } + + interface OS { + android: boolean; + androidNative: boolean; // Android native browser + iOS: boolean; + mobile: boolean; + mac: boolean; + iPad: boolean; + iPhone: boolean; + windows: boolean; + version: Version; + } + + interface Features { + flash: boolean; + flashVersion: number; + iframe: boolean; + } + + interface Environment { + Browser: Browser; + OS: OS; + Features: Features; + } + + interface AdProgressParam { + client: 'vast' | 'googima'; + creativetype: string; + tag: string; + } + + interface AdCompanionsParam { + companions: any[]; + tag: string; + } + + interface AdErrorParam { + message: string; + tag: string; + } + + interface AdRequestParam { + adposition: 'pre' | 'mid' | 'post'; + client: 'vast' | 'googima'; + offset: 'pre' | 'mid' | 'post'; + tag: string; + } + + interface AdImpressionParam { + adposition: 'pre' | 'mid' | 'post'; + adsystem: string; + adtitle: string; + clickThroughUrl: string; + client: 'vast' | 'googima'; + creativetype: string; + linear: string; + mediafile: any; + tag: string; + vastversion: number; + wrapper: any[]; + } + + interface AdScheduleParam { + tag: string; + client: string; + adbreaks: object[]; + } + + interface AdStartedParam { + creativetype: string; + tag: string; + } + + interface AdPlayParam { + creativetype: string; + newstate: string; + oldstate: string; + tag: string; + } + + interface BufferParam { + newstate: string; + oldstate: string; + reason: 'loading' | 'complete' | 'stalled' | 'error'; + } + + interface BufferChangeParam { + duration: number; + bufferPercent: number; + position: number; + metadata: any; + } + + interface AdTimeParam { + client: 'vast' | 'googima'; + creativetype: string; + duration: number; + position: number; + sequence: number; + tag: string; + } + + interface AudioTracksParam { + levels: any[]; + } + + interface CaptionsChangedParam { + currentTrack: number; + } + + interface CaptionsListParam { + tracks: any[]; + } + + interface AudioTrackChangedParam { + currentTrack: number; + } + + interface MetadataParam { + metadata: any; + } + + interface ControlsParam { + controls: boolean; + } + + interface ErrorParam { + message: string; + } + + interface FullscreenParam { + fullscreen: boolean; + } + + interface IdleParam { + oldstate: 'buffering' | 'playing' | 'paused'; + } + + interface LevelsChangedParam { + currentQuality: number; + } + + interface MuteParam { + mute: boolean; + } + + interface VolumeParam { + volume: boolean; + } + + interface PlayParam { + oldstate: 'buffering' | 'playing'; + viewable: 0 | 1; + } + + interface PlaylistParam { + playlist: any[]; + } + + interface PlaylistItemParam { + index: number; + item: any; + } + + interface ReadyParam { + setupTime: number; + viewable: 0 | 1; + } + + interface ResizeParam { + width: number; + height: number; + } + + interface VisualQualityParam { + mode: string; + label: string; + reason: string; + } + + interface LevelsParam { + width: number; + levels: any[]; + } + + interface SeekParam { + position: number; + offset: number; + } + + interface TimeParam { + duration: number; + position: number; + viewable: 0 | 1; + } + + interface FirstFrameParam { + loadTime: number; + viewable: 0 | 1; + } + + type EventCallback = (param: T) => void; + + interface Region { + x: 0; // x and y will always be 0 according to https://developer.jwplayer.com/jw-player/docs/javascript-api-reference/#jwplayergetsaferegion + y: 0; + width: number; + height: number; + } + + interface CaptionOptions { + color: string; + fontSize: number; + fontFamily: string; + fontOpacity: number; + backgroundColor: string; + backgroundOpacity: number; + edgeStyle: string; + windowColor: string; + windowOpacity: number; + } + + interface Level { + bitrate: number; + height: number; + width: number; + label: string; + } + + interface QualityLevel { + mode: 'auto' | 'manual'; + level: Level; + reason: 'auto' | 'api' | 'initial choice'; + } + + interface CastParam { + available: boolean; + active: boolean; + deviceName: string; + type: 'cast'; + } + + interface EventParams { + adClick: AdProgressParam; + adCompanions: AdCompanionsParam; + adComplete: AdProgressParam; + adSkipped: AdProgressParam; + adError: AdErrorParam; + adRequest: AdRequestParam; + adSchedule: AdScheduleParam; + adStarted: AdStartedParam; + adImpression: AdImpressionParam; + adPlay: AdPlayParam; + adPause: AdPlayParam; + adTime: AdTimeParam; + cast: CastParam; + meta: MetadataParam; + audioTracks: AudioTracksParam; + audioTrackChanged: AudioTrackChangedParam; + firstFrame: FirstFrameParam; + buffer: BufferParam; + bufferChange: BufferChangeParam; + captionsChanged: CaptionsChangedParam; + captionsList: CaptionsListParam; + controls: ControlsParam; + error: ErrorParam; + fullscreen: FullscreenParam; + idle: IdleParam; + levelsChanged: LevelsChangedParam; + mute: MuteParam; + volume: VolumeParam; + pause: PlayParam; + play: PlayParam; + playlist: PlaylistParam; + playlistItem: PlaylistItemParam; + ready: ReadyParam; + resize: ResizeParam; + visualQuality: VisualQualityParam; + levels: LevelsParam; + seek: SeekParam; + setupError: ErrorParam; + time: TimeParam; + } + + type NoParamEvent = 'adBlock' | 'beforeComplete' | 'complete' | 'beforePlay' | 'displayClick' | 'playlistComplete' + | 'seeked' | 'remove'; + + interface JWPlayer { + addButton(icon: string, label: string, handler: () => void, id: string): void; + getAudioTracks(): any[]; + getBuffer(): number; + getCaptionsList(): any[]; + getControls(): boolean; + getCurrentAudioTrack(): number; + getCurrentCaptions(): number; + getCurrentQuality(): number; + getDuration(): number; + getHeight(): number; + getFullscreen(): boolean; + getMute(): boolean; + getPlaylist(): any[]; + getPlaylistIndex(): number; + getPlaylistItem(index?: number): any; + getPosition(): number; + getQualityLevels(): any[]; + getRenderingMode(): string; + getSafeRegion(): Region; + getState(): string; + getVolume(): number; + getContainer(): HTMLElement; + getEnvironment(): Environment; + getWidth(): number; + getVisualQuality(): QualityLevel | undefined; + load(playlist: any[] | string): void; + on(event: TEvent, callback: EventCallback): void; + on(event: NoParamEvent, callback: () => void): void; + once(event: TEvent, callback: EventCallback): void; + once(event: NoParamEvent, callback: () => void): void; + off(event: keyof EventParams | NoParamEvent): void; + trigger(event: TEvent, args: EventParams[TEvent]): void; + trigger(event: NoParamEvent): void; + pause(state?: boolean): void; + play(state?: boolean): void; + playAd(tag: string): void; + playlistItem(index: number): void; + registerPlugin(id: string, target: string, jsPlugin: () => void, swfURL?: string): void; + remove(): void; + removeButton(id: string): void; + resize(width: number, height: number): void; + seek(position: number): void; + setControls(controls: boolean): void; + setCurrentAudioTrack(index: number): void; + setCurrentCaptions(index: number): void; + setCurrentQuality(index: number): void; + setFullscreen(state: boolean): void; + setMute(state?: boolean): void; + setup(options: any): JWPlayer; + setVolume(volume: number): void; + setCaptions(options: CaptionOptions): void; + stop(): void; + } + + interface JWPlayerStatic { + (query?: string | number | Element): JWPlayer; + key: string; + version: string; + } } -interface Browser { - chrome: boolean; - edge: boolean; - facebook: boolean; - firefox: boolean; - ie: boolean; - msie: boolean; - safari: boolean; - version: Version; -} - -interface OS { - android: boolean; - androidNative: boolean; // Android native browser - iOS: boolean; - mobile: boolean; - mac: boolean; - iPad: boolean; - iPhone: boolean; - windows: boolean; - version: Version; -} - -interface Features { - flash: boolean; - flashVersion: number; - iframe: boolean; -} - -interface Environment{ - Browser: Browser; - OS: OS; - Features: Features; -} - -interface CallbackParam { -} - -interface AdProgressParam extends CallbackParam { - client: 'vast' | 'googima'; - creativetype: string; - tag: string; -} - -interface AdCompanionsParam extends CallbackParam { - companions: any[]; - tag: string; -} - -interface AdErrorParam extends CallbackParam { - message: string; - tag: string; -} - -interface AdRequestParam extends CallbackParam { - adposition: 'pre' | 'mid' | 'post'; - client: 'vast' | 'googima'; - offset: 'pre' | 'mid' | 'post'; - tag: string; -} - -interface AdImpressionParam extends CallbackParam { - adposition: 'pre' | 'mid' | 'post'; - adsystem: string; - adtitle: string; - clickThroughUrl: string; - client: 'vast' | 'googima'; - creativetype: string; - linear: string; - mediafile: any; - tag: string; - vastversion: number; - wrapper: any[]; -} - -interface AdScheduleParam extends CallbackParam { - tag: string; - client: string; - adbreaks: object[]; -} - -interface AdStartedParam extends CallbackParam { - creativetype: string; - tag: string; -} - -interface AdPlayParam extends CallbackParam { - creativetype: string; - newstate: string; - oldstate: string; - tag: string; -} - -interface BufferParam extends CallbackParam { - newstate: string; - oldstate: string; - reason: 'loading' | 'complete' | 'stalled' | 'error'; -} - -interface BufferChangeParam extends CallbackParam { - duration: number; - bufferPercent: number; - position: number; - metadata: any; -} - -interface AdTimeParam extends CallbackParam { - client: 'vast' | 'googima'; - creativetype: string; - duration: number; - position: number; - sequence: number; - tag: string; -} - -interface AudioTracksParam extends CallbackParam { - levels: any[]; -} - -interface CaptionsChangedParam extends CallbackParam { - currentTrack: number; -} - -interface CaptionsListParam extends CallbackParam { - tracks: any[]; -} - -interface AudioTrackChangedParam extends CallbackParam { - currentTrack: number; -} - -interface MetadataParam extends CallbackParam { - metadata: any; -} - -interface ControlsParam extends CallbackParam { - controls: boolean; -} - -interface ErrorParam extends CallbackParam { - message: string; -} - -interface FullscreenParam extends CallbackParam { - fullscreen: boolean; -} - -interface IdleParam extends CallbackParam { - oldstate: 'buffering' | 'playing' | 'paused'; -} - -interface LevelsChangedParam extends CallbackParam { - currentQuality: number; -} - -interface MuteParam extends CallbackParam { - mute: boolean; -} - -interface VolumeParam extends CallbackParam { - volume: boolean; -} - -interface PlayParam extends CallbackParam { - oldstate: 'buffering' | 'playing'; - viewable: 0 | 1; -} - -interface PlaylistParam extends CallbackParam { - playlist: any[]; -} - -interface PlaylistItemParam extends CallbackParam { - index: number; - item: any; -} - -interface ReadyParam extends CallbackParam { - setupTime: number; - viewable: 0 | 1; -} - -interface ResizeParam extends CallbackParam { - width: number; - height: number; -} - -interface VisualQualityParam extends CallbackParam { - mode: string; - label: string; - reason: string; -} - -interface LevelsParam extends CallbackParam { - width: number; - levels: any[]; -} - -interface SeekParam extends CallbackParam { - position: number; - offset: number; -} - -interface TimeParam extends CallbackParam { - duration: number; - position: number; - viewable: 0 | 1; -} - -interface FirstFrameParam extends CallbackParam { - loadTime: number; - viewable: 0 | 1; -} - -interface EventCallback { - (param: T): void; -} - -interface Region { - x: 0; // x and y will always be 0 according to https://developer.jwplayer.com/jw-player/docs/javascript-api-reference/#jwplayergetsaferegion - y: 0; - width: number; - height: number; -} - -interface CaptionOptions { - color: string; - fontSize: number; - fontFamily: string; - fontOpacity: number; - backgroundColor: string; - backgroundOpacity: number; - edgeStyle: string; - windowColor: string; - windowOpacity: number; -} - -interface Level { - bitrate: number; - height: number; - width: number; - label: string; -} - -interface QualityLevel { - mode: 'auto' | 'manual'; - level: Level; - reason: 'auto' | 'api' | 'initial choice'; -} - -interface JWPlayer { - addButton(icon: string, label: string, handler: () => void, id: string): void; - getAudioTracks(): any[]; - getBuffer(): number; - getCaptionsList(): any[]; - getControls(): boolean; - getCurrentAudioTrack(): number; - getCurrentCaptions(): number; - getCurrentQuality(): number; - getDuration(): number; - getHeight(): number; - getFullscreen(): boolean; - getMute(): boolean; - getPlaylist(): any[]; - getPlaylistIndex(): number; - getPlaylistItem(index?: number): any; - getPosition(): number; - getQualityLevels(): any[]; - getRenderingMode(): string; - getSafeRegion(): Region; - getState(): string; - getVolume(): number; - getContainer(): HTMLElement; - getEnvironment(): Environment; - getWidth(): number; - getVisualQuality(): QualityLevel | undefined; - load(playlist: any[]): void; - load(playlist: string): void; - on(event: 'adClick', callback: EventCallback): void; - once(event: 'adClick', callback: EventCallback): void; - off(event: 'adClick'): void; - trigger(event: 'adClick', args: AdProgressParam): void; - on(event: 'adCompanions', callback: EventCallback): void; - once(event: 'adCompanions', callback: EventCallback): void; - off(event: 'adCompanions'): void; - trigger(event: 'adCompanions', args: AdCompanionsParam): void; - on(event: 'adComplete', callback: EventCallback): void; - once(event: 'adComplete', callback: EventCallback): void; - off(event: 'adComplete'): void; - trigger(event: 'adComplete', args: AdProgressParam): void; - on(event: 'adSkipped', callback: EventCallback): void; - once(event: 'adSkipped', callback: EventCallback): void; - off(event: 'adSkipped'): void; - trigger(event: 'adSkipped', args: AdProgressParam): void; - on(event: 'adError', callback: EventCallback): void; - once(event: 'adError', callback: EventCallback): void; - off(event: 'adError'): void; - trigger(event: 'adError', args: AdErrorParam): void; - on(event: 'adBlock', callback: () => void): void; - once(event: 'adBlock', callback: () => void): void; - off(event: 'adBlock'): void; - trigger(event: 'adBlock'): void; - on(event: 'adRequest', callback: EventCallback): void; - once(event: 'adRequest', callback: EventCallback): void; - off(event: 'adRequest'): void; - trigger(event: 'adRequest', args: AdRequestParam): void; - on(event: 'adSchedule', callback: EventCallback): void; - once(event: 'adSchedule', callback: EventCallback): void; - off(event: 'adSchedule'): void; - trigger(event: 'adSchedule', args: AdScheduleParam): void; - on(event: 'adStarted', callback: EventCallback): void; - once(event: 'adStarted', callback: EventCallback): void; - off(event: 'adStarted'): void; - trigger(event: 'adStarted', args: AdStartedParam): void; - on(event: 'adImpression', callback: EventCallback): void; - once(event: 'adImpression', callback: EventCallback): void; - off(event: 'adImpression'): void; - trigger(event: 'adImpression', args: AdImpressionParam): void; - on(event: 'adPlay', callback: EventCallback): void; - once(event: 'adPlay', callback: EventCallback): void; - off(event: 'adPlay'): void; - trigger(event: 'adPlay', args: AdPlayParam): void; - on(event: 'adPause', callback: EventCallback): void; - once(event: 'adPause', callback: EventCallback): void; - off(event: 'adPause'): void; - trigger(event: 'adPause', args: AdPlayParam): void; - on(event: 'adTime', callback: EventCallback): void; - once(event: 'adTime', callback: EventCallback): void; - off(event: 'adTime'): void; - trigger(event: 'adTime', args: AdTimeParam): void; - on(event: 'meta', callback: EventCallback): void; - once(event: 'meta', callback: EventCallback): void; - off(event: 'meta'): void; - trigger(event: 'meta', args: MetadataParam): void; - on(event: 'audioTracks', callback: EventCallback): void; - once(event: 'audioTracks', callback: EventCallback): void; - off(event: 'audioTracks'): void; - trigger(event: 'audioTracks', args: AudioTracksParam): void; - on(event: 'audioTrackChanged', callback: EventCallback): void; - once(event: 'audioTrackChanged', callback: EventCallback): void; - off(event: 'audioTrackChanged'): void; - trigger(event: 'audioTrackChanged', args: AudioTrackChangedParam): void; - on(event: 'beforeComplete', callback: () => void): void; - once(event: 'beforeComplete', callback: () => void): void; - off(event: 'beforeComplete'): void; - trigger(event: 'beforeComplete'): void; - on(event: 'complete', callback: () => void): void; - once(event: 'complete', callback: () => void): void; - off(event: 'complete'): void; - trigger(event: 'complete'): void; - on(event: 'firstFrame', callback: EventCallback): void; - once(event: 'firstFrame', callback: EventCallback): void; - off(event: 'firstFrame'): void; - trigger(event: 'firstFrame', args: FirstFrameParam): void; - on(event: 'beforePlay', callback: () => void): void; - once(event: 'beforePlay', callback: () => void): void; - off(event: 'beforePlay'): void; - trigger(event: 'beforePlay'): void; - on(event: 'buffer', callback: EventCallback): void; - once(event: 'buffer', callback: EventCallback): void; - off(event: 'buffer'): void; - trigger(event: 'buffer', args: BufferParam): void; - on(event: 'bufferChange', callback: EventCallback): void; - once(event: 'bufferChange', callback: EventCallback): void; - off(event: 'bufferChange'): void; - trigger(event: 'bufferChange', args: BufferChangeParam): void; - on(event: 'captionsChanged', callback: EventCallback): void; - once(event: 'captionsChanged', callback: EventCallback): void; - off(event: 'captionsChanged'): void; - trigger(event: 'captionsChanged', args: CaptionsChangedParam): void; - on(event: 'captionsList', callback: EventCallback): void; - once(event: 'captionsList', callback: EventCallback): void; - off(event: 'captionsList'): void; - trigger(event: 'captionsList', args: CaptionsListParam): void; - on(event: 'controls', callback: EventCallback): void; - once(event: 'controls', callback: EventCallback): void; - off(event: 'controls'): void; - trigger(event: 'controls', args: ControlsParam): void; - on(event: 'displayClick', callback: () => void): void; - once(event: 'displayClick', callback: () => void): void; - off(event: 'displayClick'): void; - trigger(event: 'displayClick'): void; - on(event: 'error', callback: EventCallback): void; - once(event: 'error', callback: EventCallback): void; - off(event: 'error'): void; - trigger(event: 'error', args: ErrorParam): void; - on(event: 'fullscreen', callback: EventCallback): void; - once(event: 'fullscreen', callback: EventCallback): void; - off(event: 'fullscreen'): void; - trigger(event: 'fullscreen', args: FullscreenParam): void; - on(event: 'idle', callback: EventCallback): void; - once(event: 'idle', callback: EventCallback): void; - off(event: 'idle'): void; - trigger(event: 'idle', args: IdleParam): void; - on(event: 'levelsChanged', callback: EventCallback): void; - once(event: 'levelsChanged', callback: EventCallback): void; - off(event: 'levelsChanged'): void; - trigger(event: 'levelsChanged', args: LevelsChangedParam): void; - on(event: 'mute', callback: EventCallback): void; - once(event: 'mute', callback: EventCallback): void; - off(event: 'mute'): void; - trigger(event: 'mute', args: MuteParam): void; - on(event: 'volume', callback: EventCallback): void; - once(event: 'volume', callback: EventCallback): void; - off(event: 'volume'): void; - trigger(event: 'volume', args: VolumeParam): void; - on(event: 'pause', callback: EventCallback): void; - once(event: 'pause', callback: EventCallback): void; - off(event: 'pause'): void; - trigger(event: 'pause', args: PlayParam): void; - on(event: 'play', callback: EventCallback): void; - once(event: 'play', callback: EventCallback): void; - off(event: 'play'): void; - trigger(event: 'play', args: PlayParam): void; - on(event: 'playlist', callback: EventCallback): void; - once(event: 'playlist', callback: EventCallback): void; - off(event: 'playlist'): void; - trigger(event: 'playlist', args: PlaylistParam): void; - on(event: 'playlistItem', callback: EventCallback): void; - once(event: 'playlistItem', callback: EventCallback): void; - off(event: 'playlistItem'): void; - trigger(event: 'playlistItem', args: PlaylistItemParam): void; - on(event: 'playlistComplete', callback: () => void): void; - once(event: 'playlistComplete', callback: () => void): void; - off(event: 'playlistComplete'): void; - trigger(event: 'playlistComplete'): void; - on(event: 'ready', callback: EventCallback): void; - once(event: 'ready', callback: EventCallback): void; - off(event: 'ready'): void; - trigger(event: 'ready'): void; - on(event: 'resize', callback: EventCallback): void; - once(event: 'resize', callback: EventCallback): void; - off(event: 'resize'): void; - trigger(event: 'resize', args: ResizeParam): void; - on(event: 'visualQuality', callback: EventCallback): void; - once(event: 'visualQuality', callback: EventCallback): void; - off(event: 'visualQuality'): void; - trigger(event: 'visualQuality', args: VisualQualityParam): void; - on(event: 'levels', callback: EventCallback): void; - once(event: 'levels', callback: EventCallback): void; - off(event: 'levels'): void; - trigger(event: 'levels', args: LevelsParam): void; - on(event: 'seek', callback: EventCallback): void; - once(event: 'seek', callback: EventCallback): void; - off(event: 'seek'): void; - trigger(event: 'seek', args: SeekParam): void; - on(event: 'seeked', callback: () => void): void; - once(event: 'seeked', callback: () => void): void; - off(event: 'seeked'): void; - trigger(event: 'seeked'): void - on(event: 'setupError', callback: EventCallback): void; - once(event: 'setupError', callback: EventCallback): void; - off(event: 'setupError'): void; - trigger(event: 'setupError', args: ErrorParam): void; - on(event: 'remove', callback: () => void): void; - once(event: 'remove', callback: () => void): void; - off(event: 'remove'): void; - trigger(event: 'remove'): void; - on(event: 'time', callback: EventCallback): void; - once(event: 'time', callback: EventCallback): void; - off(event: 'time'): void; - trigger(event: 'time', args: TimeParam): void; - pause(state?: boolean): void; - play(state?: boolean): void; - playAd(tag: string): void; - playlistItem(index: number): void; - registerPlugin(id: string, target: string, jsPlugin: () => void, swfURL?: string): void; - remove(): void; - removeButton(id: string): void; - resize(width: number, height: number): void; - seek(position: number): void; - setControls(controls: boolean): void; - setCurrentAudioTrack(index: number): void; - setCurrentCaptions(index: number): void; - setCurrentQuality(index: number): void; - setFullscreen(state: boolean): void; - setMute(state?: boolean): void; - setup(options: any): JWPlayer; - setVolume(volume: number): void; - setCaptions(options: CaptionOptions): void; - stop(): void; -} - -interface JWPlayerStatic { - (id: string): JWPlayer; - key: string; - version: string; -} - -declare const jwplayer:JWPlayerStatic; +declare const jwplayer: jwplayer.JWPlayerStatic; diff --git a/types/jwplayer/tslint.json b/types/jwplayer/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/jwplayer/tslint.json +++ b/types/jwplayer/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/jws/index.d.ts b/types/jws/index.d.ts index fdbf1851c4..6c9d7194f5 100644 --- a/types/jws/index.d.ts +++ b/types/jws/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jws 3.1 +// Type definitions for jws 3.2 // Project: https://github.com/brianloveswords/node-jws // Definitions by: Justin Beckwith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -145,7 +145,8 @@ export interface VerifyOptions { export type Algorithm = 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512' | 'ES256' | 'ES384' | - 'ES512' | 'none'; + 'ES512' | 'PS256' | 'PS384' | 'PS512' | + 'none'; export interface Header { alg: Algorithm; diff --git a/types/katex/index.d.ts b/types/katex/index.d.ts index 19c7e79d06..ae126b3444 100644 --- a/types/katex/index.d.ts +++ b/types/katex/index.d.ts @@ -1,14 +1,90 @@ -// Type definitions for KaTeX 0.5 +// Type definitions for KaTeX 0.10 // Project: http://khan.github.io/KaTeX/ // Definitions by: Michael Randolph +// Kevin Nguyen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace katex; +/** Documentation: https://katex.org/docs/options.html */ export interface KatexOptions { + /** + * If `true`, math will be rendered in display mode + * (math in display style and center math on page) + * + * If `false`, math will be rendered in inline mode + * @default false + */ displayMode?: boolean; - breakOnUnsupportedCmds?: boolean; + /** + * If `true`, KaTeX will throw a `ParseError` when + * it encounters an unsupported command or invalid LaTex + * + * If `false`, KaTeX will render unsupported commands as + * text, and render invalid LaTeX as its source code with + * hover text giving the error, in color given by errorColor + * @default true + */ + throwOnError?: boolean; + /** + * A Color string given in format `#XXX` or `#XXXXXX` + */ errorColor?: string; + /** + * A collection of custom macros. + * + * See `src/macros.js` for its usage + */ + macros?: any; + /** + * If `true`, `\color` will work like LaTeX's `\textcolor` + * and takes 2 arguments + * + * If `false`, `\color` will work like LaTeX's `\color` + * and takes 1 argument + * + * In both cases, `\textcolor` works as in LaTeX + * + * @default false + */ + colorIsTextColor?: boolean; + /** + * All user-specified sizes will be caped to `maxSize` ems + * + * If set to Infinity, users can make elements and space + * arbitrarily large + * + * @default Infinity + */ + maxSize?: number; + /** + * Limit the number of macro expansions to specified number + * + * If set to `Infinity`, marco expander will try to fully expand + * as in LaTex + * + * @default 1000 + */ + maxExpand?: number; + /** + * Allowed protocols in `\href` + * + * Use `_relative` to allow relative urls + * + * Use `*` to allow all protocols + */ + allowedProtocols?: string[] + /** + * If `false` or `"ignore"`, allow features that make + * writing in LaTex convenient but not supported by LaTex + * + * If `true` or `"error"`, throw an error for such transgressions + * + * If `"warn"`, warn about behavior via `console.warn` + * + * @default "warn" + */ + strict?: boolean | string | Function; } export class ParseError implements Error { diff --git a/types/katex/katex-tests.ts b/types/katex/katex-tests.ts index 77e745d6a0..6fd614c82c 100644 --- a/types/katex/katex-tests.ts +++ b/types/katex/katex-tests.ts @@ -5,7 +5,7 @@ class KatexTest { katexLib.render('My Latex String', document.createElement('div')); try { - let options: katexLib.KatexOptions = { breakOnUnsupportedCmds: true }; + let options: katexLib.KatexOptions = { throwOnError: true }; let value: string = katexLib.renderToString('My Latex String', options); } catch (error) { if (error instanceof katexLib.ParseError) { diff --git a/types/kefir/index.d.ts b/types/kefir/index.d.ts index e892e1b291..05fd7a7aab 100644 --- a/types/kefir/index.d.ts +++ b/types/kefir/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for Kefir 3.7.3 +// Type definitions for Kefir 3.8.0 // Project: http://rpominov.github.io/kefir/ // Definitions by: Aya Morisawa // Piotr Hitori Bosak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.7 /// @@ -11,7 +11,7 @@ export type ValueOfAnObservable> = T['']; export interface Subscription { unsubscribe(): void; - closed: boolean; // Actually, `readonly` but it's avaiable in tsc starting with 2.0.0 + readonly closed: boolean; } export interface Observer { @@ -20,21 +20,24 @@ export interface Observer { end?: () => void; } -export interface Subscription { - unsubscribe(): void; - closed: boolean; // Actually, `readonly` but it's avaiable in tsc starting with 2.0.0 +interface ESObserver { + start?: Function, + next?: (value: T) => any, + error?: (error: S) => any, + complete?: () => any, } -export interface Observer { - value?: (value: T) => void; - error?: (error: S) => void; - end?: () => void; +interface ESObservable { + subscribe(callbacks: ESObserver): { unsubscribe(): void }; } -export interface Observable { +export class Observable { '': T; // TypeScript hack to enable value unwrapping for combine/flatMap - toProperty(getCurrent?: () => T): Property; + toProperty(): Property; + toProperty(getCurrent?: () => T2): Property; + changes(): Observable; + // Subscribe / add side effects onValue(callback: (value: T) => void): this; offValue(callback: (value: T) => void): this; @@ -42,8 +45,8 @@ export interface Observable { offError(callback: (error: S) => void): this; onEnd(callback: () => void): this; offEnd(callback: () => void): this; - onAny(callback: (event: Event) => void): this; - offAny(callback: (event: Event) => void): this; + onAny(callback: (event: Event) => void): this; + offAny(callback: (event: Event) => void): this; log(name?: string): this; spy(name?: string): this; offLog(name?: string): this; @@ -51,7 +54,7 @@ export interface Observable { flatten(transformer?: (value: T) => U[]): Stream; toPromise(): Promise; toPromise>(PromiseConstructor: () => W): W; - toESObservable(): any; + toESObservable(): ESObservable; // This method is designed to replace all other methods for subscribing observe(params: Observer): Subscription; observe( @@ -61,172 +64,174 @@ export interface Observable { ): Subscription; setName(source: Observable, selfName: string): this; setName(selfName: string): this; -} -export interface Stream extends Observable { + thru(cb: (obs: Observable) => Observable): Observable; // Modify an stream - map(fn: (value: T) => U): Stream; - filter(predicate?: (value: T) => boolean): Stream; - take(n: number): Stream; - takeWhile(predicate?: (value: T) => boolean): Stream; - last(): Stream; - skip(n: number): Stream; - skipWhile(predicate?: (value: T) => boolean): Stream; - skipDuplicates(comparator?: (a: T, b: T) => boolean): Stream; - diff(fn?: (prev: T, next: T) => T, seed?: T): Stream; - scan(fn: (prev: T | W, next: T) => W): Stream; - scan(fn: (prev: W, next: T) => W, seed: W): Stream; - delay(wait: number): Stream; - throttle(wait: number, options?: { leading?: boolean, trailing?: boolean }): Stream; - debounce(wait: number, options?: { immediate: boolean }): Stream; - valuesToErrors(): Stream; - valuesToErrors(handler: (value: T) => { convert: boolean, error: U }): Stream; - errorsToValues(handler?: (error: S) => { convert: boolean, value: U }): Stream; - mapErrors(fn: (error: S) => U): Stream; - filterErrors(predicate?: (error: S) => boolean): Stream; - endOnError(): Stream; - takeErrors(n: number): Stream; - ignoreValues(): Stream; - ignoreErrors(): Stream; - ignoreEnd(): Stream; - beforeEnd(fn: () => U): Stream; - slidingWindow(max: number, mix?: number): Stream; - bufferWhile(predicate: (value: T) => boolean): Stream; - bufferWithCount(count: number, options?: { flushOnEnd: boolean }): Stream; - bufferWithTimeOrCount(interval: number, count: number, options?: { flushOnEnd: boolean }): Stream; - transduce(transducer: any): Stream; - withHandler(handler: (emitter: Emitter, event: Event) => void): Stream; + map(fn: (value: T) => U): Observable; + filter(fn: (value: T) => value is U): Observable + filter(predicate?: (value: T) => boolean): Observable; + take(n: number): Observable; + takeWhile(predicate?: (value: T) => boolean): Observable; + last(): Observable; + skip(n: number): Observable; + skipWhile(predicate?: (value: T) => boolean): Observable; + skipDuplicates(comparator?: (a: T, b: T) => boolean): Observable; + diff(fn?: (prev: T, next: T) => T, seed?: T): Observable; + scan(fn: (prev: T | W, next: T) => W): Observable; + scan(fn: (prev: W, next: T) => W, seed: W): Observable; + delay(wait: number): Observable; + throttle(wait: number, options?: { leading?: boolean, trailing?: boolean }): Observable; + debounce(wait: number, options?: { immediate: boolean }): Observable; + valuesToErrors(): Observable; + valuesToErrors(handler: (value: T) => { convert: boolean, error: U }): Observable; + errorsToValues(handler?: (error: S) => { convert: boolean, value: U }): Observable; + mapErrors(fn: (error: S) => U): Observable; + filterErrors(predicate?: (error: S) => boolean): Observable; + endOnError(): Observable; + takeErrors(n: number): Observable; + ignoreValues(): Observable; + ignoreErrors(): Observable; + ignoreEnd(): Observable; + beforeEnd(fn: () => U): Observable; + slidingWindow(max: number, mix?: number): Observable; + bufferWhile(predicate: (value: T) => boolean): Observable; + bufferWithCount(count: number, options?: { flushOnEnd: boolean }): Observable; + bufferWithTimeOrCount(interval: number, count: number, options?: { flushOnEnd: boolean }): Observable; + transduce(transducer: any): Observable; + withHandler(handler: (emitter: Emitter, event: Event) => void): Observable; // Combine streams - combine(otherObs: Stream, combinator?: (value: T, ...values: U[]) => W): Stream; - zip(otherObs: Stream, combinator?: (value: T, ...values: U[]) => W): Stream; - merge(otherObs: Stream): Stream; - concat(otherObs: Stream): Stream; - flatMap(transform: (value: T) => Stream): Stream; - flatMap>(): Stream, any>; - flatMapLatest(fn: (value: T) => Stream): Stream; - flatMapLatest>(): Stream, any>; - flatMapFirst(fn: (value: T) => Stream): Stream; - flatMapFirst>(): Stream, any>; - flatMapConcat(fn: (value: T) => Stream): Stream; - flatMapConcat>(): Stream, any>; - flatMapConcurLimit(fn: (value: T) => Stream, limit: number): Stream; - flatMapErrors(transform: (error: S) => Stream): Stream; + combine(otherObs: Observable, combinator?: (value: T, ...values: U[]) => W): Observable; + zip(otherObs: Observable, combinator?: (value: T, ...values: U[]) => W): Observable; + merge(otherObs: Observable): Observable; + concat(otherObs: Observable): Observable; + flatMap(transform: (value: T) => Observable): Observable; + flatMap>(): Observable, any>; + flatMapLatest(fn: (value: T) => Observable): Observable; + flatMapLatest>(): Observable, any>; + flatMapFirst(fn: (value: T) => Observable): Observable; + flatMapFirst>(): Observable, any>; + flatMapConcat(fn: (value: T) => Observable): Observable; + flatMapConcat>(): Observable, any>; + flatMapConcurLimit(fn: (value: T) => Observable, limit: number): Observable; + flatMapErrors(transform: (error: S) => Observable): Observable; // Combine two streams - filterBy(otherObs: Observable): Stream; - sampledBy(otherObs: Observable, combinator?: (a: T, b: U) => W): Stream; - skipUntilBy(otherObs: Observable): Stream; - takeUntilBy(otherObs: Observable): Stream; - bufferBy(otherObs: Observable, options?: { flushOnEnd: boolean }): Stream; - bufferWhileBy(otherObs: Observable, options?: { flushOnEnd?: boolean, flushOnChange?: boolean }): Stream; - awaiting(otherObs: Observable): Stream; + filterBy(otherObs: Observable): Observable; + sampledBy(otherObs: Observable): Observable; + sampledBy(otherObs: Observable, combinator: (a: T, b: U) => W): Observable; + skipUntilBy(otherObs: Observable): Observable; + takeUntilBy(otherObs: Observable): Observable; + bufferBy(otherObs: Observable, options?: { flushOnEnd: boolean }): Observable; + bufferWhileBy(otherObs: Observable, options?: { flushOnEnd?: boolean, flushOnChange?: boolean }): Observable; + awaiting(otherObs: Observable): Observable; } -export interface Property extends Observable { - changes(): Stream; - // Modify an property - map(fn: (value: T) => U): Property; - filter(predicate?: (value: T) => boolean): Property; - take(n: number): Property; - takeWhile(predicate?: (value: T) => boolean): Property; - last(): Property; - skip(n: number): Property; - skipWhile(predicate?: (value: T) => boolean): Property; - skipDuplicates(comparator?: (a: T, b: T) => boolean): Property; - diff(fn?: (prev: T, next: T) => T, seed?: T): Property; - scan(fn: (prev: T, next: T) => T, seed?: T): Property; - delay(wait: number): Property; - throttle(wait: number, options?: { leading?: boolean, trailing?: boolean }): Property; - debounce(wait: number, options?: { immediate: boolean }): Property; - valuesToErrors(handler?: (value: T) => { convert: boolean, error: U }): Property; - errorsToValues(handler?: (error: S) => { convert: boolean, value: U }): Property; - mapErrors(fn: (error: S) => U): Property; - filterErrors(predicate?: (error: S) => boolean): Property; - endOnError(): Property; - takeErrors(n: number): Stream; - ignoreValues(): Property; - ignoreErrors(): Property; - ignoreEnd(): Property; - beforeEnd(fn: () => U): Property; - slidingWindow(max: number, mix?: number): Property; - bufferWhile(predicate: (value: T) => boolean): Property; - bufferWithCount(count: number, options?: { flushOnEnd: boolean }): Property; - bufferWithTimeOrCount(interval: number, count: number, options?: { flushOnEnd: boolean }): Property; - transduce(transducer: any): Property; - withHandler(handler: (emitter: Emitter, event: Event) => void): Property; - // Combine properties - combine(otherObs: Property, combinator?: (value: T, ...values: U[]) => W): Property; - zip(otherObs: Property, combinator?: (value: T, ...values: U[]) => W): Property; - merge(otherObs: Property): Property; - concat(otherObs: Property): Property; - flatMap(transform: (value: T) => Property): Property; - flatMap>(): Property, any>; - flatMapLatest(fn: (value: T) => Property): Property; - flatMapLatest>(): Property, any>; - flatMapFirst(fn: (value: T) => Property): Property; - flatMapFirst>(): Property, any>; - flatMapConcat(fn: (value: T) => Property): Property; - flatMapConcurLimit(fn: (value: T) => Property, limit: number): Property; - flatMapErrors(transform: (error: S) => Property): Property; - // Combine two properties - filterBy(otherObs: Observable): Property; - sampledBy(otherObs: Observable, combinator?: (a: T, b: U) => W): Property; - skipUntilBy(otherObs: Observable): Property; - takeUntilBy(otherObs: Observable): Property; - bufferBy(otherObs: Observable, options?: { flushOnEnd: boolean }): Property; - bufferWhileBy(otherObs: Observable, options?: { flushOnEnd?: boolean, flushOnChange?: boolean }): Property; - awaiting(otherObs: Observable): Property; +export class Stream extends Observable { + } -export interface ObservablePool extends Observable { +export class Property extends Observable { + +} + +export class Pool extends Observable { plug(obs: Observable): this; - unPlug(obs: Observable): this; + unplug(obs: Observable): this; } -export interface Event { - type: string; - value: T; -} +export type Event = + { type: 'value', value: V } | + { type: 'error', value: E } | + { type: 'end', value: void }; -export interface Emitter { - emit(value: T): void; - error(error: S): void; +export interface Emitter { + value(value: V): boolean; + event(event: Event): boolean; + error(e: E): boolean; end(): void; - emitEvent(event: { type: string, value: T | S }): void; + + // Deprecated methods + emit(value: V): boolean; + emitEvent(event: Event): boolean; } // Create a stream -export declare function never(): Stream; -export declare function later(wait: number, value: T): Stream; -export declare function interval(interval: number, value: T): Stream; -export declare function sequentially(interval: number, values: T[]): Stream; -export declare function fromPoll(interval: number, fn: () => T): Stream; -export declare function withInterval(interval: number, handler: (emitter: Emitter) => void): Stream; -export declare function fromCallback(fn: (callback: (value: T) => void) => void): Stream; -export declare function fromNodeCallback(fn: (callback: (error: S, result: T) => void) => void): Stream; -export declare function fromEvents(target: EventTarget | NodeJS.EventEmitter | { on: Function, off: Function }, eventName: string, transform?: (value: T) => S): Stream; -export declare function stream(subscribe: (emitter: Emitter) => Function | void): Stream; -export declare function fromESObservable(observable: any): Stream +export function never(): Stream; +export function later(wait: number, value: T): Stream; +export function interval(interval: number, value: T): Stream; +export function sequentially(interval: number, values: T[]): Stream; +export function fromPoll(interval: number, fn: () => T): Stream; +export function withInterval(interval: number, handler: (emitter: Emitter) => void): Stream; +export function fromCallback(fn: (callback: (value: T) => void) => void): Stream; +export function fromNodeCallback(fn: (callback: (error: S, result: T) => void) => void): Stream; +export function fromEvents(target: EventTarget | NodeJS.EventEmitter | { on: Function, off: Function }, eventName: string, transform?: (value: T) => S): Stream; +export function stream(subscribe: (emitter: Emitter) => Function | void): Stream; +export function fromESObservable(observable: any): Stream // Create a property -export declare function constant(value: T): Property; -export declare function constantError(error: T): Property; -export declare function fromPromise(promise: Promise): Property; +export function constant(value: T): Property; +export function constantError(error: T): Property; +export function fromPromise(promise: Promise): Property; // Combine observables -export declare function combine(obss: Observable[], passiveObss: Observable[], combinator?: (...values: T[]) => U): Stream; -export declare function combine(obss: Observable[], combinator: (...values: T[]) => U): Stream; -export declare function combine }>(obss: T): Stream<{ [P in keyof T]: ValueOfAnObservable }, any>; -export declare function combine], P extends keyof T>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable], any>; -export declare function combine]>(obss: T): Stream<[ValueOfAnObservable], any>; -export declare function combine(obss: T): Stream; -export declare function zip(obss: Observable[], passiveObss?: Observable[], combinator?: (...values: T[]) => U): Observable; -export declare function merge(obss: Observable[]): Observable; -export declare function concat(obss: Observable[]): Observable; -export declare function pool(): ObservablePool; -export declare function repeat(generator: (i: number) => Observable | boolean): Observable; +export function combine(obss: Observable[], passiveObss: Observable[], combinator?: (...values: T[]) => U): Stream; +export function combine(obss: Observable[], combinator: (...values: T[]) => U): Stream; +export function combine }>(obss: T): Stream<{ [P in keyof T]: ValueOfAnObservable }, any>; +export function combine], P extends keyof T>(obss: T): Stream<[ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine, Observable]>(obss: T): Stream<[ValueOfAnObservable, ValueOfAnObservable], any>; +export function combine]>(obss: T): Stream<[ValueOfAnObservable], any>; +export function combine(obss: T): Stream; +export function combine], P extends [Observable], K>(obss: T, obssP: P, combinator: (a: T[0][''], b: P[0]['']) => K): Observable; +export function zip(obss: Observable[], passiveObss?: Observable[], combinator?: (...values: T[]) => U): Observable; +export function merge(obss: Observable[]): Observable; +export function concat(obss: Observable[]): Observable; +export function pool(): Pool; +export function repeat(generator: (i: number) => Observable | boolean): Observable; + +export var staticLand: { + Observable: { + ap(obsF: Observable<(x: A) => B, E1>, obsV: Observable): Observable; + bimap(fnE: (x: E1) => E2, fnV: (x: V1) => V2, obs: Observable): Observable; + chain(cb: (value: V) => Observable, s: Observable): Observable; + concat(obs1: Observable, obs2: Observable): Observable; + empty(): Observable; + map(cb: (value: V) => V2, s: Observable): Observable; + of(value: V): Observable; + } +} + +declare var kefir: { + Observable: typeof Observable; + Pool: typeof Pool; + Stream: typeof Stream; + Property: typeof Property; + + never: typeof never, + later: typeof later, + interval: typeof interval, + sequentially: typeof sequentially, + fromPoll: typeof fromPoll, + withInterval: typeof withInterval, + fromCallback: typeof fromCallback, + fromNodeCallback: typeof fromNodeCallback, + fromEvents: typeof fromEvents, + stream: typeof stream, + fromESObservable: typeof fromESObservable, + constant: typeof constant, + constantError: typeof constantError, + fromPromise: typeof fromPromise, + combine: typeof combine, + zip: typeof zip, + merge: typeof merge, + concat: typeof concat, + pool: typeof pool, + repeat: typeof repeat, + + staticLand: typeof staticLand +}; + +export default kefir; diff --git a/types/kefir/kefir-tests.ts b/types/kefir/kefir-tests.ts index d2dbd5835e..0fba9c5d21 100644 --- a/types/kefir/kefir-tests.ts +++ b/types/kefir/kefir-tests.ts @@ -1,6 +1,6 @@ import * as Kefir from 'kefir'; -import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'kefir'; +import { Observable, Pool, Stream, Property, Event, Emitter } from 'kefir'; //Create a stream { @@ -130,7 +130,7 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke var myTransducer: any; let observable28: Stream = Kefir.sequentially(100, [1, 2, 3, 4, 5, 6]).transduce(myTransducer); } - let observable28: Stream = Kefir.sequentially(100, [0, 1, 2, 3]).withHandler((emitter: Emitter, event: Event) => { + let observable28: Stream = Kefir.sequentially(100, [0, 1, 2, 3]).withHandler((emitter: Emitter, event: Event) => { if (event.type === 'end') { emitter.emit('bye'); emitter.end(); @@ -141,6 +141,9 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke } } }); + type First = 'first'; + type Second = 'second'; + let observable32: Stream = Kefir.sequentially(100, ['first', 'second']).filter((value): value is First => value === 'first'); } // Combine observables @@ -177,7 +180,7 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke let a: Stream = Kefir.sequentially(100, [0, 1, 2]); let b: Stream = Kefir.sequentially(100, [0, 1, 2]).delay(30); let c: Observable = Kefir.sequentially(100, [0, 1, 2]).delay(60); - let pool: ObservablePool = Kefir.pool(); + let pool: Pool = Kefir.pool(); pool.plug(a); pool.plug(b); pool.plug(c); @@ -207,7 +210,7 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke { let a: Property = Kefir.sequentially(200, [2, 3]).toProperty(() => 1); let b: Stream = Kefir.interval(100, 0).delay(40).take(5); - let observable02: Property = a.sampledBy(b) + let observable02: Property = a.sampledBy(b) } { let foo: Stream = Kefir.sequentially(100, [1, 2, 3, 4]); diff --git a/types/kendo-ui/index.d.ts b/types/kendo-ui/index.d.ts index 819e28404d..7ea79365ee 100644 --- a/types/kendo-ui/index.d.ts +++ b/types/kendo-ui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kendo UI Professional v2018.3.911 +// Type definitions for Kendo UI Professional v2019.1.115 // Project: http://www.telerik.com/kendo-ui // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,7 @@ /* * Please, submit Pull Requests in the telerik/kendo-ui-core repo at * https://github.com/telerik/kendo-ui-core/tree/master/typescript - * + * * See contributor instructions at * https://github.com/telerik/kendo-ui-core#how-to-contribute */ @@ -919,14 +919,13 @@ declare namespace kendo.data { } interface DataSourceTransport { - create?: DataSourceTransportCreate | ((options: DataSourceTransportOptions) => void); - destroy?: DataSourceTransportDestroy | ((options: DataSourceTransportOptions) => void); + create?: string | DataSourceTransportCreate | ((options: DataSourceTransportOptions) => void); + destroy?: string | DataSourceTransportDestroy | ((options: DataSourceTransportOptions) => void); push?: Function; submit?: Function; - read?: DataSourceTransportRead | ((options: DataSourceTransportOptions) => void); + read?: string | DataSourceTransportRead | ((options: DataSourceTransportOptions) => void); signalr?: DataSourceTransportSignalr | ((options: DataSourceTransportOptions) => void); - update?: DataSourceTransportUpdate | ((options: DataSourceTransportOptions) => void); - + update?: string | DataSourceTransportUpdate | ((options: DataSourceTransportOptions) => void); parameterMap?(data: DataSourceTransportParameterMapData, type: string): any; } @@ -1039,7 +1038,7 @@ declare namespace kendo.data { max?: any; minLength?: any; maxLength?: any; - [rule: string]: any; + [rule: string]: any; } class ObservableArray extends Observable { @@ -1124,6 +1123,7 @@ declare namespace kendo.data { query(options?: any): JQueryPromise; read(data?: any): JQueryPromise; remove(model: kendo.data.ObservableObject): void; + skip(): number; sort(sort: DataSourceSortItem): void; sort(sort: DataSourceSortItem[]): void; sort(): DataSourceSortItem[]; @@ -1301,7 +1301,7 @@ declare namespace kendo.data { type?: string; change? (e: DataSourceChangeEvent): void; error?(e: DataSourceErrorEvent): void; - push?(e: DataSourcePushEvent): void; + push?(e: DataSourcePushEvent): void; sync?(e: DataSourceEvent): void; requestStart?(e: DataSourceRequestStartEvent): void; requestEnd?(e: DataSourceRequestEndEvent): void; @@ -1331,9 +1331,9 @@ declare namespace kendo.data { node?: any; } - interface DataSourcePushEvent extends DataSourceEvent { + interface DataSourcePushEvent extends DataSourceEvent { items?: DataSourceItemOrGroup[]; - type?: string; + type?: string; } @@ -1550,7 +1550,7 @@ declare namespace kendo.mobile { statusBarStyle?: string; transition?: string; useNativeScrolling?: boolean; - init?(e: ApplicationEvent): void; + init?(e: ApplicationEvent): void; } interface ApplicationEvent { @@ -1819,6 +1819,7 @@ declare namespace kendo.ui { enable(enable: boolean): void; select(li: JQuery): void; select(li: number): void; + selectedIndices: Array; } @@ -2583,6 +2584,89 @@ declare namespace kendo.ui { interface DatePickerOpenEvent extends DatePickerEvent { } + class DateRangePicker extends kendo.ui.Widget { + + static fn: DateRangePicker; + + options: DateRangePickerOptions; + + + element: JQuery; + wrapper: JQuery; + + static extend(proto: Object): DateRangePicker; + + constructor(element: Element, options?: DateRangePickerOptions); + + + close(): void; + destroy(): void; + enable(enable: boolean): void; + readonly(readonly: boolean): void; + max(): Date; + max(value: Date): void; + max(value: string): void; + min(): Date; + min(value: Date): void; + min(value: string): void; + open(): void; + range(): any; + range(range: DateRangePickerRange): void; + setOptions(options: any): void; + + } + + interface DateRangePickerMessages { + startLabel?: string; + endLabel?: string; + } + + interface DateRangePickerMonth { + content?: string; + weekNumber?: string; + empty?: string; + } + + interface DateRangePickerRange { + start?: Date; + end?: Date; + } + + interface DateRangePickerOptions { + name?: string; + ARIATemplate?: string; + culture?: string; + dates?: any; + depth?: string; + disableDates?: any|Function; + footer?: string|Function; + format?: string; + max?: Date; + messages?: DateRangePickerMessages; + min?: Date; + month?: DateRangePickerMonth; + labels?: boolean; + weekNumber?: boolean; + range?: DateRangePickerRange; + start?: string; + change?(e: DateRangePickerChangeEvent): void; + close?(e: DateRangePickerCloseEvent): void; + open?(e: DateRangePickerOpenEvent): void; + } + interface DateRangePickerEvent { + sender: DateRangePicker; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + interface DateRangePickerChangeEvent extends DateRangePickerEvent { + } + + interface DateRangePickerCloseEvent extends DateRangePickerEvent { + } + + interface DateRangePickerOpenEvent extends DateRangePickerEvent { + } class DateTimePicker extends kendo.ui.Widget { @@ -2734,6 +2818,10 @@ declare namespace kendo.ui { promptInput?: string; } + interface DialogModal { + preventScroll?: string; + } + interface DialogOptions { name?: string; actions?: DialogAction[]; @@ -2747,10 +2835,11 @@ declare namespace kendo.ui { messages?: DialogMessages; minHeight?: number; minWidth?: number; - modal?: boolean; + modal?: boolean | DialogModal; title?: string|boolean; visible?: boolean; width?: number|string; + size?: string; close?(e: DialogCloseEvent): void; hide?(e: DialogEvent): void; initOpen?(e: DialogEvent): void; @@ -3429,6 +3518,7 @@ declare namespace kendo.ui { interface EditorOptions { name?: string; + placeholder?: string; deserialization?: EditorDeserialization; domain?: string; encoded?: boolean; @@ -4104,6 +4194,11 @@ declare namespace kendo.ui { ui?: string|Function; } + interface GridColumnGroupable { + compare?: Function; + dir?: string; + } + interface GridColumnSortable { allowUnsort?: boolean; compare?: Function; @@ -4122,7 +4217,7 @@ declare namespace kendo.ui { footerAttributes?: any; footerTemplate?: string|Function; format?: string; - groupable?: boolean; + groupable?: boolean | GridColumnGroupable; groupHeaderColumnTemplate?: string|Function; groupHeaderTemplate?: string|Function; groupFooterTemplate?: string|Function; @@ -4245,6 +4340,8 @@ declare namespace kendo.ui { enabled?: boolean; showFooter?: boolean; messages?: GridGroupableMessages; + compare?: Function; + dir?: string; } interface GridMessagesCommands { @@ -4370,7 +4467,7 @@ declare namespace kendo.ui { scrollable?: boolean | GridScrollable; selectable?: boolean|string; sortable?: boolean | GridSortable; - toolbar?: GridToolbarItem[]; + toolbar?: (string|GridToolbarItem)[]; beforeEdit?(e: GridBeforeEditEvent): void; cancel?(e: GridCancelEvent): void; cellClose?(e: GridCellCloseEvent): void; @@ -4404,6 +4501,7 @@ declare namespace kendo.ui { saveChanges?(e: GridSaveChangesEvent): void; sort?(e: GridSortEvent): void; } + interface GridEvent { sender: Grid; preventDefault: Function; @@ -5291,6 +5389,89 @@ declare namespace kendo.ui { item?: JQuery; } + class MultiViewCalendar extends kendo.ui.Widget { + + static fn: MultiViewCalendar; + + options: MultiViewCalendarOptions; + + + element: JQuery; + wrapper: JQuery; + + static extend(proto: Object): MultiViewCalendar; + + constructor(element: Element, options?: MultiViewCalendarOptions); + + + current(): Date; + destroy(): void; + max(): Date; + max(value: Date): void; + max(value: string): void; + min(): Date; + min(value: Date): void; + min(value: string): void; + navigate(value: Date, view: string): void; + navigateDown(value: Date): void; + navigateToFuture(): void; + navigateToPast(): void; + navigateUp(): void; + selectDates(): any; + selectDates(dates: any): void; + selectRange(): any; + selectRange(range: any): void; + value(): Date; + value(value: Date): void; + value(value: string): void; + view(): any; + + } + + interface MultiViewCalendarMessages { + weekColumnHeader?: string; + } + + interface MultiViewCalendarMonth { + content?: string; + weekNumber?: string; + empty?: string; + } + + interface MultiViewCalendarRange { + start?: Date; + end?: Date; + } + + interface MultiViewCalendarOptions { + name?: string; + culture?: string; + dates?: any; + depth?: string; + disableDates?: any|Function; + footer?: string|Function; + format?: string; + max?: Date; + messages?: MultiViewCalendarMessages; + min?: Date; + month?: MultiViewCalendarMonth; + views?: number; + range?: MultiViewCalendarRange; + selectable?: string; + selectDates?: any; + showViewHeader?: boolean; + weekNumber?: boolean; + start?: string; + value?: Date; + change?(e: MultiViewCalendarEvent): void; + navigate?(e: MultiViewCalendarEvent): void; + } + + interface MultiViewCalendarEvent { + sender: MultiViewCalendar; + preventDefault: Function; + isDefaultPrevented(): boolean; + } class Notification extends kendo.ui.Widget { @@ -6581,6 +6762,65 @@ declare namespace kendo.ui { event?: kendo.data.SchedulerEvent; } + class ScrollView extends kendo.ui.Widget { + + static fn: ScrollView; + + options: ScrollViewOptions; + + dataSource: kendo.data.DataSource; + + element: JQuery; + wrapper: JQuery; + + static extend(proto: Object): ScrollView; + + constructor(element: Element, options?: ScrollViewOptions); + + + content(content: string): void; + content(content: JQuery): void; + destroy(): void; + next(): void; + prev(): void; + refresh(): void; + scrollTo(page: number, instant: boolean): void; + setDataSource(dataSource: kendo.data.DataSource): void; + + } + + interface ScrollViewOptions { + name?: string; + autoBind?: boolean; + bounceVelocityThreshold?: number; + contentHeight?: number|string; + dataSource?: kendo.data.DataSource|any; + duration?: number; + emptyTemplate?: string; + enablePager?: boolean; + page?: number; + template?: string; + velocityThreshold?: number; + change?(e: ScrollViewChangeEvent): void; + refresh?(e: ScrollViewRefreshEvent): void; + } + interface ScrollViewEvent { + sender: ScrollView; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + interface ScrollViewChangeEvent extends ScrollViewEvent { + currentPage?: number; + nextPage?: number; + element?: JQuery; + data?: any; + } + + interface ScrollViewRefreshEvent extends ScrollViewEvent { + pageCount?: number; + page?: number; + } class Slider extends kendo.ui.Widget { @@ -7180,6 +7420,52 @@ declare namespace kendo.ui { } + class Switch extends kendo.ui.Widget { + + static fn: Switch; + + options: SwitchOptions; + + + element: JQuery; + wrapper: JQuery; + + static extend(proto: Object): Switch; + + constructor(element: Element, options?: SwitchOptions); + + check(): boolean; + check(check: boolean): void; + destroy(): void; + enable(enable: boolean): void; + toggle(): void; + setOptions(options: any): void; + } + + interface SwitchOptions { + name?: string; + checked?: boolean; + enabled?: boolean; + readonly?: boolean; + width?: number|string; + change?(e: SwitchChangeEvent): void; + } + + interface SwitchMessages { + checked?: string; + unchecked?: string; + } + + interface SwitchEvent { + sender: Switch; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + interface SwitchChangeEvent extends SwitchEvent { + checked?: any; + } + class TabStrip extends kendo.ui.Widget { static fn: TabStrip; @@ -8652,6 +8938,10 @@ declare namespace kendo.ui { left?: number|string; } + interface WindowModal { + preventScroll?: boolean; + } + interface WindowRefreshOptions { url?: string; cache?: boolean; @@ -8661,6 +8951,12 @@ declare namespace kendo.ui { iframe?: boolean; } + interface WindowDraggable { + containment?: any|string; + dragHandle?: any|string; + axis?: string; + } + interface WindowOptions { name?: string; actions?: any; @@ -8668,14 +8964,14 @@ declare namespace kendo.ui { appendTo?: any|string; autoFocus?: boolean; content?: string | WindowContent; - draggable?: boolean; + draggable?: boolean | WindowDraggable; iframe?: boolean; height?: number|string; maxHeight?: number; maxWidth?: number; minHeight?: number; minWidth?: number; - modal?: boolean; + modal?: boolean | WindowModal; pinned?: boolean; position?: WindowPosition; resizable?: boolean; @@ -8683,6 +8979,7 @@ declare namespace kendo.ui { title?: string|boolean; visible?: boolean; width?: number|string; + size?: string; activate?(e: WindowEvent): void; close?(e: WindowCloseEvent): void; deactivate?(e: WindowEvent): void; @@ -9350,16 +9647,15 @@ declare namespace kendo.drawing { class Surface extends kendo.Observable { - - options: SurfaceOptions; - constructor(options?: SurfaceOptions); static create(element: JQuery, options?: any): kendo.drawing.Surface; static create(element: Element, options?: any): kendo.drawing.Surface; + element: JQuery; + clear(): void; draw(element: kendo.drawing.Element): void; eventTarget(e: any): kendo.drawing.Element; @@ -18436,6 +18732,10 @@ declare namespace kendo { namespace date { + var MS_PER_DAY: number; + var MS_PER_HOUR: number; + var MS_PER_MINUTE: number; + function setDayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): void; function dayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): Date; function weekInYear(date: Date, weekStart?: number): number; @@ -18453,7 +18753,7 @@ declare namespace kendo { function toInvariantTime(targetDate: Date): Date; function firstDayOfMonth(targetDate: Date): Date; function lastDayOfMonth(targetDate: Date): Date; - function getMilliseconds(targetDate: Date): Date; + function getMilliseconds(targetDate: Date): number; } namespace drawing { @@ -20495,16 +20795,15 @@ declare namespace kendo.dataviz.drawing { class Surface extends kendo.Observable { - - options: SurfaceOptions; - constructor(options?: SurfaceOptions); static create(element: JQuery, options?: any): kendo.drawing.Surface; static create(element: Element, options?: any): kendo.drawing.Surface; + element: JQuery; + clear(): void; draw(element: kendo.drawing.Element): void; eventTarget(e: any): kendo.drawing.Element; @@ -20936,15 +21235,6 @@ interface JQueryPromise { interface JQuery { - kendoDraggable(): JQuery; - kendoDraggable(options: kendo.ui.DraggableOptions): JQuery; - - kendoDropTarget(): JQuery; - kendoDropTarget(options: kendo.ui.DropTargetOptions): JQuery; - - kendoDropTargetArea(): JQuery; - kendoDropTargetArea(options: kendo.ui.DropTargetAreaOptions): JQuery; - data(key: any): any; kendoAlert(): JQuery; @@ -21011,6 +21301,10 @@ interface JQuery { kendoDatePicker(options: kendo.ui.DatePickerOptions): JQuery; data(key: "kendoDatePicker"): kendo.ui.DatePicker; + kendoDateRangePicker(): JQuery; + kendoDateRangePicker(options: kendo.ui.DateRangePickerOptions): JQuery; + data(key: "kendoDateRangePicker"): kendo.ui.DateRangePicker; + kendoDateTimePicker(): JQuery; kendoDateTimePicker(options: kendo.ui.DateTimePickerOptions): JQuery; data(key: "kendoDateTimePicker"): kendo.ui.DateTimePicker; @@ -21023,6 +21317,10 @@ interface JQuery { kendoDialog(options: kendo.ui.DialogOptions): JQuery; data(key: "kendoDialog"): kendo.ui.Dialog; + kendoDraggable(): JQuery; + kendoDraggable(options: kendo.ui.DraggableOptions): JQuery; + data(key: "kendoDraggable"): kendo.ui.Draggable; + kendoDropDownList(): JQuery; kendoDropDownList(options: kendo.ui.DropDownListOptions): JQuery; data(key: "kendoDropDownList"): kendo.ui.DropDownList; @@ -21031,6 +21329,14 @@ interface JQuery { kendoDropDownTree(options: kendo.ui.DropDownTreeOptions): JQuery; data(key: "kendoDropDownTree"): kendo.ui.DropDownTree; + kendoDropTarget(): JQuery; + kendoDropTarget(options: kendo.ui.DropTargetOptions): JQuery; + data(key: "kendoDropTarget"): kendo.ui.DropTarget; + + kendoDropTargetArea(): JQuery; + kendoDropTargetArea(options: kendo.ui.DropTargetAreaOptions): JQuery; + data(key: "kendoDropTargetArea"): kendo.ui.DropTargetArea; + kendoEditor(): JQuery; kendoEditor(options: kendo.ui.EditorOptions): JQuery; data(key: "kendoEditor"): kendo.ui.Editor; @@ -21167,6 +21473,10 @@ interface JQuery { kendoMultiSelect(options: kendo.ui.MultiSelectOptions): JQuery; data(key: "kendoMultiSelect"): kendo.ui.MultiSelect; + kendoMultiViewCalendar(): JQuery; + kendoMultiViewCalendar(options: kendo.ui.MultiViewCalendarOptions): JQuery; + data(key: "kendoMultiViewCalendar"): kendo.ui.MultiViewCalendar; + kendoNotification(): JQuery; kendoNotification(options: kendo.ui.NotificationOptions): JQuery; data(key: "kendoNotification"): kendo.ui.Notification; @@ -21223,6 +21533,10 @@ interface JQuery { kendoScheduler(options: kendo.ui.SchedulerOptions): JQuery; data(key: "kendoScheduler"): kendo.ui.Scheduler; + kendoScrollView(): JQuery; + kendoScrollView(options: kendo.ui.ScrollViewOptions): JQuery; + data(key: "kendoScrollView"): kendo.ui.ScrollView; + kendoSlider(): JQuery; kendoSlider(options: kendo.ui.SliderOptions): JQuery; data(key: "kendoSlider"): kendo.ui.Slider; @@ -21247,6 +21561,10 @@ interface JQuery { kendoStockChart(options: kendo.dataviz.ui.StockChartOptions): JQuery; data(key: "kendoStockChart"): kendo.dataviz.ui.StockChart; + kendoSwitch(): JQuery; + kendoSwitch(options: kendo.ui.SwitchOptions): JQuery; + data(key: "kendoSwitch"): kendo.ui.Switch; + kendoTabStrip(): JQuery; kendoTabStrip(options: kendo.ui.TabStripOptions): JQuery; data(key: "kendoTabStrip"): kendo.ui.TabStrip; diff --git a/types/koa-bouncer/index.d.ts b/types/koa-bouncer/index.d.ts index 7b881f2b5c..af3a8b6693 100644 --- a/types/koa-bouncer/index.d.ts +++ b/types/koa-bouncer/index.d.ts @@ -7,7 +7,7 @@ import { Middleware, Context } from 'koa'; declare namespace KoaBouncer { - export class ValidatorError extends Error { + export class ValidationError extends Error { name: string; message: string; bouncer: { @@ -88,4 +88,4 @@ declare module "koa" { } } -export = KoaBouncer; \ No newline at end of file +export = KoaBouncer; diff --git a/types/koa-bunyan-logger/index.d.ts b/types/koa-bunyan-logger/index.d.ts index 1cf77fec92..ab201bfc27 100644 --- a/types/koa-bunyan-logger/index.d.ts +++ b/types/koa-bunyan-logger/index.d.ts @@ -1,17 +1,47 @@ -// Type definitions for koa-bunyan-logger 2.0 +// Type definitions for koa-bunyan-logger 2.1 // Project: https://github.com/koajs/bunyan-logger // Definitions by: Steven McDowall +// Jan Karlo Dela Cruz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { Middleware } from 'koa'; +import { Middleware, Request, Response } from 'koa'; import Logger = require('bunyan'); -export = koaBunyanLogger; - declare function koaBunyanLogger(logger?: Logger): Middleware; +declare namespace koaBunyanLogger { + interface RequestData { + req: Request; + } + + interface ResponseData { + req: Request; + res: Response; + } + + interface RequestIdContextOptions { + header?: string; + prop?: string; + requestProp?: string; + field?: string; + } + + interface RequestLoggerOptions { + durationField?: string; + levelFn?: (status: number, err: Error) => string; + updateLogFields?: (data: RequestData) => RequestData; + updateRequestLogFields?: (requestData: RequestData) => RequestData; + updateResponseLogFields?: (responseData: ResponseData) => ResponseData; + formatRequestMessage?: (requestData: RequestData) => string; + formatResponseMessage?: (responseData: ResponseData) => string; + } + + function requestLogger(opts?: RequestLoggerOptions): Middleware; + function requestIdContext(opts?: RequestIdContextOptions): Middleware; +} + // Extend the Koa context to add the logger.. declare module 'koa' { // tslint:disable-next-line: interface-name @@ -19,3 +49,5 @@ declare module 'koa' { log: Logger; } } + +export = koaBunyanLogger; diff --git a/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts b/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts index daaf26b7a3..3d66a72a13 100644 --- a/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts +++ b/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts @@ -3,6 +3,8 @@ import koaBunyanLogger = require('koa-bunyan-logger'); const app = new Koa(); app.use(koaBunyanLogger()); +app.use(koaBunyanLogger.requestIdContext()); +app.use(koaBunyanLogger.requestLogger()); app.use(async (ctx, next) => { ctx.log.info('Got a request from %s for %s', ctx.request.ip, ctx.path); diff --git a/types/koa-pino-logger/index.d.ts b/types/koa-pino-logger/index.d.ts index 24f59b8925..04eea930ce 100644 --- a/types/koa-pino-logger/index.d.ts +++ b/types/koa-pino-logger/index.d.ts @@ -7,25 +7,18 @@ /// import { Middleware } from 'koa'; -import { LoggerOptions, Logger, Level } from 'pino'; +import { DestinationStream, LoggerOptions, Logger, Level } from 'pino'; +import { Options } from 'pino-http'; import * as stream from 'stream'; import * as http from 'http'; export = logger; declare function logger( - opts?: logger.HttpLoggerOptions, - stream?: stream.Writable | stream.Duplex | stream.Transform + opts?: Options, + stream?: DestinationStream ): Middleware; - -declare namespace logger { - interface HttpLoggerOptions extends LoggerOptions { - logger?: Logger; - genReqId?(req: http.IncomingMessage): number; - useLevel?: Level; - stream?: stream.Writable | stream.Duplex | stream.Transform; - } -} +declare function logger(stream?: DestinationStream): Middleware; declare module 'koa' { interface Context { diff --git a/types/koa-pino-logger/koa-pino-logger-tests.ts b/types/koa-pino-logger/koa-pino-logger-tests.ts index 5315ee5baa..e5b6514884 100644 --- a/types/koa-pino-logger/koa-pino-logger-tests.ts +++ b/types/koa-pino-logger/koa-pino-logger-tests.ts @@ -1,8 +1,12 @@ import koa = require('koa'); import logger = require('koa-pino-logger'); +import { Writable } from 'stream'; const app = new koa(); app.use(logger()); +app.use(logger(new Writable())); +app.use(logger({stream: new Writable()})); +app.use(logger({genReqId: () => 'foo'})); app.use((ctx) => { ctx.log.info('something else'); diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index b2163d09d1..4df53d0e8b 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -43,7 +43,7 @@ declare namespace Router { strict?: boolean; } - export interface IRouterContext extends Koa.Context { + export interface IRouterParamContext { /** * url params */ @@ -51,15 +51,26 @@ declare namespace Router { /** * the router instance */ - router: Router; + router: Router; + /** + * Matched route + */ + _matchedRoute: string | RegExp | undefined; + _matchedRouteName: string | undefined; } - export interface IMiddleware { - (ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise): any; - } + export type RouterContext = + Koa.ParameterizedContext>; + + // For backward compatibility IRouterContext needs to be an interface + // But it's deprecated - please use `RouterContext` instead + export interface IRouterContext extends RouterContext {} + + export type IMiddleware = + Koa.Middleware> export interface IParamMiddleware { - (param: string, ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise): any; + (param: string, ctx: RouterContext, next: () => Promise): any; } export interface IRouterAllowedMethodsOptions { @@ -148,7 +159,7 @@ declare namespace Router { } } -declare class Router { +declare class Router { params: Object; stack: Array; @@ -164,109 +175,195 @@ declare class Router { * sequentially, requests start at the first middleware and work their way * "down" the middleware stack. */ - use(...middleware: Array): Router; - use(path: string | string[] | RegExp, ...middleware: Array): Router; + use(...middleware: Array>): Router; + use( + path: string | string[] | RegExp, + ...middleware: Array> + ): Router; /** * HTTP get method */ - get(name: string, path: string | RegExp, ...middleware: Array): Router; - get(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + get( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + get( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP post method */ - post(name: string, path: string | RegExp, ...middleware: Array): Router; - post(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + post( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + post( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP put method */ - put(name: string, path: string | RegExp, ...middleware: Array): Router; - put(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + put( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + put( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP link method */ - link(name: string, path: string | RegExp, ...middleware: Array): Router; - link(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + link( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + link( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP unlink method */ - unlink(name: string, path: string | RegExp, ...middleware: Array): Router; - unlink(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; - + unlink( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + unlink( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP delete method */ - delete(name: string, path: string | RegExp, ...middleware: Array): Router; - delete(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + delete( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + delete( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * Alias for `router.delete()` because delete is a reserved word */ - del(name: string, path: string | RegExp, ...middleware: Array): Router; - del(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + del( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + del( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP head method */ - head(name: string, path: string | RegExp, ...middleware: Array): Router; - head(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + head( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + head( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP options method */ - options(name: string, path: string | RegExp, ...middleware: Array): Router; - options(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + options( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + options( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * HTTP path method */ - patch(name: string, path: string | RegExp, ...middleware: Array): Router; - patch(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + patch( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + patch( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * Register route with all methods. */ - all(name: string, path: string | RegExp, ...middleware: Array): Router; - all(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; + all( + name: string, + path: string | RegExp, + ...middleware: Array> + ): Router; + all( + path: string | RegExp | (string | RegExp)[], + ...middleware: Array> + ): Router; /** * Set the path prefix for a Router instance that was already initialized. */ - prefix(prefix: string): Router; + prefix(prefix: string): Router; /** * Returns router middleware which dispatches a route matching the request. */ - routes(): Koa.Middleware; + routes(): Router.IMiddleware; /** * Returns router middleware which dispatches a route matching the request. */ - middleware(): Koa.Middleware; + middleware(): Router.IMiddleware; /** * Returns separate middleware for responding to `OPTIONS` requests with * an `Allow` header containing the allowed methods, as well as responding * with `405 Method Not Allowed` and `501 Not Implemented` as appropriate. */ - allowedMethods(options?: Router.IRouterAllowedMethodsOptions): Koa.Middleware; + allowedMethods( + options?: Router.IRouterAllowedMethodsOptions + ): Router.IMiddleware; /** * Redirect `source` to `destination` URL with optional 30x status `code`. * * Both `source` and `destination` can be route names. */ - redirect(source: string, destination: string, code?: number): Router; + redirect(source: string, destination: string, code?: number): Router; /** * Create and register a route. */ - register(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Object): Router.Layer; + register( + path: string | RegExp, + methods: string[], + middleware: Router.IMiddleware, + opts?: Object + ): Router.Layer; /** * Lookup route with given `name`. @@ -304,7 +401,7 @@ declare class Router { /** * Run middleware for named route parameters. Useful for auto-loading or validation. */ - param(param: string, middleware: Router.IParamMiddleware): Router; + param(param: string, middleware: Router.IParamMiddleware): Router; /** * Generate URL from url pattern and given `params`. diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index 50e66509ea..96fa0d1751 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -1,9 +1,15 @@ import Koa = require("koa"); +import { Context } from "koa"; +import compose = require("koa-compose"); +import etag = require("koa-etag"); import Router = require("koa-router"); +type MyState = {foo: string} +type MyContext = {bar: string} + const app = new Koa<{}, {}>(); -const router = new Router({ +const router = new Router({ prefix: "/users" }); @@ -31,9 +37,10 @@ router } }) .post('/users', function (ctx, next) { - // ... + ctx.state.foo = 'foo'; }) .put('/users/:id', function (ctx, next) { + ctx.bar = 'bar'; ctx.body = ctx.params.id; }) .del('/users/:id', function () { @@ -49,11 +56,72 @@ const match = router.match('/users/:id', 'GET'); let layer: Router.Layer let layerOptions: Router.ILayerOptions -const mw: Router.IMiddleware = (ctx: Router.IRouterContext, next: () => Promise) => { +const mw: Router.IMiddleware = (ctx: Koa.ParameterizedContext, next: () => Promise) => { ctx.body = "Ok"; }; -app.use(router.routes()); -app.use(router.allowedMethods()); +const mw2: Router.IMiddleware = (ctx: Router.IRouterContext, next: () => Promise) => { + ctx.body = "Ok"; +}; -app.listen(3000); +app.use(async (ctx: Koa.ParameterizedContext, next) => { + ctx.state.foo = 'foo'; + await next(); + }) + .use(router.routes()) + .use(router.allowedMethods()) + .use(async (ctx, next) => { + ctx.state.foo = '3'; + await next(); + }) + .listen(3000); + +const router3 = new Router(); +router3.get('/', (ctx) => { + ctx.foo = "bar"; + console.log(ctx.router.params); + ctx.body = "Hello World!"; +}); +router3.get('/foo', (ctx: Router.IRouterContext) => { + ctx.body = "Yup"; +}) +new Koa() + .use(async (ctx, next) => next()) + .use(router3.routes()) + .use(router.allowedMethods()) + .listen(3001); + +// It's from https://github.com/DefinitelyTyped/DefinitelyTyped/pull/31704#issuecomment-451075919, +// to make sure we don't break it again + +declare module "koa" { + interface Context { + name: string; + } +} + +const app2 = new Koa(); + +const conditional = async (ctx: Context, next: any) => { + await next(); + if (ctx.fresh) { + ctx.status = 304; + ctx.body = null; + } +}; + +const router2 = compose([conditional, etag()]); + +app2.use(router2); + +app2.use(async (ctx: Context, next: any) => { + ctx.name = "hello world"; + await next(); +}); + +app2.use((ctx: Context, next: any) => { + console.log(ctx.name); + ctx.body = ctx.name; +}); + +app2.listen(8000); diff --git a/types/koa-session/index.d.ts b/types/koa-session/index.d.ts index 08e6e66f70..512b888e1c 100644 --- a/types/koa-session/index.d.ts +++ b/types/koa-session/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for koa-session 5.7 +// Type definitions for koa-session 5.10 // Project: https://github.com/koajs/session // Definitions by: Yu Hsin Lu // Tomek Łaziuk +// Hiroshi Ioka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /* =================== USAGE =================== @@ -16,6 +17,9 @@ =============================================== */ import Koa = require("koa"); +import Cookies = require("cookies"); + +type Omit = Pick>; declare namespace session { /** @@ -108,7 +112,7 @@ declare namespace session { hash(sess: any): string; } - interface opts { + interface opts extends Omit { /** * cookie key (default is koa:sess) */ @@ -121,21 +125,6 @@ declare namespace session { */ maxAge?: number | "session"; - /** - * can overwrite or not (default true) - */ - overwrite: boolean; - - /** - * httpOnly or not (default true) - */ - httpOnly: boolean; - - /** - * signed or not (default true) - */ - signed: boolean; - /** * custom encode method */ diff --git a/types/koa-session/koa-session-tests.ts b/types/koa-session/koa-session-tests.ts index a647b43e42..4930a6f1c2 100644 --- a/types/koa-session/koa-session-tests.ts +++ b/types/koa-session/koa-session-tests.ts @@ -37,6 +37,7 @@ app.use(session({ console.log(key); }, }, + path: "/", }, app)); app.use((ctx, next) => { diff --git a/types/koa2-session-redis/index.d.ts b/types/koa2-session-redis/index.d.ts index 24e85e1674..049c655f5f 100644 --- a/types/koa2-session-redis/index.d.ts +++ b/types/koa2-session-redis/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/lonord/koa2-session-redis // Definitions by: Dima Mukhin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as Redis from 'redis'; import * as session from 'koa-session'; diff --git a/types/latest-semver/index.d.ts b/types/latest-semver/index.d.ts new file mode 100644 index 0000000000..761a487b88 --- /dev/null +++ b/types/latest-semver/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for latest-semver 1.0 +// Project: https://github.com/sindresorhus/latest-semver#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = latestSemver; + +declare function latestSemver(versions: string[]): string | undefined; diff --git a/types/latest-semver/latest-semver-tests.ts b/types/latest-semver/latest-semver-tests.ts new file mode 100644 index 0000000000..ec8312e467 --- /dev/null +++ b/types/latest-semver/latest-semver-tests.ts @@ -0,0 +1,4 @@ +import latestSemver = require('latest-semver'); + +// $ExpectType string | undefined +latestSemver(['v1.8.0-alpha.1', 'v1.3.16', 'v1.7.0', 'v1.6.9']); diff --git a/types/latest-semver/tsconfig.json b/types/latest-semver/tsconfig.json new file mode 100644 index 0000000000..54f1df51e2 --- /dev/null +++ b/types/latest-semver/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", + "latest-semver-tests.ts" + ] +} diff --git a/types/latest-semver/tslint.json b/types/latest-semver/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/latest-semver/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/latest-version/index.d.ts b/types/latest-version/index.d.ts new file mode 100644 index 0000000000..5127714c15 --- /dev/null +++ b/types/latest-version/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for latest-version 4.0 +// Project: https://github.com/sindresorhus/latest-version#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = latestVersion; + +declare function latestVersion(name: string, options?: latestVersion.Options): Promise; + +declare namespace latestVersion { + interface Options { + version?: string; + } +} diff --git a/types/latest-version/latest-version-tests.ts b/types/latest-version/latest-version-tests.ts new file mode 100644 index 0000000000..2cbd29b61f --- /dev/null +++ b/types/latest-version/latest-version-tests.ts @@ -0,0 +1,4 @@ +import latestVersion = require('latest-version'); + +latestVersion('ava'); // $ExpectType Promise +latestVersion('npm', { version: 'latest-5' }); // $ExpectType Promise diff --git a/types/latest-version/tsconfig.json b/types/latest-version/tsconfig.json new file mode 100644 index 0000000000..a62d14b69d --- /dev/null +++ b/types/latest-version/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", + "latest-version-tests.ts" + ] +} diff --git a/types/latest-version/tslint.json b/types/latest-version/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/latest-version/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 8177ba1aa6..22f71a9187 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for Leaflet.js 1.2 +// Type definitions for Leaflet.js 1.4 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Alejandro Sánchez // Arne Schubert // Michael Auer +// Roni Karilkar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -323,7 +324,7 @@ export abstract class Evented extends Class { * Note that if you passed a custom context to on, you must pass the same context * to off in order to remove the listener. */ - removeEventListener(type: string, fn: LeafletEventHandlerFn, context?: any): this; + removeEventListener(type: string, fn?: LeafletEventHandlerFn, context?: any): this; /** * Alias for off(...) @@ -579,6 +580,32 @@ export class ImageOverlay extends Layer { export function imageOverlay(imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions): ImageOverlay; +export interface VideoOverlayOptions extends ImageOverlayOptions { + autoplay?: boolean; + loop?: boolean; +} + +export class VideoOverlay extends Layer { /** VideoOverlay doesn't extend ImageOverlay because ImageOverlay.getElement returns HTMLImageElement */ + constructor(video: string | string[] | HTMLVideoElement, bounds: LatLngBoundsExpression, options?: VideoOverlayOptions); + setOpacity(opacity: number): this; + bringToFront(): this; + bringToBack(): this; + setUrl(url: string): this; + + /** Update the bounds that this VideoOverlay covers */ + setBounds(bounds: LatLngBounds): this; + + /** Get the bounds that this VideoOverlay covers */ + getBounds(): LatLngBounds; + + /** Get the video element that represents the VideoOverlay on the map */ + getElement(): HTMLVideoElement | undefined; + + options: VideoOverlayOptions; +} + +export function videoOverlay(video: string | string[] | HTMLVideoElement, bounds: LatLngBoundsExpression, options?: VideoOverlayOptions): VideoOverlay; + export type LineCapShape = 'butt' | 'round' | 'square' | 'inherit'; export type LineJoinShape = 'miter' | 'round' | 'bevel' | 'inherit'; @@ -1181,6 +1208,12 @@ export interface FitBoundsOptions extends ZoomOptions, PanOptions { maxZoom?: number; } +export interface PanInsideOptions { + paddingTopLeft?: PointExpression; + paddingBottomRight?: PointExpression; + padding?: PointExpression; +} + export interface LocateOptions { watch?: boolean; setView?: boolean; @@ -1355,6 +1388,7 @@ export class Map extends Evented { setMaxBounds(bounds: LatLngBoundsExpression): this; setMinZoom(zoom: number): this; setMaxZoom(zoom: number): this; + panInside(latLng: LatLngExpression, options?: PanInsideOptions): this; panInsideBounds(bounds: LatLngBoundsExpression, options?: PanOptions): this; /** * Boolean for animate or advanced ZoomPanOptions diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index 6debf6b0d6..8b024d790e 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -1,13 +1,13 @@ import * as L from 'leaflet'; -const latLngLiteral: L.LatLngLiteral = {lat: 12, lng: 13}; +const latLngLiteral: L.LatLngLiteral = { lat: 12, lng: 13 }; const latLngTuple: L.LatLngTuple = [12, 13]; let latLng: L.LatLng; latLng = L.latLng(12, 13); latLng = L.latLng(12, 13, 0); latLng = L.latLng(latLngLiteral); -latLng = L.latLng({lat: 12, lng: 13, alt: 0}); +latLng = L.latLng({ lat: 12, lng: 13, alt: 0 }); latLng = L.latLng(latLngTuple); latLng = L.latLng([12, 13, 0]); @@ -34,14 +34,14 @@ let point: L.Point; point = L.point(12, 13); point = L.point(12, 13, true); point = L.point(pointTuple); -point = L.point({x: 12, y: 13}); +point = L.point({ x: 12, y: 13 }); point = new L.Point(12, 13); point = new L.Point(12, 13, true); let distance: number; -point.distanceTo(point); -point.distanceTo(pointTuple); +distance = point.distanceTo(point); +distance = point.distanceTo(pointTuple); const transformation = new L.Transformation(1, 2, 3, 4); point = transformation.transform(point); @@ -163,6 +163,16 @@ map = new L.Map(htmlElement, mapOptions); let doesItHaveLayer: boolean; doesItHaveLayer = map.hasLayer(L.tileLayer('')); +map.off('moveend'); +map.off('moveend', () => {}); +map.off('moveend', () => {}, {}); + +map.removeEventListener('moveend'); +map.removeEventListener('moveend', () => {}); +map.removeEventListener('moveend', () => {}, {}); + +map.panInside(latLng, { padding: [50, 50], paddingBottomRight: point, paddingTopLeft: [100, 100] }); + // map.getRenderer let html: HTMLElement; @@ -208,25 +218,25 @@ mapPixelBounds = map.getPixelWorldBounds(12); let tileLayerOptions: L.TileLayerOptions = {}; tileLayerOptions = { - minZoom: 0, - maxZoom: 18, - maxNativeZoom: 2, - errorTileUrl: '', - zoomOffset: 0, - tms: true, - zoomReverse: true, - detectRetina: true, - crossOrigin: false, - opacity: 1, - updateWhenIdle: true, - updateWhenZooming: true, - updateInterval: 500, - attribution: '', - zIndex: 1, - noWrap: true, - pane: '', - className: '', - keepBuffer: 1, + minZoom: 0, + maxZoom: 18, + maxNativeZoom: 2, + errorTileUrl: '', + zoomOffset: 0, + tms: true, + zoomReverse: true, + detectRetina: true, + crossOrigin: false, + opacity: 1, + updateWhenIdle: true, + updateWhenZooming: true, + updateInterval: 500, + attribution: '', + zIndex: 1, + noWrap: true, + pane: '', + className: '', + keepBuffer: 1, }; tileLayerOptions.subdomains = 'a'; @@ -249,14 +259,14 @@ tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', tileLayer // imageOverlay let imageOverlayOptions: L.ImageOverlayOptions; imageOverlayOptions = { - opacity: 100, - alt: 'alt', - interactive: true, - attribution: 'attribution', - crossOrigin: true, - className: 'className', - bubblingMouseEvents: false, - pane: 'pane' + opacity: 100, + alt: 'alt', + interactive: true, + attribution: 'attribution', + crossOrigin: true, + className: 'className', + bubblingMouseEvents: false, + pane: 'pane' }; const imageOverlayBounds = latLngBounds; @@ -264,22 +274,42 @@ let imageOverlay: L.ImageOverlay; imageOverlay = L.imageOverlay('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png', imageOverlayBounds); imageOverlay = L.imageOverlay('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png', imageOverlayBounds, imageOverlayOptions); imageOverlay = L.imageOverlay('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png', imageOverlayBounds, { - opacity: 100, - alt: 'alt', - className: 'className', + opacity: 100, + alt: 'alt', + className: 'className', }); -const eventHandler = () => {}; +// videoOverlay +let videoOverlayOptions: L.VideoOverlayOptions; +videoOverlayOptions = { + interactive: true, + opacity: 100, + autoplay: true, + loop: false +}; + +const videoOverlayBounds = latLngBounds; +const videoOverlayUrls = ['https://www.mapbox.com/bites/00188/patricia_nasa.webm']; +const videoElement = document.createElement('video'); + +let videoOverlay: L.VideoOverlay; +videoOverlay = L.videoOverlay('https://www.mapbox.com/bites/00188/patricia_nasa.webm', videoOverlayBounds); +videoOverlay = L.videoOverlay(videoOverlayUrls, videoOverlayBounds, videoOverlayOptions); +videoOverlay = L.videoOverlay(videoElement, videoOverlayBounds, { + autoplay: true +}); + +const eventHandler = () => { }; const domEvent: Event = {} as Event; L.DomEvent .on(htmlElement, 'click', eventHandler) .addListener(htmlElement, 'click', eventHandler) .off(htmlElement, 'click', eventHandler) .removeListener(htmlElement, 'click', eventHandler) - .on(htmlElement, {click: eventHandler}) - .addListener(htmlElement, {click: eventHandler}) - .off(htmlElement, {click: eventHandler}, eventHandler) - .removeListener(htmlElement, {click: eventHandler}, eventHandler) + .on(htmlElement, { click: eventHandler }) + .addListener(htmlElement, { click: eventHandler }) + .off(htmlElement, { click: eventHandler }, eventHandler) + .removeListener(htmlElement, { click: eventHandler }, eventHandler) .stopPropagation(domEvent) .disableScrollPropagation(htmlElement) .disableClickPropagation(htmlElement) @@ -405,13 +435,13 @@ let threeCoords: [number, number, number] = [1, 2, 3]; latLng = L.GeoJSON.coordsToLatLng(threeCoords); threeCoords = L.GeoJSON.latLngToCoords(latLng) as [number, number, number]; -let nestedTwoCoords = [ [12, 13], [13, 14], [14, 15] ]; +let nestedTwoCoords = [[12, 13], [13, 14], [14, 15]]; const nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); nestedTwoCoords = L.GeoJSON.latLngsToCoords(nestedLatLngs, 1); const geojson = new L.GeoJSON(); const style: L.PathOptions = { - className: "string", + className: "string", }; const styler: L.StyleFunction = () => style; geojson.setStyle(style); @@ -431,7 +461,7 @@ class MyLayer extends L.Layer { class MyIcon extends L.Icon { constructor() { - super({iconUrl: 'icon.png'}); + super({ iconUrl: 'icon.png' }); } } @@ -441,9 +471,9 @@ class MyDivIcon extends L.DivIcon { } } -const divIcon = L.divIcon({html: ''}); +const divIcon = L.divIcon({ html: '' }); let defaultIcon = new L.Icon.Default(); -defaultIcon = new L.Icon.Default({imagePath: 'apath'}); +defaultIcon = new L.Icon.Default({ imagePath: 'apath' }); const myControlClass = L.Control.extend({}); const myControl = new myControlClass(); @@ -501,11 +531,11 @@ const complexPolygonLatLngs2: L.LatLng[][] = polygon.getLatLngs() as L.LatLng[][ // multi polygon const multiPolygonLatLngs: L.LatLngExpression[][][] = [ [ // first polygon - [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring - [[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole + [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring + [[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole ], [ // second polygon - [[41, -111.03], [45, -111.04], [45, -104.05], [41, -104.05]] + [[41, -111.03], [45, -111.04], [45, -104.05], [41, -104.05]] ] ]; polygon = L.polygon(multiPolygonLatLngs); @@ -524,8 +554,8 @@ const simplePolylineLatLngs2: L.LatLng[] = polyline.getLatLngs() as L.LatLng[]; // multi polyline const multiPolylineLatLngs: L.LatLngExpression[][] = [ - [[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], - [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]] + [[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], + [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]] ]; polyline = L.polyline(multiPolylineLatLngs); polyline = new L.Polyline(multiPolylineLatLngs); @@ -559,7 +589,7 @@ const extended3: typeof obj1 & typeof obj2 & typeof obj3 & typeof obj4 = L.Util. 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.create(null, { foo: { writable: true, value: 'bar' } }); L.Util.bind(() => {}, {}); L.Util.stamp({}); diff --git a/types/libsodium-wrappers/index.d.ts b/types/libsodium-wrappers/index.d.ts index 2fcbe30a98..155448bcc2 100644 --- a/types/libsodium-wrappers/index.d.ts +++ b/types/libsodium-wrappers/index.d.ts @@ -1031,7 +1031,7 @@ export function crypto_stream_keygen(outputFormat?: Uint8ArrayOutputFormat | nul export function crypto_stream_keygen(outputFormat?: StringOutputFormat | null): string; -export function from_base64(input: string, variant: base64_variants): Uint8Array; +export function from_base64(input: string, variant?: base64_variants): Uint8Array; export function from_hex(input: string): Uint8Array; @@ -1077,7 +1077,7 @@ export function sodium_version_string(): string; export function symbols(): string[]; -export function to_base64(input: string | Uint8Array, variant: base64_variants): string; +export function to_base64(input: string | Uint8Array, variant?: base64_variants): string; export function to_hex(input: string | Uint8Array): string; diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts new file mode 100644 index 0000000000..0c31e24e20 --- /dev/null +++ b/types/list.js/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for list.js 1.5 +// Project: http://listjs.com +// Definitions by: Jeffrey Meng +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +interface ListOptions { + valueNames?: string[]; + item?: string; + listClass?: string; + searchClass?: string; + sortClass?: string; + indexAsync?: boolean; + page?: number; + i?: number; + pagination?: boolean; +} + +interface SortOptions { + order?: string; + alphabet?: string; + insensitive?: boolean; + sortFunction?: ((a: object, b: object) => number|undefined); +} + +declare class List { + listContainer: HTMLElement; + list: HTMLElement; + items: object[]; + visibleItems: object[]; + matchingItems: object[]; + searched: boolean; + filtered: boolean; + + constructor(element: string|HTMLElement, options?: ListOptions, values?: object[]); + + add(values: object[], callback?: (item: ListItem) => void): void; + remove(valueName: string, value: any): number; + get(valueName: string, value: any): ListItem[]; + sort(valueName: string, options: SortOptions): void; + search(searchString: string, columns?: string[]): void; + clear(): void; + filter(filterFunction: (item: ListItem) => boolean): void; + size(): number; + show(i: number, page: number): void; + update(): void; + reIndex(): void; + fuzzySearch(searchString: string, columns?: string[]): void; + on(event: string, callback: () => void): void; +} + +declare class ListItem { + elm: HTMLElement; + + values(newValues: object): void; + values(): object; + show(): void; + hide(): void; + matching(): boolean; + visible(): boolean; +} + +export = List; diff --git a/types/list.js/list.js-tests.ts b/types/list.js/list.js-tests.ts new file mode 100644 index 0000000000..b2852c1a55 --- /dev/null +++ b/types/list.js/list.js-tests.ts @@ -0,0 +1,49 @@ +import List from "list.js"; + +const list = new List(new HTMLElement(), { + page: 3, + searchClass: "class" +}); + +list.list; // $ExpectType HTMLElement +list.listContainer; // $ExpectType HTMLElement +list.items; // $ExpectType object[] +list.visibleItems; // $ExpectType object[] +list.matchingItems; // $ExpectType object[] +list.searched; // $ExpectType boolean +list.filtered; // $ExpectType boolean + +list.add([{ // $ExpectType void + name: "value", + value: true +}], (item) => {}); // $ExpectType (item: ListItem) => void + +list.remove("name", "value"); // $ExpectType number +list.get("name", "value"); // $ExpectType ListItem[] +list.sort("name", { // $ExpectType void + order: "asec", + alphabet: "ABCD1234EFGH" +}); +list.search("name", ["col1", "col2"]); // $ExpectType void +list.clear(); // $ExpectType void +list.filter((item) => { + return true; +}); +list.size(); // $ExpectType number +list.show(0, 0); // $ExpectType void +list.update(); // $ExpectType void +list.reIndex(); // $ExpectType void +list.fuzzySearch("search", ["col1", "col2"]); // $ExpectType void +list.on("event", () => { // void + // Do Something +}); + +const item = list.get("name", "value")[0]; + +item.elm; // $ExpectType HTMLElement +item.values(["new1", "new2"]); // $ExpectType void +item.values(); // $ExpectType object +item.show(); // $ExpectType void +item.hide(); // $ExpectType void +item.matching(); // $ExpectType boolean +item.visible(); // $ExpectType boolean diff --git a/types/list.js/tsconfig.json b/types/list.js/tsconfig.json new file mode 100644 index 0000000000..85166b0860 --- /dev/null +++ b/types/list.js/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "esModuleInterop": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "list.js-tests.ts" + ] +} diff --git a/types/list.js/tslint.json b/types/list.js/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/list.js/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/load-google-maps-api/index.d.ts b/types/load-google-maps-api/index.d.ts new file mode 100644 index 0000000000..818957ff5f --- /dev/null +++ b/types/load-google-maps-api/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for load-google-maps-api 1.3 +// Project: https://github.com/yuanqing/load-google-maps-api#readme +// Definitions by: Oscar Busk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface Options { + /** + * Client usage reporting channel + * + * https://developers.google.com/maps/premium/reports/usage-reports#channels + */ + channel?: string; + /** + * Client ID + * + * https://developers.google.com/maps/documentation/javascript/get-api-key#specifying-a-client-id-when-loading-the-api + */ + client?: string; + /** + * Your API key + * + * https://developers.google.com/maps/documentation/javascript/get-api-key#step-2-add-the-api-key-to-your-application + */ + key?: string; + /** + * https://developers.google.com/maps/documentation/javascript/localization#Language + */ + language?: string; + /** + * Supplemental libraries to load + * + * Default Value `[]` + * + * https://developers.google.com/maps/documentation/javascript/libraries + */ + libraries?: string[]; + /** + * https://developers.google.com/maps/documentation/javascript/localization#Region + */ + region?: string; + /** + * Time in milliseconds before rejecting the Promise + * + * Default Value `10000` + */ + timeout?: number; + /** + * API Version + * + * https://developers.google.com/maps/documentation/javascript/versions + */ + v?: string; +} + +declare function loadGoogleMapsApi(options?: Options): Promise; + +export = loadGoogleMapsApi; diff --git a/types/load-google-maps-api/load-google-maps-api-tests.ts b/types/load-google-maps-api/load-google-maps-api-tests.ts new file mode 100644 index 0000000000..0d2495de64 --- /dev/null +++ b/types/load-google-maps-api/load-google-maps-api-tests.ts @@ -0,0 +1,38 @@ +import loadGoogleMapsApi = require('load-google-maps-api'); + +// Example from README.md https://github.com/yuanqing/load-google-maps-api#usage +loadGoogleMapsApi().then((googleMaps) => { + new googleMaps.Map(document.querySelector('.map'), { + center: { + lat: 40.7484405, + lng: -73.9944191 + }, + zoom: 12 + }); +}).catch((error) => { + console.error(error); +}); + +loadGoogleMapsApi({ libraries: 'drawing' }); // $ExpectError +loadGoogleMapsApi({ v: 3 }); // $ExpectError +loadGoogleMapsApi({ timeout: '1000' }); // $ExpectError + +loadGoogleMapsApi({ + channel: 'customer', + client: '12345', + key: 'abcde', + language: 'se', + libraries: [ + 'drawing', + 'geometry', + 'places', + 'visualization', + ], + region: 'SE', + timeout: 500, + v: '3.33', +}).then(gm => { + gm; // $ExpectType typeof maps + const map = new gm.Map(document.querySelector('.map')); // $ExpectType Map + const polygon = new gm.Polygon(); // $ExpectType Polygon +}); diff --git a/types/load-google-maps-api/tsconfig.json b/types/load-google-maps-api/tsconfig.json new file mode 100644 index 0000000000..7d3af9db08 --- /dev/null +++ b/types/load-google-maps-api/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", + "load-google-maps-api-tests.ts" + ] +} diff --git a/types/load-google-maps-api/tslint.json b/types/load-google-maps-api/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/load-google-maps-api/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/loadable__server/index.d.ts b/types/loadable__server/index.d.ts index eafbd7eec7..33a3366ca9 100644 --- a/types/loadable__server/index.d.ts +++ b/types/loadable__server/index.d.ts @@ -51,7 +51,7 @@ export class ChunkExtractor { /** * Get scripts as a string of `