diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index a03915a264..a769c20dfc 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,5 +1,4 @@ /types/abbrev/ @BendingBender -/types/ably/ @ably /types/abs/ @AyaMorisawa /types/absolute/ @AyaMorisawa /types/acc-wizard/ @cyrilschumacher @@ -14,8 +13,11 @@ /types/activex-access/ @zspitz /types/activex-adodb/ @zspitz /types/activex-dao/ @zspitz +/types/activex-diskquota/ @zspitz /types/activex-excel/ @zspitz +/types/activex-faxcomexlib/ @zspitz /types/activex-infopath/ @zspitz +/types/activex-iwshruntimelibrary/ @zspitz /types/activex-libreoffice/ @zspitz /types/activex-msforms/ @zspitz /types/activex-mshtml/ @zspitz @@ -24,6 +26,8 @@ /types/activex-outlook/ @zspitz /types/activex-powerpoint/ @zspitz /types/activex-scripting/ @zspitz +/types/activex-shdocvw/ @zspitz +/types/activex-shell/ @zspitz /types/activex-stdole/ @zspitz /types/activex-vbide/ @zspitz /types/activex-wia/ @zspitz @@ -36,7 +40,7 @@ /types/agenda/ @meirgottlieb /types/aggregate-error/ @BendingBender /types/alertify/ @jjeffery -/types/alexa-sdk/ @petebeegle @hoo29 @pascalwhoop @blforce @rk-7 +/types/alexa-sdk/ @petebeegle @hoo29 @pascalwhoop @blforce @rk-7 @alexmalcoci /types/alexa-voice-service/ @dolanmiu /types/algebra.js/ @CaselIT /types/algoliasearch/ @cbaptiste @haroenv @aherve @@ -49,7 +53,7 @@ /types/amqp/ @seikho @jonnysparkplugs /types/amqp-rpc/ @wokim /types/amqplib/ @mnahkies @abreits @nfantone -/types/analytics-node/ @fongandrew +/types/analytics-node/ @fongandrew @thomasthiebaud /types/angular/ @diegovilar @thorn0 @calebstdenis @leonard-thieu /types/angular-agility/ @rolandzwaga /types/angular-animate/ @michelsalib @adidahiya @rasch @codyschaaf @@ -136,12 +140,14 @@ /types/api-error-handler/ @tkrotoff /types/apigee-access/ @CasperSkydt /types/apollo-codegen/ @bradleyayers +/types/app-root-dir/ @chenyang-biu /types/app-root-path/ @shantmarouti /types/appdmg/ @unindented /types/appframework/ @kyo-ago /types/applepayjs/ @martincostello /types/appletvjs/ @brainded /types/applicationinsights-js/ @kamilszostak +/types/aqb/ @Athenkosi-Mase /types/arbiter/ @arash16 /types/arcgis-js-api/v3/ @Esri /types/arcgis-js-api/ @Esri @@ -167,15 +173,16 @@ /types/aspnet-identity-pw/ @jt000 /types/assert-equal-jsx/ @seryl /types/assert-plus/ @KostyaTretyak -/types/assertion-error/ @Bartvds /types/assertsharp/ @brunolm /types/assets-webpack-plugin/ @kryops /types/async/ @borisyankov @kern0 @Penryn @fenying @pascalmartin /types/async-cache/ @BendingBender -/types/async-lock/ @elisee +/types/async-lock/ @elisee @afharo @rhymmor /types/async-polling/ @Goldsmith42 +/types/async-retry/ @albertywu /types/async.nexttick/ @pyrho /types/asynciterator/ @rubensworks +/types/atlaskit__button/ @dijimsta /types/atmosphere.js/ @toedter @Mory1879 /types/atom/ @GlenCFL @smhxx @lierdakil /types/atom-keymap/ @GlenCFL @@ -186,7 +193,7 @@ /types/auth0-angular/ @homesar /types/auth0-js/v7/ @advancedrei /types/auth0-js/ @adrianchia @mdurrant @peterblazejewicz -/types/auth0-lock/ @carusology @goldcaddy77 +/types/auth0-lock/ @carusology @goldcaddy77 @lfaudreejr /types/auth0.widget/ @advancedrei /types/auto-launch/ @rhysd @unindented /types/auto-sni/ @janwo @@ -194,10 +201,11 @@ /types/autolinker/ @leonyu /types/autoprefixer/ @odnamrataizem /types/autosize/ @kingdango @keika299 @NeekSandhu +/types/autosuggest-highlight/ @senukartur /types/awesomplete/ @webbiesdk @bmdixon @tbekolay /types/aws-iot-device-sdk/ @niik @mlamp -/types/aws-lambda/ @skarum @tobyhede @buggy @y13i @wwwy3y3 @OrthoDex @MichaelMarner @daniel-cottone @kostya-misura @coderbyheart -/types/aws-serverless-express/ @threesquared @jcaffey @mattmeye +/types/aws-lambda/ @skarum @tobyhede @buggy @y13i @wwwy3y3 @OrthoDex @MichaelMarner @daniel-cottone @kostya-misura @coderbyheart @palmithor @daniloraisi @simonbuchan @Haydabase +/types/aws-serverless-express/ @threesquared @jcaffey @mattmeye @albertovasquez /types/aws4/ @ajcrites /types/axel/ @ruslan-molodyko /types/azure/ @AndrewGaspar @antiveeranna @SomaticIT @@ -237,6 +245,7 @@ /types/base-x/ @chrootsu /types/base16/ @alechill /types/base64-js/ @pe8ter +/types/base64topdf/ @lucasriondel /types/bases/ @harikv /types/bash-glob/ @mrmlnc /types/basic-auth/ @moonpyk @vesse @@ -267,6 +276,7 @@ /types/bip39/ @micksatana /types/bit-array/ @mudkipme /types/bitcoinjs-lib/ @mhegazy @dlebrecht @rbuckton @micksatana @youssefgh +/types/bitcore-lib/ @lautarodragan /types/bittorrent-protocol/ @feross @tlaziuk /types/bitwise-xor/ @rogierschouten /types/bl/ @Bartvds @@ -295,8 +305,10 @@ /types/bootbox/ @vbortone @konpikwastaken @kanup @icereed @trodi @stannynuytkens @renjfk /types/bootpag/ @rdeneau /types/bootstrap/ @borisyankov +/types/bootstrap-3-typeahead/ @AndersonFriaca /types/bootstrap-datepicker/ @borisyankov /types/bootstrap-fileinput/ @CheCoxshall +/types/bootstrap-growl-ifightcrime/ @AndersonFriaca /types/bootstrap-maxlength/ @danmana /types/bootstrap-notify/ @niemyjski @mouse0270 @robert-voica /types/bootstrap-select/ @LKay @@ -334,8 +346,9 @@ /types/buffer-equal/ @Bartvds /types/buffers/ @rhencke /types/bufferstream/ @Bartvds +/types/builtin-modules/ @ajafff /types/bull/v2/ @bgrieder @JProgrammer -/types/bull/ @bgrieder @JProgrammer @marshall007 @weeco +/types/bull/ @bgrieder @JProgrammer @marshall007 @weeco @blaugold /types/bump-regex/ @silkentrance /types/bunnymq/ @cyrilschumacher /types/bunyan/ @amikhalev @@ -351,27 +364,31 @@ /types/byline/ @reppners /types/bytebuffer/ @cappellin /types/bytes/ @danny8002 -/types/c3/ @mcliment @gerinjacob @denyo +/types/c3/ @mcliment @gerinjacob @denyo @dmitryshindin /types/cache-manager/ @GausSim /types/cal-heatmap/ @RetroChrisB /types/callsite/ @newclear /types/callsites/ @BendingBender /types/calq/ @eirikhm +/types/camaro/ @tuananh /types/camelcase/ @samverschueren /types/camelcase-keys/ @mhegazy /types/camo/ @lucasmciruzzi /types/cancan/ @Vincent-Pang /types/cannon/ @clark-stevenson @Gelio +/types/canvas-confetti/ @matracey /types/canvas-gauges/ @Mikhus /types/canvasjs/ @brutalimp /types/capitalize/ @frederickfogerty /types/card-validator/ @ChanceM /types/case-sensitive-paths-webpack-plugin/ @r3nya -/types/caseless/ @downace +/types/caseless/ @downace @mastermatt /types/cash/ @akvlko /types/casperjs/ @jedmao @urielch /types/cassandra-driver/ @Svjard -/types/catbox/ @jasonswearingen @AJamesPhillips +/types/catalog/ @grossbart @wereHamster +/types/catbox/v7/ @jasonswearingen @AJamesPhillips +/types/catbox/ @jasonswearingen @AJamesPhillips @saboya /types/cbor/ @pushplay /types/ccap/ @taoqf /types/chai/v2/ @Bartvds @AGBrown @@ -382,7 +399,7 @@ /types/chai-dom/ @mattlewis92 /types/chai-enzyme/ @asvetliakov /types/chai-fuzzy/ @Bartvds -/types/chai-http/ @Nemo157 @G1itcher @CaselIT +/types/chai-http/ @Nemo157 @G1itcher @CaselIT @bas-l /types/chai-jest-snapshot/ @mattvperry /types/chai-jquery/ @kazimanzurrashid /types/chai-json-schema/ @ulrichheiniger @@ -395,7 +412,8 @@ /types/chance/ @cbowdon @brikou /types/change-emitter/ @iskandersierra /types/charm/ @Xananax -/types/chart.js/ @anuti @FabienLavocat @KentarouTakeda @larrybahr @mernen @josefpaij @danmana +/types/charset/ @cspotcode +/types/chart.js/ @anuti @FabienLavocat @KentarouTakeda @larrybahr @mernen @josefpaij @danmana @guillaume-ro-fr @chicoxyzzy /types/chartist/ @mtgibbs @psimonski @clottman /types/chayns/ @HenningKuehl /types/check-sum/ @BendingBender @@ -403,6 +421,7 @@ /types/checkstyle-formatter/ @mhegazy /types/checksum/ @rogierschouten /types/cheerio/ @blittle @wmaurer @umarniz @LiJinyao +/types/chessboardjs/ @sliverb @davidmpaz /types/chmodr/ @BendingBender /types/chokidar/ @reppners @felixfbecker @bayssmekanique /types/chosen-js/ @borisyankov @denisname @@ -420,7 +439,7 @@ /types/clean-stack/ @BendingBender /types/clean-webpack-plugin/ @j-f1 /types/clear-require/ @dan-j -/types/cleave.js/ @clentfort @jasongi-at-sportsbet +/types/cleave.js/ @clentfort @jasongi-at-sportsbet @sashashakun /types/cli/ @kayahr /types/cli-color/ @ChaosinaCan /types/cli-spinner/ @janslow @@ -449,9 +468,11 @@ /types/collections/ @scarabedore /types/color/v0/ @LKay /types/color/v1/ @LKay -/types/color/ @Airlun +/types/color/v2/ @Airlun +/types/color/ @Airlun @jameswlane /types/color-convert/ @Airlun /types/color-name/ @Ailrun +/types/color-namer/ @in19farkt /types/color-string/ @BendingBender @danmarshall /types/colorbrewer/ @mtraynham /types/colors/ @Bartvds @staeke @@ -479,7 +500,7 @@ /types/conf/v0/ @SamVerschueren /types/conf/ @SamVerschueren @BendingBender /types/confidence/ @jppellerin -/types/config/ @RWander @forrestbice @jndonald3 +/types/config/ @RWander @forrestbice @jndonald3 @albertovasquez /types/configstore/ @ArcticLight /types/confit/ @ethanresnick /types/connect/ @SomaticIT @@ -561,6 +582,7 @@ /types/cron/ @horiuchi /types/cropperjs/ @stepancar /types/croppie/ @connor4312 @dklmuc @sarunint +/types/cross-spawn/ @Alorel /types/crossfilter/ @schmuli @iebaker @nordfjord /types/crossroads/ @diullei /types/cryptiles/ @awendland @@ -579,6 +601,7 @@ /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/currency-formatter/ @mhegazy @davidmpaz /types/custom-error-generator/ @thmiceli @@ -586,8 +609,9 @@ /types/cwise-compiler/ @taoqf /types/cwise-parser/ @taoqf /types/cybozulabs-md5/ @pine613 -/types/cytoscape/ @phreed @wy193777 @ypconstante +/types/cytoscape/ @phreed @wy193777 @ypconstante @janniclas /types/d3/v3/ @gustavderdrache @borisyankov @MatthiasJobst +/types/d3/v4/ @tomwanzek @gustavderdrache @borisyankov /types/d3/ @tomwanzek @gustavderdrache @borisyankov /types/d3-array/ @gustavderdrache @borisyankov @tomwanzek /types/d3-axis/ @tomwanzek @gustavderdrache @borisyankov @@ -601,6 +625,7 @@ /types/d3-drag/ @tomwanzek @gustavderdrache @borisyankov /types/d3-dsv/ @tomwanzek @gustavderdrache @borisyankov /types/d3-ease/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-fetch/ @ledragon /types/d3-force/ @tomwanzek @gustavderdrache @borisyankov /types/d3-format/ @tomwanzek @gustavderdrache @borisyankov /types/d3-geo/ @Ledragon @tomwanzek @gustavderdrache @borisyankov @@ -615,6 +640,7 @@ /types/d3-random/ @tomwanzek @gustavderdrache @borisyankov /types/d3-request/ @Ledragon @gustavderdrache @borisyankov @tomwanzek /types/d3-sankey/ @tomwanzek @gustavderdrache +/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 @@ -635,12 +661,14 @@ /types/dagre-d3/ @markwongsk /types/dagre-layout/ @qinfchen @Frankrike @vilterp /types/dargs/ @BendingBender -/types/dat-gui/ @gyohk @sonic3d @rroylance +/types/dashify/ @rokt33r +/types/dat.gui/ @gyohk @sonic3d @rroylance /types/data-driven/ @mrhen /types/datadog-metrics/ @pushplay /types/datatables.net/ @Silver-Connection @omidkrad @pragmatrix @CNBoland /types/datatables.net-buttons/ @Silver-Connection @SammyG4Free @jimhartford /types/datatables.net-fixedheader/ @szechyjs @Silver-Connection +/types/datatables.net-rowgroup/ @maixiu /types/datatables.net-rowreorder/ @baywet /types/datatables.net-select/ @szechyjs /types/date-arithmetic/ @HeeL @@ -659,6 +687,7 @@ /types/decamelize/ @samverschueren /types/decay/ @enaeseth /types/decompress/ @plantain-00 +/types/decompress-response/ @DanielRosenwasser /types/decorum/ @dflor003 /types/dedent/ @douglasduteil /types/deep-assign/ @souldreamer @@ -706,7 +735,7 @@ /types/discontinuous-range/ @OiCMudkips /types/disposable-email-domains/ @geoffreak /types/doccookies/ @jonegerton -/types/dockerode/ @seikho @nlaplante @isac322 @lazarusx @meisenzahl +/types/dockerode/ @seikho @nlaplante @isac322 @lazarusx @meisenzahl @thegecko /types/docopt/ @giggio /types/doctrine/ @rictic /types/documentdb/ @NoelAbrahams @brettferdosi @ctstone @yifanwu @@ -761,6 +790,7 @@ /types/dynatable/ @francoismassart /types/dynogels/ @SpartanLabs /types/each/ @misak113 +/types/earcut/ @NaridaL /types/easeljs/ @evilangelist /types/easy-api-request/ @DeadAlready /types/easy-jsend/ @DeadAlready @@ -772,6 +802,7 @@ /types/echarts/ @xieisabug @AntiMoron /types/ecurve/ @mhegazy /types/ed25519/ @erikma +/types/ed2curve/ @ffflorian /types/egg-mock/ @sheperdwind /types/egg.js/ @ToastHawaii /types/egjs__axes/ @naver @@ -788,11 +819,11 @@ /types/electron-json-storage/ @stpettersens @nrlquaker @jbw91 /types/electron-notifications/ @djpereira /types/electron-notify/ @djpereira -/types/electron-packager/ @SomaticIT @cortopy +/types/electron-packager/ @SomaticIT @cortopy @jkleinsc /types/electron-settings/v2/ @leonard-thieu /types/electron-settings/ @icopp @nrlquaker /types/electron-spellchecker/ @unindented -/types/electron-store/ @unindented +/types/electron-store/ @unindented @jsynowiec /types/electron-util/ @kputh /types/electron-window-state/ @rhysd /types/electron-winstaller/ @shiftkey @unindented @@ -803,7 +834,7 @@ /types/email-templates/ @cyrilschumacher @gurisko @blankstar85 /types/ember/v1/ @jedmao /types/ember/ @jedmao @bttf @dwickern @chriskrycho @theroncross @mfeckie -/types/ember-data/ @dwickern @mike-north +/types/ember-data/ @dwickern @mike-north @chriskrycho /types/ember-feature-flags/ @tansongyang /types/ember-mocha/ @dwickern /types/ember-modal-dialog/ @tansongyang @@ -827,6 +858,7 @@ /types/envify/ @tkQubo /types/enzyme/ @MarianPalkus @NoHomey @jwbay @huhuanming @MartynasZilinskas @thovden /types/enzyme-adapter-react-15/ @tkrotoff +/types/enzyme-adapter-react-15.4/ @nali /types/enzyme-adapter-react-16/ @tkrotoff /types/enzyme-to-json/ @joscha /types/eonasdan-bootstrap-datetimepicker/ @ToastHawaii @@ -836,14 +868,17 @@ /types/eq.js/ @stephenlautier /types/errorhandler/ @santialbo /types/es6-collections/ @rbuckton -/types/es6-promisify/ @harryshipton +/types/es6-promisify/ @harryshipton @bschlenk /types/es6-shim/ @rbuckton /types/es6-weak-map/ @pine /types/escape-html/ @elisee /types/escape-latex/ @olsio /types/escape-string-regexp/ @kruncher @faergeek /types/escodegen/ @simondel +/types/eslint/ @pmdartus @j-f1 /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-walk/ @tswaters @@ -872,8 +907,9 @@ /types/expect.js/ @teppeis /types/expectations/ @vvakame /types/expo/v23/ @KonstantinKai -/types/expo/ @KonstantinKai @martynaskadisa -/types/expr-eval/ @connor4312 +/types/expo/v24/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger +/types/expo/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger +/types/expo__vector-icons/ @incleaf /types/express/ @borisyankov /types/express-brute/ @cyrilschumacher /types/express-brute-memcached/ @cyrilschumacher @@ -889,7 +925,7 @@ /types/express-flash-2/ @mathsalmi /types/express-flash-notification/ @Mister4Eyes /types/express-formidable/ @tdolsen @evanshortiss -/types/express-graphql/ @isman-usoh @nitintutlani @hubel +/types/express-graphql/ @isman-usoh @nitintutlani @hubel @zya /types/express-handlebars/ @stpettersens @yhaskell /types/express-jwt/ @wokim @kacepe @Sl1MBoy /types/express-less/ @xieyubo @@ -905,8 +941,9 @@ /types/express-rate-limit/ @cyrilschumacher @makepost /types/express-route-fs/ @kripod /types/express-sanitized/ @cjbarth -/types/express-serve-static-core/ @borisyankov @19majkel94 @kacepe @micksatana -/types/express-session/ @horiuchi @jacobbogers +/types/express-serve-static-core/ @borisyankov @19majkel94 @kacepe @micksatana @samijaber +/types/express-session/ @horiuchi @jacobbogers @builtinnya @ry7n +/types/express-to-koa/ @xiaohanzhang /types/express-unless/ @wokim /types/express-winston/ @bricka /types/extend/ @reppners @@ -916,7 +953,7 @@ /types/extract-zip/ @mizunashi-mana /types/eyes/ @brynbellomy /types/f1/ @neolwc -/types/fabric/ @oklemencic @joewashear007 @mrand01 +/types/fabric/ @oklemencic @joewashear007 @mrand01 @NotWoods /types/facebook-js-sdk/ @amritk /types/facebook-pixel/ @noctishsu /types/faker/v3/ @Kuniwak @@ -939,6 +976,22 @@ /types/fb/ @JoshStrobl /types/fbemitter/ @kmxz /types/featherlight/ @xStrom +/types/feathersjs__authentication/ @AbraaoAlves @j2L4e +/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__configuration/ @j2L4e +/types/feathersjs__errors/ @j2L4e +/types/feathersjs__express/ @j2L4e +/types/feathersjs__feathers/ @j2L4e @AbraaoAlves +/types/feathersjs__primus/ @j2L4e +/types/feathersjs__primus-client/ @j2L4e +/types/feathersjs__rest-client/ @j2L4e +/types/feathersjs__socket-commons/ @j2L4e +/types/feathersjs__socketio/ @j2L4e +/types/feathersjs__socketio-client/ @j2L4e /types/feedme/ @codeanimal /types/feedparser/ @cortopy /types/fetch-jsonp/ @tkrotoff @@ -954,11 +1007,12 @@ /types/file-type/ @tcaesvk @BendingBender /types/file-url/ @coderslagoon /types/filenamify/ @rokt33r -/types/filesize/ @GiedriusGrabauskas +/types/filesize/ @GiedriusGrabauskas @renchap /types/fill-pdf/ @westy92 /types/finalhandler/ @chrootsu /types/finch/ @DavidSichau /types/find/ @andypyrope +/types/find-root/ @Alorel /types/find-up/ @BendingBender /types/findup-sync/ @Bartvds @ngbrown /types/fingerprintjs/ @zaneli @@ -986,6 +1040,7 @@ /types/fm-websync/ @markusmauch /types/fontfaceobserver/ @RandScullard /types/fontoxml/ @rolandzwaga +/types/forever-agent/ @yavanosta /types/forever-monitor/ @shuntksh /types/forge-di/ @adamcarr /types/form-data/ @soywiz @leonyu @BendingBender @@ -995,6 +1050,7 @@ /types/format-io/ @amitbeck /types/format-unicorn/ @kruncher /types/formidable/ @Nemo157 +/types/forms/ @suXinjke /types/forwarded/ @BendingBender /types/fossil-delta/ @endel /types/foundation/ @borisyankov @@ -1028,12 +1084,11 @@ /types/ftpd/ @rogierschouten /types/fullname/ @kayahr /types/fullpage.js/ @jodiwarren -/types/fuse/ @smrq /types/fusioncharts/ @rohitkr @shivarajkv /types/fuzzaldrin/ @mhegazy /types/fuzzaldrin-plus/ @jeancroy @jkillian -/types/fuzzyset/ @lgrignon -/types/fuzzyset.js/ @lgrignon +/types/fuzzyset/ @lgrignon @narainsagar +/types/fuzzyset.js/ @lgrignon @narainsagar /types/fxn/ @charrondev /types/gae.channel.api/ @vvakame /types/gamequery/ @Laubi @@ -1176,6 +1231,7 @@ /types/gapi.youtube/ @sgtfrankieboy /types/gapi.youtubeanalytics/ @sgtfrankieboy /types/gaussian/ @scttcper +/types/geetest/ @plantain-00 /types/gen-readlines/ @CodeAnimal /types/generic-functions/ @stpettersens /types/generic-pool/ @jerray @@ -1186,9 +1242,12 @@ /types/geokdbush/ @DenisCarriere /types/geometry-dom/ @nakakura /types/geopattern/ @Gaelan +/types/get-caller-file/ @ajafff /types/get-node-dimensions/ @vincekovacs /types/get-stdin/ @DanielRosenwasser /types/get-stream/ @douglasduteil @BendingBender +/types/get-value/ @DanielRosenwasser +/types/getopts/ @azasypkin /types/getos/ @BendingBender /types/gettext.js/ @jucrouzet /types/gifffer/ @gatimus @@ -1214,7 +1273,7 @@ /types/gm/ @ChaosinaCan @maartenvanvliet /types/go/ @NorthwoodsSoftware /types/google-adwords-scripts/ @jafaircl -/types/google-apps-script/ @motemen +/types/google-apps-script/ @motemen @grant /types/google-apps-script-oauth2/ @dhayab /types/google-cloud__datastore/ @beaulac /types/google-cloud__pubsub/ @pheromonez @@ -1238,9 +1297,11 @@ /types/graceful-fs/ @Bartvds @BendingBender /types/graham_scan/ @hberntsen /types/graphite-udp/ @EricByers -/types/graphql/ @TonyPythoneer @calebmer @intellix @firede @kepennar @freiksenet @IvanGoncharov @DxCx @rportugal +/types/graphql/ @TonyPythoneer @calebmer @intellix @firede @kepennar @freiksenet @IvanGoncharov @DxCx @rportugal @tgriesser @dyst5422 @adnsio /types/graphql-date/ @enaeseth +/types/graphql-iso-date/ @jwaldrip /types/graphql-relay/ @arvitaly @nitintutlani @Grelinfo +/types/graphql-resolve-batch/ @nayni /types/graphql-type-json/ @schfkt /types/graphviz/ @mhfrantz /types/grasp/ @agnoster @@ -1250,10 +1311,11 @@ /types/grecaptcha/v0/ @brentj73 /types/grecaptcha/ @DethAriel /types/gregorian-calendar/ @cwalv +/types/grid-styled/ @antonvasin /types/gridfs-stream/ @liorm /types/gridstack/ @PascalSenn @ZoolWay @Sl1MBoy /types/grunt/ @jeffmay @basarat -/types/gsap/ @codebelt @ProbablePrime +/types/gsap/ @codebelt @ProbablePrime @philipbulley /types/guid/ @maroy1986 /types/gulp/ @GiedriusGrabauskas /types/gulp-angular-templatecache/ @amanmahajan7 @@ -1331,7 +1393,8 @@ /types/hapi/v8/ @jasonswearingen /types/hapi/v12/ @jasonswearingen /types/hapi/v15/ @jasonswearingen -/types/hapi/ @jasonswearingen @AJamesPhillips +/types/hapi/v16/ @jasonswearingen @AJamesPhillips +/types/hapi/ @BorntraegerMarc @rafaelsouzaf @jhsimms /types/hapi-auth-basic/ @AJamesPhillips @saboya /types/hapi-auth-jwt2/ @warrenseymour /types/hapi-decorators/ @kenhowardpdx @@ -1346,13 +1409,14 @@ /types/hashids/ @pocesar /types/hashmap/ @outring /types/haversine/ @screendriver +/types/hbs/ @davidm77 /types/he/ @sedwards2009 /types/headroom/ @hakubo /types/heap/ @ryan10132 /types/heapdump/ @weekens /types/heatmap.js/ @lookuptable @rhys-vdw /types/hedron/ @dborysov -/types/hellojs/ @PavelPZ @vuorinem +/types/hellojs/ @PavelPZ @vuorinem @baywet /types/hellosign-embedded/ @xt0rted /types/helmet/ @cyrilschumacher @EvanHahn @bluehatbrit /types/heredatalens/ @denyo @@ -1395,7 +1459,7 @@ /types/http-codes/ @mhegazy /types/http-context/ @mtraynham /types/http-errors/ @tkrotoff @BendingBender -/types/http-proxy/ @SomaticIT +/types/http-proxy/ @SomaticIT @Raigen /types/http-proxy-agent/ @mrmlnc /types/http-proxy-middleware/ @zebMcCorkle @BendingBender /types/http-server/ @plantain-00 @@ -1406,6 +1470,7 @@ /types/hubspot-pace/ @borislavjivkov /types/humane/ @jmvrbanac /types/humanize-plus/ @DenisCarriere +/types/humanize-string/ @ragnarok56 /types/humanparser/ @MichalPodeszwa /types/humps/ @nikeee /types/hyco-ws/ @mrcabellom @@ -1443,12 +1508,12 @@ /types/imap/ @psnider /types/imap-simple/ @pushplay /types/imgur-rest-api/ @lukewestby -/types/immutability-helper/ @seansfkelley /types/impress/ @borisyankov /types/in-range/ @DanielRosenwasser /types/incremental-dom/ @basarat @lanthaler @vvakame /types/indent-string/ @mhegazy -/types/inert/ @nycdotnet @AJamesPhillips +/types/inert/v4/ @nycdotnet @AJamesPhillips +/types/inert/ @nycdotnet @AJamesPhillips @lenovouser /types/inflected/ @dsci /types/inflection/ @shiwano /types/inherits/ @chrootsu @@ -1477,6 +1542,7 @@ /types/iota.lib.js/ @fogsh /types/ip/ @codeanimal /types/ip-regex/ @unindented +/types/ipcheck/ @bengry /types/irc/ @phillips1012 /types/iron/ @simonschick @rafaelsouzaf /types/is/ @cabralRodrigo @@ -1488,6 +1554,7 @@ /types/is-compressed/ @mhegazy /types/is-finite/ @mhegazy /types/is-glob/ @mrmlnc +/types/is-hotkey/ @petester42 /types/is-ip/ @coderslagoon /types/is-my-json-valid/ @kruncher /types/is-negated-glob/ @ajafff @@ -1508,6 +1575,7 @@ /types/is-windows/ @mizunashi-mana /types/isbn-utils/ @elhaard /types/iscroll/ @csrakowski +/types/ismobilejs/ @Ty3uK /types/iso-3166-2/ @sicilica /types/iso8601-localizer/ @avielfedida /types/isomorphic-fetch/ @toddlucas @@ -1525,7 +1593,7 @@ /types/jade/ @panuhorsmalahti /types/jalaali-js/ @alitaheri /types/japanese-holidays/ @syamatoo -/types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software +/types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B /types/jasmine-ajax/ @lgrignon /types/jasmine-data_driven_tests/ @AnthonyMacKinnon /types/jasmine-enzyme/ @bolatovumar @@ -1549,7 +1617,7 @@ /types/jdataview/ @RReverser /types/jdenticon/ @mtr /types/jest/v16/ @NoHomey @jwbay -/types/jest/ @NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang @wsmd @JamieMason @douglasduteil +/types/jest/ @NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang @wsmd @JamieMason @douglasduteil @AhnpGit /types/jest-diff/ @myabc /types/jest-docblock/ @ikatyang /types/jest-get-type/ @myabc @@ -1562,11 +1630,12 @@ /types/jjv/ @Nemo157 /types/jjve/ @Nemo157 /types/jmespath/ @pushplay -/types/johnny-five/ @nakakura +/types/johnny-five/ @nakakura @ujvzolee @workshop2 /types/joi/v6/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW /types/joi/v10/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku -/types/joi/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @dankraus +/types/joi/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @dankraus @wanganjun /types/joigoose/ @boothwhack +/types/josa/ @vichyssoise /types/jpeg-js/ @DanielRosenwasser /types/jpm/ @github-account-because-they-want-it /types/jqgrid/ @lokeshpeta @@ -1576,7 +1645,9 @@ /types/jquery/ @leonard-thieu @borisyankov @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @johnnyreilly @DickvdBrink @King2500 /types/jquery-ajax-chain/ @humana-fragilitas /types/jquery-alertable/ @stever +/types/jquery-awesome-cursor/ @zskovacs /types/jquery-backstretch/ @dkulyk +/types/jquery-countdown/ @AndersonFriaca /types/jquery-cropbox/ @PerKastman /types/jquery-deparam/ @patsissons /types/jquery-easy-loading/ @delphinus35 @@ -1587,7 +1658,9 @@ /types/jquery-jcrop/ @joeskeen /types/jquery-jsonrpcclient/ @Ty3uK /types/jquery-knob/ @iain8 -/types/jquery-mask-plugin/ @avidenic +/types/jquery-lazyload/ @AndersonFriaca +/types/jquery-mask-plugin/ @avidenic @AndersonFriaca +/types/jquery-maskmoney/ @AndersonFriaca /types/jquery-match-height/ @kbytesys /types/jquery-mockjax/ @laszlojakab @vladeck /types/jquery-mousewheel/ @xt0rted @@ -1595,6 +1668,8 @@ /types/jquery-param/ @patsissons /types/jquery-sortable/ @Seltzer /types/jquery-steps/ @jblank @nickwph +/types/jquery-sticky/ @maixiu +/types/jquery-tags-input/ @AndersonFriaca /types/jquery-timeentry/ @marknadig /types/jquery-toastmessage-plugin/ @joeskeen /types/jquery-truncate-html/ @abraaoalves @@ -1649,6 +1724,7 @@ /types/jquery.slimscroll/ @Promact /types/jquery.soap/ @tigerxy /types/jquery.sortelements/ @tbureck +/types/jquery.stickem/ @davidmpaz /types/jquery.superlink/ @niemyjski /types/jquery.tagsmanager/ @vbortone /types/jquery.tile/ @zaneli @@ -1679,6 +1755,7 @@ /types/js-quantities/ @wrummler /types/js-schema/ @marcinporebski @roblabat /types/js-search/ @guoyunhe +/types/js-sha512/ @nicojs /types/js-to-java/ @skyitachi /types/js-url/ @pine613 /types/js-yaml/ @Bartvds @sclausen @@ -1696,7 +1773,9 @@ /types/jshamcrest/ @dharkness /types/jsmockito/ @shiver-me-timbers /types/jsnox/ @stkb @DovydasNavickas +/types/json-js/ @NN--- /types/json-merge-patch/ @senyaarseniy +/types/json-parse-better-errors/ @DanielRosenwasser /types/json-patch/ @vvakame /types/json-pointer/ @Bartvds /types/json-query/ @mtraynham @@ -1714,12 +1793,14 @@ /types/jsonnet/ @hookclaw /types/jsonp/ @surenkov /types/jsonpath/ @horiuchi @ikatyang -/types/jsonrpc-serializer/ @Akim95 +/types/jsonrpc-serializer/ @Akim95 @many20 /types/jsonstream/ @Bartvds +/types/jsontoxml/ @benstevens48 /types/jsonwebtoken/ @SomaticIT @danielheim @brikou /types/jspdf/ @amberjs /types/jsqrcode/ @lordazzi /types/jsrender/ @zakki +/types/jsreport-core/ @taoqf /types/jsrp/ @harryshipton /types/jss/ @appsforartists @kof /types/jssha/ @randombk @SrTobi @@ -1737,7 +1818,7 @@ /types/jui-core/ @easylogic /types/jui-grid/ @easylogic /types/jweixin/ @taoqf @gomydodo -/types/jwplayer/ @martinduparc @kutomer +/types/jwplayer/ @martinduparc @kutomer @philippguertler /types/jws/ @JustinBeckwith /types/jwt-client/ @timoteoponce /types/jwt-decode/v1/ @QuatroDevOfficial @@ -1767,6 +1848,7 @@ /types/klaw/v1/ @mceachen /types/klaw/ @mceachen /types/klaw-sync/ @shiftkey +/types/kms-json/ @sunnyone /types/knex/ @tkQubo @baronfel @MeLlamoPablo @mastermatt @micksatana /types/knex-postgis/ @vesse /types/knockback/ @borisyankov @@ -1807,7 +1889,8 @@ /types/koa-logger/ @geoffreak @tlaziuk /types/koa-logger-winston/ @stevehipwell /types/koa-morgan/ @vesse -/types/koa-mount/ @amirsaber +/types/koa-mount/ @amirsaber @tlaziuk +/types/koa-multer/ @benstevens48 /types/koa-passport/ @horiuchi @tlaziuk @brendtumi /types/koa-pino-logger/ @khell /types/koa-pug/ @Xstoudi @@ -1816,7 +1899,7 @@ /types/koa-route/ @migstopheles /types/koa-router/ @hellopao @schfkt /types/koa-send/ @pe8ter @tlaziuk -/types/koa-session/ @kerol2r20 +/types/koa-session/ @kerol2r20 @tlaziuk /types/koa-session-minimal/ @longztian /types/koa-sslify/ @wingsbob /types/koa-static/ @hellopao @tlaziuk @@ -1855,6 +1938,7 @@ /types/leaflet-gpx/ @soucekv /types/leaflet-imageoverlay-rotated/ @tkleinke /types/leaflet-label/ @Nemo157 +/types/leaflet-mouse-position/ @Hanyon /types/leaflet-polylinedecorator/ @soucekv /types/leaflet-providers/ @BendingBender /types/leaflet-rotatedmarker/ @robert-prib-polestar @@ -1866,7 +1950,6 @@ /types/leaflet.locatecontrol/ @DenisCarriere /types/leaflet.markercluster/ @rimig /types/leaflet.markercluster.layersupport/ @AsamK -/types/leaflet.mouseposition/ @Hanyon /types/leaflet.pancontrol/ @Brictarus /types/leaflet.pm/ @tkleinke /types/leaflet.polylinemeasure/ @RiON69 @@ -1890,7 +1973,6 @@ /types/line-by-line/ @etomsen /types/line-reader/ @stpettersens /types/linkify-it/ @praxxis -/types/linq4js/ @morrisjdev /types/lls/ @borislavjivkov /types/load-json-file/ @SamVerschueren /types/loader-runner/ @e-cloud @@ -1898,7 +1980,6 @@ /types/loadware/ @ALyman /types/lobibox/ @itboy87 /types/local-dynamo/ @Sicilica -/types/localforage-cordovasqlitedriver/ @thgreasi /types/localized-countries/ @coderslagoon /types/localizejs-library/ @salbahra /types/locate-path/ @me @@ -1907,7 +1988,7 @@ /types/lockr/ @droritos /types/locutus/ @hookclaw /types/lodash/v3/ @bczengel @chrootsu -/types/lodash/ @bczengel @chrootsu @stepancar @ericanderson @aj-r @ailrun @e-cloud @thorn0 @jtmthf +/types/lodash/ @bczengel @chrootsu @stepancar @aj-r @ailrun @e-cloud @thorn0 @jtmthf @DomiR /types/lodash-es/ @stephenlautier @e-cloud /types/lodash-webpack-plugin/ @bumbleblym /types/lodash.add/ @bczengel @chrootsu @stepancar @@ -2197,11 +2278,12 @@ /types/log-symbols/ @BendingBender /types/log-update/ @BendingBender /types/logat/ @krvikash35 +/types/logform/ @DABH /types/logg/ @blittle /types/loggly/ @rmartone @geoffreak /types/loglevel/ @Pro @szmeti @screendriver /types/logrotate-stream/ @rogierschouten -/types/lokijs/ @TeamworkGuy2 +/types/lokijs/ @TeamworkGuy2 @thomasconner /types/lolex/ @Nemo157 @joshuakgoldberg @rogierschouten /types/long/ @peterkooijmans /types/loopback/ @kattsushi @enko @sequoia @drmikecrowe @@ -2220,7 +2302,7 @@ /types/lunr/v0/ @sebastian-lenz /types/lunr/ @seantanly /types/lusca/ @crutchcorn -/types/luxon/ @colbydehart @FourwingsY +/types/luxon/ @colbydehart @FourwingsY @jsiebern /types/lwip/ @AyaMorisawa /types/lz-string/ @M0ns1gn0r /types/magic-number/ @stpettersens @@ -2255,15 +2337,36 @@ /types/massive/v3/ @swissspidy @clarenceh /types/massive/ @swissspidy @clarenceh @AmazingTurtle /types/match-media-mock/ @asvetliakov +/types/material-components-web/ @BrentDouglas /types/material-design-lite/ @bradzacher /types/material-ui/ @ngbrown @theigor @alitaheri @herrmanno @DaIgeb @allienna @schlesingermatthias @InsidersByte @artyomsv @dan-j @minodisk /types/material-ui-datatables/ @coding2012 -/types/materialize-css/v0/ @eriklieben @leonyu @SinghSukhdeep @jfcere @scote +/types/material__animation/ @BrentDouglas +/types/material__auto-init/ @BrentDouglas +/types/material__base/ @BrentDouglas +/types/material__checkbox/ @BrentDouglas +/types/material__dialog/ @BrentDouglas +/types/material__drawer/ @BrentDouglas +/types/material__form-field/ @BrentDouglas +/types/material__grid-list/ @BrentDouglas +/types/material__icon-toggle/ @BrentDouglas +/types/material__linear-progress/ @BrentDouglas +/types/material__menu/ @BrentDouglas +/types/material__radio/ @BrentDouglas +/types/material__ripple/ @BrentDouglas +/types/material__select/ @BrentDouglas +/types/material__selection-control/ @BrentDouglas +/types/material__slider/ @BrentDouglas +/types/material__snackbar/ @BrentDouglas +/types/material__tabs/ @BrentDouglas +/types/material__textfield/ @BrentDouglas +/types/material__toolbar/ @BrentDouglas +/types/materialize-css/v0/ @eriklieben @leonyu @SinghSukhdeep @jfcere @scote @LiadIdan /types/materialize-css/ @huww98 /types/math3d/ @laszlojakab @jimsmart /types/mathjax/ @rolandzwaga /types/mathjs/ @siavol -/types/matter-js/ @piranha771 +/types/matter-js/ @piranha771 @hasparus /types/maxmind/ @geoffreak /types/mcustomscrollbar/ @flurg /types/md5/ @arcdev1 @jprogrammer @@ -2277,10 +2380,11 @@ /types/memory-cache/ @jedigo @thieman /types/memory-fs/ @e-cloud /types/memwatch-next/ @cyrilschumacher -/types/meow/ @KnisterPeter +/types/meow/ @KnisterPeter @praxxis /types/merge-descriptors/ @danny8002 /types/merge-stream/ @k-kagurazaka @daniel-zazula /types/merge2/ @tkrotoff @smac89 +/types/merkle/ @kerol2r20 /types/mersenne-twister/ @KentarouTakeda /types/meshblu/ @fnipo /types/mess/ @Nemo157 @@ -2315,6 +2419,7 @@ /types/minimatch/ @vvakame @shantmarouti /types/minimist/ @Bartvds @Necroskillz @kamranayub /types/minimist-options/ @ikatyang +/types/minio/ @barinbritva /types/minipass/ @BendingBender /types/mirrorx/ @aaronphy /types/mithril/ @spacejack @andraaspar @isiahmeadows @@ -2326,7 +2431,9 @@ /types/mkpath/ @optical /types/mobx-apollo/ @pselden /types/mocha/ @kazimanzurrashid @otiai10 @jt000 @enlight +/types/mocha-each/ @magnostherobot /types/mocha-phantomjs/ @ErikSchierboom +/types/mocha-steps/ @Arylo /types/mochaccino/ @thomas-p /types/mock-aws-s3/ @bluehatbrit /types/mock-fs/ @Nemo157 @tkqubo @@ -2340,15 +2447,18 @@ /types/moji/ @yasupeke /types/moment-business/ @wonbyte /types/moment-business-time/ @swist -/types/moment-duration-format/ @SwintDC @TwoStone @leonard-thieu +/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-round/ @jacobbaskin /types/moment-strftime2/ @dex4er /types/moment-timezone/ @michelsalib @alanblins +/types/mongo-sanitize/ @CedricCazin +/types/mongodb/v2/ @CaselIT @alanmarcell @kikar @bitjson @dante-101 @mcortesi /types/mongodb/ @CaselIT @alanmarcell @kikar @bitjson @dante-101 @mcortesi -/types/mongoose/ @simonxca @horiuchi @sindrenm @lukasz-zak +/types/mongoose/v4/ @simonxca @horiuchi @sindrenm @lukasz-zak +/types/mongoose/ @simonxca @horiuchi @sindrenm @lukasz-zak @Alorel @jendrikw @ethanresnick /types/mongoose-auto-increment/ @AyaMorisawa /types/mongoose-deep-populate/ @AyaMorisawa /types/mongoose-geojson-schema/ @bondz @@ -2367,6 +2477,7 @@ /types/move-concurrently/ @mgroenhoff /types/moviedb/ @basarat @0x6368656174 /types/moxios/ @itoasuka +/types/mozilla-readability/ @charlesvdv /types/mpromise/ @sgkim126 /types/mri/ @shiftkey @j-f1 /types/ms/ @danny8002 @@ -2385,7 +2496,7 @@ /types/multiparty/ @kenfdev /types/multiplexjs/ @KamyarNazeri /types/multisort/ @CzBuCHi -/types/multistream/ @mrmlnc +/types/multistream/ @mrmlnc @kenzierocks /types/murmurhash-js/ @cvle /types/murmurhash3js/ @dlee-nvisia /types/musicmetadata/ @Xstoudi @@ -2396,6 +2507,7 @@ /types/n3/ @phreed /types/nano/ @timjacobi @vincekovacs /types/nanoajax/ @nathancahill +/types/nanoid/ @bash /types/nanomsg/ @titan /types/nanoscroller/ @zihark17 /types/nanp/ @karn @@ -2405,7 +2517,7 @@ /types/natural-sort/ @a-morales /types/navigation/ @grahammendick /types/navigation-react/ @grahammendick -/types/navigo/ @aersamkull +/types/navigo/ @aersamkull @dancespiele /types/nblas/ @erikgerrits /types/nconf/ @jedigo @jmthibault /types/ncp/ @bartvds @@ -2421,6 +2533,9 @@ /types/nes/ @NoHomey @saboya /types/net-keepalive/ @hertzg /types/netmask/ @mhfrantz +/types/new-relic-browser/ @renehamburger @piotrkubisa +/types/newline-remove/ @OpenByteDev +/types/newrelic/ @mastermatt /types/nexpect/ @vvakame /types/next/ @dru89 @brikou /types/next-redux-wrapper/ @stevegeek @@ -2447,19 +2562,20 @@ /types/nightmare/ @horiuchi @samyang-au /types/nightwatch/ @rkavalap @schlesiger /types/noble/ @swook @wind-rider @shantanubhadoria @lukel99 @bioball @keton -/types/nock/ @bonnici @horiuchi @afharo @mastermatt +/types/nock/ @bonnici @horiuchi @afharo @mastermatt @damour /types/nodal/ @charrondev /types/node/v4/ @eps1lon -/types/node/v6/ @WilcoBakker @inlined @eps1lon +/types/node/v6/ @WilcoBakker @inlined @eps1lon @Alorel /types/node/v7/ @parambirs @tellnes @WilcoBakker @eps1lon -/types/node/v8/ @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @OliverJAsh @eps1lon @Hannes-Magnusson-CK @jkomyno -/types/node/ @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @OliverJAsh @eps1lon @Hannes-Magnusson-CK @jkomyno @ajafff +/types/node/v8/ @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @OliverJAsh @eps1lon @Hannes-Magnusson-CK @jkomyno @hoo29 +/types/node/ @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @OliverJAsh @eps1lon @Hannes-Magnusson-CK @jkomyno @ajafff @hoo29 /types/node-7z/ @erkie /types/node-array-ext/ @Beng89 /types/node-cache/ @chrootsu @dthunell @useltmann /types/node-calendar/ @luzianz /types/node-cleanup/ @agadar /types/node-common-errors/ @icopp +/types/node-cron/ @maximelkin /types/node-dir/ @panuhorsmalahti /types/node-dogstatsd/ @chrisbobo /types/node-emoji/ @jonestristand @styu @@ -2478,7 +2594,6 @@ /types/node-json-db/ @kuzn-ilya /types/node-mysql-wrapper/ @kataras /types/node-notifier/ @tkQubo -/types/node-pg-migrate/ @bradleyayers /types/node-polyglot/ @timjk /types/node-powershell/ @rodrigoff /types/node-ral/ @ssddi456 @@ -2494,7 +2609,6 @@ /types/node-uuid/ @jeffmay /types/node-validator/ @kengorab /types/node-vault/ @YuJianrong -/types/node-waves/ @stephenlautier /types/node-wit/ @julienduf /types/node-xmpp-client/ @PJakcson /types/node-xmpp-core/ @PJakcson @@ -2527,6 +2641,7 @@ /types/novnc-core/ @smithkl42 @BendingBender /types/npm/ @SomaticIT /types/npm-package-arg/ @mgroenhoff +/types/npm-packlist/ @ajafff /types/ns-api/ @Archcry /types/nslog/ @unindented /types/nsqjs/ @cezaryrk @@ -2549,6 +2664,7 @@ /types/object-hash/ @misak113 /types/object-inspect/ @demurgos /types/object-map/ @wolfgang42 +/types/object-merge/ @OpenByteDev /types/object-path/ @pocesar /types/object-refs/ @3fd /types/oblo-util/ @Oblosys @@ -2557,10 +2673,11 @@ /types/oclazyload/ @rolandzwaga /types/odata/ @janhommes @jcchalte /types/ofe/ @Morfent -/types/office-js/ @OfficeDev @LanceEA +/types/office-js/ @OfficeDev @LanceEA @Zlatkovsky @kbrandl @Rick-Kirkham /types/offline-js/ @cgwrench /types/oibackoff/ @geoffreak /types/oidc-token-manager/ @rosieks +/types/ol/ @yairtawil /types/on-finished/ @czechboy0 @BendingBender /types/on-headers/ @jjeffery @BendingBender /types/once/ @denis-sokolov @BendingBender @@ -2574,16 +2691,16 @@ /types/openjscad/ @danmarshall /types/openlayers/v2/ @bolhovsky /types/openlayers/v3/ @osechet @matthiasdailey-ccri -/types/openlayers/ @osechet @wb14123 @ailrun @mylen @iamthechad @danmana +/types/openlayers/ @osechet @wb14123 @ailrun @mylen @iamthechad @danmana @yairtawil @pierremarc /types/openstack-wrapper/ @sanjaymadane /types/opentok/ @westy92 @CatGuardian -/types/opentype.js/ @danmarshall +/types/opentype.js/ @danmarshall @edzis /types/opn/ @shinnn @SomaticIT @tlent /types/optics-agent/ @crevil /types/optimist/ @soywiz @chbrown /types/optimize-css-assets-webpack-plugin/ @odnamrataizem /types/ora/v0/ @screendriver -/types/ora/ @basarat @screendriver @BendingBender +/types/ora/ @basarat @screendriver @BendingBender @azasypkin /types/oracledb/ @Bigous /types/orchestrator/ @tkQubo @TeamworkGuy2 /types/orderedmap/ @bradleyayers @@ -2593,7 +2710,7 @@ /types/os-locale/ @AyaMorisawa @BendingBender /types/os-name/ @BendingBender /types/os-tmpdir/ @mhegazy -/types/osmosis/ @jurajkocan +/types/osmosis/ @jurajkocan @evanshortiss /types/osmtogeojson/ @tkqubo /types/osrm/ @DenisCarriere /types/otplib/ @renjfk @@ -2611,6 +2728,7 @@ /types/p-every/ @BendingBender /types/p-lazy/ @BendingBender /types/p-limit/ @BendingBender +/types/p-loading/ @renjfk /types/p-locate/ @BendingBender /types/p-log/ @BendingBender /types/p-map/ @BendingBender @@ -2641,7 +2759,10 @@ /types/paper/ @clark-stevenson @Xakaloz /types/paralleljs/ @jbaldwin /types/parent-package-json/ @sgmccli -/types/parse/ @dpoetzsch @jaeggerr @flavionegrao +/types/parity-pmd/ @leovujanic @jewbre +/types/parity-pmr/ @leovujanic +/types/parity-poe/ @leovujanic +/types/parse/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes /types/parse-git-config/ @leonard-thieu /types/parse-glob/ @glen-84 /types/parse-json/ @mrmlnc @@ -2653,7 +2774,7 @@ /types/parse-unit/ @Jack-Works /types/parseurl/ @bomret /types/parsimmon/ @Bartvds @mizunashi-mana @bcherny @bvanreeven @leonard-thieu -/types/passport/ @horiuchi @enaeseth @theigor @tlaziuk +/types/passport/ @horiuchi @enaeseth @theigor @tlaziuk @danielpa9708 /types/passport-anonymous/ @0x6368656174 /types/passport-beam/ @AtlasDev /types/passport-discord/ @kzay @@ -2663,10 +2784,13 @@ /types/passport-github2/ @yasupeke @mthmulders /types/passport-google-oauth/ @staticfunction /types/passport-google-oauth2/ @bluehatbrit -/types/passport-http/ @krizalys +/types/passport-http/ @krizalys @tlaziuk @cjbarth /types/passport-http-bearer/ @isman-usoh +/types/passport-jwt/ @jindev +/types/passport-kakao/ @Park9eon /types/passport-local/ @SomaticIT /types/passport-local-mongoose/ @linusbrolin +/types/passport-naver/ @Park9eon /types/passport-oauth2/ @pasieronen /types/passport-oauth2-client-password/ @akaNightmare /types/passport-saml/ @cjbarth @@ -2741,7 +2865,7 @@ /types/playcanvas/ @Neoflash1979 /types/playerframework/ @ricardosabino /types/pleasejs/ @nakakura -/types/plotly.js/ @chrisgervang @martinduparc @frederikaalund @taoqf +/types/plotly.js/ @chrisgervang @martinduparc @frederikaalund @taoqf @Dadstart /types/plugapi/ @BNedry /types/plugin-error/ @rogierschouten /types/plupload/ @patrickbussmann @@ -2802,6 +2926,7 @@ /types/promise-pg/ @coldacid /types/promise-polyfill/ @skysteve /types/promise-pool/ @vilic +/types/promise-queue/ @LachlanStuart /types/promise-retry/ @shirakaba /types/promise.prototype.finally/ @slavik57 @BendingBender /types/promised-temp/ @rokadias @@ -2820,7 +2945,7 @@ /types/prosemirror-keymap/ @bradleyayers @davidka @timjb /types/prosemirror-markdown/ @bradleyayers @davidka @timjb /types/prosemirror-menu/ @bradleyayers @davidka @timjb -/types/prosemirror-model/ @bradleyayers @davidka @timjb +/types/prosemirror-model/ @bradleyayers @davidka @timjb @neknalb /types/prosemirror-schema-basic/ @bradleyayers @davidka @timjb /types/prosemirror-schema-list/ @bradleyayers @davidka @timjb /types/prosemirror-state/ @bradleyayers @davidka @timjb @@ -2835,18 +2960,19 @@ /types/proxyquire/ @jt000 /types/pty.js/ @enlight /types/public-ip/ @BendingBender -/types/pubnub/ @bitbankinc @rollymaduk +/types/pubnub/ @bitbankinc @rollymaduk @vitosamson /types/pubsub-js/ @borisyankov /types/pug/ @TonyPythoneer @19majkel94 -/types/pulltorefreshjs/ @DanielRosenwasser +/types/pulltorefreshjs/ @DanielRosenwasser @humpedli /types/pump/ @tlaziuk /types/pupa/ @nju33 -/types/puppeteer/ @marvinhagemeister @cdeutsch +/types/puppeteer/v0/ @marvinhagemeister @cdeutsch +/types/puppeteer/ @marvinhagemeister @cdeutsch @jwbay /types/pure-render-decorator/ @seansfkelley /types/purl/ @danfma /types/pusher-js/ @tkqubo /types/pvutils/ @microshine -/types/python-shell/ @dolanmiu +/types/python-shell/ @dolanmiu @WORMSS /types/q/v0/ @bnemetchek @johnnyreilly /types/q/ @bnemetchek @AndrewGaspar @johnnyreilly @mboudreau /types/q-io/ @Bartvds @@ -2859,7 +2985,7 @@ /types/qrcode.react/ @mleko /types/qs/ @RWander @leonyu @tehbelinda @zyml @artursvonda @CarlosBonetti /types/qtip2/ @Seltzer @leonard-thieu -/types/query-string/ @SamVerschueren @tkrotoff @huhuanming +/types/query-string/ @SamVerschueren @tkrotoff @huhuanming @MadaraUchiha /types/quick-lru/ @BendingBender /types/quill/ @sumitkm @guillaume-ro-fr @43081j /types/quixote/ @greybax @@ -2871,8 +2997,9 @@ /types/rabbit.js/ @wokim /types/radium/ @alexgorbatchev @nupplaphil @asvetliakov @mihe /types/radius/ @codeanimal -/types/ramda/ @donnut @mdekrey @mrdziuban @sbking @afharo @teves-castro @1M0reBug @hojberg @charlespwd @samsonkeung @angeloocana @raynerd @googol @moshensky +/types/ramda/ @donnut @mdekrey @mrdziuban @sbking @afharo @teves-castro @1M0reBug @hojberg @charlespwd @samsonkeung @angeloocana @raynerd @googol @moshensky @ethanresnick /types/random-js/ @pistacchio +/types/random-number/ @OpenByteDev /types/random-seed/ @endel /types/random-string/ @stpettersens /types/randomcolor/ @feitzi @BradyLiles @@ -2882,7 +3009,14 @@ /types/rappid/ @DenEwout /types/raspi/ @nebrius /types/raspi-board/ @nebrius +/types/raspi-gpio/ @nebrius +/types/raspi-i2c/ @nebrius +/types/raspi-led/ @nebrius +/types/raspi-onewire/ @nebrius /types/raspi-peripheral/ @nebrius +/types/raspi-pwm/ @nebrius +/types/raspi-serial/ @nebrius +/types/raspi-soft-pwm/ @nebrius /types/ratelimiter/ @AyaMorisawa /types/raty/ @terrawheat /types/raven/ @scttcper @1999 @@ -2904,13 +3038,14 @@ /types/react-aria-menubutton/ @forabi @crohlfs /types/react-autosuggest/ @nicolas-schmitt @pjo256 @robessog @tbayne @cdeutsch @rosskevin /types/react-beautiful-dnd/ @varHarrie @bradleyayers +/types/react-big-calendar/ @piotrwitek @paustint @pikpok /types/react-body-classname/ @mhegazy /types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @mretolaza @katbusch @vitosamson @LKay @aaronbeall /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 +/types/react-bootstrap-typeahead/ @Guymestef @radziksh /types/react-breadcrumbs/ @KostyaEsmukov /types/react-breadcrumbs-dynamic/ @mitsuruog /types/react-broadcast/ @kandros @@ -2918,12 +3053,13 @@ /types/react-calendar-heatmap/ @9renpoto /types/react-calendar-timeline/ @radziksh /types/react-cartographer/ @trevonmckay +/types/react-click-outside/ @screendriver /types/react-codemirror/ @velveret @rudi-c /types/react-collapse/ @Kimahriman /types/react-color/ @LKay @markspolakovs @mntdn /types/react-confirm/ @santiagodoldan /types/react-content-loader/ @alaatm -/types/react-copy-to-clipboard/ @mabels +/types/react-copy-to-clipboard/ @mabels @BernabeFelix /types/react-cropper/ @stepancar /types/react-css-modules/ @KostyaEsmukov @skirsdeda /types/react-css-transition-replace/ @LKay @@ -2933,7 +3069,7 @@ /types/react-data-grid/ @SupernaviX @KieranPeat @martinnov92 /types/react-datagrid/ @stephenjelfs /types/react-date-range/ @Junbong -/types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue +/types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue @KoalaHuman /types/react-daterange-picker/ @uncovertruth @MartynasZilinskas /types/react-dates/ @Artur-A /types/react-daum-postcode/ @Sa-ryong @@ -2948,13 +3084,15 @@ /types/react-dropzone/v2/ @matdube @LynxEyes @goblindegook @benbayard /types/react-dropzone/v3/ @matdube @LynxEyes @goblindegook @benbayard @LKay /types/react-dropzone/ @matdube @LynxEyes @goblindegook @benbayard @LKay @codeaid @jurosh +/types/react-dynamic-number/ @eugrdn /types/react-easy-chart/ @danzel /types/react-event-listener/ @asvetliakov /types/react-fa/ @flaub @patsissons @LKay /types/react-facebook-login/ @apare @jankarres -/types/react-faux-dom/ @alitaheri @cleverguy25 +/types/react-faux-dom/ @alitaheri @cleverguy25 @deviousm /types/react-file-input/ @dmitryrogozhny /types/react-file-reader-input/ @dmitryrogozhny @alitaheri +/types/react-flags-select/ @senukartur /types/react-flatpickr/ @begincalendar /types/react-flex/ @pushplay /types/react-flexr/ @pushplay @@ -2969,6 +3107,7 @@ /types/react-hamburger-menu/ @grzesie2k /types/react-helmet/v4/ @evanbb @isman-usoh /types/react-helmet/ @evanbb @isman-usoh @lith-light-g @sammkj @yuit +/types/react-helmet-async/ @forabi /types/react-highlight-words/ @mhegazy /types/react-highlighter/ @oizie /types/react-holder/ @isman-usoh @@ -2986,7 +3125,7 @@ /types/react-input-calendar/ @stepancar /types/react-input-mask/ @apare /types/react-intl/v1/ @bgrieder -/types/react-intl/ @bgrieder @cdroulers @gyzerok @tillwolff @LKay @bhouser @kristerkari +/types/react-intl/ @bgrieder @cdroulers @gyzerok @tillwolff @LKay @bhouser @kristerkari @formatlos /types/react-intl-redux/ @LKay /types/react-is-deprecated/ @seansfkelley /types/react-joyride/ @DanielRosenwasser @bendxn @@ -2997,7 +3136,7 @@ /types/react-lazyload/ @m0a /types/react-leaflet/ @danzel @davschne @yuit /types/react-list/ @buptyyf @tomshen -/types/react-loadable/ @Kovensky @odensc +/types/react-loadable/ @Kovensky @odensc @ianks @tlaziuk /types/react-loader/ @artfuldev /types/react-maskedinput/ @LKay @lavoaster @CarlosBonetti /types/react-mce/ @morphologue @@ -3006,7 +3145,7 @@ /types/react-mixin/ @tkqubo /types/react-modal/ @radziksh @drewnoakes @homburg @ttamminen @hallowatcher @peterblazejewicz /types/react-monaco-editor/ @jnetterf -/types/react-motion/ @stepancar @asvetliakov +/types/react-motion/ @stepancar @asvetliakov @dimitarnestorov /types/react-motion-slider/ @asvetliakov /types/react-native/ @alloy @huhuanming @iRoachie @timwangdev @kamal @nelyousfi /types/react-native-collapsible/ @iRoachie @@ -3023,19 +3162,21 @@ /types/react-native-google-signin/ @j-fro /types/react-native-keep-awake/ @huhuanming /types/react-native-linear-gradient/ @j-fro +/types/react-native-loading-spinner-overlay/ @fhelwanger /types/react-native-material-design-searchbar/ @iRoachie /types/react-native-material-kit/ @iRoachie @timwangdev /types/react-native-material-ui/ @iRoachie /types/react-native-mixpanel/ @r3nya /types/react-native-modalbox/ @iRoachie +/types/react-native-navigation/ @egorshulga /types/react-native-orientation/ @MoLow /types/react-native-popup-dialog/ @PaitoAnderson @connectdotz -/types/react-native-push-notification/ @PaitoAnderson +/types/react-native-push-notification/ @PaitoAnderson @tomSawkins /types/react-native-qrcode/ @plantain-00 /types/react-native-safari-view/ @mrand01 -/types/react-native-scrollable-tab-view/ @CaiHuan +/types/react-native-scrollable-tab-view/ @CaiHuan @egorshulga /types/react-native-sensor-manager/ @SahinVardar -/types/react-native-snap-carousel/ @jnbt +/types/react-native-snap-carousel/ @jnbt @j-fro /types/react-native-sortable-grid/ @j-fro /types/react-native-sortable-list/ @sivolobov /types/react-native-svg-uri/ @iRoachie @@ -3045,12 +3186,13 @@ /types/react-native-touch-id/ @huhuanming /types/react-native-vector-icons/ @iRoachie @timwangdev /types/react-native-video/ @huhuanming @abrahambotros -/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @abrahambotros @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko +/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @abrahambotros @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @robertohuertasm @YourGamesBeOver /types/react-notification-system/ @GiedriusGrabauskas @DeividasBakanas @LKay @sztobar /types/react-notification-system-redux/ @LKay /types/react-numeric-input/ @heatherbooker /types/react-onclickoutside/v5/ @LKay /types/react-onclickoutside/ @LKay +/types/react-onsenui/ @salim7 @jemmyw /types/react-overlays/ @aaronbeall @vitosamson /types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold /types/react-pointable/ @istefo @mdibyo @@ -3058,29 +3200,32 @@ /types/react-props-decorators/ @tkqubo /types/react-recaptcha/ @mhegazy @zzanol /types/react-redux/ @tkqubo @thasner @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva +/types/react-redux-epic/ @forabi /types/react-redux-i18n/ @clementdevos /types/react-redux-toastr/ @Smiche @artyomsv @kulmajaba -/types/react-relay/ @graphcool @voxmatt @alloy +/types/react-relay/ @graphcool @voxmatt @alloy @npirotte /types/react-resolver/ @forabi /types/react-responsive/v1/ @asvetliakov /types/react-responsive/ @asvetliakov @alechill @xaviergonz /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 -/types/react-router/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @tkrotoff @huy-nguyen @grmiade @DaIgeb @egorshulga +/types/react-router/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @tkrotoff @huy-nguyen @grmiade @DaIgeb @egorshulga @neuoy /types/react-router-bootstrap/ @vlesierse @LKay @olmobrutall /types/react-router-config/ @lith-light-g /types/react-router-dom/ @tkrotoff @huy-nguyen /types/react-router-native/ @ezintz +/types/react-router-navigation/ @kaoDev +/types/react-router-navigation-core/ @kaoDev /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 /types/react-s-alert/ @mitsuruog /types/react-scroll/ @sudoplz @GiedriusGrabauskas /types/react-scrollbar/ @stephenjelfs -/types/react-select/ @Hesquibet @giladgray @iebaker @skirsdeda @vujevits @devrelm @MartynasZilinskas @onatm @ninjaferret @tehbi4 +/types/react-select/ @Hesquibet @giladgray @iebaker @skirsdeda @vujevits @devrelm @MartynasZilinskas @onatm @ninjaferret @tehbi4 @misantronic /types/react-side-effect/ @remojansen /types/react-sidebar/ @jeroenvervaeke -/types/react-sketchapp/ @ricokahler +/types/react-sketchapp/ @ricokahler @DomiR /types/react-slick/ @andrewBalekha @GiedriusGrabauskas @r3nya /types/react-smooth-scrollbar/ @asvetliakov /types/react-sortable-hoc/ @NoHomey @charlesrey @@ -3105,6 +3250,7 @@ /types/react-test-renderer/v15/ @arvitaly @lochbrunner @lochbrunner @johnnyreilly /types/react-test-renderer/ @arvitaly @lochbrunner @johnnyreilly @jgoz /types/react-tether/ @ryprice +/types/react-text-mask/ @guilhermehubner /types/react-textarea-autosize/ @asvetliakov @zry656565 /types/react-toastr/ @shssoichiro /types/react-toggle/v2/ @LKay @@ -3116,28 +3262,31 @@ /types/react-transition-group/ @LKay /types/react-treeview/ @janslow /types/react-truncate/ @mattvperry +/types/react-twitter-auth/ @paulfasola /types/react-user-tour/ @ccancellieri /types/react-virtual-keyboard/ @bsurai /types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @kraenhansen /types/react-virtualized-select/ @seansfkelley /types/react-weui/ @tairan -/types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 +/types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 @r3nya /types/react-widgets-moment/ @dawnmist /types/react-youtube/ @kgtkr /types/reactable/ @spielc /types/reactcss/ @chrisgervang @LKay /types/reactstrap/v4/ @alihammad @mfal @danilobjr @fabiopaiva -/types/reactstrap/ @alihammad @mfal @danilobjr @fabiopaiva @FaithForHumans @KurtPreston +/types/reactstrap/ @alihammad @mfal @danilobjr @fabiopaiva @FaithForHumans @KurtPreston @kraenhansen @timc13 /types/read/ @timjk /types/read-chunk/ @crispybee /types/read-package-tree/ @mgroenhoff /types/read-pkg/ @jdxcode /types/read-pkg-up/ @dudeofawesome @jdxcode +/types/readdir-enhanced/ @mrmlnc /types/readdir-stream/ @Bartvds /types/readline-sync/ @jonestristand +/types/readline-transform/ @dex4er /types/reapop/ @Barrokgl /types/recase/ @18steps -/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong +/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong @richbai90 /types/recompose/ @iskandersierra @mrapogee @clayne11 /types/reconnectingwebsocket/ @nguarracino /types/recursive-readdir/v1/ @elisee @@ -3171,6 +3320,7 @@ /types/redux-immutable-state-invariant/ @remojansen @highflying /types/redux-infinite-scroll/ @silkyfray /types/redux-injectable-store/ @unindented +/types/redux-little-router/ @priecint /types/redux-localstorage/ @LKay /types/redux-localstorage-debounce/ @LKay /types/redux-localstorage-filter/ @LKay @@ -3184,6 +3334,7 @@ /types/redux-promise-middleware/ @ianks /types/redux-recycle/ @LKay /types/redux-router/ @stepancar +/types/redux-socket.io/ @snakeego /types/redux-storage/ @asvetliakov /types/redux-storage-engine-jsurl/ @screendriver /types/redux-storage-engine-localstorage/ @screendriver @@ -3196,20 +3347,23 @@ /types/relateurl/ @tkrotoff /types/relaxed-json/ @18steps /types/relay-runtime/ @voxmatt @alloy +/types/remarkable/ @makepost /types/remote-redux-devtools/ @ColinEberhardt @unindented /types/remove-markdown/ @RagibHasin /types/replace-ext/ @DeividasBakanas /types/request/ @soywiz @bonnici @Bartvds @joeskeen @ccurrens @lookfirst @mastermatt /types/request-ip/ @mrhen -/types/request-promise/ @cglantschnig @joeskeen @AyaMorisawa -/types/request-promise-native/ @gustavohenke +/types/request-promise/ @cglantschnig @joeskeen @AyaMorisawa @mastermatt +/types/request-promise-native/ @gustavohenke @mastermatt /types/requestretry/ @EricByers @trainerbill /types/require-dir/ @weekens /types/require-directory/ @Igmat /types/require-from-string/ @ikatyang +/types/require-relative/ @MattiasBuelens /types/requirejs/ @jbaldwin /types/requirejs-domready/ @lefb766 /types/resemblejs/ @pimterry +/types/reservoir/ @danvk /types/resolve/ @marionebl @ajafff /types/resolve-from/ @unional /types/resourcejs/ @shaunluttin @@ -3228,12 +3382,14 @@ /types/resumablejs/ @DanielMcAssey /types/rethinkdb/ @alexgorbatchev /types/retry/ @krenor +/types/retry-as-promised/ @Raigen /types/rev-hash/ @ikatyang /types/revalidate/ @alex3165 /types/revalidator/ @brewsoftware /types/reveal/ @robertop87 @Nava2 /types/rewire/ @borislavjivkov @CaselIT /types/rfc2047/ @mugifly +/types/rgrove__parse-xml/ @petejohanson /types/rheostat/ @SashaBayan @kourge /types/rickshaw/ @niemyjski /types/rimraf/ @soywiz @e-cloud @bash @@ -3244,16 +3400,16 @@ /types/riotjs/ @vvakame /types/rison/ @impworks /types/rivets/ @TrevorDev @matjanos -/types/rollup/ @flying-sheep @csvn +/types/roads/ @dancespiele /types/rollup-plugin-json/ @asmockler /types/ronomon__crypto-async/ @BendingBender /types/rosie/ @abner @subvertallchris -/types/roslib/ @Pro @skycoop +/types/roslib/ @Pro @skycoop @dgorobopec /types/rot-js/ @atiaxi /types/route-parser/ @ianks @bobbuehler /types/routie/ @Adilson /types/royalslider/ @csrakowski -/types/rpio/ @DominikPalo +/types/rpio/ @DominikPalo @Pencl /types/rrc/ @DeividasBakanas /types/rrule/ @waratuman /types/rsmq/ @MugeSo @@ -3280,6 +3436,7 @@ /types/rx-lite-time/ @Igorbek /types/rx-lite-virtualtime/ @Igorbek /types/rx.wamp/ @darkl +/types/s3-download-stream/ @everettcaleb /types/s3-upload-stream/ @geoffreak /types/safari-extension/ @luukd /types/safari-extension-content/ @luukd @@ -3298,6 +3455,7 @@ /types/sanitize-html/ @rogierschouten @afshin @BehindTheMath /types/sap__xsenv/ @mad-mike /types/sass-graph/ @marvinhagemeister +/types/sass-webpack-plugin/ @AepKill /types/sat/ @omni360 /types/satnav/ @DotNetNerd /types/saywhen/ @SeanSobey @@ -3310,7 +3468,7 @@ /types/scroller/ @haskellcamargo /types/scrollreveal/ @Davidblkx /types/scrolltofixed/ @bmdixon -/types/scrypt-async/ @xStrom +/types/scrypt-async/ @xStrom @stesix /types/scryptsy/ @micksatana /types/seamless/ @danmana /types/seamless-immutable/ @alex3165 @xsburg @geirsagberg @@ -3350,7 +3508,7 @@ /types/send/ @MikeJerred /types/seneca/ @psnider /types/sequelize/v3/ @samuelneff @codeanimal @drinchev @morpheusxaut @torhal -/types/sequelize/ @samuelneff @codeanimal @drinchev @babolivier @kukoo1 @oktapodia @morpheusxaut @TitaneBoy @zjy01 +/types/sequelize/ @samuelneff @codeanimal @drinchev @babolivier @kukoo1 @oktapodia @morpheusxaut @TitaneBoy @zjy01 @nidzov @Raigen @todd /types/sequelize-fixtures/ @cschwarz /types/sequencify/ @npenin /types/sequester/ @Strate @@ -3363,6 +3521,7 @@ /types/server-destroy/ @gyszalai /types/session-file-store/ @blendsdk @rokt33r /types/set-cookie-parser/ @nickp10 +/types/set-value/ @DanielRosenwasser /types/sha1/ @arcdev1 /types/shallowequal/ @seansfkelley /types/shapefile/ @DenisCarriere @@ -3379,6 +3538,7 @@ /types/shopify-buy/ @openminder /types/shortid/ @stpettersens @despairblue /types/shot/ @AJamesPhillips +/types/should-sinon/ @Arylo /types/showdown/ @cbowdon @tan9 /types/shrink-ray/ @forabi /types/siema/ @Irmiz @0x6368656174 @samnau @@ -3391,33 +3551,37 @@ /types/signature_pad/ @AbubakerB @jrmihalick /types/simple-assign/ @NoHomey /types/simple-cw-node/ @vvakame +/types/simple-lru/ @NN--- /types/simple-mock/ @leonyu /types/simple-oauth2/ @mad-mike /types/simple-peer/ @tlaziuk /types/simple-url-cache/ @a-lucas /types/simple-xml/ @notVitaliy /types/simplebar/v1/ @gregonnet @leonard-thieu -/types/simplebar/ @leonard-thieu +/types/simplebar/ @gregonnet @leonard-thieu /types/simplemde/ @Scalesoft /types/simplesmtp/ @rogierschouten /types/simplestorage.js/ @axelcostaspena @mxl +/types/single-line-log/ @ffflorian /types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j /types/sinon-as-promised/ @igrayson /types/sinon-chai/ @kazimanzurrashid @jedmao -/types/sinon-chrome/ @pimterry +/types/sinon-chrome/ @pimterry @crimx /types/sinon-express-mock/ @jpchip @tlaziuk /types/sinon-mongoose/ @stevehipwell -/types/sinon-stub-promise/ @vintem +/types/sinon-stub-promise/ @vintem @tstackhouse /types/sinon-test/ @mummybot /types/sip.js/ @decyrus /types/sipml/ @chookies /types/sitemap2/ @shundy /types/sizzle/ @leonard-thieu /types/sjcl/ @Evgenus +/types/skatejs/ @Hotell /types/ski/ @AyaMorisawa /types/skyway/ @nakakura /types/slack-node/ @geoffreak /types/slack-winston/ @BlueHatbRit +/types/slackdown/ @nju33 /types/slackify-html/ @hypexr /types/slate-irc/ @elisee /types/sleep/ @rajarz @@ -3439,8 +3603,9 @@ /types/socket.io/ @progre @divillysausages @florentpoujol @KentarouTakeda @gigi /types/socket.io-client/ @progre @divillysausages @florentpoujol /types/socket.io-parser/ @plantain-00 -/types/socket.io-redis/ @nupplaphil +/types/socket.io-redis/ @nupplaphil @seeLuck /types/socket.io.users/ @kataras +/types/socketio-jwt-auth/ @codeanimal /types/socketio-wildcard/ @BendingBender /types/socketty/ @Nax /types/sockjs/ @pmccloghrylaing @@ -3461,7 +3626,7 @@ /types/spdx-correct/ @jinwoo /types/spdx-satisfies/ @jinwoo /types/spdy/ @tony19 -/types/speakeasy/ @legendecas @mrOlorin +/types/speakeasy/ @legendecas @mrOlorin @xeoneux /types/speakingurl/ @Goldsmith42 /types/spectacle/ @zmaybury /types/spectrum/ @M-Zuber @@ -3469,7 +3634,7 @@ /types/split.js/ @icholy /types/split2/ @mugeso /types/spotify-api/ @skovmand -/types/spotify-web-playback-sdk/ @Festify +/types/spotify-web-playback-sdk/ @Festify @mraerino @NeoLegends /types/sprintf/ @soywiz @BendingBender /types/sprintf-js/ @jasonswearingen @BendingBender /types/sql.js/ @Hozuki @@ -3493,21 +3658,24 @@ /types/stats.js/ @gregolai @hberntsen @danvk /types/statsd-client/ @peterkooijmans @chrisleck /types/statuses/ @tkrotoff @BendingBender +/types/std-mocks/ @jdxcode /types/steam/ @kant2002 /types/steed/ @Paul-Isache /types/stemmer/ @will-ockmore /types/sticky-cluster/ @paustint -/types/stompjs/ @jimic +/types/stompjs/ @jimic @Dr4k4n /types/stoppable/ @EricByers /types/storejs/ @vbortone @harry0000 +/types/storybook__addon-a11y/ @hyunseob /types/storybook__addon-actions/ @joscha /types/storybook__addon-backgrounds/ @hyunseob /types/storybook__addon-info/ @mkornblum @fyrkant /types/storybook__addon-knobs/ @joscha @martynaskadisa -/types/storybook__addon-links/ @joscha +/types/storybook__addon-links/ @joscha @jessepinho /types/storybook__addon-notes/ @joscha /types/storybook__addon-options/ @joscha /types/storybook__react/ @joscha @wapgear +/types/storybook__vue/ @pntgupta /types/stream-buffers/ @Jason3S /types/stream-meter/ @mugeso /types/stream-series/ @k-kagurazaka @@ -3530,7 +3698,9 @@ /types/stripe-v2/ @ejsmith @amritk @adamcmiel @jleider @galuszkak /types/stripe-v3/ @ejsmith @amritk @adamcmiel @jleider @galuszkak /types/strong-cluster-control/ @shuntksh +/types/strong-log-transformer/ @azasypkin /types/strophe/ @DavidKDeutsch +/types/structured-source/ @azu /types/styled-jsx/ @R1ZZU /types/stylelint/ @alan-agius4 /types/stylelint-webpack-plugin/ @bahlo @@ -3541,7 +3711,7 @@ /types/suitescript/ @darrenhillconsulting /types/sumo-logger/ @forabi /types/superagent/v2/ @varju @NicoZelaya @mxl -/types/superagent/ @NicoZelaya @mxl @paplorinc +/types/superagent/ @NicoZelaya @mxl @paplorinc @shreyjain1994 /types/superagent-no-cache/ @mxl /types/superagent-prefix/ @mxl /types/supercluster/ @DenisCarriere @@ -3555,7 +3725,7 @@ /types/svg4everybody/ @BendingBender /types/svgjs.draggable/ @LiFeleSs /types/svgjs.resize/ @jkevingutierrez -/types/svgo/ @bradleyayers +/types/svgo/ @bradleyayers @giladgray /types/swag/ @shiwano /types/swagger-express-middleware/ @alexandreroba /types/swagger-express-mw/ @micmro @@ -3588,6 +3758,7 @@ /types/tapable/ @e-cloud /types/tape/ @Bartvds @sodatea @DennisSchwartz @mikehenrty /types/tar/ @SomaticIT @connor4312 +/types/tar-fs/ @Umoxfo /types/tcp-ping/ @stegano /types/tedious/ @rogierschouten @cjthompson /types/tedious-connection-pool/ @sandorfr @@ -3604,7 +3775,7 @@ /types/text-buffer/ @GlenCFL /types/text-encoding/ @pine613 /types/text-encoding-utf-8/ @trxcllnt -/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv +/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas /types/thrift/ @kamek-pf @kevin-greene-ck @jessezhang91 /types/throng/ @cyrilschumacher @tatethurston /types/throttle/ @BendingBender @@ -3623,7 +3794,7 @@ /types/tinder/ @pingec /types/tinycolor2/ @M-Zuber @geertjansen @nvh /types/tinycopy/ @vvatanabe -/types/tinymce/ @martinduparc @ipoul +/types/tinymce/ @martinduparc @ipoul @nicohartto /types/titanium/ @cyounkins /types/title/ @fa7ad /types/tldjs/ @geoffreak @@ -3660,17 +3831,19 @@ /types/tweezer.js/ @praxxis /types/twig/ @soywiz @enko /types/twilio/ @nickiannone @ashleybrener -/types/twit/ @Volox @lostfictions +/types/twit/ @Volox @lostfictions @sapphiredev /types/twitter/ @chitoku-k /types/twitter-stream-channels/ @adrianbardan /types/twitter-text/ @rhysd /types/twix/ @j3ko /types/type-check/ @hansrwindhoff +/types/type-detect/v0/ @Bartvds /types/type-detect/ @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/tz-format/ @samverschueren /types/ua-parser-js/ @superduper @legendecas @MeLlamoPablo @@ -3703,26 +3876,31 @@ /types/untildify/ @BendingBender /types/unused-filename/ @BendingBender /types/unzip/ @coding2012 +/types/unzipper/ @s73obrien +/types/update-notifier/v1/ @vvakame @nchen63 /types/update-notifier/ @vvakame @nchen63 +/types/upng-js/ @plantain-00 /types/uppercamelcase/ @plantain-00 /types/urbanairship-cordova/ @Justin-Credible /types/uri-templates/ @Bartvds -/types/urijs/ @RodneyJT @xt0rted +/types/urijs/ @RodneyJT @xt0rted @petejohanson /types/uritemplate/ @teyc @rubensworks /types/url-assembler/ @wolfgang42 /types/url-join/ @rogierschouten @devrelm /types/url-metadata/ @mrkmg /types/url-parse/ @ChernenkoPaul /types/url-regex/ @unindented -/types/url-search-params/ @nick121212 +/types/url-search-params/ @nick121212 @nrathi /types/url-template/ @marcinporebski +/types/urllib/ @sorayama +/types/urlparser/ @OpenByteDev /types/urlrouter/ @soywiz /types/urlsafe-base64/ @tkrotoff /types/usage/ @pvomhoff -/types/usb/ @underscorebrody +/types/usb/ @underscorebrody @thegecko /types/user-home/ @mhegazy /types/useragent/ @geoffreak -/types/username/ @kayahr +/types/username/ @kayahr @krivachy /types/utf8/ @zelein /types/util-deprecate/ @BendingBender /types/util.promisify/ @adamvoss @@ -3752,13 +3930,14 @@ /types/vex-js/ @gdcohan /types/vexflow/ @rquiring @sebastianhaas @bohoffi /types/vfile/ @bizen241 @rokt33r +/types/vfile-location/ @ikatyang /types/victory/ @asvetliakov @snerks @Havret /types/video.js/ @vbortone @scleriot @SWBennett06 @IgelCampus /types/viewability-helper/ @lironzluf /types/viewerjs/ @lrh3321 /types/viewporter/ @borisyankov /types/vimeo/ @DazWilkin -/types/vimeo__player/ @denisyilmaz +/types/vimeo__player/ @denisyilmaz @timc13 /types/vinyl/v0/ @jedmao /types/vinyl/ @vvakame @jedmao @thorn0 /types/vinyl-buffer/ @tkQubo @@ -3767,11 +3946,14 @@ /types/virtual-dom/ @chbrown /types/virtual-keyboard/ @bsurai /types/vis/ @MichaelBitard @macleodbroad-wf @adripanico @seveves @kaktus40 @mmaitre314 @supercargo @takato1314 -/types/vision/ @jasonswearingen @AJamesPhillips +/types/vision/v4/ @jasonswearingen @AJamesPhillips +/types/vision/ @jasonswearingen @AJamesPhillips @lenovouser /types/vitalsigns/ @cyrilschumacher /types/vivus/ @DanielRosenwasser @lekhmanrus /types/vkbeautify/ @sch3lp +/types/vnu-jar/ @Umoxfo /types/voca/ @pine +/types/void-elements/ @ajafff /types/voronoi-diagram/ @michaelneu /types/vortex-web-client/ @Pro /types/voximplant-websdk/ @aylarov @@ -3794,7 +3976,7 @@ /types/watchpack/ @e-cloud /types/waterline/ @arvitaly /types/watson-developer-cloud/ @waldo000000 @Naktibalda -/types/waypoints/ @dominikbulaj @Koloto +/types/waypoints/ @dominikbulaj @Koloto @evil-shrike /types/wcwidth/ @rokt33r /types/weak/ @int0h /types/weapp-api/ @vargeek @@ -3809,9 +3991,8 @@ /types/webfontloader/ @doskallemaskin /types/webgl-ext/ @zenmumbler /types/webgl2/ @nkemnitz -/types/webix/ @mkozhukh /types/webmidi/ @lostfictions -/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @ahmed-taj @alan-agius4 +/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @ahmed-taj @alan-agius4 @elliottsj @jason0x43 /types/webpack-bundle-analyzer/ @kryops /types/webpack-chain/ @eirikurn @psachs21 /types/webpack-chunk-hash/ @mtraynham @@ -3832,7 +4013,7 @@ /types/webpack-stream/ @iclanton @bumbleblym /types/webpack-validator/ @deevus /types/webrtc/ @nakakura -/types/websocket/ @loyd @flynetworks @zhaoleimxd +/types/websocket/ @loyd @flynetworks @zhaoleimxd @jdneo /types/webspeechapi/ @saschanaz /types/websql/ @TeamworkGuy2 /types/webtorrent/ @niieani @tlaziuk @@ -3869,7 +4050,8 @@ /types/wrench/ @soywiz /types/write-file-atomic/ @BendingBender /types/write-json-file/ @DenisCarriere -/types/ws/ @loyd @elithrar @mlamp +/types/write-pkg/ @azasypkin +/types/ws/ @loyd @elithrar @mlamp @TitaneBoy /types/wtfnode/ @dex4er /types/wu/ @phiresky /types/wx-js-sdk-dt/ @agasbzj @@ -3878,13 +4060,12 @@ /types/x-ray-crawler/ @mtraynham /types/xdate/ @yamada28go /types/xdg-basedir/ @tlaziuk -/types/xhr-mock/ @joscha /types/xml/ @YuJianrong /types/xml-parser/ @mhfrantz /types/xml2js/ @michelsalib @jasonrm @ccurrens @edwardhinkle @BehindTheMath /types/xml2json/ @dolanmiu /types/xmlbuilder/ @wallymathieu -/types/xmldoc/ @Xstoudi @ajsheehan +/types/xmldoc/ @Xstoudi @ajsheehan @notlaforge /types/xmldom/ @tkqubo /types/xmlpoke/ @garthk /types/xmltojson/ @traviscrowe @@ -3895,18 +4076,19 @@ /types/xrm/ @6ix4our @mattngan @markusmauch @daryllabar @clownwilleatme @scottdurow /types/xsd-schema-validator/ @Goldsmith42 /types/xsockets/ @pushplay -/types/xterm/ @blink1073 @LucianBuzzo /types/xxhashjs/ @mDibyo /types/yallist/ @BendingBender /types/yandex-maps/ @Delagen /types/yandex-money-sdk/ @chrootsu +/types/yar/ @SimonSchick /types/yargs/v8/ @poelstra @mizunashi-mana @pushplay @jeffkenney +/types/yargs/v10/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC /types/yargs/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC +/types/yauzl/ @ffflorian /types/yayson/ @Codesleuth /types/ydn-db/ @yathit @gabrielmaldi /types/yeoman-generator/ @armorik83 @janslow @ikatyang /types/yeoman-test/ @ikatyang -/types/yfiles/ @yGuy /types/yog-bigpipe/ @ssddi456 /types/yog-log/ @ssddi456 /types/yog2-kernel/ @ssddi456 @@ -3914,7 +4096,7 @@ /types/youtube/ @DazWilkin @JoshuaKGoldberg @eliotfallon213 /types/youtube-dl/ @bsurai /types/yui/ @giabao -/types/yup/ @dhardtke @vtserman +/types/yup/ @dhardtke @vtserman @MoretonBayRC /types/z-schema/ @pgonzal /types/zapier-platform-core/ @bradleyayers /types/zen-observable/ @aicest @@ -3923,9 +4105,13 @@ /types/zepto/ @jbaldwin /types/zeroclipboard/v1/ @ejsmith @niemyjski @balassy @leonyu /types/zeroclipboard/ @ejsmith @niemyjski @balassy @leonyu -/types/zeromq/ @davemckeown @erikma +/types/zeromq/ @davemckeown @erikma @TitaneBoy /types/zip.js/ @lgrignon /types/zipcodes/ @headdetect +/types/zipkin-context-cls/ @plantain-00 +/types/zipkin-instrumentation-express/ @plantain-00 +/types/zipkin-instrumentation-fetch/ @plantain-00 +/types/zipkin-transport-http/ @plantain-00 /types/zmq/ @davemckeown /types/zookeeper/ @xialeistudio /types/zui/ @yuanxu diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 4217471f9d..79793c16c1 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -2,6 +2,7 @@ Please fill in this template. - [ ] Use a meaningful title for the pull request. Include the name of the package modified. - [ ] Test the change in your own code. (Compile and run.) +- [ ] Add or edit tests to reflect the change. (Run with `npm test`.) - [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request). - [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes). - [ ] Run `npm run lint package-name` (or `tsc` if no `tslint.json` is present). diff --git a/README.es.md b/README.es.md new file mode 100644 index 0000000000..ce94bb0298 --- /dev/null +++ b/README.es.md @@ -0,0 +1,335 @@ +# 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) + +> El repositorio de definiciones de TypeScript de alta calidad. + +Vea también el sitio web [definitelytyped.org](http://definitelytyped.org), aunque la información en este README está más actualizada. + + +## ¿Qué son los `declaration files`? + +Vea el [Manual de TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). + + +## ¿Cómo los obtengo? + +### npm + +Este es el método preferido. Solo está disponible para usuarios TypeScript 2.0+. Por ejemplo: + +```sh +npm install --save-dev @types/node +``` + +Los types deberían ser incluidos automaticamente por el compilador. +Vea más en el [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html). + +Para un paquete NPM "foo", Estos `typings` estarán en "@types/foo". +Si no puedes encontrar tu paquete, búscalo en [TypeSearch](https://microsoft.github.io/TypeSearch/). + +Si aún no puedes encontrarlo, comprueba si el paquete ya [incluye](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) los typings. +Esto es provisto usualmente en el campo `"types"` o `"typings"` en el `package.json`, +o solo busca por cualquier archivo ".d.ts" en el paquete e incluyelo manualmente con un `/// `. + + +### Otros métodos + +Estos pueden ser utilizados por TypeScript 1.0. + +* [Typings](https://github.com/typings/typings) +* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use las alternativas preferidas, la publicación DT type de nuget ha sido desactivada) +* Descarguelo manualmente desde la `master` branch de este repositorio + +Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). + + +## ¿Cómo puedo contribuir? + +¡DefinitelyTyped solo trabaja gracias a contribuidores como tú! + +### Prueba + +Antes de compartir tu mejora con el mundo, úselo usted mismo. + +#### Prueba editando un paquete existente + +Para agregar nuevas funciones puedes usar el [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html). +También puedes editar directamente los types en `node_modules/@types/foo/index.d.ts`, o copiarlos de ahí y seguir los pasos explicados a continuación. + + +#### Prueba un nuevo paquete + +Añade a tu `tsconfig.json`: + +```json +"baseUrl": "types", +"typeRoots": ["types"], +``` + +(También puedes usar `src/types`.) +Crea un `types/foo/index.d.ts` que contenga declaraciones del módulo "foo". +Ahora deberías poder importar desde `"foo"` a tu código y te enviara a un nuevo tipo de definición. +Entonces compila *y* ejecuta el código para asegurarte que el tipo de definición en realidad corresponde a lo que suceda en el momento de la ejecución. +Una vez que hayas probado tus definiciones con el código real, haz un [PR](#make-a-pull-request) +luego sigue las instrucciones para [editar un paquete existente](#edit-an-existing-package) o +[crear un nuevo paquete](#create-a-new-package). + + +### Haz un pull request + +Una vez que hayas probado tu paquete, podrás compartirlo en DefinitelyTyped. + +Primero, haz un [fork](https://guides.github.com/activities/forking/) en este repositorio, instala [node](https://nodejs.org/), y luego ejecuta la `npm install`. + + +#### Editar un paquete existente + +* `cd types/my-package-to-edit` +* Haz cambios. Recuerda editar las pruebas. +* También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete. + - Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete. + - Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice , Bob `. + - O si hay más personas, puede ser multiline + ```typescript + // Definitions by: Alice + // Bob + // Steve + // John + ``` +* Si hay un `tslint.json`, ejecuta `npm run lint package-name`. De lo contrario, ejecuta `tsc` en el directorio del paquete. + +Cuando hagas un PR para editar un paquete existente, `dt-bot` deberá @-mencionar a los autores previos. +Si no lo hace, puedes hacerlo en el comentario asociado con el PR. + + +#### Crear un nuevo paquete + +Si eres el autor de la librería, o puedes hacer un pull request a la biblioteca, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) en vez de publicarlo en DefinitelyTyped. + +Si estás agregando typings para un paquete NPM, crea un directorio con el mismo nombre. +Si el paquete al que le estás agregando typings no es para NPM, asegurate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM. +(Puedes usar `npm info foo` para verificar la existencia del paquete `foo`.) + +Tu paquete debería tener esta estructura: + +| Archivo | Propósito | +| --- | --- | +| index.d.ts | Este contiene los typings del paquete. | +| foo-tests.ts | Este contiene una muestra del código con el que se realiza la prueba de escritura. Este código *no* es ejecutable, pero sí es type-checked. | +| tsconfig.json | Este permite ejecutar `tsc` dentro del paquete. | +| tslint.json | Permite linting. | + +Generalas ejecutando `npm install -g dts-gen` y `dts-gen --dt --name my-package-name --template module`. +Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen). + +También puedes configurar el `tsconfig.json` para añadir nuevos archivos, para agregar un `"target": "es6"` (necesitado por las funciones asíncronas), para agregar a la `"lib"`, o para agregar la opción de compilación `"jsx"`. + +Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrian ralentizar el proceso. + +Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js). + + +#### Errores comunes + +* Primero, sigue el consejo del [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html). +* Formatear: Ya sea utilizar todo en tabs, o siempre utiliza 4 espacios. +* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una funcion no escribe a sus parámetros. +* `interface Foo { new(): Foo; }`: + Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`. +* `const Class: { new(): IClass; }`: + Prefiere usar una declaración de clase `class Class { constructor(); }` En vez de una nueva constante. +* `getMeAT(): T`: + Si un tipo de parámetro no aparece en los tipos de ningún parámetro, no tienes una función genérica, solo tienes un afirmación del tipo disfrazado. + Prefiera utilizar una afirmación de tipo real, p.ej. `getMeAT() as number`. + Un ejemplo donde un tipo de parámetro es aceptable: `function id(value: T): T;`. + Un ejemplo donde no es aceptable: `function parseJson(json: string): T;`. + Una excepción: `new Map()` está bien. +* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más especifico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`. +* `var foo: string | any`: + Cuando es usado `any` en un tipo de unión, el tipo resultante todavía es `any`. Así que mientras la porción `string` de este tipo de anotación puede _verse_ útil, de hecho, no ofrece ningún typechecking adicional más que un simple `any`. + Dependiendo de la intención, una alternativa aceptable puede ser `any`, `string`, o `string | object`. + + +#### Remover un paquete + +Cuando un paquete [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) sus propios tipos, estos tipos deberán ser removidos de DefinitelyTyped para evitar que generen confusión. + +Se puede remover ejecutando `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`. +- `typingsPackageName`: Este es el nombre del directorio que tienes que eliminar. +- `asOfVersion`: Un stub será publicado a `@types/foo` con esta versión. Debería ser más grande que cualquier versión publicada actualmente. +- `sourceRepoURL`: Esto debería señalar el repositorio que contiene los typings. +- `libraryName`: Un nombre descriptivo de la librería, p.ej. "Angular 2" en vez de "angular2". (Si es omitido, será idéntico a "typingsPackageName".) + +Cualquier otro paquete en DefinitelyTyped que referencie el paquete eliminado deberá ser actualizado para referenciar los tipos bundled. para hacer esto, añade `package.json` con `"dependencies": { "foo": "x.y.z" }`. + +Si un paquete nunca estuvo en DefinitelyTyped, no será necesario añadirlo a `notNeededPackages.json`. + + +#### Lint + +Para realizar el lint a un paquete, solo añade `tslint.json` al paquete que contiene `{ "extends": "dtslint/dt.json" }`. Todos los paquetes nuevos deberán pasar por el proceso de linted. +Si el `tslint.json` deshabilita algunas reglas esto se debe a que aún no se ha acomodado. Por ejemplo: + +```js +{ + "extends": "dtslint/dt.json", + "rules": { + // This package uses the Function type, and it will take effort to fix. + "ban-types": false + } +} +``` + +(Para indicar que la regla lint realmente no es utilizada, usa `// tslint:disable rule-name` o mejor, `//tslint:disable-next-line rule-name`.) + +Para afirmar que una expresión es de un tipo dado, utilice `$ExpectType`. Para afirmar que una expresión causa un error de compilación, utilice `$ExpectError`. + +```js +// $ExpectType void +f(1); + +// $ExpectError +f("one"); +``` + +Para más detalles, vea el [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme. + +Realiza una prueba ejecutando `npm run lint package-name` donde `package-name` es el nombre de tu paquete. +Este script utiliza [dtslint](https://github.com/Microsoft/dtslint). + + +## FAQ + +#### ¿Cuál es exactamente la relación entre este repositorio y los paquetes de `@types` en NPM? + +La `master` branch es automaticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher). + +#### He enviado un pull request. ¿Cuánto tardará en ser merged? + +Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprovados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor se paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan on los PRs abiertos. + +#### Mi PR ha sido merged; ¿cuándo será actualizado el paquete de `@types` NPM? + +Los paquetes NPM deberán ser actualizados en unas cuantas horas. Si ha pasado más de 24 horas, menciona a @RyanCavanaugh y/o a @andy-ms en el PR para investigar. + +#### Estoy escribiendo una definición que depende de otra definición. Debería utilizar `` o una import? + +Si el modulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import. +Si el módulo al cual te refieres es un módulo ambiente (utiliza `declare module`, o simplemente declara las globales), utilice ``. + +#### He notado que algunos paquetes aquí tienen `package.json`. + +Normalmente no lo necesitaras. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso. +Un `package.json` puede ser incluido por el bien de especificar dependencias. Aquí tienen un [ejemplo](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json). +No aceptamos otros campos, tales como `"description"`, para que sean definidos manualmente. +Además, si necesitas referencia a una versión anterior de typings, debes hacerlo añadiendo `"dependencies": { "@types/foo": "x.y.z" }` al package.json. + +#### Algunos paquetes no tienen `tslint.json`, y algunos `tsconfig.json` no contienen `"noImplicitAny": true`, `"noImplicitThis": true`, o `"strictNullChecks": true`. + +Entonces están equivocados. Puedes ayudar enviando un pull request para arreglarlos. + +#### Puedo pedir una definition? + +Aquí están las [definiciones solicitadas actualmente](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest). + +#### ¿Qué pasa con las type definitions para el DOM? + +Si las types son parte de los estándares web, estas deberán ser contribuidas a [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) para que se hagan parte de la librería predeterminada `lib.dom.d.ts`. + +#### Un paquete utiliza `export =`, pero prefiero utilizar las import predeterminadas. ¿Puedo cambiar `export =` por `export default`? + +Si la import predeterminada trabaja en tu ambiente, considera hacer un cambio en la opción de compilación [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) opción compilar. +No cambies la type definition si es preciso. +Para un paquete NPM, `export =` es exacto si `node -p 'require("foo")'` es la export, y `export default` es exacto si `node -p 'require("foo").default'` es el export. + +#### Quiero usar las características de TypeScript 2.1 o superior. + +Entonces deberás añadir un comentario a la última línea de la definición en el encabezado (despues de `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`. + +#### Quiero añadir un DOM API que no está presente en TypeScript por defecto. + +Esto puede pertenecer a [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Vea las guías allí. +Si el estándar sigue siendo un borrador, este pertenece aquí. +Utilice un nombre que empiece con `dom-` e incluya un link al estándar como el "Project" con el link en el encabezado. +Cuando ya no sea un borrador, lo podremos eliminar desde DefinitelyType y hacer obsoleto el paquete `@types` asociado. + +#### Quiero actualizar un paquete a una nueva versión principal + +Si planeas continuar actualizando la versión anterior del paquete, puedes crear una subcarpeta con la versión actual p.ej. `v2`, y copia los archivos existentes. Si es así, necesitarás: + +1. Actualiza las rutas relativas en `tsconfig.json` al igual que `tslint.json`. +2. Añadir reglas de mapeo de rutas para asegurart de que la prueba se está ejecutando contra la versión prevista. + +Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) se ve así: + +```json +{ + "compilerOptions": { + "baseUrl": "../../", + "typeRoots": ["../../"], + "paths": { + "history": [ "history/v2" ] + }, + }, + "files": [ + "index.d.ts", + "history-tests.ts" + ] +} +``` + +Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitaras mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior. + +Por ejemplo, `react-router` depende de `history@2`, así que [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) tiene una ruta mapeada a "history": `[ "history/v2" ]`; +transitivo así mismo, `react-router-bootstrap` (que depende de `react-router`) también añade una ruta mapeada en su [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json). + +Además, `/// ` no trabajara con rutas mapeadas, así que las dependencias deberán utilizar `import`. + +#### ¿Cómo escribo definitions para paquetes que pueden ser usados globalmente y como un módulo? + +El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), ademas [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada practicamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a travéz de una etiqueta script en una página web, o importada via require o imports estilo ES6. + +Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas un propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js. + +Por favor tenga en cuenta que no es necesario para ejercer plenamente la definición en cada archivo de prueba - Es suficiente con probar solo los elementos globalmente accesibles en la prueba de archivos globales y ejercer la definición en el módulo del archivo de prueba, o viceversa. + +#### ¿Qué pasa con paquetes scoped? + +Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guion bajo. + +Cuando `dts-gen` es utilizado como scaffold en un paquete scoped, las propiedades `paths` deberán ser adaptadas manualmente en el paquete generado +`tsconfig.json` para referenciar correctamente el paquete scoped: + +```json +{ + "paths":{ + "@foo/bar": ["foo__bar"] + } +} +``` + +#### El historial de archivos en GitHub parece incompleto. + +GitHub no le hace [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) historial de archivos para archivos renombrados. Utilice [`git log --follow`](https://www.git-scm.com/docs/git-log) en su lugar. + +#### Debería añadir un namespace que no exporte un módulo que utilice que utilice imports estilo ES6? + +Algunos paquetes, como [chai-http](https://github.com/chaijs/chai-http), exportan una función. + +importar este módulo con un ES6 style import de forma `import * as foo from "foo";` conduce al error: + +> error ts2497: El módulo 'foo' se resuelve en una entidad que no es un módulo y no se puede importar mediante esta construcción + +Este error puede ser suprimido al unir la declaración de una función con un namespace vacío del mismo nombre pero esta práctica no es recomendable. +Esto es un citado común [Respuestas de Stack Overflow](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) con respecto a este asunto. + +Es más apropiado importar este módulo utilizando la sintaxis `import foo = require("foo");`, o utilizando una importación predeterminada como `import foo from "foo";` si usas la bandera `--allowSyntheticDefaultImports` si la ejecución de tu módulo soporta un esquema de interoperación para módulos no ECMAScript como tal. + +## Licencia + +Este proyecto es licenciado bajo la licencia MIT. + +Los derechos de autor de cada archivo de definición son respectivos de cada contribuidor listado al comienzo de cada archivo de definición. + +[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) diff --git a/README.md b/README.md index 854cae7e40..cc59284394 100644 --- a/README.md +++ b/README.md @@ -6,12 +6,12 @@ Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date. +*[You can also read this README in Spanish!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md)* ## What are declaration files? See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). - ## How do I get them? ### npm @@ -256,7 +256,7 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat #### I want to update a package to a new major version -Before making your change, please create a new subfolder with the current version e.g. `v2`, and copy existing files to it. You will need to: +If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to: 1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. 2. Add path mapping rules to ensure that tests are running against the intended version. @@ -279,7 +279,8 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi } ``` -Please note that unless upgrading something backwards-compatible like `node`, all packages depending of the updated package need a path mapping to it, as well as packages depending on *those*. +If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version. + For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`; transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json). diff --git a/notNeededPackages.json b/notNeededPackages.json index 7051c16568..8c587f7c43 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -6,6 +6,12 @@ "sourceRepoURL": "https://github.com/betterwaysystems/packer", "asOfVersion": "1.1.3" }, + { + "libraryName": "Ably Realtime and Rest client library", + "typingsPackageName": "ably", + "sourceRepoURL": "https://www.ably.io/", + "asOfVersion": "1.0.0" + }, { "libraryName": "ag-grid", "typingsPackageName": "ag-grid", @@ -18,6 +24,12 @@ "sourceRepoURL": "https://github.com/epoberezkin/ajv", "asOfVersion": "1.0.0" }, + { + "libraryName": "angular-touchspin", + "typingsPackageName": "angular-touchspin", + "sourceRepoURL": "https://github.com/nkovacic/angular-touchspin", + "asOfVersion": "1.8.2" + }, { "libraryName": "angular-ui-router-default", "typingsPackageName": "angular-ui-router-default", @@ -78,6 +90,12 @@ "sourceRepoURL": "https://github.com/AlexTeixeira/Askmethat-Rating", "asOfVersion": "0.4.0" }, + { + "libraryName": "assertion-error", + "typingsPackageName": "assertion-error", + "sourceRepoURL": "https://github.com/chaijs/assertion-error", + "asOfVersion": "1.1.0" + }, { "libraryName": "asyncblock", "typingsPackageName": "asyncblock", @@ -155,6 +173,12 @@ "typingsPackageName": "bignumber.js", "sourceRepoURL": "https://github.com/MikeMcl/bignumber.js/", "asOfVersion": "5.0.0" + }, + { + "libraryName": "bingmaps", + "typingsPackageName": "bingmaps", + "sourceRepoURL": "https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions", + "asOfVersion": "2.0.15" }, { "libraryName": "botvs", @@ -228,12 +252,6 @@ "sourceRepoURL": "https://github.com/blakeembrey/constant-case", "asOfVersion": "1.1.2" }, - { - "libraryName": "core-decorators.js", - "typingsPackageName": "core-decorators", - "sourceRepoURL": "https://github.com/jayphelps/core-decorators.js", - "asOfVersion": "0.20.0" - }, { "libraryName": "cordova-plugin-battery-status", "typingsPackageName": "cordova-plugin-battery-status", @@ -342,6 +360,12 @@ "sourceRepoURL": "https://github.com/dpa99c/cordova-diagnostic-plugin", "asOfVersion": "3.7.0" }, + { + "libraryName": "core-decorators.js", + "typingsPackageName": "core-decorators", + "sourceRepoURL": "https://github.com/jayphelps/core-decorators.js", + "asOfVersion": "0.20.0" + }, { "libraryName": "cypress", "typingsPackageName": "cypress", @@ -390,12 +414,6 @@ "sourceRepoURL": "https://github.com/dvajs/dva", "asOfVersion": "1.1.0" }, - { - "libraryName": "EasyStar.js", - "typingsPackageName": "easystarjs", - "sourceRepoURL": "http://easystarjs.com/", - "asOfVersion": "0.3.1" - }, { "libraryName": "easy-x-headers", "typingsPackageName": "easy-x-headers", @@ -408,6 +426,12 @@ "sourceRepoURL": "https://github.com/DeadAlready/easy-xapi-supertest", "asOfVersion": "1.0.0" }, + { + "libraryName": "EasyStar.js", + "typingsPackageName": "easystarjs", + "sourceRepoURL": "http://easystarjs.com/", + "asOfVersion": "0.3.1" + }, { "libraryName": "ecmarkup", "typingsPackageName": "ecmarkup", @@ -474,6 +498,12 @@ "sourceRepoURL": "https://github.com/primus/eventemitter3", "asOfVersion": "2.0.2" }, + { + "libraryName": "expr-eval", + "typingsPackageName": "expr-eval", + "sourceRepoURL": "https://github.com/silentmatt/expr-eval", + "asOfVersion": "1.1.0" + }, { "libraryName": "express-validator", "typingsPackageName": "express-validator", @@ -540,6 +570,12 @@ "sourceRepoURL": "http://arshaw.com/fullcalendar/", "asOfVersion": "3.8.0" }, + { + "libraryName": "fuse", + "typingsPackageName": "fuse", + "sourceRepoURL": "https://github.com/krisk/Fuse", + "asOfVersion": "2.6.0" + }, { "libraryName": "gaea-model", "typingsPackageName": "gaea-model", @@ -576,6 +612,12 @@ "sourceRepoURL": "https://github.com/panuhorsmalahti/gulp-tslint", "asOfVersion": "4.2.0" }, + { + "libraryName": "gulp-typedoc", + "typingsPackageName": "gulp-typedoc", + "sourceRepoURL": "https://github.com/rogierschouten/gulp-typedoc", + "asOfVersion": "2.2.0" + }, { "libraryName": "gulp-typescript", "typingsPackageName": "gulp-typescript", @@ -588,24 +630,30 @@ "sourceRepoURL": "https://handsontable.com/", "asOfVersion": "0.35.0" }, - { - "libraryName": "http-status-codes", - "typingsPackageName": "http-status-codes", - "sourceRepoURL": "https://github.com/prettymuchbryce/node-http-status", - "asOfVersion": "1.2.0" - }, { "libraryName": "homeworks", "typingsPackageName": "homeworks", "sourceRepoURL": "https://github.com/IGAWorksDev/homeworks/", "asOfVersion": "1.0.19" }, + { + "libraryName": "http-status-codes", + "typingsPackageName": "http-status-codes", + "sourceRepoURL": "https://github.com/prettymuchbryce/node-http-status", + "asOfVersion": "1.2.0" + }, { "libraryName": "iconv-lite", "typingsPackageName": "iconv-lite", "sourceRepoURL": "https://github.com/ashtuchkin/iconv-lite", "asOfVersion": "0.4.14" }, + { + "libraryName": "immutability-helper", + "typingsPackageName": "immutability-helper", + "sourceRepoURL": "https://github.com/kolodny/immutability-helper", + "asOfVersion": "2.6.3" + }, { "libraryName": "Facebook's Immutable", "typingsPackageName": "immutable", @@ -786,6 +834,12 @@ "sourceRepoURL": "https://linqjs.codeplex.com/", "asOfVersion": "2.2.33" }, + { + "libraryName": "Linq4JS", + "typingsPackageName": "linq4js", + "sourceRepoURL": "https://github.com/morrisjdev/Linq4JS", + "asOfVersion": "2.1.8" + }, { "libraryName": "LinqSharp", "typingsPackageName": "linqsharp", @@ -798,6 +852,12 @@ "sourceRepoURL": "https://github.com/localForage/localForage", "asOfVersion": "0.0.34" }, + { + "libraryName": "localforage-cordovasqlitedriver", + "typingsPackageName": "localforage-cordovasqlitedriver", + "sourceRepoURL": "https://github.com/thgreasi/localForage-cordovaSQLiteDriver", + "asOfVersion": "1.5.0" + }, { "libraryName": "lodash-decorators", "typingsPackageName": "lodash-decorators", @@ -894,6 +954,18 @@ "sourceRepoURL": "https://github.com/esvit/ng-table", "asOfVersion": "2.0.1" }, + { + "libraryName": "node-pg-migrate", + "typingsPackageName": "node-pg-migrate", + "sourceRepoURL": "https://github.com/theoephraim/node-pg-migrate#readme", + "asOfVersion": "2.15.0" + }, + { + "libraryName": "node-waves", + "typingsPackageName": "node-waves", + "sourceRepoURL": "http://fian.my.id/Waves", + "asOfVersion": "0.7.6" + }, { "libraryName": "Normalizr", "typingsPackageName": "normalizr", @@ -1176,6 +1248,12 @@ "sourceRepoURL": "https://github.com/EnoF/rest-io", "asOfVersion": "4.1.0" }, + { + "libraryName": "rollup", + "typingsPackageName": "rollup", + "sourceRepoURL": "https://github.com/rollup/rollup", + "asOfVersion": "0.54.0" + }, { "libraryName": "route-recognizer", "typingsPackageName": "route-recognizer", @@ -1464,6 +1542,12 @@ "sourceRepoURL": "https://webgme.org", "asOfVersion": "2.11.0" }, + { + "libraryName": "Webix UI", + "typingsPackageName": "webix", + "sourceRepoURL": "http://webix.com", + "asOfVersion": "5.1.1" + }, { "libraryName": "wolfy87-eventemitter", "typingsPackageName": "wolfy87-eventemitter", @@ -1494,6 +1578,12 @@ "sourceRepoURL": "https://github.com/PeculiarVentures/xadesjs", "asOfVersion": "2.0.2" }, + { + "libraryName": "xhr-mock", + "typingsPackageName": "xhr-mock", + "sourceRepoURL": "https://github.com/jameslnewell/xhr-mock#readme", + "asOfVersion": "2.0.0" + }, { "libraryName": "xlsx", "typingsPackageName": "xlsx", @@ -1512,6 +1602,18 @@ "sourceRepoURL": "github.com/node-xmpp/node-xmpp/", "asOfVersion": "1.2.0" }, + { + "libraryName": "xterm.js", + "typingsPackageName": "xterm", + "sourceRepoURL": "https://github.com/sourcelair/xterm.js/", + "asOfVersion": "3.0.0" + }, + { + "libraryName": "yFiles for HTML", + "typingsPackageName": "yfiles", + "sourceRepoURL": "none", + "asOfVersion": "2.1.0" + }, { "libraryName": "zetapush-js", "typingsPackageName": "zetapush-js", @@ -1523,13 +1625,6 @@ "typingsPackageName": "zone.js", "sourceRepoURL": "https://github.com/angular/zone.js", "asOfVersion": "0.5.12" - }, - - { - "libraryName": "immutability-helper", - "typingsPackageName": "immutability-helper", - "sourceRepoURL": "https://github.com/kolodny/immutability-helper", - "asOfVersion": "2.6.3" } ] } diff --git a/scripts/generate-tsconfigs.ts b/scripts/generate-tsconfigs.ts index 0115067e34..e1e1998950 100644 --- a/scripts/generate-tsconfigs.ts +++ b/scripts/generate-tsconfigs.ts @@ -5,7 +5,7 @@ import * as fs from 'fs'; import * as path from 'path'; -const home = path.join(__dirname, '..'); +const home = path.join(__dirname, "..", "types"); for (const dirName of fs.readdirSync(home)) { if (dirName.startsWith(".") || dirName === "node_modules" || dirName === "scripts") { diff --git a/types/ably/ably-tests.ts b/types/ably/ably-tests.ts deleted file mode 100644 index bc50d03ce6..0000000000 --- a/types/ably/ably-tests.ts +++ /dev/null @@ -1,253 +0,0 @@ -import * as Ably from 'ably'; - -declare const console: { log(message: any): void }; - -const ApiKey = 'appId.keyId:secret'; -const client = new Ably.Realtime(ApiKey); -const restClient = new Ably.Rest(ApiKey); - -// Connection -// Successful connection: - -client.connection.on('connected', () => { - // successful connection -}); - -// Failed connection: - -client.connection.on('failed', () => { - // failed connection -}); - -// Subscribing to a channel - -const channel = client.channels.get('test'); -channel.subscribe(message => { - message.name; // 'greeting' - message.data; // 'Hello World!' -}); - -// Only certain events: - -channel.subscribe('myEvent', message => { - message.name; // 'myEvent' - message.data; // 'myData' -}); - -// Publishing to a channel - -// Publish a single message with name and data -channel.publish('greeting', 'Hello World!'); - -// Optionally, you can use a callback to be notified of success or failure -channel.publish('greeting', 'Hello World!', err => { - if (err) { - console.log('publish failed with error ' + err); - } else { - console.log('publish succeeded'); - } -}); - -// Publish several messages at once -channel.publish([{name: 'greeting', data: 'Hello World!'}], () => { }); - -// Querying the History - -channel.history((err, messagesPage) => { - messagesPage.items; // array of Message - messagesPage.items[0].data; // payload for first message - messagesPage.items.length; // number of messages in the current page of history - messagesPage.hasNext(); // true if there are further pages - messagesPage.isLast(); // true if this page is the last page - messagesPage.next(nextPage => { nextPage; }); // retrieves the next page as PaginatedResult -}); - -// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history -channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards'}, (err, messagesPage) => { - console.log(messagesPage.items.length); -}); - -// Presence on a channel -// Getting presence: - -channel.presence.get(presenceSet => { - presenceSet; // array of PresenceMessages -}); - -// Note that presence#get on a realtime channel does not return a PaginatedResult, as the library maintains a local copy of the presence set. - -// Entering (and leaving) the presence set: - -channel.presence.enter('my status', err => { - // now I am entered -}); - -channel.presence.update('new status', err => { - // my presence data is updated -}); - -channel.presence.leave(null, err => { - // I've left the presence set -}); - -channel.presence.enterClient('myClientId', 'status', err => { -}); - -// and similiarly, updateClient and leaveClient -// Querying the Presence History - -channel.presence.history((err, messagesPage) => { // PaginatedResult - messagesPage.items; // array of PresenceMessage - messagesPage.items[0].data; // payload for first message - messagesPage.items.length; // number of messages in the current page of history - messagesPage.hasNext(); // true if there are further pages - messagesPage.isLast(); // true if this page is the last page - messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult -}); - -// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history -channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); - -// Symmetrical end-to-end encrypted payloads on a channel - -// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key. -// The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption - -// Generate a random 256-bit key for demonstration purposes (in -// practice you need to create one and distribute it to clients yourselves) -Ably.Realtime.Crypto.generateRandomKey((err, key) => { - const channel = client.channels.get('channelName', { cipher: { key } }); - - channel.subscribe(message => { - message.name; // 'name is not encrypted' - message.data; // 'sensitive data is encrypted' - }); - - channel.publish('name is not encrypted', 'sensitive data is encrypted'); -}); - -// You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect): - -channel.setOptions({cipher: {key: ''}}, () => { - // New encryption settings are in effect -}); - -// Using the REST API - -const restChannel = restClient.channels.get('test'); - -// Publishing to a channel - -// Publish a single message with name and data -restChannel.publish('greeting', 'Hello World!'); - -// Optionally, you can use a callback to be notified of success or failure -restChannel.publish('greeting', 'Hello World!', err => { - if (err) { - console.log('publish failed with error ' + err); - } else { - console.log('publish succeeded'); - } -}); - -// Publish several messages at once -restChannel.publish([{name: 'greeting', data: 'Hello World!'}], () => {}); - -// Querying the History - -restChannel.history((err, messagesPage) => { - messagesPage; // PaginatedResult - messagesPage.items; // array of Message - messagesPage.items[0].data; // payload for first message - messagesPage.items.length; // number of messages in the current page of history - messagesPage.hasNext(); // true if there are further pages - messagesPage.isLast(); // true if this page is the last page - messagesPage.next(nextPage => {}); // retrieves the next page as PaginatedResult -}); - -// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history -restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); - -// Presence on a channel - -restChannel.presence.get((err, presencePage) => { // PaginatedResult - presencePage.items; // array of PresenceMessage - presencePage.items[0].data; // payload for first message - presencePage.items.length; // number of messages in the current page of members - presencePage.hasNext(); // true if there are further pages - presencePage.isLast(); // true if this page is the last page - presencePage.next(nextPage => {}); // retrieves the next page as PaginatedResult -}); - -// Querying the Presence History - -restChannel.presence.history((err, messagesPage) => { // PaginatedResult - messagesPage.items; // array of PresenceMessage - messagesPage.items[0].data; // payload for first message - messagesPage.items.length; // number of messages in the current page of history - messagesPage.hasNext(); // true if there are further pages - messagesPage.isLast(); // true if this page is the last page - messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult -}); - -// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history -restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); - -// Generate Token and Token Request -// See https://www.ably.io/documentation/general/authentication for an explanation of Ably's authentication mechanism. - -// Requesting a token: - -client.auth.requestToken((err, tokenDetails) => { - // tokenDetails is instance of TokenDetails - // see https://www.ably.io/documentation/rest/authentication/#token-details for its properties - - // Now we have the token, we can send it to someone who can instantiate a client with it: - const clientUsingToken = new Ably.Realtime(tokenDetails.token); -}); - -// requestToken can take two optional params -// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params -// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options -client.auth.requestToken({}, {}, (err, tokenDetails) => { }); - -// Creating a token request (for example, on a server in response to a request by a client using the authCallback or authUrl mechanisms): - -client.auth.createTokenRequest((err, tokenRequest) => { - // now send the tokenRequest back to the client, which will - // use it to request a token and connect to Ably -}); - -// createTokenRequest can take two optional params -// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params -// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options -client.auth.createTokenRequest({}, {}, (err, tokenRequest) => { }); - -// Fetching your application's stats - -client.stats({ limit: 50 }, (err, statsPage) => { // statsPage as PaginatedResult - statsPage.items; // array of Stats - statsPage.items[0].inbound.rest.messages.count; // total messages published over REST - statsPage.items.length; // number of stats in the current page of history - statsPage.hasNext(); // true if there are wrther pages - statsPage.isLast(); // true if this page is the last page - statsPage.next((nextPage) => {}); // retrieves the next page as PaginatedResult -}); - -// Fetching the Ably service time - -client.time({}, (err, time) => {}); // time is in ms since epoch - -// Getting decoded Message objects from JSON -const messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]); -console.log(messages[0].id); - -const message = Ably.Rest.Message.fromEncoded({ id: 'foo' }); -console.log(message.id); - -// Getting decoded PresenceMessage objects from JSON -const presenceMessages = Ably.Realtime.PresenceMessage.fromEncodedArray([{ id: 'foo' }]); -console.log(presenceMessages[0].action); - -const presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' }); -console.log(presenceMessage.action); diff --git a/types/ably/index.d.ts b/types/ably/index.d.ts deleted file mode 100644 index 3a150257ba..0000000000 --- a/types/ably/index.d.ts +++ /dev/null @@ -1,473 +0,0 @@ -// Type definitions for Ably Realtime and Rest client library 0.9 -// Project: https://www.ably.io/ -// Definitions by: Ably -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export namespace ablyLib { - namespace ChannelState { - type INITIALIZED = 'initialized'; - type ATTACHING = 'attaching'; - type ATTACHED = "attached"; - type DETACHING = "detaching"; - type DETACHED = "detached"; - type SUSPENDED = "suspended"; - type FAILED = "failed"; - } - type ChannelState = ChannelState.FAILED | ChannelState.INITIALIZED | ChannelState.SUSPENDED | ChannelState.ATTACHED | ChannelState.ATTACHING | ChannelState.DETACHED | ChannelState.DETACHING; - - namespace ConnectionState { - type INITIALIZED = "initialized"; - type CONNECTING = "connecting"; - type CONNECTED = "connected"; - type DISCONNECTED = "disconnected"; - type SUSPENDED = "suspended"; - type CLOSING = "closing"; - type CLOSED = "closed"; - type FAILED = "failed"; - } - type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED | - ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED; - - namespace ConnectionEvent { - type INITIALIZED = "initialized"; - type CONNECTING = "connecting"; - type CONNECTED = "connected"; - type DISCONNECTED = "disconnected"; - type SUSPENDED = "suspended"; - type CLOSING = "closing"; - type CLOSED = "closed"; - type FAILED = "failed"; - type UPDATE = "update"; - } - type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED | - ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE; - - namespace PresenceAction { - type ABSENT = "absent"; - type PRESENT = "present"; - type ENTER = "enter"; - type LEAVE = "leave"; - type UPDATE = "update"; - } - type PresenceAction = PresenceAction.ABSENT | PresenceAction.PRESENT | PresenceAction.ENTER | PresenceAction.LEAVE | PresenceAction.UPDATE; - - namespace StatsIntervalGranularity { - type MINUTE = "minute"; - type HOUR = "hour"; - type DAY = "day"; - type MONTH = "month"; - } - type StatsIntervalGranularity = StatsIntervalGranularity.MINUTE | StatsIntervalGranularity.HOUR | StatsIntervalGranularity.DAY | StatsIntervalGranularity.MONTH; - - namespace HTTPMethods { - type POST = "POST"; - type GET = "GET"; - } - type HTTPMethods = HTTPMethods.GET | HTTPMethods.POST; - - // Interfaces - interface ClientOptions extends AuthOptions { - /** - * When true will automatically connect to Ably when library is instanced. This is true by default - */ - autoConnect?: boolean; - - /** - * Optional clientId that can be used to specify the identity for this client. In most cases - * it is preferable to instead specift a clientId in the token issued to this client. - */ - clientId?: string; - - defaultTokenParams?: TokenParams; - - /** - * When true, messages published on channels by this client will be echoed back to this client. - * This is true by default - */ - echoMessages?: boolean; - - /** - * Use this only if you have been provided a dedicated environment by Ably - */ - environment?: string; - - /** - * Logger configuration - */ - log?: LogInfo; - port?: number; - - /** - * When true, messages will be queued whilst the connection is disconnected. True by default. - */ - queueMessages?: boolean; - - restHost?: string; - realtimeHost?: string; - fallbackHosts?: string[]; - - /** - * Can be used to explicitly recover a connection. - * See https://www.ably.io/documentation/realtime/connection#connection-state-recovery - */ - recover?: standardCallback | string; - - /** - * Use a non-secure connection connection. By default, a TLS connection is used to connect to Ably - */ - tls?: boolean; - tlsPort?: number; - - /** - * When true, the more efficient MsgPack binary encoding is used. - * When false, JSON text encoding is used. - */ - useBinaryProtocol?: boolean; - } - - interface AuthOptions { - /** - * A function which is called when a new token is required. - * The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically - * by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object. - */ - authCallback?(data: TokenParams, callback: (error: ErrorInfo | string, tokenRequestOrDetails: TokenDetails | TokenRequest | string) => void): void; - authHeaders?: { [index: string]: string }; - authMethod?: HTTPMethods; - authParams?: { [index: string]: string }; - - /** - * A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format). - */ - authUrl?: string; - key?: string; - queryTime?: boolean; - token?: TokenDetails | string; - tokenDetails?: TokenDetails; - useTokenAuth?: boolean; - } - - interface TokenParams { - capability?: string; - clientId?: string; - nonce?: string; - timestamp?: number; - ttl?: number; - } - - interface CipherParams { - algorithm: string; - key: any; - keyLength: number; - mode: string; - } - - interface ErrorInfo { - code: number; - message: string; - statusCode: number; - } - - interface StatsMessageCount { - count: number; - data: number; - } - - interface StatsMessageTypes { - all: StatsMessageCount; - messages: StatsMessageCount; - presence: StatsMessageCount; - } - - interface StatsRequestCount { - failed: number; - refused: number; - succeeded: number; - } - - interface StatsResourceCount { - mean: number; - min: number; - opened: number; - peak: number; - refused: number; - } - - interface StatsConnectionTypes { - all: StatsResourceCount; - plain: StatsResourceCount; - tls: StatsResourceCount; - } - - interface StatsMessageTraffic { - all: StatsMessageTypes; - realtime: StatsMessageTypes; - rest: StatsMessageTypes; - webhook: StatsMessageTypes; - } - - interface TokenDetails { - capability: string; - clientId?: string; - expires: number; - issued: number; - token: string; - } - - interface TokenRequest { - capability: string; - clientId?: string; - keyName: string; - mac: string; - nonce: string; - timestamp: number; - ttl?: number; - } - - interface ChannelOptions { - cipher: any; - } - - interface RestPresenceHistoryParams { - start?: number; - end?: number; - direction?: string; - limit?: number; - } - - interface RestPresenceParams { - limit?: number; - clientId?: string; - connectionId?: string; - } - - interface RealtimePresenceParams { - waitForSync?: boolean; - clientId?: string; - connectionId?: string; - } - - interface RealtimePresenceHistoryParams { - start?: number; - end?: number; - direction?: string; - limit?: number; - untilAttach?: boolean; - } - - interface LogInfo { - /** - * A number controlling the verbosity of the output. Valid values are: 0 (no logs), 1 (errors only), - * 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output). - */ - level?: number; - - /** - * A function to handle each line of log output. If handler is not specified, console.log is used. - */ - handler?(...args: any[]): void; - } - - interface ChannelEvent { - state: ChannelState; - } - - interface ChannelStateChange { - current: ChannelState; - previous: ChannelState; - reason?: ErrorInfo; - resumed: boolean; - } - - interface ConnectionStateChange { - current: ConnectionState; - previous: ConnectionState; - reason?: ErrorInfo; - retryIn?: number; - } - - // Common Listeners - type paginatedResultCallback = (error: ErrorInfo, results: PaginatedResult) => void; - type standardCallback = (error: ErrorInfo, results: any) => void; - type messageCallback = (message: T) => void; - type errorCallback = (error: ErrorInfo) => void; - type channelEventCallback = (channelEvent: ChannelEvent, changeStateChange: ChannelStateChange) => void; - type connectionEventCallback = (connectionEvent: ConnectionEvent, connectionStateChange: ConnectionStateChange) => void; - type timeCallback = (error: ErrorInfo, time: number) => void; - type realtimePresenceGetCallback = (error: ErrorInfo, messages: PresenceMessage[]) => void; - type tokenDetailsCallback = (error: ErrorInfo, Results: TokenDetails) => void; - type tokenRequestCallback = (error: ErrorInfo, Results: TokenRequest) => void; - type fromEncoded = (JsonObject: any, channelOptions?: ChannelOptions) => T; - type fromEncodedArray = (JsonArray: any[], channelOptions?: ChannelOptions) => T[]; - - // Internal Classes - class EventEmitter { - on: (eventOrCallback: string | T, callback?: T) => void; - once: (eventOrCallback: string | T, callback?: T) => void; - off: (eventOrCallback?: string | T, callback?: T) => void; - } - - // Classes - class Auth { - clientId: string; - authorize: (tokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void; - createTokenRequest: (tokenParams?: TokenParams | tokenRequestCallback, authOptions?: AuthOptions | tokenRequestCallback, callback?: tokenRequestCallback) => void; - requestToken: (TokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void; - } - - class Presence { - get: (params: RestPresenceParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; - history: (params: RestPresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; - } - - class RealtimePresence { - syncComplete: () => boolean; - get: (Params: realtimePresenceGetCallback | RealtimePresenceParams, callback?: realtimePresenceGetCallback) => void; - history: (ParamsOrCallback: RealtimePresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; - subscribe: (presenceOrCallback: PresenceAction | messageCallback, listener?: messageCallback) => void; - unsubscribe: (presence?: PresenceAction, listener?: messageCallback) => void; - enter: (data?: errorCallback | any, callback?: errorCallback) => void; - update: (data?: errorCallback | any, callback?: errorCallback) => void; - leave: (data?: errorCallback | any, callback?: errorCallback) => void; - enterClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void; - updateClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void; - leaveClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void; - } - - class Channel { - name: string; - presence: Presence; - history: (paramsOrCallback?: RestPresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; - publish: (messagesOrName: any, messagedataOrCallback?: errorCallback | any, callback?: errorCallback) => void; - } - - class RealtimeChannel extends EventEmitter { - name: string; - errorReason: ErrorInfo; - state: ChannelState; - presence: RealtimePresence; - attach: (callback?: standardCallback) => void; - detach: (callback?: standardCallback) => void; - history: (paramsOrCallback?: RealtimePresenceHistoryParams | paginatedResultCallback, callback?: paginatedResultCallback) => void; - subscribe: (eventOrCallback: messageCallback | string, listener?: messageCallback) => void; - unsubscribe: (eventOrCallback?: messageCallback | string, listener?: messageCallback) => void; - publish: (messagesOrName: any, messageDataOrCallback?: errorCallback | any, callback?: errorCallback) => void; - setOptions: (options: any, callback?: errorCallback) => void; - } - - class Channels { - get: (name: string, channelOptions?: ChannelOptions) => T; - release: (name: string) => void; - } - - class Message { - constructor(); - static fromEncoded: fromEncoded; - static fromEncodedArray: fromEncodedArray; - clientId: string; - connectionId: string; - data: any; - encoding: string; - extras: any; - id: string; - name: string; - timestamp: number; - } - - interface MessageStatic { - fromEncoded: fromEncoded; - fromEncodedArray: fromEncodedArray; - } - - class PresenceMessage { - constructor(); - static fromEncoded: fromEncoded; - static fromEncodedArray: fromEncodedArray; - action: PresenceAction; - clientId: string; - connectionId: string; - data: any; - encoding: string; - id: string; - timestamp: number; - } - - interface PresenceMessageStatic { - fromEncoded: fromEncoded; - fromEncodedArray: fromEncodedArray; - } - - interface Crypto { - generateRandomKey(callback: (error: ErrorInfo, key: string) => void): void; - } - - class Connection extends EventEmitter { - errorReason: ErrorInfo; - id: string; - key: string; - recoveryKey: string; - serial: number; - state: ConnectionState; - close: () => void; - connect: () => void; - ping: (callback?: (error: ErrorInfo, responseTime: number) => void) => void; - } - - class Stats { - all: StatsMessageTypes; - apiRequests: StatsRequestCount; - channels: StatsResourceCount; - connections: StatsConnectionTypes; - inbound: StatsMessageTraffic; - intervalId: string; - outbound: StatsMessageTraffic; - persisted: StatsMessageTypes; - tokenRequests: StatsRequestCount; - } - - class PaginatedResult { - items: T[]; - first: (results: paginatedResultCallback) => void; - next: (results: paginatedResultCallback) => void; - current: (results: paginatedResultCallback) => void; - hasNext: () => boolean; - isLast: () => boolean; - } - - class HttpPaginatedResponse extends PaginatedResult { - items: string[]; - statusCode: number; - success: boolean; - errorCode: number; - errorMessage: string; - headers: any; - } -} - -export class Rest { - constructor(options: ablyLib.ClientOptions | string); - static Crypto: ablyLib.Crypto; - static Message: ablyLib.MessageStatic; - static PresenceMessage: ablyLib.PresenceMessageStatic; - auth: ablyLib.Auth; - channels: ablyLib.Channels; - request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void; - stats: (paramsOrCallback?: ablyLib.paginatedResultCallback | any, callback?: ablyLib.paginatedResultCallback) => void; - time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void; -} - -export class Realtime { - constructor(options: ablyLib.ClientOptions | string); - static Crypto: ablyLib.Crypto; - static Message: ablyLib.MessageStatic; - static PresenceMessage: ablyLib.PresenceMessageStatic; - auth: ablyLib.Auth; - channels: ablyLib.Channels; - clientId: string; - connection: ablyLib.Connection; - request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void; - stats: (paramsOrCallback?: ablyLib.paginatedResultCallback | any, callback?: ablyLib.paginatedResultCallback) => void; - close: () => void; - connect: () => void; - time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void; -} diff --git a/types/accepts/index.d.ts b/types/accepts/index.d.ts index 33ee0db8a1..02cb0fbb97 100644 --- a/types/accepts/index.d.ts +++ b/types/accepts/index.d.ts @@ -12,36 +12,75 @@ declare namespace accepts { interface Accepts { /** * Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned. + * If no charsets are supplied, all accepted charsets are returned, in the order of the client's preference + * (most preferred first). */ + charset(): string[]; charset(charsets: string[]): string | false; charset(...charsets: string[]): string | false; /** - * Return the charsets that the request accepts, in the order of the client's preference (most preferred first). + * Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned. + * If no charsets are supplied, all accepted charsets are returned, in the order of the client's preference + * (most preferred first). */ charsets(): string[]; + charsets(charsets: string[]): string | false; + charsets(...charsets: string[]): string | false; /** * Return the first accepted encoding. If nothing in `encodings` is accepted, then `false` is returned. + * If no encodings are supplied, all accepted encodings are returned, in the order of the client's preference + * (most preferred first). */ + encoding(): string[]; encoding(encodings: string[]): string | false; encoding(...encodings: string[]): string | false; /** - * Return the encodings that the request accepts, in the order of the client's preference (most preferred first). + * Return the first accepted encoding. If nothing in `encodings` is accepted, then `false` is returned. + * If no encodings are supplied, all accepted encodings are returned, in the order of the client's preference + * (most preferred first). */ encodings(): string[]; + encodings(encodings: string[]): string | false; + encodings(...encodings: string[]): string | false; /** * Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned. + * If no languaes are supplied, all accepted languages are returned, in the order of the client's preference + * (most preferred first). */ + language(): string[]; language(languages: string[]): string | false; language(...languages: string[]): string | false; /** - * Return the languages that the request accepts, in the order of the client's preference (most preferred first). + * Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned. + * If no languaes are supplied, all accepted languages are returned, in the order of the client's preference + * (most preferred first). */ languages(): string[]; + languages(languages: string[]): string | false; + languages(...languages: string[]): string | false; + + /** + * Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned. + * If no languaes are supplied, all accepted languages are returned, in the order of the client's preference + * (most preferred first). + */ + lang(): string[]; + lang(languages: string[]): string | false; + lang(...languages: string[]): string | false; + + /** + * Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned. + * If no languaes are supplied, all accepted languages are returned, in the order of the client's preference + * (most preferred first). + */ + langs(): string[]; + langs(languages: string[]): string | false; + langs(...languages: string[]): string | false; /** * Return the first accepted type (and it is returned as the same text as what appears in the `types` array). If nothing in `types` is accepted, then `false` is returned. diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index 822c394a32..1f7dd9752b 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -52,6 +52,10 @@ declare namespace AceAjax { export interface TokenInfo { value: string; + + index?: number; + + start?: number; } export interface Position { @@ -575,7 +579,7 @@ declare namespace AceAjax { * @param row The row number to retrieve from * @param column The column number to retrieve from **/ - getTokenAt(row: number, column: number): TokenInfo; + getTokenAt(row: number, column: number): TokenInfo|null; /** * Sets the undo manager. diff --git a/types/actions-on-google/actions-on-google-tests.ts b/types/actions-on-google/actions-on-google-tests.ts index e57e1e8d98..d24c3093b4 100644 --- a/types/actions-on-google/actions-on-google-tests.ts +++ b/types/actions-on-google/actions-on-google-tests.ts @@ -1,6 +1,6 @@ import { ActionsSdkApp, ActionsSdkAppOptions, DialogflowApp, DialogflowAppOptions, AssistantApp, Responses, Transactions } from 'actions-on-google'; -import * as express from 'express'; +import express = require('express'); function testActionsSdk(request: express.Request, response: express.Response) { const app = new ActionsSdkApp({request, response}); diff --git a/types/actions-on-google/assistant-app.d.ts b/types/actions-on-google/assistant-app.d.ts index 58d933baf2..d835915259 100644 --- a/types/actions-on-google/assistant-app.d.ts +++ b/types/actions-on-google/assistant-app.d.ts @@ -263,8 +263,8 @@ export interface UserName { * User's permissioned device location. */ export interface DeviceLocation { - /** {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */ - coordinates: object; + /** Coordinates: {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */ + coordinates: Coordinates; /** Full, formatted street address. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */ address: string; /** Zip code. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION. */ @@ -273,6 +273,16 @@ export interface DeviceLocation { city: string; } +/** + * Coordinates containing latitude and longitude + */ +export interface Coordinates { + /** Latitude coordinate. */ + latitude: number; + /** Longitude coordinate. */ + longitude: number; +} + /** * User object. */ diff --git a/types/actions-on-google/index.d.ts b/types/actions-on-google/index.d.ts index 23a2c1483d..937943e1f0 100644 --- a/types/actions-on-google/index.d.ts +++ b/types/actions-on-google/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for actions-on-google 1.7 +// Type definitions for actions-on-google 1.8 // Project: https://github.com/actions-on-google/actions-on-google-nodejs // Definitions by: Joel Hegg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/actions-on-google/response-builder.d.ts b/types/actions-on-google/response-builder.d.ts index 4ebb9b3007..227d102958 100644 --- a/types/actions-on-google/response-builder.d.ts +++ b/types/actions-on-google/response-builder.d.ts @@ -20,7 +20,9 @@ export enum ImageDisplays { */ WHITE, /** - * Image is centered and resized so the image fits perfectly in the container. + * Image is scaled such that the image width matches the container width. This may crop the top + * and bottom of the image if the scaled image height is greater than the container height. This + * is similar to "Zoom Mode" on a widescreen TV when playing a 4:3 video. */ CROPPED } diff --git a/types/actions-on-google/transactions.d.ts b/types/actions-on-google/transactions.d.ts index 59e6cd9b37..06e44b33dd 100644 --- a/types/actions-on-google/transactions.d.ts +++ b/types/actions-on-google/transactions.d.ts @@ -594,7 +594,12 @@ export namespace TransactionValues { /** * Use external payment gateway tokenization API to tokenize selected payment method. */ - PAYMENT_GATEWAY + PAYMENT_GATEWAY, + /** + * Allows payment service to pass public key for payment info encryption and receive encrypted + * response. + */ + DIRECT } } diff --git a/types/actions-on-google/tsconfig.json b/types/actions-on-google/tsconfig.json index 6682b5c194..776b12264b 100644 --- a/types/actions-on-google/tsconfig.json +++ b/types/actions-on-google/tsconfig.json @@ -25,4 +25,4 @@ "transactions.d.ts", "actions-on-google-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/activex-access/tslint.json b/types/activex-access/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-access/tslint.json +++ b/types/activex-access/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-adodb/tslint.json b/types/activex-adodb/tslint.json index 2750cc0197..3224b40b8b 100644 --- a/types/activex-adodb/tslint.json +++ b/types/activex-adodb/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } \ No newline at end of file +{ + "extends": "dtslint/dt.json", + "rules": { + "no-const-enum": false + } +} diff --git a/types/activex-dao/tslint.json b/types/activex-dao/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-dao/tslint.json +++ b/types/activex-dao/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-diskquota/activex-diskquota-tests.ts b/types/activex-diskquota/activex-diskquota-tests.ts new file mode 100644 index 0000000000..2672b590ca --- /dev/null +++ b/types/activex-diskquota/activex-diskquota-tests.ts @@ -0,0 +1,44 @@ +const collectionToArray = (col: any) => { // tslint:disable-line no-unnecessary-generics + const results: T[] = []; + const enumerator = new Enumerator(col); + enumerator.moveFirst(); + while (!enumerator.atEnd()) { + results.push(enumerator.item()); + enumerator.moveNext(); + } + return results; +}; + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787925(v=vs.85).aspx +(() => { + const enumUsers = (label: string) => { + const volume = new ActiveXObject('Microsoft.DiskQuota'); + volume.Initialize(label, true); + collectionToArray(volume).forEach(x => { + // Use the QuotaUser object to retrieve or set one or more of the user's disk quota properties + }); + }; +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787916(v=vs.85).aspx +(() => { + const volume = new ActiveXObject('Microsoft.DiskQuota'); + volume.Initialize('MYDISK', true); + ActiveXObject.on(volume, 'OnUserNameChanged', ['pUser'], p => { + // Code to handle the event. + }); +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787904(v=vs.85).aspx +(() => { + const dqc = new ActiveXObject('Microsoft.DiskQuota'); + dqc.Initialize('MYDISK', true); + const findName = (name: string) => { + try { + return dqc.FindUser(name); + } catch { } + try { + return dqc.FindUser(dqc.TranslateLogonNameToSID(name)); + } catch { } + }; +})(); diff --git a/types/activex-diskquota/index.d.ts b/types/activex-diskquota/index.d.ts new file mode 100644 index 0000000000..d27863de3c --- /dev/null +++ b/types/activex-diskquota/index.d.ts @@ -0,0 +1,152 @@ +// Type definitions for DiskQuotaTypeLibrary 1.0 +// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx +// Definitions by: Zev Spitz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.5 + +declare namespace DiskQuotaTypeLibrary { + // tslint:disable-next-line no-const-enum + const enum AccountStatusConstants { + dqAcctDeleted = 2, + dqAcctInvalid = 3, + dqAcctResolved = 0, + dqAcctUnavailable = 1, + dqAcctUnknown = 4, + dqAcctUnresolved = 5, + } + + // tslint:disable-next-line no-const-enum + const enum QuotaStateConstants { + dqStateDisable = 0, + dqStateEnforce = 2, + dqStateTrack = 1, + } + + // tslint:disable-next-line no-const-enum + const enum UserNameResolutionConstants { + dqResolveAsync = 2, + dqResolveNone = 0, + dqResolveSync = 1, + } + + /** Automation interface for DiskQuotaUser */ + class DIDiskQuotaUser { + private 'DiskQuotaTypeLibrary.DIDiskQuotaUser_typekey': DIDiskQuotaUser; + private constructor(); + + /** Name of user's account container */ + readonly AccountContainerName: string; + + /** Status of user's account */ + readonly AccountStatus: AccountStatusConstants; + + /** User's display name */ + readonly DisplayName: string; + + /** Unique ID number */ + readonly ID: number; + + /** Invalidate data cached in user object */ + Invalidate(): void; + + /** User's logon account name */ + readonly LogonName: string; + + /** User's quota limit (bytes) */ + QuotaLimit: number; + + /** User's quota limit (text) */ + readonly QuotaLimitText: string; + + /** User's quota warning threshold (bytes) */ + QuotaThreshold: number; + + /** User's quota warning threshold (text) */ + readonly QuotaThresholdText: string; + + /** Quota charged to user (bytes) */ + readonly QuotaUsed: number; + + /** Quota charged to user (text) */ + readonly QuotaUsedText: string; + } + + /** Microsoft Disk Quota */ + class DiskQuotaControl { + private 'DiskQuotaTypeLibrary.DiskQuotaControl_typekey': DiskQuotaControl; + private constructor(); + + /** Add a user quota entry by Name */ + AddUser(LogonName: string): DIDiskQuotaUser; + + /** Default quota limit applied to new volume users (byte value) */ + DefaultQuotaLimit: number; + + /** Default quota limit applied to new volume users (text string) */ + readonly DefaultQuotaLimitText: string; + + /** Default warning threshold applied to new volume users (byte value) */ + DefaultQuotaThreshold: number; + + /** Default warning threshold applied to new volume users (text string) */ + readonly DefaultQuotaThresholdText: string; + + /** Delete a user quota entry */ + DeleteUser(pUser: DIDiskQuotaUser): void; + + /** Find a user quota entry by Name */ + FindUser(LogonName: string): DIDiskQuotaUser; + + /** Promote a user quota entry to the head of the name resolution queue */ + GiveUserNameResolutionPriority(pUser: DIDiskQuotaUser): void; + + /** Initialize the quota control object for a specified volume */ + Initialize(path: string, bReadWrite: boolean): void; + + /** Invalidate the cache of user name information */ + InvalidateSidNameCache(): void; + + /** Write event log entry when user exceeds quota limit */ + LogQuotaLimit: boolean; + + /** Write event log entry when user exceeds quota warning threshold */ + LogQuotaThreshold: boolean; + + /** Indicates if quota information is out of date */ + readonly QuotaFileIncomplete: boolean; + + /** Indicates if quota information is being rebuilt */ + readonly QuotaFileRebuilding: boolean; + + /** State of the volume's disk quota system */ + QuotaState: QuotaStateConstants; + + /** Terminate the user name resolution thread */ + ShutdownNameResolution(): void; + + /** Translates a user logon name to a security ID */ + TranslateLogonNameToSID(LogonName: string): string; + + /** Control the resolution of user Security IDs to user Names */ + UserNameResolution: UserNameResolutionConstants; + } +} + +interface ActiveXObject { + on( + obj: DiskQuotaTypeLibrary.DiskQuotaControl, event: 'OnUserNameChanged', argNames: ['pUser'], handler: ( + this: DiskQuotaTypeLibrary.DiskQuotaControl, parameter: {readonly pUser: DiskQuotaTypeLibrary.DIDiskQuotaUser}) => void): void; + new(progid: K): ActiveXObjectNameMap[K]; +} + +interface ActiveXObjectNameMap { + 'Microsoft.DiskQuota': DiskQuotaTypeLibrary.DiskQuotaControl; +} + +interface EnumeratorConstructor { + new(col: DiskQuotaTypeLibrary.DiskQuotaControl): Enumerator; +} + +interface SafeArray { + _brand: SafeArray; +} diff --git a/types/activex-diskquota/package.json b/types/activex-diskquota/package.json new file mode 100644 index 0000000000..d9b1031263 --- /dev/null +++ b/types/activex-diskquota/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "activex-helpers": "*" + } +} \ No newline at end of file diff --git a/types/activex-diskquota/tsconfig.json b/types/activex-diskquota/tsconfig.json new file mode 100644 index 0000000000..597d998a96 --- /dev/null +++ b/types/activex-diskquota/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "scripthost" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "activex-diskquota-tests.ts" + ] +} \ No newline at end of file diff --git a/types/activex-diskquota/tslint.json b/types/activex-diskquota/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/activex-diskquota/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/activex-excel/index.d.ts b/types/activex-excel/index.d.ts index ec2044f1e7..cdf2a79551 100644 --- a/types/activex-excel/index.d.ts +++ b/types/activex-excel/index.d.ts @@ -2,13 +2,14 @@ // Project: https://msdn.microsoft.com/en-us/library/fp179694.aspx // Definitions by: Zev Spitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 /// /// /// declare namespace Excel { + // tslint:disable-next-line:no-const-enum const enum Constants { xl3DBar = -4099, xl3DEffects1 = 13, @@ -179,6 +180,7 @@ declare namespace Excel { xlWorksheetShort = 5, } + // tslint:disable-next-line:no-const-enum const enum XlAboveBelow { xlAboveAverage = 0, xlAboveStdDev = 4, @@ -188,6 +190,7 @@ declare namespace Excel { xlEqualBelowAverage = 3, } + // tslint:disable-next-line:no-const-enum const enum XlActionType { xlActionTypeDrillthrough = 256, xlActionTypeReport = 128, @@ -195,21 +198,25 @@ declare namespace Excel { xlActionTypeUrl = 1, } + // tslint:disable-next-line:no-const-enum const enum XlAllocation { xlAutomaticAllocation = 2, xlManualAllocation = 1, } + // tslint:disable-next-line:no-const-enum const enum XlAllocationMethod { xlEqualAllocation = 1, xlWeightedAllocation = 2, } + // tslint:disable-next-line:no-const-enum const enum XlAllocationValue { xlAllocateIncrement = 2, xlAllocateValue = 1, } + // tslint:disable-next-line:no-const-enum const enum XlApplicationInternational { xl24HourClock = 33, xl4DigitYears = 43, @@ -258,11 +265,13 @@ declare namespace Excel { xlYearCode = 19, } + // tslint:disable-next-line:no-const-enum const enum XlApplyNamesOrder { xlColumnThenRow = 2, xlRowThenColumn = 1, } + // tslint:disable-next-line:no-const-enum const enum XlArabicModes { xlArabicBothStrict = 3, xlArabicNone = 0, @@ -270,6 +279,7 @@ declare namespace Excel { xlArabicStrictFinalYaa = 2, } + // tslint:disable-next-line:no-const-enum const enum XlArrangeStyle { xlArrangeStyleCascade = 7, xlArrangeStyleHorizontal = -4128, @@ -277,12 +287,14 @@ declare namespace Excel { xlArrangeStyleVertical = -4166, } + // tslint:disable-next-line:no-const-enum const enum XlArrowHeadLength { xlArrowHeadLengthLong = 3, xlArrowHeadLengthMedium = -4138, xlArrowHeadLengthShort = 1, } + // tslint:disable-next-line:no-const-enum const enum XlArrowHeadStyle { xlArrowHeadStyleClosed = 3, xlArrowHeadStyleDoubleClosed = 5, @@ -291,12 +303,14 @@ declare namespace Excel { xlArrowHeadStyleOpen = 2, } + // tslint:disable-next-line:no-const-enum const enum XlArrowHeadWidth { xlArrowHeadWidthMedium = -4138, xlArrowHeadWidthNarrow = 1, xlArrowHeadWidthWide = 3, } + // tslint:disable-next-line:no-const-enum const enum XlAutoFillType { xlFillCopy = 1, xlFillDays = 5, @@ -311,6 +325,7 @@ declare namespace Excel { xlLinearTrend = 9, } + // tslint:disable-next-line:no-const-enum const enum XlAutoFilterOperator { xlAnd = 1, xlBottom10Items = 4, @@ -328,6 +343,7 @@ declare namespace Excel { xlTop10Percent = 5, } + // tslint:disable-next-line:no-const-enum const enum XlAxisCrosses { xlAxisCrossesAutomatic = -4105, xlAxisCrossesCustom = -4114, @@ -335,23 +351,27 @@ declare namespace Excel { xlAxisCrossesMinimum = 4, } + // tslint:disable-next-line:no-const-enum const enum XlAxisGroup { xlPrimary = 1, xlSecondary = 2, } + // tslint:disable-next-line:no-const-enum const enum XlAxisType { xlCategory = 1, xlSeriesAxis = 3, xlValue = 2, } + // tslint:disable-next-line:no-const-enum const enum XlBackground { xlBackgroundAutomatic = -4105, xlBackgroundOpaque = 3, xlBackgroundTransparent = 2, } + // tslint:disable-next-line:no-const-enum const enum XlBarShape { xlBox = 0, xlConeToMax = 5, @@ -361,6 +381,7 @@ declare namespace Excel { xlPyramidToPoint = 1, } + // tslint:disable-next-line:no-const-enum const enum XlBordersIndex { xlDiagonalDown = 5, xlDiagonalUp = 6, @@ -372,6 +393,7 @@ declare namespace Excel { xlInsideVertical = 11, } + // tslint:disable-next-line:no-const-enum const enum XlBorderWeight { xlHairline = 1, xlMedium = -4138, @@ -379,6 +401,7 @@ declare namespace Excel { xlThin = 2, } + // tslint:disable-next-line:no-const-enum const enum XlBuiltInDialog { _xlDialogChartSourceData = 541, _xlDialogPhonetic = 538, @@ -641,53 +664,62 @@ declare namespace Excel { xlDialogZoom = 256, } + // tslint:disable-next-line:no-const-enum const enum XlCalcFor { xlAllValues = 0, xlColGroups = 2, xlRowGroups = 1, } + // tslint:disable-next-line:no-const-enum const enum XlCalculatedMemberType { xlCalculatedMember = 0, xlCalculatedSet = 1, } + // tslint:disable-next-line:no-const-enum const enum XlCalculation { xlCalculationAutomatic = -4105, xlCalculationManual = -4135, xlCalculationSemiautomatic = 2, } + // tslint:disable-next-line:no-const-enum const enum XlCalculationInterruptKey { xlAnyKey = 2, xlEscKey = 1, xlNoKey = 0, } + // tslint:disable-next-line:no-const-enum const enum XlCalculationState { xlCalculating = 1, xlDone = 0, xlPending = 2, } + // tslint:disable-next-line:no-const-enum const enum XlCategoryType { xlAutomaticScale = -4105, xlCategoryScale = 2, xlTimeScale = 3, } + // tslint:disable-next-line:no-const-enum const enum XlCellChangedState { xlCellChangeApplied = 3, xlCellChanged = 2, xlCellNotChanged = 1, } + // tslint:disable-next-line:no-const-enum const enum XlCellInsertionMode { xlInsertDeleteCells = 1, xlInsertEntireRows = 2, xlOverwriteCells = 0, } + // tslint:disable-next-line:no-const-enum const enum XlCellType { xlCellTypeAllFormatConditions = -4172, xlCellTypeAllValidation = -4174, @@ -701,17 +733,20 @@ declare namespace Excel { xlCellTypeVisible = 12, } + // tslint:disable-next-line:no-const-enum const enum XlChartElementPosition { xlChartElementPositionAutomatic = -4105, xlChartElementPositionCustom = -4114, } + // tslint:disable-next-line:no-const-enum const enum XlChartGallery { xlAnyGallery = 23, xlBuiltIn = 21, xlUserDefined = 22, } + // tslint:disable-next-line:no-const-enum const enum XlChartItem { xlAxis = 21, xlAxisTitle = 17, @@ -747,12 +782,14 @@ declare namespace Excel { xlYErrorBars = 11, } + // tslint:disable-next-line:no-const-enum const enum XlChartLocation { xlLocationAsNewSheet = 1, xlLocationAsObject = 2, xlLocationAutomatic = 3, } + // tslint:disable-next-line:no-const-enum const enum XlChartPicturePlacement { xlAllFaces = 7, xlEnd = 2, @@ -763,12 +800,14 @@ declare namespace Excel { xlSides = 1, } + // tslint:disable-next-line:no-const-enum const enum XlChartPictureType { xlStack = 2, xlStackScale = 3, xlStretch = 1, } + // tslint:disable-next-line:no-const-enum const enum XlChartSplitType { xlSplitByCustomSplit = 4, xlSplitByPercentValue = 3, @@ -776,6 +815,7 @@ declare namespace Excel { xlSplitByValue = 2, } + // tslint:disable-next-line:no-const-enum const enum XlChartType { xl3DArea = -4098, xl3DAreaStacked = 78, @@ -852,12 +892,14 @@ declare namespace Excel { xlXYScatterSmoothNoMarkers = 73, } + // tslint:disable-next-line:no-const-enum const enum XlCheckInVersionType { xlCheckInMajorVersion = 1, xlCheckInMinorVersion = 0, xlCheckInOverwriteVersion = 2, } + // tslint:disable-next-line:no-const-enum const enum XlClipboardFormat { xlClipboardFormatBIFF = 8, xlClipboardFormatBIFF12 = 63, @@ -895,6 +937,7 @@ declare namespace Excel { xlClipboardFormatWK1 = 10, } + // tslint:disable-next-line:no-const-enum const enum XlCmdType { xlCmdCube = 1, xlCmdDefault = 4, @@ -903,11 +946,13 @@ declare namespace Excel { xlCmdTable = 3, } + // tslint:disable-next-line:no-const-enum const enum XlColorIndex { xlColorIndexAutomatic = -4105, xlColorIndexNone = -4142, } + // tslint:disable-next-line:no-const-enum const enum XlColumnDataType { xlDMYFormat = 4, xlDYMFormat = 7, @@ -921,18 +966,21 @@ declare namespace Excel { xlYMDFormat = 5, } + // tslint:disable-next-line:no-const-enum const enum XlCommandUnderlines { xlCommandUnderlinesAutomatic = -4105, xlCommandUnderlinesOff = -4146, xlCommandUnderlinesOn = 1, } + // tslint:disable-next-line:no-const-enum const enum XlCommentDisplayMode { xlCommentAndIndicator = 1, xlCommentIndicatorOnly = -1, xlNoIndicator = 0, } + // tslint:disable-next-line:no-const-enum const enum XlConditionValueTypes { xlConditionValueAutomaticMax = 7, xlConditionValueAutomaticMin = 6, @@ -945,6 +993,7 @@ declare namespace Excel { xlConditionValuePercentile = 5, } + // tslint:disable-next-line:no-const-enum const enum XlConnectionType { xlConnectionTypeODBC = 2, xlConnectionTypeOLEDB = 1, @@ -953,6 +1002,7 @@ declare namespace Excel { xlConnectionTypeXMLMAP = 3, } + // tslint:disable-next-line:no-const-enum const enum XlConsolidationFunction { xlAverage = -4106, xlCount = -4112, @@ -968,6 +1018,7 @@ declare namespace Excel { xlVarP = -4165, } + // tslint:disable-next-line:no-const-enum const enum XlContainsOperator { xlBeginsWith = 2, xlContains = 0, @@ -975,27 +1026,32 @@ declare namespace Excel { xlEndsWith = 3, } + // tslint:disable-next-line:no-const-enum const enum XlCopyPictureFormat { xlBitmap = 2, xlPicture = -4147, } + // tslint:disable-next-line:no-const-enum const enum XlCorruptLoad { xlExtractData = 2, xlNormalLoad = 0, xlRepairFile = 1, } + // tslint:disable-next-line:no-const-enum const enum XlCreator { xlCreatorCode = 1480803660, } + // tslint:disable-next-line:no-const-enum const enum XlCredentialsMethod { xlCredentialsMethodIntegrated = 0, xlCredentialsMethodNone = 1, xlCredentialsMethodStored = 2, } + // tslint:disable-next-line:no-const-enum const enum XlCubeFieldSubType { xlCubeAttribute = 4, xlCubeCalculatedMeasure = 5, @@ -1009,17 +1065,20 @@ declare namespace Excel { xlCubeSet = 3, } + // tslint:disable-next-line:no-const-enum const enum XlCubeFieldType { xlHierarchy = 1, xlMeasure = 2, xlSet = 3, } + // tslint:disable-next-line:no-const-enum const enum XlCutCopyMode { xlCopy = 1, xlCut = 2, } + // tslint:disable-next-line:no-const-enum const enum XlCVError { xlErrDiv0 = 2007, xlErrNA = 2042, @@ -1030,27 +1089,32 @@ declare namespace Excel { xlErrValue = 2015, } + // tslint:disable-next-line:no-const-enum const enum XlDataBarAxisPosition { xlDataBarAxisAutomatic = 0, xlDataBarAxisMidpoint = 1, xlDataBarAxisNone = 2, } + // tslint:disable-next-line:no-const-enum const enum XlDataBarBorderType { xlDataBarBorderNone = 0, xlDataBarBorderSolid = 1, } + // tslint:disable-next-line:no-const-enum const enum XlDataBarFillType { xlDataBarFillGradient = 1, xlDataBarFillSolid = 0, } + // tslint:disable-next-line:no-const-enum const enum XlDataBarNegativeColorType { xlDataBarColor = 0, xlDataBarSameAsPositive = 1, } + // tslint:disable-next-line:no-const-enum const enum XlDataLabelPosition { xlLabelPositionAbove = 0, xlLabelPositionBelow = 1, @@ -1065,10 +1129,12 @@ declare namespace Excel { xlLabelPositionRight = -4152, } + // tslint:disable-next-line:no-const-enum const enum XlDataLabelSeparator { xlDataLabelSeparatorDefault = 1, } + // tslint:disable-next-line:no-const-enum const enum XlDataLabelsType { xlDataLabelsShowBubbleSizes = 6, xlDataLabelsShowLabel = 4, @@ -1078,6 +1144,7 @@ declare namespace Excel { xlDataLabelsShowValue = 2, } + // tslint:disable-next-line:no-const-enum const enum XlDataSeriesDate { xlDay = 1, xlMonth = 3, @@ -1085,6 +1152,7 @@ declare namespace Excel { xlYear = 4, } + // tslint:disable-next-line:no-const-enum const enum XlDataSeriesType { xlAutoFill = 4, xlChronological = 3, @@ -1092,11 +1160,13 @@ declare namespace Excel { xlGrowth = 2, } + // tslint:disable-next-line:no-const-enum const enum XlDeleteShiftDirection { xlShiftToLeft = -4159, xlShiftUp = -4162, } + // tslint:disable-next-line:no-const-enum const enum XlDirection { xlDown = -4121, xlToLeft = -4159, @@ -1104,18 +1174,21 @@ declare namespace Excel { xlUp = -4162, } + // tslint:disable-next-line:no-const-enum const enum XlDisplayBlanksAs { xlInterpolated = 3, xlNotPlotted = 1, xlZero = 2, } + // tslint:disable-next-line:no-const-enum const enum XlDisplayDrawingObjects { xlDisplayShapes = -4104, xlHide = 3, xlPlaceholders = 2, } + // tslint:disable-next-line:no-const-enum const enum XlDisplayUnit { xlHundredMillions = -8, xlHundreds = -2, @@ -1128,17 +1201,20 @@ declare namespace Excel { xlThousands = -3, } + // tslint:disable-next-line:no-const-enum const enum XlDupeUnique { xlDuplicate = 1, xlUnique = 0, } + // tslint:disable-next-line:no-const-enum const enum XlDVAlertStyle { xlValidAlertInformation = 3, xlValidAlertStop = 1, xlValidAlertWarning = 2, } + // tslint:disable-next-line:no-const-enum const enum XlDVType { xlValidateCustom = 7, xlValidateDate = 4, @@ -1150,6 +1226,7 @@ declare namespace Excel { xlValidateWholeNumber = 1, } + // tslint:disable-next-line:no-const-enum const enum XlDynamicFilterCriteria { xlFilterAboveAverage = 33, xlFilterAllDatesInPeriodApril = 24, @@ -1187,6 +1264,7 @@ declare namespace Excel { xlFilterYesterday = 2, } + // tslint:disable-next-line:no-const-enum const enum XlEditionFormat { xlBIFF = 2, xlPICT = 1, @@ -1194,6 +1272,7 @@ declare namespace Excel { xlVALU = 8, } + // tslint:disable-next-line:no-const-enum const enum XlEditionOptionsOption { xlAutomaticUpdate = 4, xlCancel = 1, @@ -1205,33 +1284,39 @@ declare namespace Excel { xlUpdateSubscriber = 2, } + // tslint:disable-next-line:no-const-enum const enum XlEditionType { xlPublisher = 1, xlSubscriber = 2, } + // tslint:disable-next-line:no-const-enum const enum XlEnableCancelKey { xlDisabled = 0, xlErrorHandler = 2, xlInterrupt = 1, } + // tslint:disable-next-line:no-const-enum const enum XlEnableSelection { xlNoRestrictions = 0, xlNoSelection = -4142, xlUnlockedCells = 1, } + // tslint:disable-next-line:no-const-enum const enum XlEndStyleCap { xlCap = 1, xlNoCap = 2, } + // tslint:disable-next-line:no-const-enum const enum XlErrorBarDirection { xlX = -4168, xlY = 1, } + // tslint:disable-next-line:no-const-enum const enum XlErrorBarInclude { xlErrorBarIncludeBoth = 1, xlErrorBarIncludeMinusValues = 3, @@ -1239,6 +1324,7 @@ declare namespace Excel { xlErrorBarIncludePlusValues = 2, } + // tslint:disable-next-line:no-const-enum const enum XlErrorBarType { xlErrorBarTypeCustom = -4114, xlErrorBarTypeFixedValue = 1, @@ -1247,6 +1333,7 @@ declare namespace Excel { xlErrorBarTypeStError = 4, } + // tslint:disable-next-line:no-const-enum const enum XlErrorChecks { xlEmptyCellReferences = 7, xlEvaluateToError = 1, @@ -1259,11 +1346,13 @@ declare namespace Excel { xlUnlockedFormulaCells = 6, } + // tslint:disable-next-line:no-const-enum const enum XlFileAccess { xlReadOnly = 3, xlReadWrite = 2, } + // tslint:disable-next-line:no-const-enum const enum XlFileFormat { xlAddIn = 18, xlAddIn8 = 18, @@ -1321,23 +1410,27 @@ declare namespace Excel { xlXMLSpreadsheet = 46, } + // tslint:disable-next-line:no-const-enum const enum XlFileValidationPivotMode { xlFileValidationPivotDefault = 0, xlFileValidationPivotRun = 1, xlFileValidationPivotSkip = 2, } + // tslint:disable-next-line:no-const-enum const enum XlFillWith { xlFillWithAll = -4104, xlFillWithContents = 2, xlFillWithFormats = -4122, } + // tslint:disable-next-line:no-const-enum const enum XlFilterAction { xlFilterCopy = 2, xlFilterInPlace = 1, } + // tslint:disable-next-line:no-const-enum const enum XlFilterAllDatesInPeriod { xlFilterAllDatesInPeriodDay = 2, xlFilterAllDatesInPeriodHour = 3, @@ -1347,22 +1440,26 @@ declare namespace Excel { xlFilterAllDatesInPeriodYear = 0, } + // tslint:disable-next-line:no-const-enum const enum XlFindLookIn { xlComments = -4144, xlFormulas = -4123, xlValues = -4163, } + // tslint:disable-next-line:no-const-enum const enum XlFixedFormatQuality { xlQualityMinimum = 1, xlQualityStandard = 0, } + // tslint:disable-next-line:no-const-enum const enum XlFixedFormatType { xlTypePDF = 0, xlTypeXPS = 1, } + // tslint:disable-next-line:no-const-enum const enum XlFormatConditionOperator { xlBetween = 1, xlEqual = 3, @@ -1374,6 +1471,7 @@ declare namespace Excel { xlNotEqual = 4, } + // tslint:disable-next-line:no-const-enum const enum XlFormatConditionType { xlAboveAverageCondition = 12, xlBlanksCondition = 10, @@ -1391,6 +1489,7 @@ declare namespace Excel { xlUniqueValues = 8, } + // tslint:disable-next-line:no-const-enum const enum XlFormatFilterTypes { xlFilterBottom = 0, xlFilterBottomPercent = 2, @@ -1398,6 +1497,7 @@ declare namespace Excel { xlFilterTopPercent = 3, } + // tslint:disable-next-line:no-const-enum const enum XlFormControl { xlButtonControl = 0, xlCheckBox = 1, @@ -1411,6 +1511,7 @@ declare namespace Excel { xlSpinner = 9, } + // tslint:disable-next-line:no-const-enum const enum XlFormulaLabel { xlColumnLabels = 2, xlMixedLabels = 3, @@ -1418,16 +1519,19 @@ declare namespace Excel { xlRowLabels = 1, } + // tslint:disable-next-line:no-const-enum const enum XlGenerateTableRefs { xlGenerateTableRefA1 = 0, xlGenerateTableRefStruct = 1, } + // tslint:disable-next-line:no-const-enum const enum XlGradientFillType { xlGradientFillLinear = 0, xlGradientFillPath = 1, } + // tslint:disable-next-line:no-const-enum const enum XlHAlign { xlHAlignCenter = -4108, xlHAlignCenterAcrossSelection = 7, @@ -1439,6 +1543,7 @@ declare namespace Excel { xlHAlignRight = -4152, } + // tslint:disable-next-line:no-const-enum const enum XlHebrewModes { xlHebrewFullScript = 0, xlHebrewMixedAuthorizedScript = 3, @@ -1446,12 +1551,14 @@ declare namespace Excel { xlHebrewPartialScript = 1, } + // tslint:disable-next-line:no-const-enum const enum XlHighlightChangesTime { xlAllChanges = 2, xlNotYetReviewed = 3, xlSinceMyLastSave = 1, } + // tslint:disable-next-line:no-const-enum const enum XlHtmlType { xlHtmlCalc = 1, xlHtmlChart = 3, @@ -1459,6 +1566,7 @@ declare namespace Excel { xlHtmlStatic = 0, } + // tslint:disable-next-line:no-const-enum const enum XlIcon { xlIcon0Bars = 37, xlIcon0FilledBoxes = 52, @@ -1515,6 +1623,7 @@ declare namespace Excel { xlIconYellowUpInclineArrow = 25, } + // tslint:disable-next-line:no-const-enum const enum XlIconSet { xl3Arrows = 1, xl3ArrowsGray = 2, @@ -1539,6 +1648,7 @@ declare namespace Excel { xlCustomSet = -1, } + // tslint:disable-next-line:no-const-enum const enum XlIMEMode { xlIMEModeAlpha = 8, xlIMEModeAlphaFull = 7, @@ -1553,33 +1663,39 @@ declare namespace Excel { xlIMEModeOn = 1, } + // tslint:disable-next-line:no-const-enum const enum XlImportDataAs { xlPivotTableReport = 1, xlQueryTable = 0, xlTable = 2, } + // tslint:disable-next-line:no-const-enum const enum XlInsertFormatOrigin { xlFormatFromLeftOrAbove = 0, xlFormatFromRightOrBelow = 1, } + // tslint:disable-next-line:no-const-enum const enum XlInsertShiftDirection { xlShiftDown = -4121, xlShiftToRight = -4161, } + // tslint:disable-next-line:no-const-enum const enum XlLayoutFormType { xlOutline = 1, xlTabular = 0, } + // tslint:disable-next-line:no-const-enum const enum XlLayoutRowType { xlCompactRow = 0, xlOutlineRow = 2, xlTabularRow = 1, } + // tslint:disable-next-line:no-const-enum const enum XlLegendPosition { xlLegendPositionBottom = -4107, xlLegendPositionCorner = 2, @@ -1589,6 +1705,7 @@ declare namespace Excel { xlLegendPositionTop = -4160, } + // tslint:disable-next-line:no-const-enum const enum XlLineStyle { xlContinuous = 1, xlDash = -4115, @@ -1600,6 +1717,7 @@ declare namespace Excel { xlSlantDashDot = 13, } + // tslint:disable-next-line:no-const-enum const enum XlLink { xlExcelLinks = 1, xlOLELinks = 2, @@ -1607,18 +1725,21 @@ declare namespace Excel { xlSubscribers = 6, } + // tslint:disable-next-line:no-const-enum const enum XlLinkInfo { xlEditionDate = 2, xlLinkInfoStatus = 3, xlUpdateState = 1, } + // tslint:disable-next-line:no-const-enum const enum XlLinkInfoType { xlLinkInfoOLELinks = 2, xlLinkInfoPublishers = 5, xlLinkInfoSubscribers = 6, } + // tslint:disable-next-line:no-const-enum const enum XlLinkStatus { xlLinkStatusCopiedValues = 10, xlLinkStatusIndeterminate = 5, @@ -1633,11 +1754,13 @@ declare namespace Excel { xlLinkStatusSourceOpen = 9, } + // tslint:disable-next-line:no-const-enum const enum XlLinkType { xlLinkTypeExcelLinks = 1, xlLinkTypeOLELinks = 2, } + // tslint:disable-next-line:no-const-enum const enum XlListConflict { xlListConflictDialog = 0, xlListConflictDiscardAllConflicts = 2, @@ -1645,6 +1768,7 @@ declare namespace Excel { xlListConflictRetryAllConflicts = 1, } + // tslint:disable-next-line:no-const-enum const enum XlListDataType { xlListDataTypeCheckbox = 9, xlListDataTypeChoice = 6, @@ -1661,6 +1785,7 @@ declare namespace Excel { xlListDataTypeText = 1, } + // tslint:disable-next-line:no-const-enum const enum XlListObjectSourceType { xlSrcExternal = 0, xlSrcQuery = 3, @@ -1668,6 +1793,7 @@ declare namespace Excel { xlSrcXml = 2, } + // tslint:disable-next-line:no-const-enum const enum XlLocationInTable { xlColumnHeader = -4110, xlColumnItem = 5, @@ -1680,23 +1806,27 @@ declare namespace Excel { xlTableBody = 8, } + // tslint:disable-next-line:no-const-enum const enum XlLookAt { xlPart = 2, xlWhole = 1, } + // tslint:disable-next-line:no-const-enum const enum XlLookFor { xlLookForBlanks = 0, xlLookForErrors = 1, xlLookForFormulas = 2, } + // tslint:disable-next-line:no-const-enum const enum XlMailSystem { xlMAPI = 1, xlNoMailSystem = 0, xlPowerTalk = 2, } + // tslint:disable-next-line:no-const-enum const enum XlMarkerStyle { xlMarkerStyleAutomatic = -4105, xlMarkerStyleCircle = 8, @@ -1712,18 +1842,21 @@ declare namespace Excel { xlMarkerStyleX = -4168, } + // tslint:disable-next-line:no-const-enum const enum XlMeasurementUnits { xlCentimeters = 1, xlInches = 0, xlMillimeters = 2, } + // tslint:disable-next-line:no-const-enum const enum XlMouseButton { xlNoButton = 0, xlPrimaryButton = 1, xlSecondaryButton = 2, } + // tslint:disable-next-line:no-const-enum const enum XlMousePointer { xlDefault = -4143, xlIBeam = 3, @@ -1731,6 +1864,7 @@ declare namespace Excel { xlWait = 2, } + // tslint:disable-next-line:no-const-enum const enum XlMSApplication { xlMicrosoftAccess = 4, xlMicrosoftFoxPro = 5, @@ -1741,39 +1875,46 @@ declare namespace Excel { xlMicrosoftWord = 1, } + // tslint:disable-next-line:no-const-enum const enum XlOartHorizontalOverflow { xlOartHorizontalOverflowClip = 1, xlOartHorizontalOverflowOverflow = 0, } + // tslint:disable-next-line:no-const-enum const enum XlOartVerticalOverflow { xlOartVerticalOverflowClip = 1, xlOartVerticalOverflowEllipsis = 2, xlOartVerticalOverflowOverflow = 0, } + // tslint:disable-next-line:no-const-enum const enum XlObjectSize { xlFitToPage = 2, xlFullPage = 3, xlScreenSize = 1, } + // tslint:disable-next-line:no-const-enum const enum XlOLEType { xlOLEControl = 2, xlOLEEmbed = 1, xlOLELink = 0, } + // tslint:disable-next-line:no-const-enum const enum XlOLEVerb { xlVerbOpen = 2, xlVerbPrimary = 1, } + // tslint:disable-next-line:no-const-enum const enum XlOrder { xlDownThenOver = 1, xlOverThenDown = 2, } + // tslint:disable-next-line:no-const-enum const enum XlOrientation { xlDownward = -4170, xlHorizontal = -4128, @@ -1781,22 +1922,26 @@ declare namespace Excel { xlVertical = -4166, } + // tslint:disable-next-line:no-const-enum const enum XlPageBreak { xlPageBreakAutomatic = -4105, xlPageBreakManual = -4135, xlPageBreakNone = -4142, } + // tslint:disable-next-line:no-const-enum const enum XlPageBreakExtent { xlPageBreakFull = 1, xlPageBreakPartial = 2, } + // tslint:disable-next-line:no-const-enum const enum XlPageOrientation { xlLandscape = 2, xlPortrait = 1, } + // tslint:disable-next-line:no-const-enum const enum XlPaperSize { xlPaper10x14 = 16, xlPaper11x17 = 17, @@ -1842,6 +1987,7 @@ declare namespace Excel { xlPaperUser = 256, } + // tslint:disable-next-line:no-const-enum const enum XlParameterDataType { xlParamTypeBigInt = -5, xlParamTypeBinary = -2, @@ -1866,12 +2012,14 @@ declare namespace Excel { xlParamTypeWChar = -8, } + // tslint:disable-next-line:no-const-enum const enum XlParameterType { xlConstant = 1, xlPrompt = 0, xlRange = 2, } + // tslint:disable-next-line:no-const-enum const enum XlPasteSpecialOperation { xlPasteSpecialOperationAdd = 2, xlPasteSpecialOperationDivide = 5, @@ -1880,6 +2028,7 @@ declare namespace Excel { xlPasteSpecialOperationSubtract = 3, } + // tslint:disable-next-line:no-const-enum const enum XlPasteType { xlPasteAll = -4104, xlPasteAllExceptBorders = 7, @@ -1895,6 +2044,7 @@ declare namespace Excel { xlPasteValuesAndNumberFormats = 12, } + // tslint:disable-next-line:no-const-enum const enum XlPattern { xlPatternAutomatic = -4105, xlPatternChecker = 9, @@ -1920,6 +2070,7 @@ declare namespace Excel { xlPatternVertical = -4166, } + // tslint:disable-next-line:no-const-enum const enum XlPhoneticAlignment { xlPhoneticAlignCenter = 2, xlPhoneticAlignDistributed = 3, @@ -1927,6 +2078,7 @@ declare namespace Excel { xlPhoneticAlignNoControl = 0, } + // tslint:disable-next-line:no-const-enum const enum XlPhoneticCharacterType { xlHiragana = 2, xlKatakana = 1, @@ -1934,11 +2086,13 @@ declare namespace Excel { xlNoConversion = 3, } + // tslint:disable-next-line:no-const-enum const enum XlPictureAppearance { xlPrinter = 2, xlScreen = 1, } + // tslint:disable-next-line:no-const-enum const enum XlPictureConvertorType { xlBMP = 1, xlCGM = 7, @@ -1955,6 +2109,7 @@ declare namespace Excel { xlWPG = 3, } + // tslint:disable-next-line:no-const-enum const enum XlPieSliceIndex { xlCenterPoint = 5, xlInnerCenterPoint = 8, @@ -1967,11 +2122,13 @@ declare namespace Excel { xlOuterCounterClockwisePoint = 1, } + // tslint:disable-next-line:no-const-enum const enum XlPieSliceLocation { xlHorizontalCoordinate = 1, xlVerticalCoordinate = 2, } + // tslint:disable-next-line:no-const-enum const enum XlPivotCellType { xlPivotCellBlankCell = 9, xlPivotCellCustomSubtotal = 7, @@ -1985,12 +2142,14 @@ declare namespace Excel { xlPivotCellValue = 0, } + // tslint:disable-next-line:no-const-enum const enum XlPivotConditionScope { xlDataFieldScope = 2, xlFieldsScope = 1, xlSelectionScope = 0, } + // tslint:disable-next-line:no-const-enum const enum XlPivotFieldCalculation { xlDifferenceFrom = 2, xlIndex = 9, @@ -2009,12 +2168,14 @@ declare namespace Excel { xlRunningTotal = 5, } + // tslint:disable-next-line:no-const-enum const enum XlPivotFieldDataType { xlDate = 2, xlNumber = -4145, xlText = -4158, } + // tslint:disable-next-line:no-const-enum const enum XlPivotFieldOrientation { xlColumnField = 2, xlDataField = 4, @@ -2023,11 +2184,13 @@ declare namespace Excel { xlRowField = 1, } + // tslint:disable-next-line:no-const-enum const enum XlPivotFieldRepeatLabels { xlDoNotRepeatLabels = 1, xlRepeatLabels = 2, } + // tslint:disable-next-line:no-const-enum const enum XlPivotFilterType { xlAfter = 33, xlAfterOrEqualTo = 34, @@ -2099,6 +2262,7 @@ declare namespace Excel { xlYearToDate = 52, } + // tslint:disable-next-line:no-const-enum const enum XlPivotFormatType { xlPTClassic = 20, xlPTNone = 21, @@ -2124,6 +2288,7 @@ declare namespace Excel { xlTable9 = 18, } + // tslint:disable-next-line:no-const-enum const enum XlPivotLineType { xlPivotLineBlank = 3, xlPivotLineGrandTotal = 2, @@ -2131,6 +2296,7 @@ declare namespace Excel { xlPivotLineSubtotal = 1, } + // tslint:disable-next-line:no-const-enum const enum XlPivotTableMissingItems { xlMissingItemsDefault = -1, xlMissingItemsMax = 32500, @@ -2138,6 +2304,7 @@ declare namespace Excel { xlMissingItemsNone = 0, } + // tslint:disable-next-line:no-const-enum const enum XlPivotTableSourceType { xlConsolidation = 3, xlDatabase = 1, @@ -2146,6 +2313,7 @@ declare namespace Excel { xlScenario = 4, } + // tslint:disable-next-line:no-const-enum const enum XlPivotTableVersionList { xlPivotTableVersion10 = 1, xlPivotTableVersion11 = 2, @@ -2155,24 +2323,28 @@ declare namespace Excel { xlPivotTableVersionCurrent = -1, } + // tslint:disable-next-line:no-const-enum const enum XlPlacement { xlFreeFloating = 3, xlMove = 2, xlMoveAndSize = 1, } + // tslint:disable-next-line:no-const-enum const enum XlPlatform { xlMacintosh = 1, xlMSDOS = 3, xlWindows = 2, } + // tslint:disable-next-line:no-const-enum const enum XlPortugueseReform { xlPortugueseBoth = 3, xlPortuguesePostReform = 2, xlPortuguesePreReform = 1, } + // tslint:disable-next-line:no-const-enum const enum XlPrintErrors { xlPrintErrorsBlank = 1, xlPrintErrorsDash = 2, @@ -2180,36 +2352,42 @@ declare namespace Excel { xlPrintErrorsNA = 3, } + // tslint:disable-next-line:no-const-enum const enum XlPrintLocation { xlPrintInPlace = 16, xlPrintNoComments = -4142, xlPrintSheetEnd = 1, } + // tslint:disable-next-line:no-const-enum const enum XlPriority { xlPriorityHigh = -4127, xlPriorityLow = -4134, xlPriorityNormal = -4143, } + // tslint:disable-next-line:no-const-enum const enum XlPropertyDisplayedIn { xlDisplayPropertyInPivotTable = 1, xlDisplayPropertyInPivotTableAndTooltip = 3, xlDisplayPropertyInTooltip = 2, } + // tslint:disable-next-line:no-const-enum const enum XlProtectedViewCloseReason { xlProtectedViewCloseEdit = 1, xlProtectedViewCloseForced = 2, xlProtectedViewCloseNormal = 0, } + // tslint:disable-next-line:no-const-enum const enum XlProtectedViewWindowState { xlProtectedViewWindowMaximized = 2, xlProtectedViewWindowMinimized = 1, xlProtectedViewWindowNormal = 0, } + // tslint:disable-next-line:no-const-enum const enum XlPTSelectionMode { xlBlanks = 4, xlButton = 15, @@ -2220,6 +2398,7 @@ declare namespace Excel { xlOrigin = 3, } + // tslint:disable-next-line:no-const-enum const enum XlQueryType { xlADORecordset = 7, xlDAORecordset = 2, @@ -2229,6 +2408,7 @@ declare namespace Excel { xlWebQuery = 4, } + // tslint:disable-next-line:no-const-enum const enum XlRangeAutoFormat { xlRangeAutoFormat3DEffects1 = 13, xlRangeAutoFormat3DEffects2 = 14, @@ -2275,17 +2455,20 @@ declare namespace Excel { xlRangeAutoFormatTable9 = 40, } + // tslint:disable-next-line:no-const-enum const enum XlRangeValueDataType { xlRangeValueDefault = 10, xlRangeValueMSPersistXML = 12, xlRangeValueXMLSpreadsheet = 11, } + // tslint:disable-next-line:no-const-enum const enum XlReferenceStyle { xlA1 = 1, xlR1C1 = -4150, } + // tslint:disable-next-line:no-const-enum const enum XlReferenceType { xlAbsolute = 1, xlAbsRowRelColumn = 2, @@ -2293,6 +2476,7 @@ declare namespace Excel { xlRelRowAbsColumn = 3, } + // tslint:disable-next-line:no-const-enum const enum XlRemoveDocInfoType { xlRDIAll = 99, xlRDIComments = 1, @@ -2313,6 +2497,7 @@ declare namespace Excel { xlRDISendForReview = 7, } + // tslint:disable-next-line:no-const-enum const enum XlRgbColor { rgbAliceBlue = 16775408, rgbAntiqueWhite = 14150650, @@ -2460,28 +2645,33 @@ declare namespace Excel { rgbYellowGreen = 3329434, } + // tslint:disable-next-line:no-const-enum const enum XlRobustConnect { xlAlways = 1, xlAsRequired = 0, xlNever = 2, } + // tslint:disable-next-line:no-const-enum const enum XlRoutingSlipDelivery { xlAllAtOnce = 2, xlOneAfterAnother = 1, } + // tslint:disable-next-line:no-const-enum const enum XlRoutingSlipStatus { xlNotYetRouted = 0, xlRoutingComplete = 2, xlRoutingInProgress = 1, } + // tslint:disable-next-line:no-const-enum const enum XlRowCol { xlColumns = 2, xlRows = 1, } + // tslint:disable-next-line:no-const-enum const enum XlRunAutoMacro { xlAutoActivate = 3, xlAutoClose = 2, @@ -2489,43 +2679,51 @@ declare namespace Excel { xlAutoOpen = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSaveAction { xlDoNotSaveChanges = 2, xlSaveChanges = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSaveAsAccessMode { xlExclusive = 3, xlNoChange = 1, xlShared = 2, } + // tslint:disable-next-line:no-const-enum const enum XlSaveConflictResolution { xlLocalSessionChanges = 2, xlOtherSessionChanges = 3, xlUserResolution = 1, } + // tslint:disable-next-line:no-const-enum const enum XlScaleType { xlScaleLinear = -4132, xlScaleLogarithmic = -4133, } + // tslint:disable-next-line:no-const-enum const enum XlSearchDirection { xlNext = 1, xlPrevious = 2, } + // tslint:disable-next-line:no-const-enum const enum XlSearchOrder { xlByColumns = 2, xlByRows = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSearchWithin { xlWithinSheet = 1, xlWithinWorkbook = 2, } + // tslint:disable-next-line:no-const-enum const enum XlSheetType { xlChart = -4109, xlDialogSheet = -4116, @@ -2534,29 +2732,34 @@ declare namespace Excel { xlWorksheet = -4167, } + // tslint:disable-next-line:no-const-enum const enum XlSheetVisibility { xlSheetHidden = 0, xlSheetVeryHidden = 2, xlSheetVisible = -1, } + // tslint:disable-next-line:no-const-enum const enum XlSizeRepresents { xlSizeIsArea = 1, xlSizeIsWidth = 2, } + // tslint:disable-next-line:no-const-enum const enum XlSlicerCrossFilterType { xlSlicerCrossFilterShowItemsWithDataAtTop = 2, xlSlicerCrossFilterShowItemsWithNoData = 3, xlSlicerNoCrossFilter = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSlicerSort { xlSlicerSortAscending = 2, xlSlicerSortDataSourceOrder = 1, xlSlicerSortDescending = 3, } + // tslint:disable-next-line:no-const-enum const enum XlSmartTagControlType { xlSmartTagControlActiveX = 13, xlSmartTagControlButton = 6, @@ -2574,27 +2777,32 @@ declare namespace Excel { xlSmartTagControlTextbox = 10, } + // tslint:disable-next-line:no-const-enum const enum XlSmartTagDisplayMode { xlButtonOnly = 2, xlDisplayNone = 1, xlIndicatorAndButton = 0, } + // tslint:disable-next-line:no-const-enum const enum XlSortDataOption { xlSortNormal = 0, xlSortTextAsNumbers = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSortMethod { xlPinYin = 1, xlStroke = 2, } + // tslint:disable-next-line:no-const-enum const enum XlSortMethodOld { xlCodePage = 2, xlSyllabary = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSortOn { xlSortOnCellColor = 1, xlSortOnFontColor = 2, @@ -2602,21 +2810,25 @@ declare namespace Excel { xlSortOnValues = 0, } + // tslint:disable-next-line:no-const-enum const enum XlSortOrder { xlAscending = 1, xlDescending = 2, } + // tslint:disable-next-line:no-const-enum const enum XlSortOrientation { xlSortColumns = 1, xlSortRows = 2, } + // tslint:disable-next-line:no-const-enum const enum XlSortType { xlSortLabels = 2, xlSortValues = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSourceType { xlSourceAutoFilter = 3, xlSourceChart = 5, @@ -2628,35 +2840,41 @@ declare namespace Excel { xlSourceWorkbook = 0, } + // tslint:disable-next-line:no-const-enum const enum XlSpanishModes { xlSpanishTuteoAndVoseo = 1, xlSpanishTuteoOnly = 0, xlSpanishVoseoOnly = 2, } + // tslint:disable-next-line:no-const-enum const enum XlSparklineRowCol { xlSparklineColumnsSquare = 2, xlSparklineNonSquare = 0, xlSparklineRowsSquare = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSparkScale { xlSparkScaleCustom = 3, xlSparkScaleGroup = 1, xlSparkScaleSingle = 2, } + // tslint:disable-next-line:no-const-enum const enum XlSparkType { xlSparkColumn = 2, xlSparkColumnStacked100 = 3, xlSparkLine = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSpeakDirection { xlSpeakByColumns = 1, xlSpeakByRows = 0, } + // tslint:disable-next-line:no-const-enum const enum XlSpecialCellsValue { xlErrors = 16, xlLogical = 4, @@ -2664,6 +2882,7 @@ declare namespace Excel { xlTextValues = 2, } + // tslint:disable-next-line:no-const-enum const enum XlStdColorScale { xlColorScaleBlackWhite = 3, xlColorScaleGYR = 2, @@ -2671,31 +2890,37 @@ declare namespace Excel { xlColorScaleWhiteBlack = 4, } + // tslint:disable-next-line:no-const-enum const enum XlSubscribeToFormat { xlSubscribeToPicture = -4147, xlSubscribeToText = -4158, } + // tslint:disable-next-line:no-const-enum const enum XlSubtototalLocationType { xlAtBottom = 2, xlAtTop = 1, } + // tslint:disable-next-line:no-const-enum const enum XlSummaryColumn { xlSummaryOnLeft = -4131, xlSummaryOnRight = -4152, } + // tslint:disable-next-line:no-const-enum const enum XlSummaryReportType { xlStandardSummary = 1, xlSummaryPivotTable = -4148, } + // tslint:disable-next-line:no-const-enum const enum XlSummaryRow { xlSummaryAbove = 0, xlSummaryBelow = 1, } + // tslint:disable-next-line:no-const-enum const enum XlTableStyleElementType { xlBlankRow = 19, xlColumnStripe1 = 7, @@ -2737,27 +2962,32 @@ declare namespace Excel { xlWholeTable = 0, } + // tslint:disable-next-line:no-const-enum const enum XlTabPosition { xlTabPositionFirst = 0, xlTabPositionLast = 1, } + // tslint:disable-next-line:no-const-enum const enum XlTextParsingType { xlDelimited = 1, xlFixedWidth = 2, } + // tslint:disable-next-line:no-const-enum const enum XlTextQualifier { xlTextQualifierDoubleQuote = 1, xlTextQualifierNone = -4142, xlTextQualifierSingleQuote = 2, } + // tslint:disable-next-line:no-const-enum const enum XlTextVisualLayoutType { xlTextVisualLTR = 1, xlTextVisualRTL = 2, } + // tslint:disable-next-line:no-const-enum const enum XlThemeColor { xlThemeColorAccent1 = 5, xlThemeColorAccent2 = 6, @@ -2773,17 +3003,20 @@ declare namespace Excel { xlThemeColorLight2 = 4, } + // tslint:disable-next-line:no-const-enum const enum XlThemeFont { xlThemeFontMajor = 1, xlThemeFontMinor = 2, xlThemeFontNone = 0, } + // tslint:disable-next-line:no-const-enum const enum XlThreadMode { xlThreadModeAutomatic = 0, xlThreadModeManual = 1, } + // tslint:disable-next-line:no-const-enum const enum XlTickLabelOrientation { xlTickLabelOrientationAutomatic = -4105, xlTickLabelOrientationDownward = -4170, @@ -2792,6 +3025,7 @@ declare namespace Excel { xlTickLabelOrientationVertical = -4166, } + // tslint:disable-next-line:no-const-enum const enum XlTickLabelPosition { xlTickLabelPositionHigh = -4127, xlTickLabelPositionLow = -4134, @@ -2799,6 +3033,7 @@ declare namespace Excel { xlTickLabelPositionNone = -4142, } + // tslint:disable-next-line:no-const-enum const enum XlTickMark { xlTickMarkCross = 4, xlTickMarkInside = 2, @@ -2806,6 +3041,7 @@ declare namespace Excel { xlTickMarkOutside = 3, } + // tslint:disable-next-line:no-const-enum const enum XlTimePeriods { xlLast7Days = 2, xlLastMonth = 5, @@ -2819,12 +3055,14 @@ declare namespace Excel { xlYesterday = 1, } + // tslint:disable-next-line:no-const-enum const enum XlTimeUnit { xlDays = 0, xlMonths = 1, xlYears = 2, } + // tslint:disable-next-line:no-const-enum const enum XlToolbarProtection { xlNoButtonChanges = 1, xlNoChanges = 4, @@ -2833,11 +3071,13 @@ declare namespace Excel { xlToolbarProtectionNone = -4143, } + // tslint:disable-next-line:no-const-enum const enum XlTopBottom { xlTop10Bottom = 0, xlTop10Top = 1, } + // tslint:disable-next-line:no-const-enum const enum XlTotalsCalculation { xlTotalsCalculationAverage = 2, xlTotalsCalculationCount = 3, @@ -2851,6 +3091,7 @@ declare namespace Excel { xlTotalsCalculationVar = 8, } + // tslint:disable-next-line:no-const-enum const enum XlTrendlineType { xlExponential = 5, xlLinear = -4132, @@ -2860,6 +3101,7 @@ declare namespace Excel { xlPower = 4, } + // tslint:disable-next-line:no-const-enum const enum XlUnderlineStyle { xlUnderlineStyleDouble = -4119, xlUnderlineStyleDoubleAccounting = 5, @@ -2868,12 +3110,14 @@ declare namespace Excel { xlUnderlineStyleSingleAccounting = 4, } + // tslint:disable-next-line:no-const-enum const enum XlUpdateLinks { xlUpdateLinksAlways = 3, xlUpdateLinksNever = 2, xlUpdateLinksUserSetting = 1, } + // tslint:disable-next-line:no-const-enum const enum XlVAlign { xlVAlignBottom = -4107, xlVAlignCenter = -4108, @@ -2882,6 +3126,7 @@ declare namespace Excel { xlVAlignTop = -4160, } + // tslint:disable-next-line:no-const-enum const enum XlWBATemplate { xlWBATChart = -4109, xlWBATExcel4IntlMacroSheet = 4, @@ -2889,24 +3134,28 @@ declare namespace Excel { xlWBATWorksheet = -4167, } + // tslint:disable-next-line:no-const-enum const enum XlWebFormatting { xlWebFormattingAll = 1, xlWebFormattingNone = 3, xlWebFormattingRTF = 2, } + // tslint:disable-next-line:no-const-enum const enum XlWebSelectionType { xlAllTables = 2, xlEntirePage = 1, xlSpecifiedTables = 3, } + // tslint:disable-next-line:no-const-enum const enum XlWindowState { xlMaximized = -4137, xlMinimized = -4140, xlNormal = -4143, } + // tslint:disable-next-line:no-const-enum const enum XlWindowType { xlChartAsWindow = 5, xlChartInPlace = 4, @@ -2915,29 +3164,34 @@ declare namespace Excel { xlWorkbook = 1, } + // tslint:disable-next-line:no-const-enum const enum XlWindowView { xlNormalView = 1, xlPageBreakPreview = 2, xlPageLayoutView = 3, } + // tslint:disable-next-line:no-const-enum const enum XlXLMMacroType { xlCommand = 2, xlFunction = 1, xlNotXLM = 3, } + // tslint:disable-next-line:no-const-enum const enum XlXmlExportResult { xlXmlExportSuccess = 0, xlXmlExportValidationFailed = 1, } + // tslint:disable-next-line:no-const-enum const enum XlXmlImportResult { xlXmlImportElementsTruncated = 1, xlXmlImportSuccess = 0, xlXmlImportValidationFailed = 2, } + // tslint:disable-next-line:no-const-enum const enum XlXmlLoadOption { xlXmlLoadImportToList = 2, xlXmlLoadMapXml = 3, @@ -2945,6 +3199,7 @@ declare namespace Excel { xlXmlLoadPromptUser = 0, } + // tslint:disable-next-line:no-const-enum const enum XlYesNoGuess { xlGuess = 0, xlNo = 2, @@ -6547,7 +6802,7 @@ declare namespace Excel { /** @param Excel.XlSearchDirection [SearchDirection=1] */ Find(What: any, After?: any, LookIn?: XlFindLookIn, LookAt?: XlLookAt, SearchOrder?: XlSearchOrder, SearchDirection?: XlSearchDirection, MatchCase?: boolean, - MatchByte?: boolean, SearchFormat?: any): Range; + MatchByte?: boolean, SearchFormat?: any): Range; FindNext(After?: any): Range; FindPrevious(After?: any): Range; readonly Font: Font; @@ -7049,7 +7304,7 @@ declare namespace Excel { AddLabel(Orientation: Office.MsoTextOrientation, Left: number, Top: number, Width: number, Height: number): Shape; AddLine(BeginX: number, BeginY: number, EndX: number, EndY: number): Shape; AddOLEObject(ClassType?: any, Filename?: any, Link?: any, DisplayAsIcon?: any, IconFileName?: any, IconIndex?: any, IconLabel?: any, Left?: any, Top?: any, Width?: any, - Height?: any): Shape; + Height?: any): Shape; AddPicture(Filename: string, LinkToFile: Office.MsoTriState, SaveWithDocument: Office.MsoTriState, Left: number, Top: number, Width: number, Height: number): Shape; AddPolyline(SafeArrayOfPoints: any): Shape; AddShape(Type: Office.MsoAutoShapeType, Left: number, Top: number, Width: number, Height: number): Shape; @@ -9243,217 +9498,221 @@ declare namespace Excel { interface ActiveXObject { on( obj: Excel.Application, event: 'GetIDsOfNames', argNames: ['riid', 'rgszNames', 'cNames', 'lcid', 'rgdispid'], handler: ( - this: Excel.Application, parameter: {readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number}) => void): void; + this: Excel.Application, parameter: { readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number }) => void): void; on( obj: Excel.Application, event: 'GetTypeInfo', argNames: ['itinfo', 'lcid', 'pptinfo'], handler: ( - this: Excel.Application, parameter: {readonly itinfo: number, readonly lcid: number, pptinfo: undefined}) => void): void; - on(obj: Excel.Application, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.Application, parameter: {pctinfo: number}) => void): void; + this: Excel.Application, parameter: { readonly itinfo: number, readonly lcid: number, pptinfo: undefined }) => void): void; + on(obj: Excel.Application, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.Application, parameter: { pctinfo: number }) => void): void; on( obj: Excel.Application, event: 'Invoke', argNames: Excel.EventHelperTypes.Application_Invoke_ArgNames, handler: ( this: Excel.Application, parameter: Excel.EventHelperTypes.Application_Invoke_Parameter) => void): void; on( obj: Excel.Application, event: 'NewWorkbook' | 'WorkbookActivate' | 'WorkbookAddinInstall' | 'WorkbookAddinUninstall' | 'WorkbookDeactivate' | 'WorkbookOpen', - argNames: ['Wb'], handler: (this: Excel.Application, parameter: {readonly Wb: Excel.Workbook}) => void): void; + argNames: ['Wb'], handler: (this: Excel.Application, parameter: { readonly Wb: Excel.Workbook }) => void): void; on( obj: Excel.Application, event: 'ProtectedViewWindowActivate' | 'ProtectedViewWindowDeactivate' | 'ProtectedViewWindowOpen' | 'ProtectedViewWindowResize', - argNames: ['Pvw'], handler: (this: Excel.Application, parameter: {readonly Pvw: Excel.ProtectedViewWindow}) => void): void; + argNames: ['Pvw'], handler: (this: Excel.Application, parameter: { readonly Pvw: Excel.ProtectedViewWindow }) => void): void; on( obj: Excel.Application, event: 'ProtectedViewWindowBeforeClose', argNames: ['Pvw', 'Reason', 'Cancel'], handler: ( - this: Excel.Application, parameter: {readonly Pvw: Excel.ProtectedViewWindow, readonly Reason: Excel.XlProtectedViewCloseReason, Cancel: boolean}) => void): void; + this: Excel.Application, parameter: { readonly Pvw: Excel.ProtectedViewWindow, readonly Reason: Excel.XlProtectedViewCloseReason, Cancel: boolean }) => void): void; on( obj: Excel.Application, event: 'ProtectedViewWindowBeforeEdit', argNames: ['Pvw', 'Cancel'], handler: ( - this: Excel.Application, parameter: {readonly Pvw: Excel.ProtectedViewWindow, Cancel: boolean}) => void): void; - on(obj: Excel.Application, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.Application, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void; - on(obj: Excel.Application, event: 'SheetActivate' | 'SheetCalculate' | 'SheetDeactivate', argNames: ['Sh'], handler: (this: Excel.Application, parameter: {readonly Sh: any}) => void): void; + this: Excel.Application, parameter: { readonly Pvw: Excel.ProtectedViewWindow, Cancel: boolean }) => void): void; + on(obj: Excel.Application, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.Application, parameter: { readonly riid: stdole.GUID, ppvObj: undefined }) => void): void; + on(obj: Excel.Application, event: 'SheetActivate' | 'SheetCalculate' | 'SheetDeactivate', argNames: ['Sh'], handler: (this: Excel.Application, parameter: { readonly Sh: any }) => void): void; on( obj: Excel.Application, event: 'SheetBeforeDoubleClick' | 'SheetBeforeRightClick', argNames: ['Sh', 'Target', 'Cancel'], handler: ( - this: Excel.Application, parameter: {readonly Sh: any, readonly Target: Excel.Range, Cancel: boolean}) => void): void; + this: Excel.Application, parameter: { readonly Sh: any, readonly Target: Excel.Range, Cancel: boolean }) => void): void; on( obj: Excel.Application, event: 'SheetChange' | 'SheetSelectionChange', argNames: ['Sh', 'Target'], handler: ( - this: Excel.Application, parameter: {readonly Sh: any, readonly Target: Excel.Range}) => void): void; + this: Excel.Application, parameter: { readonly Sh: any, readonly Target: Excel.Range }) => void): void; on( obj: Excel.Application, event: 'SheetFollowHyperlink', argNames: ['Sh', 'Target'], handler: ( - this: Excel.Application, parameter: {readonly Sh: any, readonly Target: Excel.Hyperlink}) => void): void; + this: Excel.Application, parameter: { readonly Sh: any, readonly Target: Excel.Hyperlink }) => void): void; on( obj: Excel.Application, event: 'SheetPivotTableAfterValueChange', argNames: ['Sh', 'TargetPivotTable', 'TargetRange'], handler: ( - this: Excel.Application, parameter: {readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly TargetRange: Excel.Range}) => void): void; + this: Excel.Application, parameter: { readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly TargetRange: Excel.Range }) => void): void; on( obj: Excel.Application, event: 'SheetPivotTableBeforeAllocateChanges' | 'SheetPivotTableBeforeCommitChanges', argNames: ['Sh', 'TargetPivotTable', 'ValueChangeStart', 'ValueChangeEnd', 'Cancel'], handler: ( this: Excel.Application, - parameter: {readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number, Cancel: boolean}) => void): void; + parameter: { readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number, Cancel: boolean }) => void): void; on( obj: Excel.Application, event: 'SheetPivotTableBeforeDiscardChanges', argNames: ['Sh', 'TargetPivotTable', 'ValueChangeStart', 'ValueChangeEnd'], handler: ( - this: Excel.Application, parameter: {readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number}) => void): void; + this: Excel.Application, parameter: { readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number }) => void): void; on( obj: Excel.Application, event: 'SheetPivotTableUpdate', argNames: ['Sh', 'Target'], handler: ( - this: Excel.Application, parameter: {readonly Sh: any, readonly Target: Excel.PivotTable}) => void): void; + this: Excel.Application, parameter: { readonly Sh: any, readonly Target: Excel.PivotTable }) => void): void; on( obj: Excel.Application, event: 'WindowActivate' | 'WindowDeactivate' | 'WindowResize', argNames: ['Wb', 'Wn'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Wn: Excel.Window}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Wn: Excel.Window }) => void): void; on( obj: Excel.Application, event: 'WorkbookAfterSave', argNames: ['Wb', 'Success'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Success: boolean}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Success: boolean }) => void): void; on( obj: Excel.Application, event: 'WorkbookAfterXmlExport', argNames: ['Wb', 'Map', 'Url', 'Result'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Map: Excel.XmlMap, readonly Url: string, readonly Result: Excel.XlXmlExportResult}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Map: Excel.XmlMap, readonly Url: string, readonly Result: Excel.XlXmlExportResult }) => void): void; on( obj: Excel.Application, event: 'WorkbookAfterXmlImport', argNames: ['Wb', 'Map', 'IsRefresh', 'Result'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Map: Excel.XmlMap, readonly IsRefresh: boolean, readonly Result: Excel.XlXmlImportResult}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Map: Excel.XmlMap, readonly IsRefresh: boolean, readonly Result: Excel.XlXmlImportResult }) => void): void; on( obj: Excel.Application, event: 'WorkbookBeforeClose' | 'WorkbookBeforePrint', argNames: ['Wb', 'Cancel'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, Cancel: boolean}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, Cancel: boolean }) => void): void; on( obj: Excel.Application, event: 'WorkbookBeforeSave', argNames: ['Wb', 'SaveAsUI', 'Cancel'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly SaveAsUI: boolean, Cancel: boolean}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly SaveAsUI: boolean, Cancel: boolean }) => void): void; on( obj: Excel.Application, event: 'WorkbookBeforeXmlExport', argNames: ['Wb', 'Map', 'Url', 'Cancel'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Map: Excel.XmlMap, readonly Url: string, Cancel: boolean}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Map: Excel.XmlMap, readonly Url: string, Cancel: boolean }) => void): void; on( obj: Excel.Application, event: 'WorkbookBeforeXmlImport', argNames: ['Wb', 'Map', 'Url', 'IsRefresh', 'Cancel'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Map: Excel.XmlMap, readonly Url: string, readonly IsRefresh: boolean, Cancel: boolean}) => void): void; - on(obj: Excel.Application, event: 'WorkbookNewChart', argNames: ['Wb', 'Ch'], handler: (this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Ch: Excel.Chart}) => void): void; - on(obj: Excel.Application, event: 'WorkbookNewSheet', argNames: ['Wb', 'Sh'], handler: (this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Sh: any}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Map: Excel.XmlMap, readonly Url: string, readonly IsRefresh: boolean, Cancel: boolean }) => void): void; + on(obj: Excel.Application, event: 'WorkbookNewChart', argNames: ['Wb', 'Ch'], handler: ( + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Ch: Excel.Chart }) => void): void; + on(obj: Excel.Application, event: 'WorkbookNewSheet', argNames: ['Wb', 'Sh'], handler: (this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Sh: any }) => void): void; on( obj: Excel.Application, event: 'WorkbookPivotTableCloseConnection' | 'WorkbookPivotTableOpenConnection', argNames: ['Wb', 'Target'], - handler: (this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Target: Excel.PivotTable}) => void): void; + handler: (this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Target: Excel.PivotTable }) => void): void; on( obj: Excel.Application, event: 'WorkbookRowsetComplete', argNames: ['Wb', 'Description', 'Sheet', 'Success'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly Description: string, readonly Sheet: string, readonly Success: boolean}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly Description: string, readonly Sheet: string, readonly Success: boolean }) => void): void; on( obj: Excel.Application, event: 'WorkbookSync', argNames: ['Wb', 'SyncEventType'], handler: ( - this: Excel.Application, parameter: {readonly Wb: Excel.Workbook, readonly SyncEventType: Office.MsoSyncEventType}) => void): void; + this: Excel.Application, parameter: { readonly Wb: Excel.Workbook, readonly SyncEventType: Office.MsoSyncEventType }) => void): void; on( obj: Excel.Chart, event: 'BeforeDoubleClick', argNames: ['ElementID', 'Arg1', 'Arg2', 'Cancel'], handler: ( - this: Excel.Chart, parameter: {readonly ElementID: number, readonly Arg1: number, readonly Arg2: number, Cancel: boolean}) => void): void; - on(obj: Excel.Chart, event: 'BeforeRightClick', argNames: ['Cancel'], handler: (this: Excel.Chart, parameter: {Cancel: boolean}) => void): void; + this: Excel.Chart, parameter: { readonly ElementID: number, readonly Arg1: number, readonly Arg2: number, Cancel: boolean }) => void): void; + on(obj: Excel.Chart, event: 'BeforeRightClick', argNames: ['Cancel'], handler: (this: Excel.Chart, parameter: { Cancel: boolean }) => void): void; on( obj: Excel.Chart, event: 'GetIDsOfNames', argNames: ['riid', 'rgszNames', 'cNames', 'lcid', 'rgdispid'], handler: ( - this: Excel.Chart, parameter: {readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number}) => void): void; + this: Excel.Chart, parameter: { readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number }) => void): void; on( obj: Excel.Chart, event: 'GetTypeInfo', argNames: ['itinfo', 'lcid', 'pptinfo'], handler: ( - this: Excel.Chart, parameter: {readonly itinfo: number, readonly lcid: number, pptinfo: undefined}) => void): void; - on(obj: Excel.Chart, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.Chart, parameter: {pctinfo: number}) => void): void; + this: Excel.Chart, parameter: { readonly itinfo: number, readonly lcid: number, pptinfo: undefined }) => void): void; + on(obj: Excel.Chart, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.Chart, parameter: { pctinfo: number }) => void): void; on(obj: Excel.Chart, event: 'Invoke', argNames: Excel.EventHelperTypes.Chart_Invoke_ArgNames, handler: (this: Excel.Chart, parameter: Excel.EventHelperTypes.Chart_Invoke_Parameter) => void): void; on( obj: Excel.Chart, event: 'MouseDown' | 'MouseMove' | 'MouseUp', argNames: ['Button', 'Shift', 'x', 'y'], handler: ( - this: Excel.Chart, parameter: {readonly Button: number, readonly Shift: number, readonly x: number, readonly y: number}) => void): void; - on(obj: Excel.Chart, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.Chart, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void; + this: Excel.Chart, parameter: { readonly Button: number, readonly Shift: number, readonly x: number, readonly y: number }) => void): void; + on(obj: Excel.Chart, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.Chart, parameter: { readonly riid: stdole.GUID, ppvObj: undefined }) => void): void; on( obj: Excel.Chart, event: 'Select', argNames: ['ElementID', 'Arg1', 'Arg2'], handler: ( - this: Excel.Chart, parameter: {readonly ElementID: number, readonly Arg1: number, readonly Arg2: number}) => void): void; + this: Excel.Chart, parameter: { readonly ElementID: number, readonly Arg1: number, readonly Arg2: number }) => void): void; on( obj: Excel.Chart, event: 'SeriesChange', argNames: ['SeriesIndex', 'PointIndex'], handler: ( - this: Excel.Chart, parameter: {readonly SeriesIndex: number, readonly PointIndex: number}) => void): void; + this: Excel.Chart, parameter: { readonly SeriesIndex: number, readonly PointIndex: number }) => void): void; on( obj: Excel.OLEObject, event: 'GetIDsOfNames', argNames: ['riid', 'rgszNames', 'cNames', 'lcid', 'rgdispid'], handler: ( - this: Excel.OLEObject, parameter: {readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number}) => void): void; + this: Excel.OLEObject, parameter: { readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number }) => void): void; on( obj: Excel.OLEObject, event: 'GetTypeInfo', argNames: ['itinfo', 'lcid', 'pptinfo'], handler: ( - this: Excel.OLEObject, parameter: {readonly itinfo: number, readonly lcid: number, pptinfo: undefined}) => void): void; - on(obj: Excel.OLEObject, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.OLEObject, parameter: {pctinfo: number}) => void): void; + this: Excel.OLEObject, parameter: { readonly itinfo: number, readonly lcid: number, pptinfo: undefined }) => void): void; + on(obj: Excel.OLEObject, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.OLEObject, parameter: { pctinfo: number }) => void): void; on( obj: Excel.OLEObject, event: 'Invoke', argNames: Excel.EventHelperTypes.OLEObject_Invoke_ArgNames, handler: ( this: Excel.OLEObject, parameter: Excel.EventHelperTypes.OLEObject_Invoke_Parameter) => void): void; - on(obj: Excel.OLEObject, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.OLEObject, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void; - on(obj: Excel.QueryTable, event: 'AfterRefresh', argNames: ['Success'], handler: (this: Excel.QueryTable, parameter: {readonly Success: boolean}) => void): void; - on(obj: Excel.QueryTable, event: 'BeforeRefresh', argNames: ['Cancel'], handler: (this: Excel.QueryTable, parameter: {Cancel: boolean}) => void): void; + on(obj: Excel.OLEObject, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.OLEObject, parameter: { readonly riid: stdole.GUID, ppvObj: undefined }) => void): void; + on(obj: Excel.QueryTable, event: 'AfterRefresh', argNames: ['Success'], handler: (this: Excel.QueryTable, parameter: { readonly Success: boolean }) => void): void; + on(obj: Excel.QueryTable, event: 'BeforeRefresh', argNames: ['Cancel'], handler: (this: Excel.QueryTable, parameter: { Cancel: boolean }) => void): void; on( obj: Excel.QueryTable, event: 'GetIDsOfNames', argNames: ['riid', 'rgszNames', 'cNames', 'lcid', 'rgdispid'], handler: ( - this: Excel.QueryTable, parameter: {readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number}) => void): void; + this: Excel.QueryTable, parameter: { readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number }) => void): void; on( obj: Excel.QueryTable, event: 'GetTypeInfo', argNames: ['itinfo', 'lcid', 'pptinfo'], handler: ( - this: Excel.QueryTable, parameter: {readonly itinfo: number, readonly lcid: number, pptinfo: undefined}) => void): void; - on(obj: Excel.QueryTable, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.QueryTable, parameter: {pctinfo: number}) => void): void; + this: Excel.QueryTable, parameter: { readonly itinfo: number, readonly lcid: number, pptinfo: undefined }) => void): void; + on(obj: Excel.QueryTable, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.QueryTable, parameter: { pctinfo: number }) => void): void; on( obj: Excel.QueryTable, event: 'Invoke', argNames: Excel.EventHelperTypes.QueryTable_Invoke_ArgNames, handler: ( this: Excel.QueryTable, parameter: Excel.EventHelperTypes.QueryTable_Invoke_Parameter) => void): void; - on(obj: Excel.QueryTable, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.QueryTable, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void; - on(obj: Excel.Workbook, event: 'AfterSave', argNames: ['Success'], handler: (this: Excel.Workbook, parameter: {readonly Success: boolean}) => void): void; + on(obj: Excel.QueryTable, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.QueryTable, parameter: { readonly riid: stdole.GUID, ppvObj: undefined }) => void): void; + on(obj: Excel.Workbook, event: 'AfterSave', argNames: ['Success'], handler: (this: Excel.Workbook, parameter: { readonly Success: boolean }) => void): void; on( obj: Excel.Workbook, event: 'AfterXmlExport', argNames: ['Map', 'Url', 'Result'], handler: ( - this: Excel.Workbook, parameter: {readonly Map: Excel.XmlMap, readonly Url: string, readonly Result: Excel.XlXmlExportResult}) => void): void; + this: Excel.Workbook, parameter: { readonly Map: Excel.XmlMap, readonly Url: string, readonly Result: Excel.XlXmlExportResult }) => void): void; on( obj: Excel.Workbook, event: 'AfterXmlImport', argNames: ['Map', 'IsRefresh', 'Result'], handler: ( - this: Excel.Workbook, parameter: {readonly Map: Excel.XmlMap, readonly IsRefresh: boolean, readonly Result: Excel.XlXmlImportResult}) => void): void; - on(obj: Excel.Workbook, event: 'BeforeClose' | 'BeforePrint', argNames: ['Cancel'], handler: (this: Excel.Workbook, parameter: {Cancel: boolean}) => void): void; - on(obj: Excel.Workbook, event: 'BeforeSave', argNames: ['SaveAsUI', 'Cancel'], handler: (this: Excel.Workbook, parameter: {readonly SaveAsUI: boolean, Cancel: boolean}) => void): void; + this: Excel.Workbook, parameter: { readonly Map: Excel.XmlMap, readonly IsRefresh: boolean, readonly Result: Excel.XlXmlImportResult }) => void): void; + on(obj: Excel.Workbook, event: 'BeforeClose' | 'BeforePrint', argNames: ['Cancel'], handler: (this: Excel.Workbook, parameter: { Cancel: boolean }) => void): void; + on(obj: Excel.Workbook, event: 'BeforeSave', argNames: ['SaveAsUI', 'Cancel'], handler: (this: Excel.Workbook, parameter: { readonly SaveAsUI: boolean, Cancel: boolean }) => void): void; on( obj: Excel.Workbook, event: 'BeforeXmlExport', argNames: ['Map', 'Url', 'Cancel'], handler: ( - this: Excel.Workbook, parameter: {readonly Map: Excel.XmlMap, readonly Url: string, Cancel: boolean}) => void): void; + this: Excel.Workbook, parameter: { readonly Map: Excel.XmlMap, readonly Url: string, Cancel: boolean }) => void): void; on( obj: Excel.Workbook, event: 'BeforeXmlImport', argNames: ['Map', 'Url', 'IsRefresh', 'Cancel'], handler: ( - this: Excel.Workbook, parameter: {readonly Map: Excel.XmlMap, readonly Url: string, readonly IsRefresh: boolean, Cancel: boolean}) => void): void; + this: Excel.Workbook, parameter: { readonly Map: Excel.XmlMap, readonly Url: string, readonly IsRefresh: boolean, Cancel: boolean }) => void): void; on( obj: Excel.Workbook, event: 'GetIDsOfNames', argNames: ['riid', 'rgszNames', 'cNames', 'lcid', 'rgdispid'], handler: ( - this: Excel.Workbook, parameter: {readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number}) => void): void; + this: Excel.Workbook, parameter: { readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number }) => void): void; on( obj: Excel.Workbook, event: 'GetTypeInfo', argNames: ['itinfo', 'lcid', 'pptinfo'], handler: ( - this: Excel.Workbook, parameter: {readonly itinfo: number, readonly lcid: number, pptinfo: undefined}) => void): void; - on(obj: Excel.Workbook, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.Workbook, parameter: {pctinfo: number}) => void): void; + this: Excel.Workbook, parameter: { readonly itinfo: number, readonly lcid: number, pptinfo: undefined }) => void): void; + on(obj: Excel.Workbook, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.Workbook, parameter: { pctinfo: number }) => void): void; on( obj: Excel.Workbook, event: 'Invoke', argNames: Excel.EventHelperTypes.Workbook_Invoke_ArgNames, handler: ( this: Excel.Workbook, parameter: Excel.EventHelperTypes.Workbook_Invoke_Parameter) => void): void; - on(obj: Excel.Workbook, event: 'NewChart', argNames: ['Ch'], handler: (this: Excel.Workbook, parameter: {readonly Ch: Excel.Chart}) => void): void; - on(obj: Excel.Workbook, event: 'NewSheet' | 'SheetActivate' | 'SheetCalculate' | 'SheetDeactivate', argNames: ['Sh'], handler: (this: Excel.Workbook, parameter: {readonly Sh: any}) => void): void; + on(obj: Excel.Workbook, event: 'NewChart', argNames: ['Ch'], handler: (this: Excel.Workbook, parameter: { readonly Ch: Excel.Chart }) => void): void; + on(obj: Excel.Workbook, event: 'NewSheet' | 'SheetActivate' | 'SheetCalculate' | 'SheetDeactivate', argNames: ['Sh'], handler: ( + this: Excel.Workbook, parameter: { readonly Sh: any }) => void): void; on( obj: Excel.Workbook, event: 'PivotTableCloseConnection' | 'PivotTableOpenConnection', argNames: ['Target'], handler: ( - this: Excel.Workbook, parameter: {readonly Target: Excel.PivotTable}) => void): void; - on(obj: Excel.Workbook, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.Workbook, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void; + this: Excel.Workbook, parameter: { readonly Target: Excel.PivotTable }) => void): void; + on(obj: Excel.Workbook, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.Workbook, parameter: { readonly riid: stdole.GUID, ppvObj: undefined }) => void): void; on( obj: Excel.Workbook, event: 'RowsetComplete', argNames: ['Description', 'Sheet', 'Success'], handler: ( - this: Excel.Workbook, parameter: {readonly Description: string, readonly Sheet: string, readonly Success: boolean}) => void): void; + this: Excel.Workbook, parameter: { readonly Description: string, readonly Sheet: string, readonly Success: boolean }) => void): void; on( obj: Excel.Workbook, event: 'SheetBeforeDoubleClick' | 'SheetBeforeRightClick', argNames: ['Sh', 'Target', 'Cancel'], handler: ( - this: Excel.Workbook, parameter: {readonly Sh: any, readonly Target: Excel.Range, Cancel: boolean}) => void): void; + this: Excel.Workbook, parameter: { readonly Sh: any, readonly Target: Excel.Range, Cancel: boolean }) => void): void; on( obj: Excel.Workbook, event: 'SheetChange' | 'SheetSelectionChange', argNames: ['Sh', 'Target'], handler: ( - this: Excel.Workbook, parameter: {readonly Sh: any, readonly Target: Excel.Range}) => void): void; - on(obj: Excel.Workbook, event: 'SheetFollowHyperlink', argNames: ['Sh', 'Target'], handler: (this: Excel.Workbook, parameter: {readonly Sh: any, readonly Target: Excel.Hyperlink}) => void): void; + this: Excel.Workbook, parameter: { readonly Sh: any, readonly Target: Excel.Range }) => void): void; + on(obj: Excel.Workbook, event: 'SheetFollowHyperlink', argNames: ['Sh', 'Target'], handler: ( + this: Excel.Workbook, parameter: { readonly Sh: any, readonly Target: Excel.Hyperlink }) => void): void; on( obj: Excel.Workbook, event: 'SheetPivotTableAfterValueChange', argNames: ['Sh', 'TargetPivotTable', 'TargetRange'], handler: ( - this: Excel.Workbook, parameter: {readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly TargetRange: Excel.Range}) => void): void; + this: Excel.Workbook, parameter: { readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly TargetRange: Excel.Range }) => void): void; on( obj: Excel.Workbook, event: 'SheetPivotTableBeforeAllocateChanges' | 'SheetPivotTableBeforeCommitChanges', argNames: ['Sh', 'TargetPivotTable', 'ValueChangeStart', 'ValueChangeEnd', 'Cancel'], handler: ( this: Excel.Workbook, - parameter: {readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number, Cancel: boolean}) => void): void; + parameter: { readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number, Cancel: boolean }) => void): void; on( - obj: Excel.Workbook, event: 'SheetPivotTableBeforeDiscardChanges', argNames: ['Sh', 'TargetPivotTable', 'ValueChangeStart', 'ValueChangeEnd'], - handler: (this: Excel.Workbook, parameter: {readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number}) => void): void; + obj: Excel.Workbook, event: 'SheetPivotTableBeforeDiscardChanges', argNames: ['Sh', 'TargetPivotTable', 'ValueChangeStart', 'ValueChangeEnd'], handler: ( + this: Excel.Workbook, parameter: { readonly Sh: any, readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number }) => void): void; on( obj: Excel.Workbook, event: 'SheetPivotTableChangeSync' | 'SheetPivotTableUpdate', argNames: ['Sh', 'Target'], handler: ( - this: Excel.Workbook, parameter: {readonly Sh: any, readonly Target: Excel.PivotTable}) => void): void; - on(obj: Excel.Workbook, event: 'Sync', argNames: ['SyncEventType'], handler: (this: Excel.Workbook, parameter: {readonly SyncEventType: Office.MsoSyncEventType}) => void): void; - on(obj: Excel.Workbook, event: 'WindowActivate' | 'WindowDeactivate' | 'WindowResize', argNames: ['Wn'], handler: (this: Excel.Workbook, parameter: {readonly Wn: Excel.Window}) => void): void; + this: Excel.Workbook, parameter: { readonly Sh: any, readonly Target: Excel.PivotTable }) => void): void; + on(obj: Excel.Workbook, event: 'Sync', argNames: ['SyncEventType'], handler: (this: Excel.Workbook, parameter: { readonly SyncEventType: Office.MsoSyncEventType }) => void): void; + on(obj: Excel.Workbook, event: 'WindowActivate' | 'WindowDeactivate' | 'WindowResize', argNames: ['Wn'], handler: (this: Excel.Workbook, parameter: { readonly Wn: Excel.Window }) => void): void; on( obj: Excel.Worksheet, event: 'BeforeDoubleClick' | 'BeforeRightClick', argNames: ['Target', 'Cancel'], handler: ( - this: Excel.Worksheet, parameter: {readonly Target: Excel.Range, Cancel: boolean}) => void): void; - on(obj: Excel.Worksheet, event: 'Change' | 'SelectionChange', argNames: ['Target'], handler: (this: Excel.Worksheet, parameter: {readonly Target: Excel.Range}) => void): void; - on(obj: Excel.Worksheet, event: 'FollowHyperlink', argNames: ['Target'], handler: (this: Excel.Worksheet, parameter: {readonly Target: Excel.Hyperlink}) => void): void; + this: Excel.Worksheet, parameter: { readonly Target: Excel.Range, Cancel: boolean }) => void): void; + on(obj: Excel.Worksheet, event: 'Change' | 'SelectionChange', argNames: ['Target'], handler: (this: Excel.Worksheet, parameter: { readonly Target: Excel.Range }) => void): void; + on(obj: Excel.Worksheet, event: 'FollowHyperlink', argNames: ['Target'], handler: (this: Excel.Worksheet, parameter: { readonly Target: Excel.Hyperlink }) => void): void; on( obj: Excel.Worksheet, event: 'GetIDsOfNames', argNames: ['riid', 'rgszNames', 'cNames', 'lcid', 'rgdispid'], handler: ( - this: Excel.Worksheet, parameter: {readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number}) => void): void; + this: Excel.Worksheet, parameter: { readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number }) => void): void; on( obj: Excel.Worksheet, event: 'GetTypeInfo', argNames: ['itinfo', 'lcid', 'pptinfo'], handler: ( - this: Excel.Worksheet, parameter: {readonly itinfo: number, readonly lcid: number, pptinfo: undefined}) => void): void; - on(obj: Excel.Worksheet, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.Worksheet, parameter: {pctinfo: number}) => void): void; + this: Excel.Worksheet, parameter: { readonly itinfo: number, readonly lcid: number, pptinfo: undefined }) => void): void; + on(obj: Excel.Worksheet, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Excel.Worksheet, parameter: { pctinfo: number }) => void): void; on( obj: Excel.Worksheet, event: 'Invoke', argNames: Excel.EventHelperTypes.Worksheet_Invoke_ArgNames, handler: ( this: Excel.Worksheet, parameter: Excel.EventHelperTypes.Worksheet_Invoke_Parameter) => void): void; on( obj: Excel.Worksheet, event: 'PivotTableAfterValueChange', argNames: ['TargetPivotTable', 'TargetRange'], handler: ( - this: Excel.Worksheet, parameter: {readonly TargetPivotTable: Excel.PivotTable, readonly TargetRange: Excel.Range}) => void): void; + this: Excel.Worksheet, parameter: { readonly TargetPivotTable: Excel.PivotTable, readonly TargetRange: Excel.Range }) => void): void; on( obj: Excel.Worksheet, event: 'PivotTableBeforeAllocateChanges' | 'PivotTableBeforeCommitChanges', argNames: ['TargetPivotTable', 'ValueChangeStart', 'ValueChangeEnd', 'Cancel'], handler: ( - this: Excel.Worksheet, parameter: {readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number, Cancel: boolean}) => void): void; + this: Excel.Worksheet, parameter: { readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number, Cancel: boolean }) => void): void; on( obj: Excel.Worksheet, event: 'PivotTableBeforeDiscardChanges', argNames: ['TargetPivotTable', 'ValueChangeStart', 'ValueChangeEnd'], - handler: (this: Excel.Worksheet, parameter: {readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number}) => void): void; - on(obj: Excel.Worksheet, event: 'PivotTableChangeSync' | 'PivotTableUpdate', argNames: ['Target'], handler: (this: Excel.Worksheet, parameter: {readonly Target: Excel.PivotTable}) => void): void; - on(obj: Excel.Worksheet, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.Worksheet, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void; + handler: (this: Excel.Worksheet, parameter: { readonly TargetPivotTable: Excel.PivotTable, readonly ValueChangeStart: number, readonly ValueChangeEnd: number }) => void): void; + on(obj: Excel.Worksheet, event: 'PivotTableChangeSync' | 'PivotTableUpdate', argNames: ['Target'], handler: ( + this: Excel.Worksheet, parameter: { readonly Target: Excel.PivotTable }) => void): void; + on(obj: Excel.Worksheet, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Excel.Worksheet, parameter: { readonly riid: stdole.GUID, ppvObj: undefined }) => void): void; on(obj: Excel.Application, event: 'AddRef' | 'AfterCalculate' | 'Release', handler: (this: Excel.Application, parameter: {}) => void): void; on(obj: Excel.Chart, event: 'Activate' | 'AddRef' | 'Calculate' | 'Deactivate' | 'DragOver' | 'DragPlot' | 'Release' | 'Resize', handler: (this: Excel.Chart, parameter: {}) => void): void; on(obj: Excel.OLEObject, event: 'AddRef' | 'GotFocus' | 'LostFocus' | 'Release', handler: (this: Excel.OLEObject, parameter: {}) => void): void; @@ -9464,7 +9723,7 @@ interface ActiveXObject { set(obj: Excel.Workbook, propertyName: 'Colors', parameterTypes: [any], newValue: any): void; set(obj: Excel.Range, propertyName: 'Value', parameterTypes: [Excel.XlRangeValueDataType], newValue: any): void; set(obj: Excel.Range, propertyName: 'Value', newValue: any): void; // because Value is defined on the type as a method, not a property - new(progid: K): ActiveXObjectNameMap[K]; + new (progid: K): ActiveXObjectNameMap[K]; } interface ActiveXObjectNameMap { @@ -9474,26 +9733,8 @@ interface ActiveXObjectNameMap { } interface EnumeratorConstructor { - new(col: Excel.Actions): Enumerator; - new(col: Excel.AddIns | Excel.AddIns2): Enumerator; - new(col: Excel.AllowEditRanges): Enumerator; - new(col: Excel.Areas | Excel.Ranges): Enumerator; - new(col: Excel.Borders): Enumerator; - new(col: Excel.CalculatedFields): Enumerator; - new(col: Excel.CalculatedItems | Excel.PivotItemList): Enumerator; - new(col: Excel.CalculatedMembers): Enumerator; - new(col: Excel.Comments): Enumerator; - new(col: Excel.Connections): Enumerator; - new(col: Excel.CubeFields): Enumerator; - new(col: Excel.CustomProperties): Enumerator; - new(col: Excel.CustomViews): Enumerator; - new(col: Excel.DiagramNodeChildren | Excel.DiagramNodes): Enumerator; - new(col: Excel.Dialogs): Enumerator; - new(col: Excel.FileExportConverters): Enumerator; - new(col: Excel.Filters): Enumerator; - new( - col: Excel.FormatConditions | Excel.IconSets | Excel.MenuItems | Excel.Modules | Excel.Phonetics | Excel.PivotFields | Excel.Range | Excel.ServerViewableItems | - Excel.SheetViews | Excel.UsedObjects): Enumerator; // tslint:disable-line:use-default-type-parameter + new(col: Excel.Range): Enumerator; + new(col: Excel.GroupShapes | Excel.ShapeRange | Excel.Shapes): Enumerator; new(col: Excel.HPageBreaks): Enumerator; new(col: Excel.Hyperlinks): Enumerator; @@ -9544,7 +9785,3 @@ interface EnumeratorConstructor { new(col: Excel.XmlNamespaces): Enumerator; new(col: Excel.XmlSchemas): Enumerator; } - -interface SafeArray { - _brand: SafeArray; -} diff --git a/types/activex-excel/tslint.json b/types/activex-excel/tslint.json index 4ac54521fe..f93cf8562a 100644 --- a/types/activex-excel/tslint.json +++ b/types/activex-excel/tslint.json @@ -1,6 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "interface-name": [false] - } -} \ No newline at end of file + "extends": "dtslint/dt.json" +} diff --git a/types/activex-faxcomexlib/activex-faxcomexlib-tests.ts b/types/activex-faxcomexlib/activex-faxcomexlib-tests.ts new file mode 100644 index 0000000000..ef3e403998 --- /dev/null +++ b/types/activex-faxcomexlib/activex-faxcomexlib-tests.ts @@ -0,0 +1,729 @@ +/// + +const collectionToArray = (col: { Item(index: any): T } | SafeArray) => { + const results: T[] = []; + const enumerator = new Enumerator(col); + enumerator.moveFirst(); + while (!enumerator.atEnd()) { + results.push(enumerator.item()); + enumerator.moveNext(); + } + return results; +}; + +const toSafeArray = (...items: T[]): SafeArray => { + const dict = new ActiveXObject('Scripting.Dictionary'); + items.forEach((x, index) => dict.Add(index, x)); + return dict.Items() as SafeArray; +}; + +const VB = { + InputBox: (prompt: string): string => '' +}; + +const getServer = () => { + const server = new ActiveXObject('FaxComEx.FaxServer'); + server.Connect(''); + return server; +}; + +{ + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms693376(v=vs.85).aspx + const server = new ActiveXObject('FaxComEx.FaxServer'); + const document = new ActiveXObject('FaxComEx.FaxDocument'); + + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms692919(v=vs.85).aspx + server.Connect(''); + server.Connect('computername'); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693502(v=vs.85).aspx +{ + const getInitializedDevice = () => { + const ret = getServer().GetDevices().ItemById(1); + ret.ReceiveMode = FAXCOMEXLib.FAX_DEVICE_RECEIVE_MODE_ENUM.fdrmAUTO_ANSWER; + ret.RingsBeforeAnswer = 5; + ret.SendEnabled = true; + return ret; + }; + + // saving configuration + let device = getInitializedDevice(); + device.Save(); + + // abandoning changes to configuration, using the Refresh method + device = getInitializedDevice(); + device.Refresh(); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693502(v=vs.85).aspx +{ + const incomingJob = getServer().Folders.IncomingQueue.GetJobs().Item(1); + incomingJob.Refresh(); + const currentPage = incomingJob.CurrentPage; +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692922(v=vs.85).aspx +{ + const server = getServer(); + + WScript.Echo(`Server information: +API Version: ${server.APIVersion} +Debug: ${server.Debug} +Build and version: ${server.MajorBuild}.${server.MinorBuild}.${server.MajorVersion}.${server.MinorVersion} +Server name: ${server.ServerName}`); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693455(v=vs.85).aspx +{ + const activity = getServer().Activity; + activity.Refresh(); + + WScript.Echo(` +${activity.IncomingMessages} incoming messages +${activity.OutgoingMessages} outgoing messages +${activity.RoutingMessages} routing messages +${activity.QueuedMessages} queued messages`); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693400(v=vs.85).aspx +{ + const device = getServer().GetDevices().Item(1); + device.CSID = 'Accounts payable'; + device.Description = 'Primary fax device'; + device.ReceiveMode = FAXCOMEXLib.FAX_DEVICE_RECEIVE_MODE_ENUM.fdrmAUTO_ANSWER; + device.RingsBeforeAnswer = 5; + device.SendEnabled = true; + device.TSID = 'Accounts payable'; + device.Save(); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692985(v=vs.85).aspx +{ + const devices = getServer().GetDevices(); + WScript.Echo(`This server has ${devices.Count} fax devices`); + for (let i = 1; i <= devices.Count; i++) { + WScript.Echo(`Device ID for device number ${i} is ${devices.Item(i).Id}`); + } + + collectionToArray(devices).forEach(device => { + device.Refresh(); + WScript.Echo(` +Device name: ${device.DeviceName} +Provider unique name: ${device.ProviderUniqueName} +Powered off: ${device.PoweredOff} +Receiving now: ${device.ReceivingNow} +Ringing now: ${device.RingingNow} +Sending now: ${device.SendingNow}`); + + const routingMethods = new VBArray(device.UsedRoutingMethods).toArray(); + routingMethods.forEach((guid, index) => { + WScript.Echo(`Method number ${index} = ${guid}`); + }); + + device.UseRoutingMethod(routingMethods[0], false); + device.Save(); + }); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693486(v=vs.85).aspx +{ + const outputRuleInfo = (rule: FAXCOMEXLib.FaxOutboundRoutingRule, index?: number) => { + WScript.Echo(` +Outbound routing rule number: ${index || 'unknown'} +Area code: ${rule.AreaCode} +Country/region code: ${rule.CountryCode} +Device ID: ${rule.DeviceId} +Group name: ${rule.GroupName} +Status: ${rule.Status} +Is device used: ${rule.UseDevice}` + .trim()); + }; + + const server = getServer(); + const device = server.GetDevices().Item(1); + const id = device.Id; + const rules = server.OutboundRouting.GetRules(); + const outboundRoutingRules = server.OutboundRouting.GetRules(); + WScript.Echo(`There are ${outboundRoutingRules.Count} outbound routing rules on this server.`); + + collectionToArray(outboundRoutingRules).forEach((rule, index) => { + rule.Refresh(); + outputRuleInfo(rule, index); + + if (!rule.UseDevice) { return; } + if (VB.InputBox('Do you want to change the device for this rule (Y/N)?') === 'Y') { + const newDeviceID = parseInt(VB.InputBox('Enter new device ID'), 10); + rule.DeviceId = newDeviceID; + rule.Save(); + } + }); + + const msg = ` +Do you want to: +1) display an item based on its country/region and area code, +2) remove an item based on its country/region and area code, +3) remove an item based on its item number, or +4) add a rule? +Input 1, 2, 3, 4, or 0 to exit +`.trim(); + const result = parseInt(VB.InputBox(msg), 10); + let countryCode: number; + let areaCode: number; + let itemNumber: number; + let rule: FAXCOMEXLib.FaxOutboundRoutingRule; + switch (result) { + case 1: + countryCode = parseInt(VB.InputBox('Enter the country/region code'), 10); + areaCode = parseInt(VB.InputBox('Enter the area code'), 10); + rule = outboundRoutingRules.ItemByCountryAndArea(countryCode, areaCode); + outputRuleInfo(rule); + break; + case 2: + countryCode = parseInt(VB.InputBox('Enter the country/region code'), 10); + areaCode = parseInt(VB.InputBox('Enter the area code'), 10); + outboundRoutingRules.RemoveByCountryAndArea(countryCode, areaCode); + break; + case 3: + itemNumber = parseInt(VB.InputBox('Enter the item number'), 10); + outboundRoutingRules.Remove(itemNumber); + break; + case 4: + countryCode = parseInt(VB.InputBox('Enter the country/region code'), 10); + areaCode = parseInt(VB.InputBox('Enter the area code'), 10); + rule = outboundRoutingRules.Add(countryCode, areaCode, true, '', id); + break; + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693408(v=vs.85).aspx +{ + const server = getServer(); + const outboundRouting = server.OutboundRouting; + const outboundRoutingGroups = outboundRouting.GetGroups(); + const groupName = VB.InputBox('Provide a name for the outbound routing group'); + const outboundRoutingGroup = outboundRoutingGroups.Add(groupName); + const devices = collectionToArray(server.GetDevices()); + + // add the devices to the routing group + devices.forEach(device => outboundRoutingGroup.DeviceIds.Add(device.Id)); + // move the last device to the top of the order + outboundRoutingGroup.DeviceIds.SetOrder(devices[devices.length - 1].Id, 1); + + // display the number of devices, and the device ID of the first device,to confirm its location in the order + const msg = ` +Number of devices: ${outboundRoutingGroup.DeviceIds.Count} +ID of first device: ${outboundRoutingGroup.DeviceIds.Item(1)} +`.trim(); + WScript.Echo(msg); + + // remove the first device + outboundRoutingGroup.DeviceIds.Remove(1); + + WScript.Echo(`There are now ${outboundRoutingGroups.Count} routing groups on the server`); + + collectionToArray(outboundRoutingGroups).forEach((routingGroup, index) => { + const msg = ` +Routing group number: ${index} +Outbound routing group name: ${routingGroup.Name} +Device status: ${routingGroup.Status} +`.trim(); + }); + + // allow user to remove a routing group + if (VB.InputBox('Do you want to remove a routing group (Y/N)?') === 'Y') { + const itemNumber = VB.InputBox('Enter the item number for the group you want to remove'); + outboundRoutingGroups.Remove(itemNumber); + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa964960(v=vs.85).aspx +{ + const accountSet = getServer().FaxAccountSet; + const accounts = collectionToArray(accountSet.GetAccounts()); + WScript.Echo(`Number of accounts: ${accounts.length}`); + accounts.forEach(account => WScript.Echo(account.AccountName)); + + const accountName = VB.InputBox('Enter an account name'); + accountSet.AddAccount(accountName); + accountSet.RemoveAccount(accountName); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692952(v=vs.85).aspx +{ + const incomingJobs = collectionToArray(getServer().Folders.IncomingQueue.GetJobs()); + WScript.Echo(`There are ${incomingJobs.length} jobs in the incoming queue.`); + const n = parseInt(VB.InputBox('Input the number of a job for which you want information'), 10); + const job = incomingJobs[n - 1]; + WScript.Echo(` +Available operations: ${job.AvailableOperations} +Caller ID: ${job.CallerId} +CSID: ${job.CSID} +Current page: ${job.CurrentPage} +Device ID: ${job.DeviceId} +Extended status: ${job.ExtendedStatus} +Extended status code: ${job.ExtendedStatusCode} +Job ID: ${job.Id} +Job type: ${job.JobType} +Retries: ${job.Retries} +Routing information: ${job.RoutingInformation} +Size: ${job.Size} +Status: ${job.Status} +Transmission start: ${new Date(job.TransmissionStart)} +Transmission end: ${new Date(job.TransmissionEnd)} +TSID: ${job.TSID} +`.trim()); + + if (VB.InputBox('Cancel this fax (Y/N)?') === 'Y') { + job.Cancel(); + } + + if (VB.InputBox('Open this fax (Y/N)?') === 'Y') { + const fileName = VB.InputBox('Enter path to save'); + job.CopyTiff(fileName); + new ActiveXObject('WScript.Shell').Run(fileName); + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692914(v=vs.85).aspx +{ + const server = new ActiveXObject('FaxComEx.FaxServer'); + server.Connect(''); + const outgoingQueue = server.Folders.OutgoingQueue; + outgoingQueue.AgeLimit = 2; + outgoingQueue.AllowPersonalCoverPages = true; + outgoingQueue.Blocked = false; + outgoingQueue.Paused = false; + outgoingQueue.Branding = true; + outgoingQueue.DiscountRateStart = new Date(0, 0, 0, 0).getVarDate(); + outgoingQueue.DiscountRateStart = new Date(0, 0, 0, 1).getVarDate(); + outgoingQueue.UseDeviceTSID = true; + outgoingQueue.Save(); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693393(v=vs.85).aspx +{ + const outgoingQueue = getServer().Folders.OutgoingQueue; + outgoingQueue.Refresh(); + WScript.Echo(`There are ${outgoingQueue.GetJobs().Count} faxes in the outgoing queue`); + const inputResult = VB.InputBox('Which fax should be displayed (item number or job name)?'); + const itemNumber = parseInt(inputResult, 10); + const job = + isNaN(itemNumber) ? + outgoingQueue.GetJob(inputResult) : + outgoingQueue.GetJobs().Item(itemNumber); + + WScript.Echo(` +Available operations: ${job.AvailableOperations} +Broadcast receipts grouped? ${job.GroupBroadcastReceipts} +CSID: ${job.CSID} +Current page: ${job.CurrentPage} +Device ID: ${job.DeviceId} +Document name: ${job.DocumentName} +Extended status: ${job.ExtendedStatus} +Extended status code: ${job.ExtendedStatusCode} +Job ID: ${job.Id} +Original scheduled time: ${new Date(job.OriginalScheduledTime)} +Pages: ${job.Pages} +Priority: ${job.Priority} +Receipt type: ${job.ReceiptType} +`.trim()); + + const fileName = VB.InputBox('Enter path to save'); + job.CopyTiff(fileName); + new ActiveXObject('WScript.Shell').Run(fileName); + + const answer = VB.InputBox(` +Do you want to: +(C) cancel +(P) pause +(R) restart +(E) resume +the job? +`.trim()); + + switch (answer) { + case 'C': + job.Cancel(); + break; + case 'P': + job.Pause(); + break; + case 'R': + job.Restart(); + break; + case 'E': + job.Resume(); + break; + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692936(v=vs.85).aspx +{ + const document = new ActiveXObject('FaxComEx.FaxDocument'); + document.Body = 'C:\\docs\\body.txt'; + document.DocumentName = 'My First Fax'; + document.Priority = FAXCOMEXLib.FAX_PRIORITY_TYPE_ENUM.fptHIGH; + document.Recipients.Add('12225550100', 'Bud'); + document.AttachFaxToReceipt = true; + document.CoverPageType = FAXCOMEXLib.FAX_COVERPAGE_TYPE_ENUM.fcptSERVER; + document.Note = 'Here is the info you requested'; + document.ReceiptAddress = 'someone@example.com'; + document.ReceiptType = FAXCOMEXLib.FAX_RECEIPT_TYPE_ENUM.frtMAIL; + document.ScheduleType = FAXCOMEXLib.FAX_SCHEDULE_TYPE_ENUM.fstSPECIFIC_TIME; + document.ScheduleTime = new Date(0, 0, 0, 16, 35, 47).getVarDate(); + document.Subject = 'Today\'s fax'; + + // set sender properties + const sender = document.Sender; + sender.Title = 'Mr.'; + sender.Name = 'Bob'; + sender.City = 'Cleveland Heights'; + sender.State = 'Ohio'; + sender.Company = 'Microsoft'; + sender.Country = 'USA'; + sender.Email = 'someone@microsoft.com'; + sender.FaxNumber = '12165555554'; + sender.HomePhone = '12165555555'; + sender.OfficeLocation = 'Downtown'; + sender.OfficePhone = '12165555553'; + sender.StreetAddress = '123 Main Street'; + sender.TSID = 'Office fax machine'; + sender.ZipCode = '44118'; + sender.BillingCode = '23A54'; + sender.Department = 'Accts Payable'; + sender.SaveDefaultSender(); + + const server = getServer(); + + const jobID = document.ConnectedSubmit(server); + WScript.Echo(`The job ID is ${jobID}`); + + server.Disconnect(); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693479(v=vs.85).aspx +{ + const document = new ActiveXObject('FaxComEx.FaxDocument'); + document.Body = 'C:\\docs\\body.txt'; + document.DocumentName = 'My First Fax'; + + const recipients = document.Recipients; + recipients.Add('12225550105', 'H'); + recipients.Add('12225550104', 'N'); + recipients.Add('12225550103', 'G'); + + WScript.Echo(`Number of recipients: ${recipients.Count}`); + collectionToArray(recipients).forEach((recipient, index) => + WScript.Echo(`Recipient number ${index}: ${recipient.Name}, ${recipient.FaxNumber}`) + ); + + document.Sender.LoadDefaultSender(); + document.GroupBroadcastReceipts = true; + + const jobIDs = document.Submit(''); + collectionToArray(jobIDs).forEach(jobID => WScript.Echo(`The job ID is ${jobID}`)); + + while (recipients.Count > 0) { + recipients.Remove(1); + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa964962(v=vs.85).aspx +{ + const server = getServer(); + const prefetchCount = parseInt(VB.InputBox('How many messages should be prefetched?'), 10); + server.CurrentAccount.Folders.IncomingArchive.Refresh(); + const messageIterator = server.Folders.IncomingArchive.GetMessages(prefetchCount); + messageIterator.MoveFirst(); + for (let i = 1; i <= prefetchCount; i++) { + if (i > 1 && VB.InputBox('View next message? (Y/N)') !== 'Y') { break; } + const message = messageIterator.Message as FAXCOMEXLib.FaxIncomingMessage; + if (messageIterator.AtEOF) { + WScript.Echo(`End of file reached`); + break; + } + if (!message.WasReAssigned) { + if (VB.InputBox('Message not reassigned. Reassign (Y/N)?') === 'Y') { + message.Subject = 'Reassigning message'; + message.SenderName = 'Test user'; + message.Recipients = VB.InputBox('Enter username, e.g. Domain\\UserName'); + message.SenderFaxNumber = '1234'; + message.ReAssign(); + } + } + messageIterator.MoveNext(); + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693402(v=vs.85).aspx +{ + const server = getServer(); + const prefetchCount = parseInt(VB.InputBox('How many messages should be prefetched?'), 10); + server.Folders.OutgoingArchive.Refresh(); + const messageIterator = server.Folders.OutgoingArchive.GetMessages(prefetchCount); + messageIterator.MoveFirst(); + for (let i = 1; i <= prefetchCount; i++) { + if (i > 1 && VB.InputBox('View next message? (Y/N)') !== 'Y') { break; } + if (messageIterator.AtEOF) { + WScript.Echo(`End of file reached`); + break; + } + const message = messageIterator.Message as FAXCOMEXLib.FaxOutgoingMessage; + + const fileName = VB.InputBox('Enter path to save'); + message.CopyTiff(fileName); + new ActiveXObject('WScript.Shell').Run(fileName); + + WScript.Echo(`Message information: +CSID: ${message.CSID} +Device name: ${message.DeviceName} +Document name: ${message.DocumentName} +Message ID: ${message.Id} +Original scheduled time: ${new Date(message.OriginalScheduledTime)} +Pages: ${message.Pages} +Recipient fax number: ${message.Recipient.FaxNumber} +Retries: ${message.Retries} +Sender name: ${message.Sender.Name} +Size: ${message.Size} +Subject: ${message.Subject} +Submission ID: ${message.SubmissionId} +Submission time: ${new Date(message.SubmissionTime)} +Transmission end time: ${new Date(message.TransmissionEnd)} +Transmission start time: ${new Date(message.TransmissionStart)} +TSID: ${message.TSID}`); + + if (VB.InputBox('Delete this fax from the archive (Y/N)?') === 'Y') { + message.Delete(); + } + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693472(v=vs.85).aspx +{ + const server = getServer(); + const outgoingArchive = server.Folders.OutgoingArchive; + WScript.Echo(` +Age limit: ${outgoingArchive.AgeLimit} +Archive folder: ${outgoingArchive.ArchiveFolder} +High quota mark: ${outgoingArchive.HighQuotaWaterMark} +Low quota water mark: ${outgoingArchive.LowQuotaWaterMark} +Size high: ${outgoingArchive.SizeHigh} +Size low: ${outgoingArchive.SizeLow} +Size quota warning: ${outgoingArchive.SizeQuotaWarning} +Is archive used? ${outgoingArchive.UseArchive}`.trim() + ); + + const newLimit = VB.InputBox('Set new age limit (enter empty value or Cancel to leave unchanged'); + if (newLimit) { + outgoingArchive.AgeLimit = parseInt(newLimit, 10); + } + + const messageID = VB.InputBox('Retrieve a message by ID (enter an empty value or press Cancel to exit'); + if (messageID) { + const fileName = VB.InputBox('Enter path to save'); + outgoingArchive.GetMessage(messageID).CopyTiff(fileName); + new ActiveXObject('WScript.Shell').Run(fileName); + } +} + +{ + const server = getServer(); + const messageIterator = server.Folders.OutgoingArchive.GetMessages(); + messageIterator.MoveFirst(); + while (!messageIterator.AtEOF) { + const message = messageIterator.Message; + WScript.Echo(` +Document name: ${message.DocumentName} +ID: ${message.Id} +Transmission end: ${new Date(message.TransmissionEnd)} +Transmission start: ${new Date(message.TransmissionStart)} +`.trim()); + messageIterator.MoveNext(); + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692976(v=vs.85).aspx +{ + const server = getServer(); + const prefetchCount = parseInt(VB.InputBox('How many messages should be prefetched?'), 10); + server.Folders.IncomingArchive.Refresh(); + const messageIterator = server.Folders.IncomingArchive.GetMessages(prefetchCount); + messageIterator.MoveFirst(); + for (let i = 1; i <= prefetchCount; i++) { + if (i > 1 && VB.InputBox('View next message? (Y/N)') !== 'Y') { break; } + const message = messageIterator.Message as FAXCOMEXLib.FaxIncomingMessage; + if (messageIterator.AtEOF) { + WScript.Echo(`End of file reached`); + break; + } + const fileName = VB.InputBox('Enter path to save TIFF file'); + message.CopyTiff(fileName); + new ActiveXObject('WScript.Shell').Run(fileName); + + messageIterator.MoveNext(); + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693406(v=vs.85).aspx +{ + const server = getServer(); + const incomingArchive = server.Folders.IncomingArchive; + incomingArchive.Refresh(); + WScript.Echo(` +High quota water mark: ${incomingArchive.HighQuotaWaterMark} +Low quota water mark: ${incomingArchive.LowQuotaWaterMark} +Archive folder: ${incomingArchive.ArchiveFolder} +Age limit: ${incomingArchive.AgeLimit} +Size high: ${incomingArchive.SizeHigh} +Size low: ${incomingArchive.SizeLow} +Is size quota warning on? ${incomingArchive.SizeQuotaWarning} +Is archive used? ${incomingArchive.UseArchive} +`.trim()); + + incomingArchive.AgeLimit = 4; + incomingArchive.Save(); + + const messageID = VB.InputBox('Message ID to retrieve information? (Leave empty, or Cancel, to exit)'); + if (messageID !== '') { + const message = incomingArchive.GetMessage(messageID); + WScript.Echo(` +Caller ID: ${message.CallerId} +CSID: ${message.CSID} +Device name: ${message.DeviceName} +Message ID: ${message.Id} +Number of pages: ${message.Pages} +Retries: ${message.Retries} +Routing information: ${message.RoutingInformation} +Size: ${message.Size} +Transmission start: ${new Date(message.TransmissionStart)} +Transmission end: ${new Date(message.TransmissionEnd)} +TSID: ${message.TSID} +`.trim()); + + if (VB.InputBox('Delete this message from the archive (Y/N)?') === 'Y') { + message.Delete(); + } + } +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693401(v=vs.85).aspx +{ + const server = getServer(); + const loggingOptions = server.LoggingOptions; + const activityLogging = loggingOptions.ActivityLogging; + const eventLogging = loggingOptions.EventLogging; + + activityLogging.Refresh(); + activityLogging.LogIncoming = true; + activityLogging.LogOutgoing = true; + activityLogging.Save(); + + eventLogging.Refresh(); + eventLogging.GeneralEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllMED; + eventLogging.InboundEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllMAX; + eventLogging.InitEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllMAX; + eventLogging.OutboundEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllNONE; + eventLogging.Save(); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693387(v=vs.85).aspx +{ + const server = getServer(); + const receiptOptions = server.ReceiptOptions; + receiptOptions.Refresh(); + WScript.Echo(` +Allowed receipt types: ${receiptOptions.AllowedReceipts} +Authentication types: ${receiptOptions.AuthenticationType} +SMTP port: ${receiptOptions.SMTPPort} +SMTP sender: ${receiptOptions.SMTPSender} +SMTP server: ${receiptOptions.SMTPSender} +Use for inbound routing? ${receiptOptions.UseForInboundRouting} +`.trim()); + + receiptOptions.AllowedReceipts = FAXCOMEXLib.FAX_RECEIPT_TYPE_ENUM.frtMAIL; + receiptOptions.AuthenticationType = FAXCOMEXLib.FAX_SMTP_AUTHENTICATION_TYPE_ENUM.fsatBASIC; + receiptOptions.SMTPPort = 25; + receiptOptions.SMTPSender = 'someone@example.com'; + receiptOptions.SMTPServer = 'My SMTP Server'; + receiptOptions.UseForInboundRouting = true; + receiptOptions.Save(); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693462(v=vs.85).aspx +{ + const server = getServer(); + collectionToArray(server.GetDeviceProviders()).forEach((provider, index) => { + WScript.Echo(` +Debug: ${provider.Debug} +Name: ${provider.FriendlyName} +Image name: ${provider.ImageName} +Init error code: ${provider.InitErrorCode} +Build and version: ${provider.MajorBuild}.${provider.MajorVersion}.${provider.MinorBuild}.${provider.MinorVersion} +Status: ${provider.Status} +TAPI provider: ${provider.TapiProviderName} +Unique name: ${provider.UniqueName} +`.trim()); + + new VBArray(provider.DeviceIds).toArray().forEach(id => WScript.Echo(id)); + }); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693437(v=vs.85).aspx -- for a fax device +{ + const server = getServer(); + const device = server.GetDevices().Item(1); + const deviceProperty = toSafeArray(1, 2, 3); + const propertyName = '{B1F944B9-9A16-45d1-933A-4060A4871AB0}'; + device.SetExtensionProperty(propertyName, deviceProperty); + new VBArray(device.GetExtensionProperty(propertyName)).toArray().forEach(x => WScript.Echo(x)); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693437(v=vs.85).aspx -- for a fax device +{ + const server = getServer(); + const serverProperty = toSafeArray(4, 2, 3); + const propertyName = `{AC7D0DEE-B6E5-4a44-AF45-835C58CB44D2}`; + server.SetExtensionProperty(propertyName, serverProperty); + new VBArray(server.GetExtensionProperty(propertyName)).toArray().forEach(x => WScript.Echo(x)); +} + +// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693013(v=vs.85).aspx +{ + const server = getServer(); + + ActiveXObject.on(server, 'OnOutgoingJobAdded', ['pFaxServer', 'bstrJobId'], prm => WScript.Echo('New job added to queue')); + + ActiveXObject.on(server, 'OnOutgoingJobChanged', ['pFaxServer', 'bstrJobId', 'pJobStatus'], prm => { + const status = prm.pJobStatus; + WScript.Echo(` +Available operations: ${status.AvailableOperations} +Caller ID: ${status.CallerId} +CSID: ${status.CSID} +Current page: ${status.CurrentPage} +Device ID: ${status.DeviceId} +Extended status: ${status.ExtendedStatus} +Extended status code: ${status.ExtendedStatusCode} +Job type: ${status.JobType} +Pages: ${status.Pages} +Retries: ${status.Retries} +Routing information: ${status.RoutingInformation} +Scheduled time: ${new Date(status.ScheduledTime)} +Size: ${status.Size} +Status: ${status.Status} +Transmission start: ${new Date(status.TransmissionStart)} +TSID: ${status.TSID} +`.trim()); + + try { + WScript.Echo(`Transmission end: ${new Date(status.TransmissionEnd)}`); + } catch {} + }); + + ActiveXObject.on(server, 'OnServerShutDown', ['pFaxServer'], prm => WScript.Echo('The local fax server has been shut down')); + + server.ListenToServerEvents( + FAXCOMEXLib.FAX_SERVER_EVENTS_TYPE_ENUM.fsetFXSSVC_ENDED + + FAXCOMEXLib.FAX_SERVER_EVENTS_TYPE_ENUM.fsetOUT_QUEUE + ); +} diff --git a/types/activex-faxcomexlib/index.d.ts b/types/activex-faxcomexlib/index.d.ts new file mode 100644 index 0000000000..d4078061f7 --- /dev/null +++ b/types/activex-faxcomexlib/index.d.ts @@ -0,0 +1,2020 @@ +// Type definitions for Microsoft Fax Service Extended COM Type Library - FAXCOMEXLib 1.0 +// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684513(v=vs.85).aspx +// Definitions by: Zev Spitz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/// + +declare namespace FAXCOMEXLib { + // tslint:disable-next-line:no-const-enum + const enum FAX_ACCESS_RIGHTS_ENUM { + farMANAGE_CONFIG = 64, + farMANAGE_IN_ARCHIVE = 256, + farMANAGE_JOBS = 16, + farMANAGE_OUT_ARCHIVE = 1024, + farQUERY_CONFIG = 32, + farQUERY_IN_ARCHIVE = 128, + farQUERY_JOBS = 8, + farQUERY_OUT_ARCHIVE = 512, + farSUBMIT_HIGH = 4, + farSUBMIT_LOW = 1, + farSUBMIT_NORMAL = 2, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_ACCESS_RIGHTS_ENUM_2 { + far2MANAGE_ARCHIVES = 256, + far2MANAGE_CONFIG = 64, + far2MANAGE_OUT_JOBS = 16, + far2MANAGE_RECEIVE_FOLDER = 512, + far2QUERY_ARCHIVES = 128, + far2QUERY_CONFIG = 32, + far2QUERY_OUT_JOBS = 8, + far2SUBMIT_HIGH = 4, + far2SUBMIT_LOW = 1, + far2SUBMIT_NORMAL = 2, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_ACCOUNT_EVENTS_TYPE_ENUM { + faetFXSSVC_ENDED = 16, + faetIN_ARCHIVE = 4, + faetIN_QUEUE = 1, + faetNONE = 0, + faetOUT_ARCHIVE = 8, + faetOUT_QUEUE = 2, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_COVERPAGE_TYPE_ENUM { + fcptLOCAL = 1, + fcptNONE = 0, + fcptSERVER = 2, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_DEVICE_RECEIVE_MODE_ENUM { + fdrmAUTO_ANSWER = 1, + fdrmMANUAL_ANSWER = 2, + fdrmNO_ANSWER = 0, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_GROUP_STATUS_ENUM { + fgsALL_DEV_NOT_VALID = 2, + fgsALL_DEV_VALID = 0, + fgsEMPTY = 1, + fgsSOME_DEV_NOT_VALID = 3, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_JOB_EXTENDED_STATUS_ENUM { + fjesANSWERED = 5, + fjesBAD_ADDRESS = 10, + fjesBUSY = 8, + fjesCALL_ABORTED = 19, + fjesCALL_BLACKLISTED = 14, + fjesCALL_COMPLETED = 18, + fjesCALL_DELAYED = 13, + fjesDIALING = 3, + fjesDISCONNECTED = 1, + fjesFATAL_ERROR = 12, + fjesHANDLED = 17, + fjesINITIALIZING = 2, + fjesLINE_UNAVAILABLE = 7, + fjesNO_ANSWER = 9, + fjesNO_DIAL_TONE = 11, + fjesNONE = 0, + fjesNOT_FAX_CALL = 15, + fjesPARTIALLY_RECEIVED = 16, + fjesPROPRIETARY = 16777216, + fjesRECEIVING = 6, + fjesTRANSMITTING = 4, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_JOB_OPERATIONS_ENUM { + fjoDELETE = 16, + fjoPAUSE = 2, + fjoRECIPIENT_INFO = 32, + fjoRESTART = 8, + fjoRESUME = 4, + fjoSENDER_INFO = 64, + fjoVIEW = 1, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_JOB_STATUS_ENUM { + fjsCANCELED = 512, + fjsCANCELING = 1024, + fjsCOMPLETED = 256, + fjsFAILED = 8, + fjsINPROGRESS = 2, + fjsNOLINE = 32, + fjsPAUSED = 16, + fjsPENDING = 1, + fjsRETRIES_EXCEEDED = 128, + fjsRETRYING = 64, + fjsROUTING = 2048, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_JOB_TYPE_ENUM { + fjtRECEIVE = 1, + fjtROUTING = 2, + fjtSEND = 0, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_LOG_LEVEL_ENUM { + fllMAX = 3, + fllMED = 2, + fllMIN = 1, + fllNONE = 0, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_PRIORITY_TYPE_ENUM { + fptHIGH = 2, + fptLOW = 0, + fptNORMAL = 1, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_PROVIDER_STATUS_ENUM { + fpsBAD_GUID = 2, + fpsBAD_VERSION = 3, + fpsCANT_INIT = 6, + fpsCANT_LINK = 5, + fpsCANT_LOAD = 4, + fpsSERVER_ERROR = 1, + fpsSUCCESS = 0, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_RECEIPT_TYPE_ENUM { + frtMAIL = 1, + frtMSGBOX = 4, + frtNONE = 0, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_ROUTING_RULE_CODE_ENUM { + frrcANY_CODE = 0, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_RULE_STATUS_ENUM { + frsALL_GROUP_DEV_NOT_VALID = 2, + frsBAD_DEVICE = 4, + frsEMPTY_GROUP = 1, + frsSOME_GROUP_DEV_NOT_VALID = 3, + frsVALID = 0, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_SCHEDULE_TYPE_ENUM { + fstDISCOUNT_PERIOD = 2, + fstNOW = 0, + fstSPECIFIC_TIME = 1, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_SERVER_APIVERSION_ENUM { + fsAPI_VERSION_0 = 0, + fsAPI_VERSION_1 = 65536, + fsAPI_VERSION_2 = 131072, + fsAPI_VERSION_3 = 196608, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_SERVER_EVENTS_TYPE_ENUM { + fsetACTIVITY = 8, + fsetCONFIG = 4, + fsetDEVICE_STATUS = 256, + fsetFXSSVC_ENDED = 128, + fsetIN_ARCHIVE = 32, + fsetIN_QUEUE = 1, + fsetINCOMING_CALL = 512, + fsetNONE = 0, + fsetOUT_ARCHIVE = 64, + fsetOUT_QUEUE = 2, + fsetQUEUE_STATE = 16, + } + + // tslint:disable-next-line:no-const-enum + const enum FAX_SMTP_AUTHENTICATION_TYPE_ENUM { + fsatANONYMOUS = 0, + fsatBASIC = 1, + fsatNTLM = 2, + } + + // tslint:disable-next-line:no-const-enum + const enum FaxConstants { + bstrGROUPNAME_ALLDEVICES = '', + lDEFAULT_PREFETCH_SIZE = 100, + wcharREASSIGN_RECIPIENTS_DELIMITER = 59, + } + + /** FaxAccount Class */ + class FaxAccount { + private 'FAXCOMEXLib.FaxAccount_typekey': FaxAccount; + private constructor(); + + /** Name of the fax account */ + readonly AccountName: string; + + /** Folders belonging to the account */ + readonly Folders: FaxAccountFolders; + + /** Set bit-wise combination of events the fax account listens to */ + ListenToAccountEvents(EventTypes: FAX_ACCOUNT_EVENTS_TYPE_ENUM): void; + + /** Events the fax account is listening to */ + readonly RegisteredEvents: FAX_ACCOUNT_EVENTS_TYPE_ENUM; + } + + /** FaxAccountFolders Class */ + class FaxAccountFolders { + private 'FAXCOMEXLib.FaxAccountFolders_typekey': FaxAccountFolders; + private constructor(); + + /** Incoming archive */ + readonly IncomingArchive: FaxAccountIncomingArchive; + + /** Incoming queue */ + readonly IncomingQueue: FaxAccountIncomingQueue; + + /** Outgoing archive */ + readonly OutgoingArchive: FaxAccountOutgoingArchive; + + /** Outgoing queue */ + readonly OutgoingQueue: FaxAccountOutgoingQueue; + } + + /** FaxAccountIncomingArchive Class */ + class FaxAccountIncomingArchive { + private 'FAXCOMEXLib.FaxAccountIncomingArchive_typekey': FaxAccountIncomingArchive; + private constructor(); + + /** Get an archived message by its ID */ + GetMessage(bstrMessageId: string): IFaxIncomingMessage; + + /** + * Iterator on the archived messages + * @param number [lPrefetchSize=100] + */ + GetMessages(lPrefetchSize?: number): FaxIncomingMessageIterator; + + /** Refresh the object */ + Refresh(): void; + + /** The high 32-bit value of the archive size */ + readonly SizeHigh: number; + + /** The low 32-bit value of the archive size */ + readonly SizeLow: number; + } + + /** FaxAccountIncomingQueue Class */ + class FaxAccountIncomingQueue { + private 'FAXCOMEXLib.FaxAccountIncomingQueue_typekey': FaxAccountIncomingQueue; + private constructor(); + + /** Get incoming job by ID */ + GetJob(bstrJobId: string): FaxIncomingJob; + + /** Collection of incoming jobs */ + GetJobs(): FaxIncomingJobs; + } + + /** FaxAccountOutgoingArchive Class */ + class FaxAccountOutgoingArchive { + private 'FAXCOMEXLib.FaxAccountOutgoingArchive_typekey': FaxAccountOutgoingArchive; + private constructor(); + + /** Get an archived message by its ID */ + GetMessage(bstrMessageId: string): IFaxOutgoingMessage; + + /** + * Iterator on the archived messages + * @param number [lPrefetchSize=100] + */ + GetMessages(lPrefetchSize?: number): FaxOutgoingMessageIterator; + + /** Refresh the object */ + Refresh(): void; + + /** The high 32-bit value of the archive size */ + readonly SizeHigh: number; + + /** The low 32-bit value of the archive size */ + readonly SizeLow: number; + } + + /** FaxAccountOutgoingQueue Class */ + class FaxAccountOutgoingQueue { + private 'FAXCOMEXLib.FaxAccountOutgoingQueue_typekey': FaxAccountOutgoingQueue; + private constructor(); + + /** Get outgoing job by ID */ + GetJob(bstrJobId: string): IFaxOutgoingJob; + + /** Collection of outgoing jobs */ + GetJobs(): FaxOutgoingJobs; + } + + /** FaxAccounts Class */ + interface FaxAccounts { + readonly Count: number; + Item(vIndex: any): FaxAccount; + (vIndex: any): FaxAccount; + } + + /** FaxAccountSet Class */ + class FaxAccountSet { + private 'FAXCOMEXLib.FaxAccountSet_typekey': FaxAccountSet; + private constructor(); + + /** Adds a fax account */ + AddAccount(bstrAccountName: string): FaxAccount; + + /** Get fax account by name */ + GetAccount(bstrAccountName: string): FaxAccount; + + /** Collection of fax accounts */ + GetAccounts(): FaxAccounts; + + /** Removes a fax account by name */ + RemoveAccount(bstrAccountName: string): void; + } + + /** FaxActivity Class */ + class FaxActivity { + private 'FAXCOMEXLib.FaxActivity_typekey': FaxActivity; + private constructor(); + + /** Number of incoming messages */ + readonly IncomingMessages: number; + + /** Number of outgoing messages */ + readonly OutgoingMessages: number; + + /** Number of queued messages */ + readonly QueuedMessages: number; + + /** Refresh the object */ + Refresh(): void; + + /** Number of routed incoming messages */ + readonly RoutingMessages: number; + } + + /** FaxActivityLogging Class */ + class FaxActivityLogging { + private 'FAXCOMEXLib.FaxActivityLogging_typekey': FaxActivityLogging; + private constructor(); + + /** Activity log database files path */ + DatabasePath: string; + + /** Does the server log incoming fax activity */ + LogIncoming: boolean; + + /** Does the server log outgoing fax activity */ + LogOutgoing: boolean; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + } + + /** FaxConfiguration Class */ + class FaxConfiguration { + private 'FAXCOMEXLib.FaxConfiguration_typekey': FaxConfiguration; + private constructor(); + + /** Are personal cover pages allowed */ + AllowPersonalCoverPages: boolean; + + /** Indicates how long the fax message is kept on the server */ + ArchiveAgeLimit: number; + + /** Location of the archive on the server */ + ArchiveLocation: string; + + /** The high 32-bit value of the archive size */ + readonly ArchiveSizeHigh: number; + + /** The low 32-bit value of the archive size */ + readonly ArchiveSizeLow: number; + + /** Does the server auto-create fax account on connect */ + AutoCreateAccountOnConnect: boolean; + + /** Does the server generate a brand */ + Branding: boolean; + + /** End of the discount rate period */ + DiscountRateEnd: VarDate; + + /** Start of the discount rate period */ + DiscountRateStart: VarDate; + + /** High quota water mark */ + HighQuotaWaterMark: number; + + /** Are incoming faxes viewable by everyone */ + IncomingFaxesArePublic: boolean; + + /** Is queue blocked for incoming faxes */ + IncomingQueueBlocked: boolean; + + /** Low quota water mark */ + LowQuotaWaterMark: number; + + /** How long the failed fax job is kept on the server */ + OutgoingQueueAgeLimit: number; + + /** Is queue blocked for outgoing faxes */ + OutgoingQueueBlocked: boolean; + + /** Is queue paused for outgoing faxes */ + OutgoingQueuePaused: boolean; + + /** Refresh the object */ + Refresh(): void; + + /** Number of retries */ + Retries: number; + + /** Retry delay */ + RetryDelay: number; + + /** Save the object */ + Save(): void; + + /** Is size quota warning on */ + SizeQuotaWarning: boolean; + + /** Whether faxes should be archived */ + UseArchive: boolean; + + /** Is device Transmitting Station ID used */ + UseDeviceTSID: boolean; + } + + /** FaxDevice Class */ + class FaxDevice { + private 'FAXCOMEXLib.FaxDevice_typekey': FaxDevice; + private constructor(); + + /** Answer the call */ + AnswerCall(): void; + + /** Device's Called Station ID */ + CSID: string; + + /** Description of the device */ + Description: string; + + /** Device name */ + readonly DeviceName: string; + + /** Get the device level extention property */ + GetExtensionProperty(bstrGUID: string): SafeArray; + + /** Unique device ID */ + readonly Id: number; + + /** Is the device is turned off */ + readonly PoweredOff: boolean; + + /** Device provider */ + readonly ProviderUniqueName: string; + + /** The receive mode of the device */ + ReceiveMode: FAX_DEVICE_RECEIVE_MODE_ENUM; + + /** Is the device receiving now */ + readonly ReceivingNow: boolean; + + /** Refresh the object */ + Refresh(): void; + + /** Is the device ringing now */ + readonly RingingNow: boolean; + + /** Number of rings before the device answers */ + RingsBeforeAnswer: number; + + /** Save the object */ + Save(): void; + + /** Is the device is enabled to send */ + SendEnabled: boolean; + + /** Is the device sending now */ + readonly SendingNow: boolean; + + /** Set the device level extention property */ + SetExtensionProperty(bstrGUID: string, vProperty: SafeArray): void; + + /** Device's Transmitting Station ID */ + TSID: string; + + /** Array of routing methods GUIDs */ + readonly UsedRoutingMethods: SafeArray; + + /** Adds or removes routing method */ + UseRoutingMethod(bstrMethodGUID: string, bUse: boolean): void; + } + + /** FaxDeviceIds Class */ + interface FaxDeviceIds { + /** Add a device */ + Add(lDeviceId: number): void; + readonly Count: number; + Item(lIndex: number): number; + + /** Remove a device */ + Remove(lIndex: number): void; + + /** Set order of the device */ + SetOrder(lDeviceId: number, lNewOrder: number): void; + (lIndex: number): number; + } + + /** FaxDeviceProvider Class */ + class FaxDeviceProvider { + private 'FAXCOMEXLib.FaxDeviceProvider_typekey': FaxDeviceProvider; + private constructor(); + + /** Is device provider built in debug environment */ + readonly Debug: boolean; + + /** Array of device IDs exposed by the provider */ + readonly DeviceIds: SafeArray; + + /** Provider's friendly name */ + readonly FriendlyName: string; + + /** Full path and file name of the provider DLL */ + readonly ImageName: string; + + /** Last error code at load or initialization */ + readonly InitErrorCode: number; + + /** The major part of the device provider's build number */ + readonly MajorBuild: number; + + /** The major part of the device provider's version number */ + readonly MajorVersion: number; + + /** The minor part of the device provider's build number */ + readonly MinorBuild: number; + + /** The minor part of the device provider's version number */ + readonly MinorVersion: number; + + /** Status of the device provider */ + readonly Status: FAX_PROVIDER_STATUS_ENUM; + + /** TSP name used by the provider */ + readonly TapiProviderName: string; + + /** Unique name of the provider */ + readonly UniqueName: string; + } + + /** FaxDeviceProviders Class */ + interface FaxDeviceProviders { + readonly Count: number; + Item(vIndex: any): FaxDeviceProvider; + (vIndex: any): FaxDeviceProvider; + } + + /** FaxDevices Class */ + interface FaxDevices { + readonly Count: number; + Item(vIndex: any): FaxDevice; + + /** Get device by its ID */ + ItemById(lId: number): FaxDevice; + (vIndex: any): FaxDevice; + } + + /** FaxDocument Class */ + class FaxDocument { + private 'FAXCOMEXLib.FaxDocument_typekey': FaxDocument; + private constructor(); + + /** Whether to attach a fax to the receipt */ + AttachFaxToReceipt: boolean; + + /** Full paths to the fax document body files */ + Bodies: any; + + /** Full path to the fax document body file */ + Body: string; + + /** Call handle */ + CallHandle: number; + + /** Submit the fax document on the already connected server */ + ConnectedSubmit(pFaxServer: IFaxServer): SafeArray; + + /** Submit the fax document on the already connected server */ + ConnectedSubmit2(pFaxServer: IFaxServer, pvFaxOutgoingJobIDs: SafeArray): number; + + /** Cover page file path */ + CoverPage: string; + + /** Is server, local, or no cover page used */ + CoverPageType: FAX_COVERPAGE_TYPE_ENUM; + + /** The document name */ + DocumentName: string; + + /** Whether to group the broadcast receipts */ + GroupBroadcastReceipts: boolean; + + /** Contents of cover page note field */ + Note: string; + + /** Priority of the fax */ + Priority: FAX_PRIORITY_TYPE_ENUM; + + /** Address of the receipt */ + ReceiptAddress: string; + + /** Type of the receipt */ + ReceiptType: FAX_RECEIPT_TYPE_ENUM; + + /** Collection of recipients */ + readonly Recipients: FaxRecipients; + + /** Time to send the fax */ + ScheduleTime: VarDate; + + /** When to send the fax */ + ScheduleType: FAX_SCHEDULE_TYPE_ENUM; + + /** Sender information object */ + readonly Sender: FaxSender; + + /** Contents of cover page subject field */ + Subject: string; + + /** Submission Id for the Fax document */ + readonly SubmissionId: string; + + /** Connect to server, submit the fax document, disconnect */ + Submit(bstrFaxServerName: string): SafeArray; + + /** Connect to server, submit the fax document, disconnect */ + Submit2(bstrFaxServerName: string, pvFaxOutgoingJobIDs: any): number; + + /** Tapi connection */ + TapiConnection: any; + } + + /** FaxEventLogging Class */ + class FaxEventLogging { + private 'FAXCOMEXLib.FaxEventLogging_typekey': FaxEventLogging; + private constructor(); + + /** Detail level of event logs for general (other) events */ + GeneralEventsLevel: FAX_LOG_LEVEL_ENUM; + + /** Detail level of event logs for inbound fax events */ + InboundEventsLevel: FAX_LOG_LEVEL_ENUM; + + /** Detail level of event logs for initialization events */ + InitEventsLevel: FAX_LOG_LEVEL_ENUM; + + /** Detail level of event logs for outbound fax events */ + OutboundEventsLevel: FAX_LOG_LEVEL_ENUM; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + } + + /** FaxFolders Class */ + class FaxFolders { + private 'FAXCOMEXLib.FaxFolders_typekey': FaxFolders; + private constructor(); + + /** Incoming archive */ + readonly IncomingArchive: FaxIncomingArchive; + + /** Incoming queue */ + readonly IncomingQueue: FaxIncomingQueue; + + /** Outgoing archive */ + readonly OutgoingArchive: FaxOutgoingArchive; + + /** Outgoing queue */ + readonly OutgoingQueue: FaxOutgoingQueue; + } + + /** FaxInboundRouting Class */ + class FaxInboundRouting { + private 'FAXCOMEXLib.FaxInboundRouting_typekey': FaxInboundRouting; + private constructor(); + + /** Registered inbound routing extensions collection */ + GetExtensions(): FaxInboundRoutingExtensions; + + /** Ordered collection of all the registered methods */ + GetMethods(): FaxInboundRoutingMethods; + } + + /** FaxInboundRoutingExtension Class */ + class FaxInboundRoutingExtension { + private 'FAXCOMEXLib.FaxInboundRoutingExtension_typekey': FaxInboundRoutingExtension; + private constructor(); + + /** Is extension built in debug environment */ + readonly Debug: boolean; + + /** Extension's friendly name */ + readonly FriendlyName: string; + + /** Full path and file name of the extension DLL */ + readonly ImageName: string; + + /** Last error code at load or initialization */ + readonly InitErrorCode: number; + + /** The major part of extension's build number */ + readonly MajorBuild: number; + + /** The major part of extension's version number */ + readonly MajorVersion: number; + + /** Array of methods exposed by extension */ + readonly Methods: SafeArray; + + /** The minor part of extension's build number */ + readonly MinorBuild: number; + + /** The minor part of extension's version number */ + readonly MinorVersion: number; + + /** Load and initialization status of the extension */ + readonly Status: FAX_PROVIDER_STATUS_ENUM; + + /** Extension's unique name */ + readonly UniqueName: string; + } + + /** FaxInboundRoutingExtensions Class */ + interface FaxInboundRoutingExtensions { + readonly Count: number; + Item(vIndex: any): FaxInboundRoutingExtension; + (vIndex: any): FaxInboundRoutingExtension; + } + + /** FaxInboundRoutingMethod Class */ + class FaxInboundRoutingMethod { + private 'FAXCOMEXLib.FaxInboundRoutingMethod_typekey': FaxInboundRoutingMethod; + private constructor(); + + /** Friendly name of the extension exposing this method */ + readonly ExtensionFriendlyName: string; + + /** Image name of the extension exposing this method */ + readonly ExtensionImageName: string; + + /** Internal function name */ + readonly FunctionName: string; + + /** GUID of the method */ + readonly GUID: string; + + /** The name of the method */ + readonly Name: string; + + /** Priority of the method */ + Priority: number; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + } + + /** FaxInboundRoutingMethods Class */ + interface FaxInboundRoutingMethods { + readonly Count: number; + Item(vIndex: any): FaxInboundRoutingMethod; + (vIndex: any): FaxInboundRoutingMethod; + } + + /** FaxIncomingArchive Class */ + class FaxIncomingArchive { + private 'FAXCOMEXLib.FaxIncomingArchive_typekey': FaxIncomingArchive; + private constructor(); + + /** How long the fax message is kept on the Server */ + AgeLimit: number; + + /** Location of the archive folder on the server */ + ArchiveFolder: string; + + /** Get archived message by its ID */ + GetMessage(bstrMessageId: string): IFaxIncomingMessage; + + /** + * Iterator on the archived messages + * @param number [lPrefetchSize=100] + */ + GetMessages(lPrefetchSize?: number): FaxIncomingMessageIterator; + + /** High quota water mark */ + HighQuotaWaterMark: number; + + /** Low quota water mark */ + LowQuotaWaterMark: number; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + + /** The high 32-bit value of the archive size */ + readonly SizeHigh: number; + + /** The low 32-bit value of the archive size */ + readonly SizeLow: number; + + /** Is size quota warning on */ + SizeQuotaWarning: boolean; + + /** Whether received faxes should be archived */ + UseArchive: boolean; + } + + /** FaxIncomingJob Class */ + class FaxIncomingJob { + private 'FAXCOMEXLib.FaxIncomingJob_typekey': FaxIncomingJob; + private constructor(); + + /** Available operations, a bit-wise combination of FAX_JOB_OPERATIONS values */ + readonly AvailableOperations: FAX_JOB_OPERATIONS_ENUM; + + /** Caller ID */ + readonly CallerId: string; + + /** Cancel the incoming job */ + Cancel(): void; + + /** Copy TIFF image to the local file */ + CopyTiff(bstrTiffPath: string): void; + + /** Called Station ID */ + readonly CSID: string; + + /** Page currently in transmision */ + readonly CurrentPage: number; + + /** Device ID that transmits the job */ + readonly DeviceId: number; + + /** Extended status description */ + readonly ExtendedStatus: string; + + /** Code of the job's extended status */ + readonly ExtendedStatusCode: FAX_JOB_EXTENDED_STATUS_ENUM; + + /** Unique message ID */ + readonly Id: string; + + /** Job type */ + readonly JobType: FAX_JOB_TYPE_ENUM; + + /** Refresh the object */ + Refresh(): void; + + /** Number of failed transmission retries */ + readonly Retries: number; + + /** Routing information */ + readonly RoutingInformation: string; + + /** Size in bytes of the message's TIFF file */ + readonly Size: number; + + /** Current queue status of the job, a bit-wise combination of FAX_JOB_STATUS values */ + readonly Status: FAX_JOB_STATUS_ENUM; + + /** Transmission end time */ + readonly TransmissionEnd: VarDate; + + /** Transmission start time */ + readonly TransmissionStart: VarDate; + + /** Transmitting Station ID */ + readonly TSID: string; + } + + /** FaxIncomingJobs Class */ + interface FaxIncomingJobs { + readonly Count: number; + Item(vIndex: any): FaxIncomingJob; + (vIndex: any): FaxIncomingJob; + } + + /** FaxIncomingMessage Class */ + class FaxIncomingMessage extends IFaxIncomingMessage { + private 'FAXCOMEXLib.FaxIncomingMessage_typekey': FaxIncomingMessage; + private constructor(); + + /** Has Cover page */ + HasCoverPage: boolean; + + /** Read flag on the message */ + Read: boolean; + + /** Reassigns the message */ + ReAssign(): void; + + /** Set of recipient names */ + Recipients: string; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + + /** Sender's fax number */ + SenderFaxNumber: string; + + /** Sender's name */ + SenderName: string; + + /** Contents of cover page subject field */ + Subject: string; + + /** Is message reassigned? */ + readonly WasReAssigned: boolean; + } + + /** FaxIncomingMessageIterator Class */ + class FaxIncomingMessageIterator { + private 'FAXCOMEXLib.FaxIncomingMessageIterator_typekey': FaxIncomingMessageIterator; + private constructor(); + + /** End of archive marker */ + readonly AtEOF: boolean; + + /** The current message */ + readonly Message: IFaxIncomingMessage; + + /** Move to the first message in the archive */ + MoveFirst(): void; + + /** Move to the next message in the archive */ + MoveNext(): void; + + /** Size of the prefetch buffer */ + PrefetchSize: number; + } + + /** FaxIncomingQueue Class */ + class FaxIncomingQueue { + private 'FAXCOMEXLib.FaxIncomingQueue_typekey': FaxIncomingQueue; + private constructor(); + + /** Is queue blocked */ + Blocked: boolean; + + /** Get incoming job by ID */ + GetJob(bstrJobId: string): FaxIncomingJob; + + /** Collection of incoming jobs */ + GetJobs(): FaxIncomingJobs; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + } + + /** FaxJobStatus Class */ + class FaxJobStatus { + private 'FAXCOMEXLib.FaxJobStatus_typekey': FaxJobStatus; + private constructor(); + + /** Available operations, a bit-wise combination of FAX_JOB_OPERATIONS values */ + readonly AvailableOperations: FAX_JOB_OPERATIONS_ENUM; + + /** Caller ID */ + readonly CallerId: string; + + /** Called Station ID */ + readonly CSID: string; + + /** Page currently in transmision */ + readonly CurrentPage: number; + + /** Device ID of device that transmits the job */ + readonly DeviceId: number; + + /** Extended status description */ + readonly ExtendedStatus: string; + + /** Code of the job's extended status */ + readonly ExtendedStatusCode: FAX_JOB_EXTENDED_STATUS_ENUM; + + /** Job type */ + readonly JobType: FAX_JOB_TYPE_ENUM; + + /** Total number of pages */ + readonly Pages: number; + + /** Number of failed transmission retries */ + readonly Retries: number; + + /** Routing information */ + readonly RoutingInformation: string; + + /** The time the fax job is scheduled to be transmitted */ + readonly ScheduledTime: VarDate; + + /** Size in bytes of TIFF file */ + readonly Size: number; + + /** Current queue status of the job, a bit-wise combination of FAX_JOB_STATUS values */ + readonly Status: FAX_JOB_STATUS_ENUM; + + /** The time the fax job finished its transmission */ + readonly TransmissionEnd: VarDate; + + /** The time the fax job started its transmission */ + readonly TransmissionStart: VarDate; + + /** Transmitting Station ID */ + readonly TSID: string; + } + + /** FaxLoggingOptions Class */ + class FaxLoggingOptions { + private 'FAXCOMEXLib.FaxLoggingOptions_typekey': FaxLoggingOptions; + private constructor(); + + /** Activity logging configuration object */ + readonly ActivityLogging: FaxActivityLogging; + + /** Event logging configuration object */ + readonly EventLogging: FaxEventLogging; + } + + /** FaxOutboundRouting Class */ + class FaxOutboundRouting { + private 'FAXCOMEXLib.FaxOutboundRouting_typekey': FaxOutboundRouting; + private constructor(); + + /** Configuration of the outbound routing groups */ + GetGroups(): FaxOutboundRoutingGroups; + + /** Configuration of the outbound routing rules */ + GetRules(): FaxOutboundRoutingRules; + } + + /** FaxOutboundRoutingGroup Class */ + class FaxOutboundRoutingGroup { + private 'FAXCOMEXLib.FaxOutboundRoutingGroup_typekey': FaxOutboundRoutingGroup; + private constructor(); + + /** Ordered collection of device IDs */ + readonly DeviceIds: FaxDeviceIds; + + /** Name of the group */ + readonly Name: string; + + /** Status of the group */ + readonly Status: FAX_GROUP_STATUS_ENUM; + } + + /** FaxOutboundRoutingGroups Class */ + interface FaxOutboundRoutingGroups { + /** Add a group */ + Add(bstrName: string): FaxOutboundRoutingGroup; + readonly Count: number; + Item(vIndex: number | string): FaxOutboundRoutingGroup; + + /** Remove a group */ + Remove(vIndex: number | string): void; + (vIndex: number | string): FaxOutboundRoutingGroup; + } + + /** FaxOutboundRoutingRule Class */ + class FaxOutboundRoutingRule { + private 'FAXCOMEXLib.FaxOutboundRoutingRule_typekey': FaxOutboundRoutingRule; + private constructor(); + + /** Area code */ + readonly AreaCode: number; + + /** Country code */ + readonly CountryCode: number; + + /** Destination device */ + DeviceId: number; + + /** Group name */ + GroupName: string; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + + /** Status */ + readonly Status: FAX_RULE_STATUS_ENUM; + + /** Uses single device or group */ + UseDevice: boolean; + } + + /** FaxOutboundRoutingRules Class */ + interface FaxOutboundRoutingRules { + /** Add a rule */ + Add(lCountryCode: number, lAreaCode: number, bUseDevice: boolean, bstrGroupName: string, lDeviceId: number): FaxOutboundRoutingRule; + readonly Count: number; + Item(lIndex: number): FaxOutboundRoutingRule; + + /** Get a rule by criteria */ + ItemByCountryAndArea(lCountryCode: number, lAreaCode: number): FaxOutboundRoutingRule; + + /** Remove a rule */ + Remove(lIndex: number): void; + + /** Remove a rule by criteria */ + RemoveByCountryAndArea(lCountryCode: number, lAreaCode: number): void; + (lIndex: number): FaxOutboundRoutingRule; + } + + /** FaxOutgoingArchive Class */ + class FaxOutgoingArchive { + private 'FAXCOMEXLib.FaxOutgoingArchive_typekey': FaxOutgoingArchive; + private constructor(); + + /** Indicates how long the fax message is kept on the server */ + AgeLimit: number; + + /** Location of the outgoing archive on the server */ + ArchiveFolder: string; + + /** Get an archived message by its ID */ + GetMessage(bstrMessageId: string): IFaxOutgoingMessage; + + /** + * Iterator on the archived messages + * @param number [lPrefetchSize=100] + */ + GetMessages(lPrefetchSize?: number): FaxOutgoingMessageIterator; + + /** High quota water mark */ + HighQuotaWaterMark: number; + + /** Low quota water mark */ + LowQuotaWaterMark: number; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + + /** The high 32-bit value of the archive size */ + readonly SizeHigh: number; + + /** The low 32-bit value of the archive size */ + readonly SizeLow: number; + + /** Is the size quota warning on or off */ + SizeQuotaWarning: boolean; + + /** Whether sent faxes should be archived */ + UseArchive: boolean; + } + + /** FaxOutgoingJob Class */ + class FaxOutgoingJob { + private 'FAXCOMEXLib.FaxOutgoingJob_typekey': FaxOutgoingJob; + private constructor(); + + /** Available operations, a bit-wise combination of FAX_JOB_OPERATIONS values */ + readonly AvailableOperations: FAX_JOB_OPERATIONS_ENUM; + + /** Cancel the outbound job */ + Cancel(): void; + + /** Copy the job's TIFF image */ + CopyTiff(bstrTiffPath: string): void; + + /** Called Station ID */ + readonly CSID: string; + + /** Page currently in transmision */ + readonly CurrentPage: number; + + /** Device ID that transmits the job */ + readonly DeviceId: number; + + /** Document's friendly name */ + readonly DocumentName: string; + + /** Extended status description */ + readonly ExtendedStatus: string; + + /** Code of the job's extended status */ + readonly ExtendedStatusCode: FAX_JOB_EXTENDED_STATUS_ENUM; + + /** Whether to group broadcast receipts */ + readonly GroupBroadcastReceipts: boolean; + + /** Has Cover page */ + readonly HasCoverPage: boolean; + + /** Unique job ID */ + readonly Id: string; + + /** Time the job was originally scheduled to be transmitted */ + readonly OriginalScheduledTime: VarDate; + + /** Total number of pages */ + readonly Pages: number; + + /** Pause the outbound job */ + Pause(): void; + + /** Priority of the fax */ + readonly Priority: FAX_PRIORITY_TYPE_ENUM; + + /** Address of the receipt */ + readonly ReceiptAddress: string; + + /** Type of receipt */ + readonly ReceiptType: FAX_RECEIPT_TYPE_ENUM; + + /** Recipient information object */ + readonly Recipient: FaxRecipient; + + /** Refresh the object */ + Refresh(): void; + + /** Restart the outbound job */ + Restart(): void; + + /** Resume the outbound job */ + Resume(): void; + + /** Number of failed transmission retries */ + readonly Retries: number; + + /** The time the fax job is scheduled to be transmitted */ + readonly ScheduledTime: VarDate; + + /** When to send the fax */ + readonly ScheduleType: FAX_SCHEDULE_TYPE_ENUM; + + /** Sender information object */ + readonly Sender: FaxSender; + + /** Size in bytes of TIFF file */ + readonly Size: number; + + /** Current queue status of the job */ + readonly Status: FAX_JOB_STATUS_ENUM; + + /** Cover page's subject field */ + readonly Subject: string; + + /** Unique ID the submission process created for the Job */ + readonly SubmissionId: string; + + /** Time the job was submitted */ + readonly SubmissionTime: VarDate; + + /** The time the fax job finished its transmission */ + readonly TransmissionEnd: VarDate; + + /** The time the fax job started its transmission */ + readonly TransmissionStart: VarDate; + + /** Transmitting Station ID */ + readonly TSID: string; + } + + /** FaxOutgoingJobs Class */ + interface FaxOutgoingJobs { + readonly Count: number; + Item(vIndex: any): IFaxOutgoingJob; + (vIndex: any): IFaxOutgoingJob; + } + + /** FaxOutgoingMessage Class */ + class FaxOutgoingMessage extends IFaxOutgoingMessage { + private 'FAXCOMEXLib.FaxOutgoingMessage_typekey': FaxOutgoingMessage; + private constructor(); + + /** Copy Tiff image to the local file */ + CopyTiff(bstrTiffPath: string): void; + + /** Has Cover page */ + readonly HasCoverPage: boolean; + + /** Read flag on the message */ + Read: boolean; + + /** Address of the receipt */ + readonly ReceiptAddress: string; + + /** Type of the receipt */ + readonly ReceiptType: FAX_RECEIPT_TYPE_ENUM; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + } + + /** FaxOutgoingMessageIterator Class */ + class FaxOutgoingMessageIterator { + private 'FAXCOMEXLib.FaxOutgoingMessageIterator_typekey': FaxOutgoingMessageIterator; + private constructor(); + + /** End of archive marker */ + readonly AtEOF: boolean; + + /** Current message */ + readonly Message: IFaxOutgoingMessage; + + /** Move to the first message */ + MoveFirst(): void; + + /** Move to the next message */ + MoveNext(): void; + + /** Size of prefetch buffer */ + PrefetchSize: number; + } + + /** FaxOutgoingQueue Class */ + class FaxOutgoingQueue { + private 'FAXCOMEXLib.FaxOutgoingQueue_typekey': FaxOutgoingQueue; + private constructor(); + + /** How long the failed fax message is kept on the server */ + AgeLimit: number; + + /** Are personal cover pages allowed */ + AllowPersonalCoverPages: boolean; + + /** Is the queue blocked */ + Blocked: boolean; + + /** Does the server generate a brand */ + Branding: boolean; + + /** End of the discount rate period */ + DiscountRateEnd: VarDate; + + /** Start of the discount rate period */ + DiscountRateStart: VarDate; + + /** Outgoing job by ID */ + GetJob(bstrJobId: string): IFaxOutgoingJob; + + /** Collection of outgoing jobs */ + GetJobs(): FaxOutgoingJobs; + + /** Is the queue paused */ + Paused: boolean; + + /** Refresh the object */ + Refresh(): void; + + /** Number of retries */ + Retries: number; + + /** Retry delay */ + RetryDelay: number; + + /** Save the object */ + Save(): void; + + /** Is device Transmitting Station ID used */ + UseDeviceTSID: boolean; + } + + /** FaxReceiptOptions Class */ + class FaxReceiptOptions { + private 'FAXCOMEXLib.FaxReceiptOptions_typekey': FaxReceiptOptions; + private constructor(); + + /** Allowed receipt types, a bit-wise combination of FAX_RECEIPT_TYPE values */ + AllowedReceipts: FAX_RECEIPT_TYPE_ENUM; + + /** Authentication type used by server */ + AuthenticationType: FAX_SMTP_AUTHENTICATION_TYPE_ENUM; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + + /** SMTP password */ + SMTPPassword: string; + + /** SMTP port number */ + SMTPPort: number; + + /** SMTP sender e-mail address */ + SMTPSender: string; + + /** Name of the SMTP server */ + SMTPServer: string; + + /** SMTP user name */ + SMTPUser: string; + + /** Whether to use the IFaxReceiptOptions settings for MS routing extension */ + UseForInboundRouting: boolean; + } + + /** FaxRecipient Class */ + class FaxRecipient { + private 'FAXCOMEXLib.FaxRecipient_typekey': FaxRecipient; + private constructor(); + + /** Recipient's fax number */ + FaxNumber: string; + + /** Recipient's name */ + Name: string; + } + + /** FaxRecipients Class */ + interface FaxRecipients { + /** + * Add a recipient + * @param string [bstrRecipientName=''] + */ + Add(bstrFaxNumber: string, bstrRecipientName?: string): FaxRecipient; + readonly Count: number; + Item(lIndex: number): FaxRecipient; + + /** Remove a recipient */ + Remove(lIndex: number): void; + (lIndex: number): FaxRecipient; + } + + /** FaxSecurity Class */ + class FaxSecurity { + private 'FAXCOMEXLib.FaxSecurity_typekey': FaxSecurity; + private constructor(); + + /** Security descriptor */ + Descriptor: any; + + /** Granted rights, a bit-wise combination of FAX_ACCESS_RIGHTS values */ + readonly GrantedRights: FAX_ACCESS_RIGHTS_ENUM; + + /** Security Information Type */ + InformationType: number; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + } + + /** FaxSecurity2 Class */ + class FaxSecurity2 { + private 'FAXCOMEXLib.FaxSecurity2_typekey': FaxSecurity2; + private constructor(); + + /** Security descriptor */ + Descriptor: any; + + /** Granted rights, a bit-wise combination */ + readonly GrantedRights: FAX_ACCESS_RIGHTS_ENUM_2; + + /** Security Information Type */ + InformationType: number; + + /** Refresh the object */ + Refresh(): void; + + /** Save the object */ + Save(): void; + } + + /** FaxSender Class */ + class FaxSender { + private 'FAXCOMEXLib.FaxSender_typekey': FaxSender; + private constructor(); + + /** Sender's billing code */ + BillingCode: string; + + /** City */ + City: string; + + /** Sender's company */ + Company: string; + + /** Sender's country or region */ + Country: string; + + /** Sender's department */ + Department: string; + + /** Sender's e-mail address */ + Email: string; + + /** Sender's fax number */ + FaxNumber: string; + + /** Sender's home phone */ + HomePhone: string; + + /** Load default sender */ + LoadDefaultSender(): void; + + /** Sender's name */ + Name: string; + + /** Sender's office location */ + OfficeLocation: string; + + /** Sender's office phone */ + OfficePhone: string; + + /** Save default sender */ + SaveDefaultSender(): void; + + /** Sender's state */ + State: string; + + /** Sender's street address */ + StreetAddress: string; + + /** Sender's title */ + Title: string; + + /** Transmitting Station ID */ + TSID: string; + + /** Sender's zip code */ + ZipCode: string; + } + + /** FaxServer Class */ + class FaxServer extends IFaxServer { + private 'FAXCOMEXLib.FaxServer_typekey': FaxServer; + private constructor(); + + /** Fax server configuration */ + readonly Configuration: FaxConfiguration; + + /** FaxAccount for the current connection */ + readonly CurrentAccount: FaxAccount; + + /** The FaxAccountSet configuration object */ + readonly FaxAccountSet: FaxAccountSet; + + /** The security configuration object */ + readonly Security2: FaxSecurity2; + } + + /** IFaxIncomingMessage interface */ + class IFaxIncomingMessage { + /** Caller ID */ + readonly CallerId: string; + + /** Copy Tiff image to the local file */ + CopyTiff(bstrTiffPath: string): void; + + /** Called Station ID */ + readonly CSID: string; + + /** Delete the message from the archive */ + Delete(): void; + + /** Name of the device that received the message */ + readonly DeviceName: string; + + /** Unique message ID */ + readonly Id: string; + + /** Total number of pages */ + readonly Pages: number; + + /** Number of failed routing retries */ + readonly Retries: number; + + /** Routing information */ + readonly RoutingInformation: string; + + /** Size in bytes of the message's TIFF file */ + readonly Size: number; + + /** Transmission end time */ + readonly TransmissionEnd: VarDate; + + /** Transmission start time */ + readonly TransmissionStart: VarDate; + + /** Transmitting Station ID */ + readonly TSID: string; + } + + /** IFaxOutgoingJob interface */ + class IFaxOutgoingJob { + private 'FAXCOMEXLib.IFaxOutgoingJob_typekey': IFaxOutgoingJob; + private constructor(); + + /** Available operations, a bit-wise combination of FAX_JOB_OPERATIONS values */ + readonly AvailableOperations: FAX_JOB_OPERATIONS_ENUM; + + /** Cancel the outbound job */ + Cancel(): void; + + /** Copy the job's TIFF image */ + CopyTiff(bstrTiffPath: string): void; + + /** Called Station ID */ + readonly CSID: string; + + /** Page currently in transmision */ + readonly CurrentPage: number; + + /** Device ID that transmits the job */ + readonly DeviceId: number; + + /** Document's friendly name */ + readonly DocumentName: string; + + /** Extended status description */ + readonly ExtendedStatus: string; + + /** Code of the job's extended status */ + readonly ExtendedStatusCode: FAX_JOB_EXTENDED_STATUS_ENUM; + + /** Whether to group broadcast receipts */ + readonly GroupBroadcastReceipts: boolean; + + /** Unique job ID */ + readonly Id: string; + + /** Time the job was originally scheduled to be transmitted */ + readonly OriginalScheduledTime: VarDate; + + /** Total number of pages */ + readonly Pages: number; + + /** Pause the outbound job */ + Pause(): void; + + /** Priority of the fax */ + readonly Priority: FAX_PRIORITY_TYPE_ENUM; + + /** Type of receipt */ + readonly ReceiptType: FAX_RECEIPT_TYPE_ENUM; + + /** Recipient information object */ + readonly Recipient: FaxRecipient; + + /** Refresh the object */ + Refresh(): void; + + /** Restart the outbound job */ + Restart(): void; + + /** Resume the outbound job */ + Resume(): void; + + /** Number of failed transmission retries */ + readonly Retries: number; + + /** The time the fax job is scheduled to be transmitted */ + readonly ScheduledTime: VarDate; + + /** Sender information object */ + readonly Sender: FaxSender; + + /** Size in bytes of TIFF file */ + readonly Size: number; + + /** Current queue status of the job */ + readonly Status: FAX_JOB_STATUS_ENUM; + + /** Cover page's subject field */ + readonly Subject: string; + + /** Unique ID the submission process created for the Job */ + readonly SubmissionId: string; + + /** Time the job was submitted */ + readonly SubmissionTime: VarDate; + + /** The time the fax job finished its transmission */ + readonly TransmissionEnd: VarDate; + + /** The time the fax job started its transmission */ + readonly TransmissionStart: VarDate; + + /** Transmitting Station ID */ + readonly TSID: string; + } + + /** IFaxOutgoingMessage interface */ + class IFaxOutgoingMessage { + /** Copy Tiff image to the local file */ + CopyTiff(bstrTiffPath: string): void; + + /** Called Station ID */ + readonly CSID: string; + + /** Delete the message from the archive */ + Delete(): void; + + /** Name of the device transmitting the message */ + readonly DeviceName: string; + + /** Document's friendly name */ + readonly DocumentName: string; + + /** Unique message ID */ + readonly Id: string; + + /** Time the job was originally scheduled to be transmitted */ + readonly OriginalScheduledTime: VarDate; + + /** Total number of pages */ + readonly Pages: number; + + /** Priority of the fax */ + readonly Priority: FAX_PRIORITY_TYPE_ENUM; + + /** Recipient information object */ + readonly Recipient: FaxRecipient; + + /** Number of failed routing retries */ + readonly Retries: number; + + /** Sender information object */ + readonly Sender: FaxSender; + + /** Size in bytes of TIFF file */ + readonly Size: number; + + /** Cover page's subject field */ + readonly Subject: string; + + /** Unique ID the submission process created for the job */ + readonly SubmissionId: string; + + /** Time the job was submitted */ + readonly SubmissionTime: VarDate; + + /** Transmission end time */ + readonly TransmissionEnd: VarDate; + + /** Transmission start time */ + readonly TransmissionStart: VarDate; + + /** Transmitting Station ID */ + readonly TSID: string; + } + + /** IFaxServer interface */ + class IFaxServer { + /** The fax server activity status object */ + readonly Activity: FaxActivity; + + /** Version of the fax server API */ + readonly APIVersion: FAX_SERVER_APIVERSION_ENUM; + + /** Connect to the fax server */ + Connect(bstrServerName: string): void; + + /** Is fax server built in debug environment */ + readonly Debug: boolean; + + /** Disconnect from the fax server */ + Disconnect(): void; + + /** The fax folders object */ + readonly Folders: FaxFolders; + + /** The collection of device providers */ + GetDeviceProviders(): FaxDeviceProviders; + + /** The collection of all available devices */ + GetDevices(): FaxDevices; + + /** Return server level extention property */ + GetExtensionProperty(bstrGUID: string): any; + + /** The inbound routing configuration object */ + readonly InboundRouting: FaxInboundRouting; + + /** Set bit-wise combination of events the fax server listens to */ + ListenToServerEvents(EventTypes: FAX_SERVER_EVENTS_TYPE_ENUM): void; + + /** The logging options configuration object */ + readonly LoggingOptions: FaxLoggingOptions; + + /** The major part of the fax server's build number */ + readonly MajorBuild: number; + + /** The major part of the fax server's version number */ + readonly MajorVersion: number; + + /** The minor part of the fax server's build number */ + readonly MinorBuild: number; + + /** The minor part of the fax server's version number */ + readonly MinorVersion: number; + + /** The outbound routing configuration object */ + readonly OutboundRouting: FaxOutboundRouting; + + /** The receipt options configuration object */ + readonly ReceiptOptions: FaxReceiptOptions; + + /** Register device provider */ + RegisterDeviceProvider(bstrGUID: string, bstrFriendlyName: string, bstrImageName: string, TspName: string, lFSPIVersion: number): void; + + /** Events the fax Server is listening to */ + readonly RegisteredEvents: FAX_SERVER_EVENTS_TYPE_ENUM; + + /** Register inbound routing extension */ + RegisterInboundRoutingExtension(bstrExtensionName: string, bstrFriendlyName: string, bstrImageName: string, vMethods: any): void; + + /** The security configuration object */ + readonly Security: FaxSecurity; + + /** The name of the fax server */ + readonly ServerName: string; + + /** Set server level extention property */ + SetExtensionProperty(bstrGUID: string, vProperty: SafeArray): void; + + /** Unregister device provider */ + UnregisterDeviceProvider(bstrUniqueName: string): void; + + /** Unregister inbound routing extension */ + UnregisterInboundRoutingExtension(bstrExtensionUniqueName: string): void; + } + + namespace EventHelperTypes { + type FaxAccount_Invoke_ArgNames = ['dispidMember', 'riid', 'lcid', 'wFlags', 'pdispparams', 'pvarResult', 'pexcepinfo', 'puArgErr']; + + type FaxServer_Invoke_ArgNames = ['dispidMember', 'riid', 'lcid', 'wFlags', 'pdispparams', 'pvarResult', 'pexcepinfo', 'puArgErr']; + + type FaxServer_OnDeviceStatusChange_ArgNames = ['pFaxServer', 'lDeviceId', 'bPoweredOff', 'bSending', 'bReceiving', 'bRinging']; + + interface FaxAccount_Invoke_Parameter { + readonly dispidMember: number; + readonly lcid: number; + readonly pdispparams: stdole.DISPPARAMS; + pexcepinfo: stdole.EXCEPINFO; + puArgErr: number; + pvarResult: any; + readonly riid: stdole.GUID; + readonly wFlags: number; + } + + interface FaxServer_Invoke_Parameter { + readonly dispidMember: number; + readonly lcid: number; + readonly pdispparams: stdole.DISPPARAMS; + pexcepinfo: stdole.EXCEPINFO; + puArgErr: number; + pvarResult: any; + readonly riid: stdole.GUID; + readonly wFlags: number; + } + + interface FaxServer_OnDeviceStatusChange_Parameter { + readonly bPoweredOff: boolean; + readonly bReceiving: boolean; + readonly bRinging: boolean; + readonly bSending: boolean; + readonly lDeviceId: number; + readonly pFaxServer: FaxServer; + } + } +} + +interface ActiveXObject { + on( + obj: FAXCOMEXLib.FaxAccount, event: 'GetIDsOfNames', argNames: ['riid', 'rgszNames', 'cNames', 'lcid', 'rgdispid'], handler: ( + this: FAXCOMEXLib.FaxAccount, parameter: {readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number}) => void): void; + on( + obj: FAXCOMEXLib.FaxAccount, event: 'GetTypeInfo', argNames: ['itinfo', 'lcid', 'pptinfo'], handler: ( + this: FAXCOMEXLib.FaxAccount, parameter: {readonly itinfo: number, readonly lcid: number, pptinfo: undefined}) => void): void; + on(obj: FAXCOMEXLib.FaxAccount, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: FAXCOMEXLib.FaxAccount, parameter: {pctinfo: number}) => void): void; + on( + obj: FAXCOMEXLib.FaxAccount, event: 'Invoke', argNames: FAXCOMEXLib.EventHelperTypes.FaxAccount_Invoke_ArgNames, handler: ( + this: FAXCOMEXLib.FaxAccount, parameter: FAXCOMEXLib.EventHelperTypes.FaxAccount_Invoke_Parameter) => void): void; + on( + obj: FAXCOMEXLib.FaxAccount, event: 'OnIncomingJobAdded' | 'OnIncomingJobRemoved' | 'OnOutgoingJobAdded' | 'OnOutgoingJobRemoved', + argNames: ['pFaxAccount', 'bstrJobId'], handler: (this: FAXCOMEXLib.FaxAccount, parameter: {readonly pFaxAccount: FAXCOMEXLib.FaxAccount, readonly bstrJobId: string}) => void): void; + on( + obj: FAXCOMEXLib.FaxAccount, event: 'OnIncomingJobChanged' | 'OnOutgoingJobChanged', argNames: ['pFaxAccount', 'bstrJobId', 'pJobStatus'], + handler: (this: FAXCOMEXLib.FaxAccount, parameter: {readonly pFaxAccount: FAXCOMEXLib.FaxAccount, readonly bstrJobId: string, readonly pJobStatus: FAXCOMEXLib.FaxJobStatus}) => void): void; + on( + obj: FAXCOMEXLib.FaxAccount, event: 'OnIncomingMessageAdded', argNames: ['pFaxAccount', 'bstrMessageId', 'fAddedToReceiveFolder'], + handler: (this: FAXCOMEXLib.FaxAccount, parameter: {readonly pFaxAccount: FAXCOMEXLib.FaxAccount, readonly bstrMessageId: string, readonly fAddedToReceiveFolder: boolean}) => void): void; + on( + obj: FAXCOMEXLib.FaxAccount, event: 'OnIncomingMessageRemoved', argNames: ['pFaxAccount', 'bstrMessageId', 'fRemovedFromReceiveFolder'], + handler: (this: FAXCOMEXLib.FaxAccount, parameter: {readonly pFaxAccount: FAXCOMEXLib.FaxAccount, readonly bstrMessageId: string, readonly fRemovedFromReceiveFolder: boolean}) => void): void; + on( + obj: FAXCOMEXLib.FaxAccount, event: 'OnOutgoingMessageAdded' | 'OnOutgoingMessageRemoved', argNames: ['pFaxAccount', 'bstrMessageId'], + handler: (this: FAXCOMEXLib.FaxAccount, parameter: {readonly pFaxAccount: FAXCOMEXLib.FaxAccount, readonly bstrMessageId: string}) => void): void; + on( + obj: FAXCOMEXLib.FaxAccount, event: 'OnServerShutDown', argNames: ['pFaxServer'], handler: ( + this: FAXCOMEXLib.FaxAccount, parameter: {readonly pFaxServer: FAXCOMEXLib.FaxServer}) => void): void; + on( + obj: FAXCOMEXLib.FaxAccount, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: ( + this: FAXCOMEXLib.FaxAccount, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'GetIDsOfNames', argNames: ['riid', 'rgszNames', 'cNames', 'lcid', 'rgdispid'], handler: ( + this: FAXCOMEXLib.FaxServer, parameter: {readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number}) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'GetTypeInfo', argNames: ['itinfo', 'lcid', 'pptinfo'], handler: ( + this: FAXCOMEXLib.FaxServer, parameter: {readonly itinfo: number, readonly lcid: number, pptinfo: undefined}) => void): void; + on(obj: FAXCOMEXLib.FaxServer, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: FAXCOMEXLib.FaxServer, parameter: {pctinfo: number}) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'Invoke', argNames: FAXCOMEXLib.EventHelperTypes.FaxServer_Invoke_ArgNames, handler: ( + this: FAXCOMEXLib.FaxServer, parameter: FAXCOMEXLib.EventHelperTypes.FaxServer_Invoke_Parameter) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'OnActivityLoggingConfigChange' | 'OnDevicesConfigChange' | 'OnEventLoggingConfigChange' | 'OnGeneralServerConfigChanged' | + 'OnIncomingArchiveConfigChange' | 'OnOutboundRoutingGroupsConfigChange' | 'OnOutboundRoutingRulesConfigChange' | 'OnOutgoingArchiveConfigChange' | + 'OnOutgoingQueueConfigChange' | 'OnReceiptOptionsChange' | 'OnSecurityConfigChange' | 'OnServerShutDown', + argNames: ['pFaxServer'], + handler: (this: FAXCOMEXLib.FaxServer, parameter: {readonly pFaxServer: FAXCOMEXLib.FaxServer}) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'OnDeviceStatusChange', argNames: FAXCOMEXLib.EventHelperTypes.FaxServer_OnDeviceStatusChange_ArgNames, + handler: (this: FAXCOMEXLib.FaxServer, parameter: FAXCOMEXLib.EventHelperTypes.FaxServer_OnDeviceStatusChange_Parameter) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'OnIncomingJobAdded' | 'OnIncomingJobRemoved' | 'OnOutgoingJobAdded' | 'OnOutgoingJobRemoved', + argNames: ['pFaxServer', 'bstrJobId'], handler: (this: FAXCOMEXLib.FaxServer, parameter: {readonly pFaxServer: FAXCOMEXLib.FaxServer, readonly bstrJobId: string}) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'OnIncomingJobChanged' | 'OnOutgoingJobChanged', argNames: ['pFaxServer', 'bstrJobId', 'pJobStatus'], + handler: (this: FAXCOMEXLib.FaxServer, parameter: {readonly pFaxServer: FAXCOMEXLib.FaxServer, readonly bstrJobId: string, readonly pJobStatus: FAXCOMEXLib.FaxJobStatus}) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'OnIncomingMessageAdded' | 'OnIncomingMessageRemoved' | 'OnOutgoingMessageAdded' | 'OnOutgoingMessageRemoved', + argNames: ['pFaxServer', 'bstrMessageId'], handler: (this: FAXCOMEXLib.FaxServer, parameter: {readonly pFaxServer: FAXCOMEXLib.FaxServer, readonly bstrMessageId: string}) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'OnNewCall', argNames: ['pFaxServer', 'lCallId', 'lDeviceId', 'bstrCallerId'], handler: ( + this: FAXCOMEXLib.FaxServer, parameter: {readonly pFaxServer: FAXCOMEXLib.FaxServer, readonly lCallId: number, readonly lDeviceId: number, readonly bstrCallerId: string}) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'OnQueuesStatusChange', argNames: ['pFaxServer', 'bOutgoingQueueBlocked', 'bOutgoingQueuePaused', 'bIncomingQueueBlocked'], + handler: ( + this: FAXCOMEXLib.FaxServer, + parameter: { + readonly pFaxServer: FAXCOMEXLib.FaxServer, readonly bOutgoingQueueBlocked: boolean, readonly bOutgoingQueuePaused: boolean, readonly bIncomingQueueBlocked: boolean}) => void): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'OnServerActivityChange', + argNames: ['pFaxServer', 'lIncomingMessages', 'lRoutingMessages', 'lOutgoingMessages', 'lQueuedMessages'], handler: ( + this: FAXCOMEXLib.FaxServer, + parameter: { + readonly pFaxServer: FAXCOMEXLib.FaxServer, readonly lIncomingMessages: number, readonly lRoutingMessages: number, readonly lOutgoingMessages: number, readonly lQueuedMessages: number + }) => void + ): void; + on( + obj: FAXCOMEXLib.FaxServer, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: ( + this: FAXCOMEXLib.FaxServer, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void; + on(obj: FAXCOMEXLib.FaxAccount, event: 'AddRef' | 'Release', handler: (this: FAXCOMEXLib.FaxAccount, parameter: {}) => void): void; + on(obj: FAXCOMEXLib.FaxServer, event: 'AddRef' | 'Release', handler: (this: FAXCOMEXLib.FaxServer, parameter: {}) => void): void; + new(progid: K): ActiveXObjectNameMap[K]; +} + +interface ActiveXObjectNameMap { + 'FaxComEx.FaxDocument': FAXCOMEXLib.FaxDocument; + 'FaxComEx.FaxServer': FAXCOMEXLib.FaxServer; +} diff --git a/types/activex-faxcomexlib/package.json b/types/activex-faxcomexlib/package.json new file mode 100644 index 0000000000..d9b1031263 --- /dev/null +++ b/types/activex-faxcomexlib/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "activex-helpers": "*" + } +} \ No newline at end of file diff --git a/types/activex-faxcomexlib/tsconfig.json b/types/activex-faxcomexlib/tsconfig.json new file mode 100644 index 0000000000..6509ab4701 --- /dev/null +++ b/types/activex-faxcomexlib/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "scripthost" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "activex-faxcomexlib-tests.ts" + ] +} \ No newline at end of file diff --git a/types/activex-faxcomexlib/tslint.json b/types/activex-faxcomexlib/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/activex-faxcomexlib/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/activex-infopath/tslint.json b/types/activex-infopath/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-infopath/tslint.json +++ b/types/activex-infopath/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-iwshruntimelibrary/activex-iwshruntimelibrary-tests.ts b/types/activex-iwshruntimelibrary/activex-iwshruntimelibrary-tests.ts new file mode 100644 index 0000000000..14a90f9a8a --- /dev/null +++ b/types/activex-iwshruntimelibrary/activex-iwshruntimelibrary-tests.ts @@ -0,0 +1,49 @@ +const wshn = new ActiveXObject('WScript.Network'); + +// https://msdn.microsoft.com/en-us/library/s6wt333f(v=vs.84).aspx +// https://msdn.microsoft.com/en-us/library/wck0hkd7(v=vs.84).aspx +// https://msdn.microsoft.com/en-us/library/tte130y1(v=vs.84).aspx +// https://msdn.microsoft.com/en-us/library/3fxhka75(v=vs.84).aspx +{ + WScript.Echo('Domain = ' + wshn.UserDomain); + WScript.Echo('Computer Name = ' + wshn.ComputerName); + WScript.Echo('User Name = ' + wshn.UserName); +} + +// https://msdn.microsoft.com/en-us/library/zsdh7hkb(v=vs.84).aspx +wshn.AddWindowsPrinterConnection('\\\\printserv\\DefaultPrinter'); + +// https://msdn.microsoft.com/en-us/library/kxsdca3c(v=vs.84).aspx +wshn.AddPrinterConnection("LPT1", "\\\\Server\\Print1"); + +// https://msdn.microsoft.com/en-us/library/t9zt39at(v=vs.84).aspx +// https://msdn.microsoft.com/en-us/library/zhds6k80(v=vs.84).aspx +{ + const drives = wshn.EnumNetworkDrives(); + const printers = wshn.EnumPrinterConnections(); + WScript.Echo("Network drive mappings:"); + for (let i = 0; i < drives.length; i += 2) { + WScript.Echo(`Drive ${drives.Item(i)} = ${drives.Item(i + 1)}`); + } + WScript.Echo(''); + WScript.Echo("Network printer mappings:"); + for (let i = 0; i < printers.length; i += 2) { + WScript.Echo(`Port ${printers.Item(i)} = ${printers.Item(i + 1)}`); + } +} + +// https://msdn.microsoft.com/en-us/library/8kst88h6(v=vs.84).aspx +wshn.MapNetworkDrive('E:', '\\\\Server\\Public'); + +// https://msdn.microsoft.com/en-us/library/d16d7wbf(v=vs.84).aspx +wshn.RemoveNetworkDrive('E:'); + +// https://msdn.microsoft.com/en-us/library/tsbh2yy7(v=vs.84).aspx +wshn.RemovePrinterConnection('\\\\PRN-CORP1\\B41-4523-A', true, true); + +// https://msdn.microsoft.com/en-us/library/2ccwwdct(v=vs.84).aspx +{ + const printerPath = "\\\\research\\library1"; + wshn.AddWindowsPrinterConnection(printerPath); + wshn.SetDefaultPrinter(printerPath); +} diff --git a/types/activex-iwshruntimelibrary/index.d.ts b/types/activex-iwshruntimelibrary/index.d.ts new file mode 100644 index 0000000000..d5b052eaae --- /dev/null +++ b/types/activex-iwshruntimelibrary/index.d.ts @@ -0,0 +1,348 @@ +// Type definitions for Windows Script Host Object Model - IWshRuntimeLibrary 1.0 +// Project: https://msdn.microsoft.com/en-us/library/9bbdkx3k(v=vs.84).aspx +// Definitions by: Zev Spitz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +declare namespace IWshRuntimeLibrary { + type WindowStyle = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; + type ShortcutWindowStyle = 1 | 3 | 7; + + // tslint:disable-next-line no-const-enum + const enum ButtonType { + OK, + OKCancel, + AbortRetryIgnore, + YesNoCancel, + YesNo, + RetryCancel, + CancelTryagainContinue + } + + // tslint:disable-next-line no-const-enum + const enum EventType { + AuditFailure = 5, + AuditSuccess = 4, + Error = 1, + Information = 3, + Success = 0, + Warning = 2 + } + + // tslint:disable-next-line no-const-enum + const enum IconType { + Stop = 16, + QuestionMark = 32, + ExclamationMakr = 48, + InformationMark = 64, + } + + // tslint:disable-next-line no-const-enum + const enum PopupType { + SecondButtonDefault = 256, + ThirdButtonDefault = 512, + Modal = 4096, + RightJustified = 524288, + RTL = 1048576, + } + + // tslint:disable-next-line no-const-enum + const enum PopupSelection { + NoButton = -1, + OK = 1, + Cancel = 2, + Abort = 3, + Retry = 4, + Ignore = 5, + Yes = 6, + No = 7, + TryAgain = 10, + Continue = 11, + } + + // tslint:disable-next-line no-const-enum + const enum WshExecStatus { + WshFailed = 2, + WshFinished = 1, + WshRunning = 0, + } + + // tslint:disable-next-line no-const-enum + const enum WshWindowStyle { + WshHide = 0, + WshMaximizedFocus = 3, + WshMinimizedFocus = 2, + WshMinimizedNoFocus = 6, + WshNormalFocus = 1, + WshNormalNoFocus = 4, + } + + class TextStream { + private 'IWshRuntimeLibrary.TextStream_typekey': TextStream; + private constructor(); + readonly AtEndOfLine: boolean; + readonly AtEndOfStream: boolean; + Close(): void; + readonly Column: number; + readonly Line: number; + Read(Characters: number): string; + ReadAll(): string; + ReadLine(): string; + Skip(Characters: number): void; + SkipLine(): void; + Write(Text: string): void; + WriteBlankLines(Lines: number): void; + + /** @param string [Text=''] */ + WriteLine(Text?: string): void; + } + + /** Generic Collection Object */ + interface WshCollection { + Count(): number; + Item(Index: any): any; + readonly length: number; + (Index: any): any; + } + + /** Environment Variables Collection Object */ + interface WshEnvironment { + Count(): number; + Item(Name: string): string; + readonly length: number; + Remove(Name: string): void; + (Name: string): string; + } + + /** WSHExec object */ + class WshExec { + private 'IWshRuntimeLibrary.WshExec_typekey': WshExec; + private constructor(); + readonly ExitCode: number; + readonly ProcessID: number; + readonly Status: WshExecStatus; + readonly StdErr: TextStream; + readonly StdIn: TextStream; + readonly StdOut: TextStream; + Terminate(): void; + } + + /** Network Object */ + class WshNetwork { + private 'IWshRuntimeLibrary.WshNetwork_typekey': WshNetwork; + private constructor(); + + /** + * Adds a remote MS-DOS-based printer connection to your computer system. + * @param LocalName Local name to assign to the connected printer. + * @param RemoteName Name of the remote printer. + * @param UpdateProfile [false] Whether the printer mapping is stored in the current user's profile. + * + * If you are mapping a remote printer using the profile of someone other than current user, you can specify _UserName_ and _Password_. + */ + AddPrinterConnection(LocalName: string, RemoteName: string, UpdateProfile?: boolean, UserName?: string, Password?: string): void; + + /** + * @param string Path to printer connection + * @param string [DriverName=''] + * @param string [Port='LPT1'] + * + * Unlike the **AddPrinterConnection** method, this method allows you to create a printer connection without directing it to a specific port, such as LPT1. + */ + AddWindowsPrinterConnection(PrinterName: string, DriverName?: string, Port?: string): void; + readonly ComputerName: string; + EnumNetworkDrives(): WshCollection; + EnumPrinterConnections(): WshCollection; + + /** + * Adds a remote MS-DOS-based printer connection to your computer system. + * @param LocalName Name by which the mapped drive will be known locally + * @param RemoteName Share's UNC name (\\xxx\yyy) + * @param UpdateProfile [false] Whether the printer mapping is stored in the current user's profile. + * + * If you are mapping a network drive using the profile of someone other than current user, you can specify _UserName_ and _Password_. + */ + MapNetworkDrive(LocalName: string, RemoteName: string, UpdateProfile?: boolean, UserName?: string, Password?: string): void; + readonly Organization: string; + + /** + * Removes a shared network drive from your computer system + * @param Name Name of the mapped drive you want to remove. This will be the drive letter if the drive has a mapping between a local name (drive letter) and a remote name (UNC name); + * it will be the UNC path if there is no such mapping + * @param Force [false] Remove the connections even if the resource is in use + * @param UpdateProfile [false] Remove the mapping from the user's profile + */ + RemoveNetworkDrive(Name: string, Force?: boolean, UpdateProfile?: boolean): void; + + /** + * Removes a shared network printer connection from your computer system + * @param Name Name that identifies the printer. Can be a UNC name (in the form `\\xxx\yyy`) or a local name (such as `LPT1`) + * @param Force [false] Remove printer connection even if a user is still connected + * @param UpdateProfile [false] Remove the printer connection from the user's profile + * + * The **RemovePrinterConnection** method removes both Windows and MS-DOS based printer connections. If the printer was connected using the method **AddPrinterConnection**, + * _Name_ must be the printer's local name. If the printer was connected using the **AddWindowsPrinterConnection** method or was added manually (using the Add Printer wizard), + * then _Name_ must be the printer's UNC name. + */ + RemovePrinterConnection(Name: string, Force?: true, UpdateProfile?: true): void; + SetDefaultPrinter(Name: string): void; + readonly Site: string; + readonly UserDomain: string; + readonly UserName: string; + readonly UserProfile: string; + } + + /** Shell Object */ + class WshShell { + private 'IWshRuntimeLibrary.WshShell_typekey': WshShell; + private constructor(); + + /** + * Activates an application window + * @param App Title of application as it appears in the title bar, or the process ID + * @param Wait + * + * This method changes the focus to the named application or window. The window must be attached to the calling thread's message queue. It does not affect whether it is maximized or + * minimized. Focus moves from the activated application window when the user takes action to change the focus (or closes the window). + * + * In determining which application to activate, the specified title is compared to the title string of each running application. If no exact match exists, any application whose title + * string begins with title is activated. If an application still cannot be found, any application whose title string ends with title is activated. If more than one instance of the + * application named by title exists, one instance is arbitrarily activated. + * + * The method might return `false` under the following conditions: + * + * * The window is not brought to the foreground. + * * The window is brought to the foreground but is not given keyboard focus. + * * A Command Prompt window (`cmd.exe`) is brought to the foreground and is given keyboard focus. + */ + AppActivate(App: string | number, Wait?: any): boolean; + + /** + * Creates a shortcut + * @param PathLink Path where the shortcut should be created + * + * The shortcut object exists in memory until you save it to disk with the **Save** method. + */ + CreateShortcut(PathLink: string): WshShortcut | WshURLShortcut; + CurrentDirectory: string; + + /** + * Note that **Environment** doesn't actually return a callable object; the call is only usable in the context of the **Environment** property. The following: + * + * let env = new ActiveXObject('WScript.Shell').Environment; + * WScript.Echo(env('System')); + * + * will return an empty string, unless there is an environment variable named `System` + */ + Environment: WshEnvironment & ((Type: 'System' | 'User' | 'Process' | 'Volatile') => WshEnvironment); + Exec(Command: string): WshExec; + ExpandEnvironmentStrings(Src: string): string; + + /** @param string [Target=''] Name of the computer system where the event should be logged; default is the local computer system */ + LogEvent(Type: EventType, Message: string, Target?: string): boolean; + Popup(Text: string, SecondsToWait?: number, Title?: string, Type?: ButtonType | IconType | PopupType): PopupSelection; + RegDelete(Name: string): void; + + /** + * Returns the value of a key or value-name from the registry + * @param Name Key (ends with a final `\`) or value-name (doesn't end with a final `\`) + * + * Returns one of the following, based on the registry value type: + * + * * **REG_SZ** -- a string + * * **REG_DWORD** -- a number + * * **REG_SBINARY** -- a binary value, as a COM SafeArray containing integers + * * **REG_EXPAND_SZ** -- an expandable string + * * **REG_MULTI_SZ** -- an array of srings, as a COM SafeArray + */ + RegRead(Name: string): string | number | SafeArray | SafeArray; + + /** + * Creates a new key, adds another value-name to an existing key and assigns it a value, or changes the value of an existing value-name + * @param Name Key (ends with a final `\`) or value-name (doesn't end with a final `\`) + * @param Value Will be coerced to `string` or `integer` based on the value-name type: + * `REG_SZ | REG_EXPAND_SZ` will be converted to `string`; + * `REG_DWORD | REG_BINARY` will be converted to `integer` + * @param Type + */ + RegWrite(Name: string, Value: any, Type?: 'REG_SZ' | 'REG_DWORD' | 'REG_BINARY' | 'REG_EXPAND_SZ'): void; + + /** + * Runs a program in a new process. + * @param Command Command-line, including any parameters you want to pass to the executable file. + * @param WindowStyle Appearance of the program window. Not all programs make use of this information. + * @param WaitOnReturn Block script until program finishes executing. + * + * If `false` is passed into **WaitOnReturn**, the **Run** method will return 0 immediately. If `true` is passed in, **Run** will return the program's error code, if any. + * + * Environment variables will be expanded within the command line. + * + * Passing a registered file type will automatically open the program registered to the file type. + * + * Possible values for **WindowStyle**: + * + * * **0** -- Hides the window and activates another window. + * * **1** -- Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag + * when displaying the window for the first time. + * * **2** -- Activates the window and displays it as a minimized window. + * * **3** -- Activates the window and displays it as a maximized window. + * * **4** -- Displays a window in its most recent size and position. The active window remains active. + * * **5** -- Activates the window and displays it in its current size and position. + * * **6** -- Minimizes the specified window and activates the next top-level window in the Z order. + * * **7** -- Displays the window as a minimized window. The active window remains active. + * * **8** -- Displays the window in its current state. The active window remains active. + * * **9** -- Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag + * when restoring a minimized window. + * * **10** -- Sets the show-state based on the state of the program that started the application. + */ + Run(Command: string, WindowStyle?: WindowStyle, WaitOnReturn?: boolean): number; + SendKeys(Keys: string, Wait?: boolean): void; + readonly SpecialFolders: WshCollection; + } + + /** Shortcut Object */ + class WshShortcut { + private 'IWshRuntimeLibrary.WshShortcut_typekey': WshShortcut; + private constructor(); + Arguments: string; + Description: string; + readonly FullName: string; + Hotkey: string; + IconLocation: string; + Load(PathLink: string): void; + readonly RelativePath: string; + Save(): void; + TargetPath: string; + + /** + * Possible values: + * + * * **1** -- Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag + * when displaying the window for the first time. + * * **3** -- Activates the window and displays it as a maximized window. + * * **7** -- Displays the window as a minimized window. The active window remains active. + */ + WindowStyle: ShortcutWindowStyle; + WorkingDirectory: string; + } + + /** URLShortcut Object */ + class WshURLShortcut { + private 'IWshRuntimeLibrary.WshURLShortcut_typekey': WshURLShortcut; + private constructor(); + readonly FullName: string; + Load(PathLink: string): void; + Save(): void; + TargetPath: string; + } +} + +interface ActiveXObject { + set(obj: IWshRuntimeLibrary.WshEnvironment, propertyName: 'Item', parameterTypes: [string], newValue: string): void; + new (progid: K): ActiveXObjectNameMap[K]; +} + +interface ActiveXObjectNameMap { + 'WScript.Network': IWshRuntimeLibrary.WshNetwork; + 'WScript.Shell': IWshRuntimeLibrary.WshShell; +} diff --git a/types/activex-iwshruntimelibrary/package.json b/types/activex-iwshruntimelibrary/package.json new file mode 100644 index 0000000000..d9b1031263 --- /dev/null +++ b/types/activex-iwshruntimelibrary/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "activex-helpers": "*" + } +} \ No newline at end of file diff --git a/types/activex-iwshruntimelibrary/tsconfig.json b/types/activex-iwshruntimelibrary/tsconfig.json new file mode 100644 index 0000000000..1fa5abc39b --- /dev/null +++ b/types/activex-iwshruntimelibrary/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "scripthost" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "activex-iwshruntimelibrary-tests.ts" + ] +} \ No newline at end of file diff --git a/types/activex-iwshruntimelibrary/tslint.json b/types/activex-iwshruntimelibrary/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/activex-iwshruntimelibrary/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/activex-libreoffice/tslint.json b/types/activex-libreoffice/tslint.json index 8e56cb082c..37a3c27489 100644 --- a/types/activex-libreoffice/tslint.json +++ b/types/activex-libreoffice/tslint.json @@ -1,8 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false], "ban-types": false, + "no-const-enum": false, "no-redundant-jsdoc": false, "no-redundant-jsdoc-2": false, "no-unnecessary-qualifier": false diff --git a/types/activex-msforms/tslint.json b/types/activex-msforms/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-msforms/tslint.json +++ b/types/activex-msforms/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-mshtml/tslint.json b/types/activex-mshtml/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-mshtml/tslint.json +++ b/types/activex-mshtml/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-msxml2/tslint.json b/types/activex-msxml2/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-msxml2/tslint.json +++ b/types/activex-msxml2/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-office/tslint.json b/types/activex-office/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-office/tslint.json +++ b/types/activex-office/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-outlook/tslint.json b/types/activex-outlook/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-outlook/tslint.json +++ b/types/activex-outlook/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-powerpoint/tslint.json b/types/activex-powerpoint/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-powerpoint/tslint.json +++ b/types/activex-powerpoint/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-scripting/activex-scripting-tests.ts b/types/activex-scripting/activex-scripting-tests.ts index 2297548b81..313e480cb5 100644 --- a/types/activex-scripting/activex-scripting-tests.ts +++ b/types/activex-scripting/activex-scripting-tests.ts @@ -1,60 +1,324 @@ -// source -- https://msdn.microsoft.com/en-us/library/ebkhfaaz.aspx +// Note -- running these tests under cscript requires some ES5 polyfills -// Generates a string describing the drive type of a given Drive object. -function showDriveType(drive: Scripting.Drive) { - switch (drive.DriveType) { - case Scripting.DriveTypeConst.Removable: - return 'Removeable'; - case Scripting.DriveTypeConst.Fixed: - return 'Fixecd'; - case Scripting.DriveTypeConst.Remote: - return 'Network'; - case Scripting.DriveTypeConst.CDRom: - return 'CD-ROM'; - case Scripting.DriveTypeConst.RamDisk: - return 'RAM Disk'; - default: - return 'Unknown'; +const collectionToArray = (col: { Item(key: any): T }): T[] => { + const results: T[] = []; + const enumerator = new Enumerator(col); + enumerator.moveFirst(); + while (!enumerator.atEnd()) { + results.push(enumerator.item()); + enumerator.moveNext(); } -} + return results; +}; -// Generates a string describing the attributes of a file or folder. -function showFileAttributes(file: Scripting.File) { - const attr = file.Attributes; - if (attr === 0) { - return 'Normal'; +const fso = new ActiveXObject('Scripting.FileSystemObject'); + +// https://msdn.microsoft.com/en-us/library/ebkhfaaz(v=vs.84).aspx +{ + /** Generates a string describing the drive type of a given Drive object. */ + const driveTypeString = (drive: Scripting.Drive) => { + switch (drive.DriveType) { + case Scripting.DriveTypeConst.Removable: + return 'Removeable'; + case Scripting.DriveTypeConst.Fixed: + return 'Fixecd'; + case Scripting.DriveTypeConst.Remote: + return 'Network'; + case Scripting.DriveTypeConst.CDRom: + return 'CD-ROM'; + case Scripting.DriveTypeConst.RamDisk: + return 'RAM Disk'; + default: + return 'Unknown'; + } + }; + + /** Generates a string describing the attributes of a file or folder. */ + const attributesString = (f: Scripting.File | Scripting.Folder) => { + const attr = f.Attributes; + if (attr === 0) { + return 'Normal'; + } + const attributeStrings: string[] = []; + if (attr & Scripting.FileAttribute.Directory) { attributeStrings.push('Directory'); } + if (attr & Scripting.FileAttribute.ReadOnly) { attributeStrings.push('Read-only'); } + if (attr & Scripting.FileAttribute.Hidden) { attributeStrings.push('Hidden'); } + if (attr & Scripting.FileAttribute.System) { attributeStrings.push('System'); } + if (attr & Scripting.FileAttribute.Volume) { attributeStrings.push('Volume'); } + if (attr & Scripting.FileAttribute.Archive) { attributeStrings.push('Archive'); } + if (attr & Scripting.FileAttribute.Alias) { attributeStrings.push('Alias'); } + if (attr & Scripting.FileAttribute.Compressed) { attributeStrings.push('Compressed'); } + return attributeStrings.join(','); + }; + + const drivesInfoReport = () => { + const driveLine = (d: Scripting.Drive) => { + let parts: Array = [ + d.DriveLetter, + d.Path, + driveTypeString(d), + d.IsReady ? 'true' : 'false' + ]; + if (d.IsReady) { + parts = parts.concat([ + d.DriveType === Scripting.DriveTypeConst.Remote ? d.ShareName : d.VolumeName, + d.FileSystem, + d.TotalSize, + d.FreeSpace, + d.AvailableSpace, + d.SerialNumber.toString(16) + ]); + } + return parts.join(' '); + }; + + const ret = ` +Number of drives: ${fso.Drives.Count} + + Drive File Total Free Available Serial +Letter Path Type Ready? Name System Space Space Space Number +${new Array(106).join('-')} +${collectionToArray(fso.Drives).map(driveLine).join('\n')}` + .trim().replace(' ', '\t'); + }; + + type fiileFolderKey = keyof Scripting.File & keyof Scripting.Folder; + type keys = fiileFolderKey | 'Attribs' | 'Created' | 'Accessed' | 'Modified'; + const detailBuilder = (f: Scripting.File | Scripting.Folder, x: fiileFolderKey | 'Attribs' | 'Created' | 'Accessed' | 'Modified') => { + if (x === 'Attribs') { return attributesString(f); } + const label = x; + switch (x) { + case 'Created': + x = 'DateCreated'; + break; + case 'Accessed': + x = 'DateLastAccessed'; + break; + case 'Modified': + x = 'DateLastModified'; + break; + } + return `${label}\t${f[x]}\n`; + }; + + const fileDetailsString = (f: Scripting.File) => { + const keys: keys[] = ['Path', 'Name', 'Type', 'Attribs', 'Created', 'Accessed', 'Modified', 'Size']; + return keys.map(x => detailBuilder(f, x)).join(''); + }; + + const folderDetailsString = (f: Scripting.Folder) => { + const keys: keys[] = ['Path', 'Name', 'Attribs', 'Created', 'Accessed', 'Modified', 'Size']; + return keys.map(x => detailBuilder(f, x)).join(''); + }; + + const folderContentsString = (f: Scripting.Folder): string => { + const files = collectionToArray(f.Files); + const subfolders = collectionToArray(f.SubFolders); + return ` +Folder: ${f.Path} + +There ${files.length === 1 ? 'is 1 file' : `are ${files.length} files`} +${files.map(fileDetailsString).join('')} + +There ${subfolders.length === 1 ? 'is 1 subfolder' : `are ${subfolders.length} subfolders`} +${subfolders.map(folderDetailsString).join('')} +${subfolders.map(folderContentsString).join('')}` + .trim().replace(' ', '\t'); + }; + + const testDrive = 'C:\\'; + const testPath = 'C:\\test'; + const testfolderInfo = () => { + if (!fso.DriveExists(testDrive) || !fso.FolderExists(testPath)) { return ''; } + return folderContentsString(fso.GetFolder(testPath)); + }; + + const deleteTestFolder = () => { + // two ways to delete a file: + const filepathToDelete = `${testPath}\\LoremIpsum\\Paragraph1.txt`; + fso.DeleteFile(filepathToDelete); + // fso.GetFile(filepathToDelete).Delete(); + + // two ways to delete a folder: + fso.DeleteFolder(`${testPath}\\LoremIpsum`); + fso.GetFolder(testPath).Delete(); + }; + + const createLyrics = (folder: Scripting.Folder) => { + let stream = folder.CreateTextFile('Paragraph1.txt'); + stream.Write('Lorem Ipsum - Paragraph 1'); + stream.WriteBlankLines(1); + stream.WriteLine('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sem.'); + stream.WriteLine('Donec ante. Nulla facilisi. Phasellus interdum nulla a nunc. Morbi laoreet nunc.'); + stream.WriteBlankLines(2); + stream.Close(); + + stream = folder.CreateTextFile('Paragraph2.txt'); + stream.WriteLine('Lorem Ipsum - Paragraph 2'); + stream.WriteBlankLines(1); + stream.WriteLine('Nullam nulla quam, sollicitudin ut, lobortis ornare, tristique a, augue.'); + stream.WriteLine('Vestibulum sem felis, fermentum eu, volutpat eu, vulputate eget, elit. '); + stream.WriteBlankLines(2); + stream.Close(); + }; + + const getLyrics = () => { + const folderPath = `${testPath}\\LoremIpsum`; + let lyrics = ''; + + // One way to read from a file + let stream = fso.OpenTextFile(fso.BuildPath(folderPath, 'Paragraph1.txt')); + lyrics = stream.ReadAll() + '\n\n'; + stream.Close(); + + // Another way to read from a file + stream = fso.GetFile(fso.BuildPath(folderPath, 'Paragraph2.txt')).OpenAsTextStream(); + while (!stream.AtEndOfStream) { + lyrics += stream.ReadLine() + '\n'; + } + stream.Close(); + + return lyrics; + }; + + const buildTestFolder = () => { + // Bail out if the drive doesn't exists ... + if (!fso.DriveExists(testDrive)) { return false; } + // or the directory already exists + if (fso.FolderExists(testPath)) { return false; } + + const testFolder = fso.CreateFolder(testPath); + + const stream = fso.CreateTextFile(fso.BuildPath(testPath, 'readme.txt')); + stream.WriteLine('My sample text collection'); + stream.Close(); + + const subfolder = testFolder.SubFolders.Add('LoremIpsum'); + createLyrics(subfolder); + return true; + }; + + const echoLines = (linecount = 1) => new Array(linecount).forEach(() => WScript.Echo('')); + + if (!buildTestFolder()) { + WScript.Echo('Test directory already exists or cannot be created. Cannot continue.'); + } else { + drivesInfoReport(); + echoLines(2); + WScript.Echo(testfolderInfo()); + echoLines(2); + WScript.Echo(getLyrics()); + echoLines(2); + deleteTestFolder(); } - const attributeStrings: string[] = []; - if (attr & Scripting.FileAttribute.Directory) { attributeStrings.push('Directory'); } - if (attr & Scripting.FileAttribute.ReadOnly) { attributeStrings.push('Read-only'); } - if (attr & Scripting.FileAttribute.Hidden) { attributeStrings.push('Hidden'); } - if (attr & Scripting.FileAttribute.System) { attributeStrings.push('System'); } - if (attr & Scripting.FileAttribute.Volume) { attributeStrings.push('Volume'); } - if (attr & Scripting.FileAttribute.Archive) { attributeStrings.push('Archive'); } - if (attr & Scripting.FileAttribute.Alias) { attributeStrings.push('Alias'); } - if (attr & Scripting.FileAttribute.Compressed) { attributeStrings.push('Compressed'); } - return attributeStrings.join(','); } // source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx -function showFreeSpace(drvPath: string) { - const fso = new ActiveXObject('Scripting.FileSystemObject'); - const d = fso.GetDrive(fso.GetDriveName(drvPath)); - let s = `Drive ${drvPath} - `; - s += d.VolumeName + '
'; - s += `Free Space: ${d.FreeSpace / 1024} Kbytes`; - return (s); +{ + const showFreeSpace = (drvPath: string) => { + const d = fso.GetDrive(fso.GetDriveName(drvPath)); + let s = `Drive ${drvPath} - `; + s += d.VolumeName + '
'; + s += `Free Space: ${d.FreeSpace / 1024} Kbytes`; + return (s); + }; } // source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx -function getALine(filespec: string) { - const fso = new ActiveXObject('Scripting.FileSystemObject'); - const file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false); +{ + const getALine = (filespec: string) => { + const file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false); - let s = ''; - while (!file.AtEndOfLine) { - s += file.Read(1); - } - file.Close(); - return (s); + let s = ''; + while (!file.AtEndOfLine) { + s += file.Read(1); + } + file.Close(); + return (s); + }; +} + +// https://msdn.microsoft.com/en-us/library/ch28h2s7(v=vs.84).aspx +{ + const showDriveInfo = (path: string) => { + const bytesPerGB = 1024 * 1024 * 1024; + const drv = fso.GetDrive(fso.GetDriveName(path)); + const ret = + drv.IsReady ? + `${drv.Path} - ${drv.FreeSpace / bytesPerGB} GB free of ${drv.TotalSize / bytesPerGB} GB` : + 'Not ready'; + WScript.Echo(ret); + }; + + const showFolderInfo = () => { + const fldr = fso.GetFolder("c:\\"); + let ret = ` +Folder: ${fldr.Path} +Drive: ${fldr.Drive} +${fldr.IsRootFolder ? 'Is root folder' : `Parent folder: ${fldr.ParentFolder}`} + `.trim(); + + // Create and delete a folder. + const newFolderName = 'C:\\TempFolder1'; + fso.CreateFolder(newFolderName); + ret += `Base Name of Added Folder: ${fso.GetBaseName(newFolderName)}`; + fso.DeleteFolder(newFolderName); + + WScript.Echo(ret); + }; +} + +// https://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx +{ + const readFiles = () => { + const file = fso.CreateTextFile("c:\\testfile.txt", true); + + // Write a line. + WScript.Echo('Writing file'); + file.WriteLine("Hello World"); + file.WriteBlankLines(1); + file.Close(); + + // Read the contents of the file. + WScript.Echo('Reading file'); + const textStream = fso.OpenTextFile("c:\\testfile.txt", Scripting.IOMode.ForReading); + WScript.Echo(`File contents = "${textStream.ReadLine()}"`); + textStream.Close(); + }; + + const manipulateFiles = () => { + const file = fso.CreateTextFile("c:\\testfile.txt", true); + + WScript.Echo('Writing file'); + + // Write a line. + file.Write("This is a test."); + + // Close the file to writing. + file.Close(); + + WScript.Echo('Moving file to c:\\tmp'); + + // Get a handle to the file in root of C:\. + let file2 = fso.GetFile("c:\\testfile.txt"); + + // Move the file to \tmp directory. + file2.Move("c:\\tmp\\testfile.txt"); + + WScript.Echo('Copying file to c:\\temp
'); + + // Copy the file to \temp. + file2.Copy('c:\\temp\\testfile.txt'); + + WScript.Echo('Deleting files
'); + + // Get handles to files' current location. + file2 = fso.GetFile('c:\\tmp\\testfile.txt'); + const file3 = fso.GetFile('c:\\temp\\testfile.txt'); + + // Delete the files. + file2.Delete(); + file3.Delete(); + WScript.Echo('All done!'); + }; } diff --git a/types/activex-scripting/index.d.ts b/types/activex-scripting/index.d.ts index c4a64c54af..42e4f0c9e0 100644 --- a/types/activex-scripting/index.d.ts +++ b/types/activex-scripting/index.d.ts @@ -1,24 +1,28 @@ // Type definitions for Microsoft Scripting Runtime 1.0 -// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx +// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7(v=vs.84).aspx // Definitions by: Zev Spitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 declare namespace Scripting { + // tslint:disable-next-line:no-const-enum const enum CompareMethod { BinaryCompare = 0, DatabaseCompare = 2, - TextCompare = 1 + TextCompare = 1, } + // tslint:disable-next-line:no-const-enum const enum DriveTypeConst { CDRom = 4, Fixed = 2, RamDisk = 5, Remote = 3, Removable = 1, - UnknownType = 0 + UnknownType = 0, } + // tslint:disable-next-line:no-const-enum const enum FileAttribute { Alias = 1024, Archive = 32, @@ -28,38 +32,42 @@ declare namespace Scripting { Normal = 0, ReadOnly = 1, System = 4, - Volume = 8 + Volume = 8, } + // tslint:disable-next-line:no-const-enum const enum IOMode { ForAppending = 8, ForReading = 1, - ForWriting = 2 + ForWriting = 2, } + // tslint:disable-next-line:no-const-enum const enum SpecialFolderConst { SystemFolder = 1, TemporaryFolder = 2, - WindowsFolder = 0 + WindowsFolder = 0, } + // tslint:disable-next-line:no-const-enum const enum StandardStreamTypes { StdErr = 2, StdIn = 0, - StdOut = 1 + StdOut = 1, } + // tslint:disable-next-line:no-const-enum const enum Tristate { TristateFalse = 0, TristateMixed = -2, TristateTrue = -1, - TristateUseDefault = -2 + TristateUseDefault = -2, } /** Scripting.Dictionary */ - interface Dictionary { + interface Dictionary { /** Add a new key and item to the dictionary. */ - Add(Key: any, Item: any): void; + Add(Key: TKey, Item: TItem): void; /** Set or get the string comparison method. */ CompareMode: CompareMethod; @@ -68,32 +76,38 @@ declare namespace Scripting { readonly Count: number; /** Determine if a given key is in the dictionary. */ - Exists(Key: any): boolean; - HashVal(Key: any): any; + Exists(Key: TKey): boolean; + HashVal(Key: TKey): any; /** Set or get the item for a given key */ - Item(Key: any): any; + Item(Key: TKey): TItem; /** Get an array containing all items in the dictionary. */ - Items(): any; + Items(): SafeArray; /** Change a key to a different key. */ - Key(Key: any): any; + Key(Key: TKey): TKey; /** Get an array containing all keys in the dictionary. */ - Keys(): any; + Keys(): SafeArray; /** Remove a given key from the dictionary. */ - Remove(Key: any): void; + Remove(Key: TKey): void; /** Remove all information from the dictionary. */ RemoveAll(): void; + + /** Set or get the item for a given key */ + (Key: TKey): TItem; } /** Drive Object */ - interface Drive { + class Drive { + private constructor(); + private 'Scripting.Drive_typekey': Drive; + /** Get available space */ - readonly AvailableSpace: any; + readonly AvailableSpace: number; /** Drive letter */ readonly DriveLetter: string; @@ -105,7 +119,7 @@ declare namespace Scripting { readonly FileSystem: string; /** Get drive free space */ - readonly FreeSpace: any; + readonly FreeSpace: number; /** Check if disk is available */ readonly IsReady: boolean; @@ -123,7 +137,7 @@ declare namespace Scripting { readonly ShareName: string; /** Get total drive size */ - readonly TotalSize: any; + readonly TotalSize: number; /** Name of volume */ VolumeName: string; @@ -134,18 +148,27 @@ declare namespace Scripting { /** Number of drives */ readonly Count: number; - /** Get drive */ - Item(Key: any): Drive; + /** Get drive using the drive letter (`C`) or path (`C:\\`) */ + Item(Key: string): Drive; + + /** Get drive using the drive letter (`C`) or path (`C:\\`) */ + (Key: string): Drive; } /** Script Encoder Object */ interface Encoder { /** Call the Encoder determined by szExt, passing bstrStreamIn and optional arguments */ EncodeScriptFile(szExt: string, bstrStreamIn: string, cFlags: number, bstrDefaultLang: string): string; + + /** Call the Encoder determined by szExt, passing bstrStreamIn and optional arguments */ + (szExt: string, bstrStreamIn: string, cFlags: number, bstrDefaultLang: string): string; } /** File object */ - interface File { + class File { + private constructor(); + private 'Scripting.File_typekey': File; + /** File attributes */ Attributes: FileAttribute; @@ -166,7 +189,7 @@ declare namespace Scripting { /** * Delete this file - * @param boolean [Force=false] + * @param boolean [Force=false] Pass `true` to delete the file even if the read-only attribute is set */ Delete(Force?: boolean): void; @@ -199,7 +222,7 @@ declare namespace Scripting { readonly ShortPath: string; /** File size */ - readonly Size: any; + readonly Size: number; /** Type description */ readonly Type: string; @@ -210,12 +233,18 @@ declare namespace Scripting { /** Number of folders */ readonly Count: number; + /** Get file object using the name and extension of the file */ + Item(Key: string): File; + /** Get file */ - Item(Key: any): File; + (Key: string): File; } /** FileSystem Object */ - interface FileSystemObject { + class FileSystemObject { + private constructor(); + private 'Scripting.FileSystemObject_typekey': FileSystemObject; + /** Generate a path from an existing path and a name */ BuildPath(Path: string, Name: string): string; @@ -243,13 +272,13 @@ declare namespace Scripting { /** * Delete a file - * @param boolean [Force=false] + * @param boolean [Force=false] Pass `true` to also delete files with the read-only attribute set */ DeleteFile(FileSpec: string, Force?: boolean): void; /** * Delete a folder - * @param boolean [Force=false] + * @param boolean [Force=false] Pass `true` to also delete folders with the read-only attribute set */ DeleteFolder(FolderSpec: string, Force?: boolean): void; @@ -317,13 +346,16 @@ declare namespace Scripting { * Open a file as a TextStream * @param Scripting.IOMode [IOMode=1] * @param boolean [Create=false] - * @param Scripting.Tristate [Format=0] + * @param Scripting.Tristate [Format=0] **TristateTrue** opens the file as Unicode; **TristateFalse** opens the file as ASCII; **TristateUseDefault** opens the file with the system default */ OpenTextFile(FileName: string, IOMode?: IOMode, Create?: boolean, Format?: Tristate): TextStream; } /** Folder object */ - interface Folder { + class Folder { + private constructor(); + private 'Scripting.Folder_typekey': Folder; + /** Folder attributes */ Attributes: FileAttribute; @@ -351,7 +383,7 @@ declare namespace Scripting { /** * Delete this folder - * @param boolean [Force=false] + * @param boolean [Force=false] Pass `true` to delete the folder even if the read-only attribute set */ Delete(Force?: boolean): void; @@ -383,7 +415,7 @@ declare namespace Scripting { readonly ShortPath: string; /** Sum of files and subfolders */ - readonly Size: any; + readonly Size: number; /** Get folders collection */ readonly SubFolders: Folders; @@ -400,12 +432,18 @@ declare namespace Scripting { /** Number of folders */ readonly Count: number; - /** Get folder */ - Item(Key: any): Folder; + /** Get folder in collection using the folder's name */ + Item(Key: string): Folder; + + /** Get folder in collection using the folder's name */ + (Key: string): Folder; } /** TextStream object */ - interface TextStream { + class TextStream { + private constructor(); + private 'Scripting.TextStream_typekey': TextStream; + /** Is the current position at the end of a line? */ readonly AtEndOfLine: boolean; @@ -451,15 +489,12 @@ declare namespace Scripting { } interface ActiveXObject { + new (progid: K): ActiveXObjectNameMap[K]; set(obj: Scripting.Dictionary, propertyName: 'Item', parameterTypes: [any], newValue: any): void; - new(progid: 'Scripting.Dictionary'): Scripting.Dictionary; - new(progid: 'Scripting.Encoder'): Scripting.Encoder; - new(progid: 'Scripting.FileSystemObject'): Scripting.FileSystemObject; } -interface EnumeratorConstructor { - new(col: Scripting.Dictionary): any; - new(col: Scripting.Drives): Scripting.Drive; - new(col: Scripting.Files): Scripting.File; - new(col: Scripting.Folders): Scripting.Folder; +interface ActiveXObjectNameMap { + 'Scripting.Dictionary': Scripting.Dictionary; + 'Scripting.Encoder': Scripting.Encoder; + 'Scripting.FileSystemObject': Scripting.FileSystemObject; } diff --git a/types/activex-scripting/tslint.json b/types/activex-scripting/tslint.json index 2750cc0197..f93cf8562a 100644 --- a/types/activex-scripting/tslint.json +++ b/types/activex-scripting/tslint.json @@ -1 +1,3 @@ -{ "extends": "dtslint/dt.json" } \ No newline at end of file +{ + "extends": "dtslint/dt.json" +} diff --git a/types/activex-shdocvw/activex-shdocvw-tests.ts b/types/activex-shdocvw/activex-shdocvw-tests.ts new file mode 100644 index 0000000000..713578fb06 --- /dev/null +++ b/types/activex-shdocvw/activex-shdocvw-tests.ts @@ -0,0 +1,12 @@ +// https://msdn.microsoft.com/en-us/library/aa752044(v=vs.85).aspx +(() => { + const ie = new ActiveXObject('InternetExplorer.Application'); + ie.Navigate('http://contoso.com'); + ie.Visible = true; +})(); + +let obj1 = new ActiveXObject('ShellNameSpace.ShellNameSpace'); + +let obj2 = new ActiveXObject('Shell.UIHelper'); + +let obj3 = new ActiveXObject('Shell.Explorer'); diff --git a/types/activex-shdocvw/index.d.ts b/types/activex-shdocvw/index.d.ts new file mode 100644 index 0000000000..86568f6c5d --- /dev/null +++ b/types/activex-shdocvw/index.d.ts @@ -0,0 +1,1577 @@ +// Type definitions for Microsoft Internet Controls - SHDocVw 1.1 +// Project: https://msdn.microsoft.com/en-us/library/aa752040(v=vs.85).aspx +// Definitions by: Zev Spitz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +declare namespace SHDocVw { + // tslint:disable-next-line no-const-enum + const enum BrowserBarConstants { + AddressBar = 0x0009, + Tools = 0x000A, + Links = 0x000B, + Search = '{30D02401-6A81-11D0-8274-00C04FD5AE38}', + Favorites = '{EFA24E61-B078-11D0-89E4-00C04FC9E26E}', + History = '{EFA24E62-B078-11D0-89E4-00C04FC9E26E}', + Channels = '{EFA24E63-B078-11D0-89E4-00C04FC9E26E}' + } + + // tslint:disable-next-line no-const-enum + const enum BrowserNavConstants { + /** Open the resource or file in a new window. */ + OpenInNewWindow = 1, + + /** Do not add the resource or file to the history list. The new page replaces the current page in the list. */ + NoHistory = 2, + + /** If the navigation fails, the autosearch functionality attempts to navigate common root domains (.com, .edu, and so on). If this also fails, the URL is passed to a search engine. */ + AllowAutosearch = 16, + + /** Causes the current Explorer Bar to navigate to the given item, if possible. */ + BrowserBar = 32, + + /** + * Internet Explorer 6 for Windows XP SP2 and later. If the navigation fails when a hyperlink is being followed, this constant specifies that the resource should then be bound to the + * moniker using the [**BINDF_HYPERLINK**](https://msdn.microsoft.com/en-us/library/ms775130(v=vs.85).aspx) flag. + */ + Hyperlink = 64, + + /** Internet Explorer 6 for Windows XP SP2 and later. Force the URL into the restricted zone. */ + EnforceRestricted = 128, + + /** Internet Explorer 6 for Windows XP SP2 and later. Use the default Popup Manager to block pop-up windows. */ + NewWindowsManaged = 256, + + /** Internet Explorer 6 for Windows XP SP2 and later. Block files that normally trigger a file download dialog box. */ + UntrustedForDownload = 512, + + /** Internet Explorer 6 for Windows XP SP2 and later. Prompt for the installation of ActiveX controls. */ + TrustedForActiveX = 1024, + + /** Internet Explorer 7. Open the resource or file in a new tab. Allow the destination window to come to the foreground, if necessary. */ + OpenInNewTab = 2048, + + /** Internet Explorer 7. Open the resource or file in a new background tab; the currently active window and/or tab remains open on top. */ + OpenInBackgroundTab = 4096, + + /** + * Internet Explorer 7. Maintain state for dynamic navigation based on the filter string entered in the search band text box (wordwheel). Restore the wordwheel text when the navigation + * completes. + */ + KeepWordWheelText = 8192, + + /** + * Internet Explorer 8. Open the resource as a replacement for the current or target tab. The existing tab is closed while the new tab takes its place in the tab bar and replaces it in the + * tab group, if any. Browser history is copied forward to the new tab. On Windows Vista, this flag is implied if the navigation would cross integrity levels and **navOpenInNewTab**, + * **navOpenInBackgroundTab**, or **navOpenInNewWindow**> is not specified. + */ + VirtualTab = 16384, + + /** + * Internet Explorer 8. Block cross-domain redirect requests. The navigation triggers the + * [**DWebBrowserEvents2::RedirectXDomainBlocked**](https://msdn.microsoft.com/en-us/library/dd565686(v=vs.85).aspx) event if blocked. + */ + BlockRedirectsXDomain = 32768, + + /** Internet Explorer 8 and later. Open the resource in a new tab that becomes the foreground tab. */ + OpenNewForegroundTab = 65536 + } + + /** Constants for WebBrowser CommandStateChange */ + // tslint:disable-next-line no-const-enum + const enum CommandStateChangeConstants { + CSC_NAVIGATEBACK = 2, + CSC_NAVIGATEFORWARD = 1, + CSC_UPDATECOMMANDS = -1, + } + + /** Constants for WebBrowser NewProcess notification */ + // tslint:disable-next-line no-const-enum + const enum NewProcessCauseConstants { + ProtectedModeRedirect = 1, + } + + // tslint:disable-next-line no-const-enum + const enum OLECMDEXECOPT { + OLECMDEXECOPT_DODEFAULT = 0, + OLECMDEXECOPT_DONTPROMPTUSER = 2, + OLECMDEXECOPT_PROMPTUSER = 1, + OLECMDEXECOPT_SHOWHELP = 3, + } + + // tslint:disable-next-line no-const-enum + const enum OLECMDF { + OLECMDF_DEFHIDEONCTXTMENU = 32, + OLECMDF_ENABLED = 2, + OLECMDF_INVISIBLE = 16, + OLECMDF_LATCHED = 4, + OLECMDF_NINCHED = 8, + OLECMDF_SUPPORTED = 1, + } + + // tslint:disable-next-line no-const-enum + const enum OLECMDID { + OLECMDID_ACTIVEXINSTALLSCOPE = 66, + OLECMDID_ADDTRAVELENTRY = 60, + OLECMDID_ALLOWUILESSSAVEAS = 46, + OLECMDID_CLEARSELECTION = 18, + OLECMDID_CLOSE = 45, + OLECMDID_COPY = 12, + OLECMDID_CUT = 11, + OLECMDID_DELETE = 33, + OLECMDID_DONTDOWNLOADCSS = 47, + OLECMDID_ENABLE_INTERACTION = 36, + OLECMDID_ENABLE_VISIBILITY = 77, + OLECMDID_EXITFULLSCREEN = 81, + OLECMDID_FIND = 32, + OLECMDID_FOCUSVIEWCONTROLS = 57, + OLECMDID_FOCUSVIEWCONTROLSQUERY = 58, + OLECMDID_GETPRINTTEMPLATE = 52, + OLECMDID_GETUSERSCALABLE = 75, + OLECMDID_GETZOOMRANGE = 20, + OLECMDID_HIDETOOLBARS = 24, + OLECMDID_HTTPEQUIV = 34, + OLECMDID_HTTPEQUIV_DONE = 35, + OLECMDID_LAYOUT_VIEWPORT_WIDTH = 71, + OLECMDID_MEDIA_PLAYBACK = 78, + OLECMDID_NEW = 2, + OLECMDID_ONBEFOREUNLOAD = 83, + OLECMDID_ONTOOLBARACTIVATED = 31, + OLECMDID_ONUNLOAD = 37, + OLECMDID_OPEN = 1, + OLECMDID_OPTICAL_GETZOOMRANGE = 64, + OLECMDID_OPTICAL_ZOOM = 63, + OLECMDID_PAGEACTIONBLOCKED = 55, + OLECMDID_PAGEACTIONUIQUERY = 56, + OLECMDID_PAGEAVAILABLE = 74, + OLECMDID_PAGESETUP = 8, + OLECMDID_PASTE = 13, + OLECMDID_PASTESPECIAL = 14, + OLECMDID_POPSTATEEVENT = 69, + OLECMDID_PREREFRESH = 39, + OLECMDID_PRINT = 6, + OLECMDID_PRINT2 = 49, + OLECMDID_PRINTPREVIEW = 7, + OLECMDID_PRINTPREVIEW2 = 50, + OLECMDID_PROPERTIES = 10, + OLECMDID_PROPERTYBAG2 = 38, + OLECMDID_REDO = 16, + OLECMDID_REFRESH = 22, + OLECMDID_SAVE = 3, + OLECMDID_SAVEAS = 4, + OLECMDID_SAVECOPYAS = 5, + OLECMDID_SCROLLCOMPLETE = 82, + OLECMDID_SELECTALL = 17, + OLECMDID_SET_HOST_FULLSCREENMODE = 80, + OLECMDID_SETDOWNLOADSTATE = 29, + OLECMDID_SETFAVICON = 79, + OLECMDID_SETPRINTTEMPLATE = 51, + OLECMDID_SETPROGRESSMAX = 25, + OLECMDID_SETPROGRESSPOS = 26, + OLECMDID_SETPROGRESSTEXT = 27, + OLECMDID_SETTITLE = 28, + OLECMDID_SHOWFIND = 42, + OLECMDID_SHOWMESSAGE = 41, + OLECMDID_SHOWMESSAGE_BLOCKABLE = 84, + OLECMDID_SHOWPAGEACTIONMENU = 59, + OLECMDID_SHOWPAGESETUP = 43, + OLECMDID_SHOWPRINT = 44, + OLECMDID_SHOWSCRIPTERROR = 40, + OLECMDID_SHOWTASKDLG = 68, + OLECMDID_SHOWTASKDLG_BLOCKABLE = 85, + OLECMDID_SPELL = 9, + OLECMDID_STOP = 23, + OLECMDID_STOPDOWNLOAD = 30, + OLECMDID_UNDO = 15, + OLECMDID_UPDATE_CARET = 76, + OLECMDID_UPDATEBACKFORWARDSTATE = 62, + OLECMDID_UPDATECOMMANDS = 21, + OLECMDID_UPDATEPAGESTATUS = 48, + OLECMDID_UPDATETRAVELENTRY = 61, + OLECMDID_UPDATETRAVELENTRY_DATARECOVERY = 67, + OLECMDID_USER_OPTICAL_ZOOM = 73, + OLECMDID_VIEWPORT_MODE = 70, + OLECMDID_VISUAL_VIEWPORT_EXCLUDE_BOTTOM = 72, + OLECMDID_WINDOWSTATECHANGED = 65, + OLECMDID_ZOOM = 19, + } + + // tslint:disable-next-line no-const-enum + const enum RefreshConstants { + Normal = 0, + IfExpired = 1, + Completely = 3 + } + + /** Constants for WebBrowser security icon notification */ + // tslint:disable-next-line no-const-enum + const enum SecureLockIconConstants { + secureLockIconMixed = 1, + secureLockIconSecure128Bit = 6, + secureLockIconSecure40Bit = 3, + secureLockIconSecure56Bit = 4, + secureLockIconSecureFortezza = 5, + secureLockIconSecureUnknownBits = 2, + secureLockIconUnsecure = 0, + } + + /** Options for ShellWindows FindWindow */ + // tslint:disable-next-line no-const-enum + const enum ShellWindowFindWindowOptions { + SWFO_COOKIEPASSED = 4, + SWFO_INCLUDEPENDING = 2, + SWFO_NEEDDISPATCH = 1, + } + + /** Constants for ShellWindows registration */ + // tslint:disable-next-line no-const-enum + const enum ShellWindowTypeConstants { + SWC_3RDPARTY = 2, + SWC_BROWSER = 1, + SWC_CALLBACK = 4, + SWC_DESKTOP = 8, + SWC_EXPLORER = 0, + } + + // tslint:disable-next-line no-const-enum + const enum tagREADYSTATE { + READYSTATE_COMPLETE = 4, + READYSTATE_INTERACTIVE = 3, + READYSTATE_LOADED = 2, + READYSTATE_LOADING = 1, + READYSTATE_UNINITIALIZED = 0, + } + + type TargetFrameValues = '_blank' | '_parent' | '_self' | '_top' ; + + class CScriptErrorList { + private 'SHDocVw.CScriptErrorList_typekey': CScriptErrorList; + private constructor(); + advanceError(): void; + canAdvanceError(): number; + canRetreatError(): number; + getAlwaysShowLockState(): number; + getDetailsPaneOpen(): number; + getErrorChar(): number; + getErrorCode(): number; + getErrorLine(): number; + getErrorMsg(): string; + getErrorUrl(): string; + getPerErrorDisplay(): number; + retreatError(): void; + setDetailsPaneOpen(fDetailsPaneOpen: number): void; + setPerErrorDisplay(fPerErrorDisplay: number): void; + } + + /** Internet Explorer Application. */ + class InternetExplorer { + private 'SHDocVw.InternetExplorer_typekey': InternetExplorer; + private constructor(); + + /** Controls whether address bar is shown */ + AddressBar: boolean; + + /** Returns the application automation object if accessible, this automation object otherwise.. */ + readonly Application: any; + + /** Query to see if something is still in progress. */ + readonly Busy: boolean; + + /** Converts client sizes into window sizes. */ + ClientToWindow(pcx: number, pcy: number): void; + + /** Returns the container/parent automation object, if any. */ + readonly Container: any; + + /** Returns the active Document automation object, if any. */ + readonly Document: any; + + /** IOleCommandTarget::Exec */ + ExecWB(cmdID: OLECMDID, cmdexecopt: OLECMDEXECOPT, pvaIn?: any, pvaOut?: any): void; + + /** Returns file specification of the application, including path. */ + readonly FullName: string; + + /** Maximizes window and turns off statusbar, toolbar, menubar, and titlebar. */ + FullScreen: boolean; + + /** Retrieve the Associated value for the property vtValue in the context of the object. */ + GetProperty(Property: string): any; + + /** Navigates to the previous item in the history list. */ + GoBack(): void; + + /** Navigates to the next item in the history list. */ + GoForward(): void; + + /** Go home/start page. */ + GoHome(): void; + + /** Go Search Page. */ + GoSearch(): void; + + /** The vertical dimension (pixels) of the frame window/object. */ + Height: number; + + /** Returns the HWND of the current IE window. */ + readonly HWND: number; + + /** The horizontal position (pixels) of the frame window relative to the screen/container. */ + Left: number; + + /** Gets the short (UI-friendly) name of the URL/file currently viewed. */ + readonly LocationName: string; + + /** Gets the full URL/path currently viewed. */ + readonly LocationURL: string; + + /** Controls whether menubar is shown. */ + MenuBar: boolean; + + /** Returns name of the application. */ + readonly Name: string; + + /** Navigates to a URL or file. */ + Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void; + + /** Navigates to a URL or file or pidl. */ + Navigate2(URL: any, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void; + + /** Controls if the frame is offline (read from cache) */ + Offline: boolean; + + /** Returns the automation object of the container/parent if one exists or this automation object. */ + readonly Parent: any; + + /** Returns the path to the application. */ + readonly Path: string; + + /** Associates vtValue with the name szProperty in the context of the object. */ + PutProperty(Property: string, vtValue: any): void; + + /** IOleCommandTarget::QueryStatus */ + QueryStatusWB(cmdID: OLECMDID): OLECMDF; + + /** Exits application and closes the open document. */ + Quit(): void; + readonly ReadyState: tagREADYSTATE; + + /** Refresh the currently viewed page. */ + Refresh(): void; + + /** Refresh the currently viewed page. */ + Refresh2(Level?: RefreshConstants): void; + + /** Registers OC as a top-level browser (for target name resolution) */ + RegisterAsBrowser: boolean; + + /** Registers OC as a drop target for navigation */ + RegisterAsDropTarget: boolean; + + /** Controls whether the window is resizable */ + Resizable: boolean; + + /** Set BrowserBar to Clsid */ + ShowBrowserBar(pvaClsid: string | BrowserBarConstants, pvarShow?: boolean): void; + + /** Controls if any dialog boxes can be shown */ + Silent: boolean; + + /** Turn on or off the statusbar. */ + StatusBar: boolean; + + /** Text of Status window. */ + StatusText: string; + + /** Stops opening a file. */ + Stop(): void; + + /** Controls if the browser is in theater mode */ + TheaterMode: boolean; + + /** Controls which toolbar is shown. */ + ToolBar: number; + + /** The vertical position (pixels) of the frame window relative to the screen/container. */ + Top: number; + + /** Returns True if this is the top level object. */ + readonly TopLevelContainer: boolean; + + /** Returns the type of the contained document object. */ + readonly Type: string; + + /** Determines whether the application is visible or hidden. */ + Visible: boolean; + + /** The horizontal dimension (pixels) of the frame window/object. */ + Width: number; + } + + /** Internet Explorer Application with default integrity of Medium */ + class InternetExplorerMedium { + private 'SHDocVw.InternetExplorerMedium_typekey': InternetExplorerMedium; + private constructor(); + + /** Controls whether address bar is shown */ + AddressBar: boolean; + + /** Returns the application automation object if accessible, this automation object otherwise.. */ + readonly Application: any; + + /** Query to see if something is still in progress. */ + readonly Busy: boolean; + + /** Converts client sizes into window sizes. */ + ClientToWindow(pcx: number, pcy: number): void; + + /** Returns the container/parent automation object, if any. */ + readonly Container: any; + + /** Returns the active Document automation object, if any. */ + readonly Document: any; + + /** IOleCommandTarget::Exec */ + ExecWB(cmdID: OLECMDID, cmdexecopt: OLECMDEXECOPT, pvaIn?: any, pvaOut?: any): void; + + /** Returns file specification of the application, including path. */ + readonly FullName: string; + + /** Maximizes window and turns off statusbar, toolbar, menubar, and titlebar. */ + FullScreen: boolean; + + /** Retrieve the Associated value for the property vtValue in the context of the object. */ + GetProperty(Property: string): any; + + /** Navigates to the previous item in the history list. */ + GoBack(): void; + + /** Navigates to the next item in the history list. */ + GoForward(): void; + + /** Go home/start page. */ + GoHome(): void; + + /** Go Search Page. */ + GoSearch(): void; + + /** The vertical dimension (pixels) of the frame window/object. */ + Height: number; + + /** Returns the HWND of the current IE window. */ + readonly HWND: number; + + /** The horizontal position (pixels) of the frame window relative to the screen/container. */ + Left: number; + + /** Gets the short (UI-friendly) name of the URL/file currently viewed. */ + readonly LocationName: string; + + /** Gets the full URL/path currently viewed. */ + readonly LocationURL: string; + + /** Controls whether menubar is shown. */ + MenuBar: boolean; + + /** Returns name of the application. */ + readonly Name: string; + + /** Navigates to a URL or file. */ + Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void; + + /** Navigates to a URL or file or pidl. */ + Navigate2(URL: any, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void; + + /** Controls if the frame is offline (read from cache) */ + Offline: boolean; + + /** Returns the automation object of the container/parent if one exists or this automation object. */ + readonly Parent: any; + + /** Returns the path to the application. */ + readonly Path: string; + + /** Associates vtValue with the name szProperty in the context of the object. */ + PutProperty(Property: string, vtValue: any): void; + + /** IOleCommandTarget::QueryStatus */ + QueryStatusWB(cmdID: OLECMDID): OLECMDF; + + /** Exits application and closes the open document. */ + Quit(): void; + readonly ReadyState: tagREADYSTATE; + + /** Refresh the currently viewed page. */ + Refresh(): void; + + /** Refresh the currently viewed page. */ + Refresh2(Level?: RefreshConstants): void; + + /** Registers OC as a top-level browser (for target name resolution) */ + RegisterAsBrowser: boolean; + + /** Registers OC as a drop target for navigation */ + RegisterAsDropTarget: boolean; + + /** Controls whether the window is resizable */ + Resizable: boolean; + + /** Set BrowserBar to Clsid */ + ShowBrowserBar(pvaClsid: string | BrowserBarConstants, pvarShow?: boolean): void; + + /** Controls if any dialog boxes can be shown */ + Silent: boolean; + + /** Turn on or off the statusbar. */ + StatusBar: boolean; + + /** Text of Status window. */ + StatusText: string; + + /** Stops opening a file. */ + Stop(): void; + + /** Controls if the browser is in theater mode */ + TheaterMode: boolean; + + /** Controls which toolbar is shown. */ + ToolBar: number; + + /** The vertical position (pixels) of the frame window relative to the screen/container. */ + Top: number; + + /** Returns True if this is the top level object. */ + readonly TopLevelContainer: boolean; + + /** Returns the type of the contained document object. */ + readonly Type: string; + + /** Determines whether the application is visible or hidden. */ + Visible: boolean; + + /** The horizontal dimension (pixels) of the frame window/object. */ + Width: number; + } + + /** Shell Browser Window. */ + class ShellBrowserWindow { + private 'SHDocVw.ShellBrowserWindow_typekey': ShellBrowserWindow; + private constructor(); + + /** Controls whether address bar is shown */ + AddressBar: boolean; + + /** Returns the application automation object if accessible, this automation object otherwise.. */ + readonly Application: any; + + /** Query to see if something is still in progress. */ + readonly Busy: boolean; + + /** Converts client sizes into window sizes. */ + ClientToWindow(pcx: number, pcy: number): void; + + /** Returns the container/parent automation object, if any. */ + readonly Container: any; + + /** Returns the active Document automation object, if any. */ + readonly Document: any; + + /** IOleCommandTarget::Exec */ + ExecWB(cmdID: OLECMDID, cmdexecopt: OLECMDEXECOPT, pvaIn?: any, pvaOut?: any): void; + + /** Returns file specification of the application, including path. */ + readonly FullName: string; + + /** Maximizes window and turns off statusbar, toolbar, menubar, and titlebar. */ + FullScreen: boolean; + + /** Retrieve the Associated value for the property vtValue in the context of the object. */ + GetProperty(Property: string): any; + + /** Navigates to the previous item in the history list. */ + GoBack(): void; + + /** Navigates to the next item in the history list. */ + GoForward(): void; + + /** Go home/start page. */ + GoHome(): void; + + /** Go Search Page. */ + GoSearch(): void; + + /** The vertical dimension (pixels) of the frame window/object. */ + Height: number; + + /** Returns the HWND of the current IE window. */ + readonly HWND: number; + + /** The horizontal position (pixels) of the frame window relative to the screen/container. */ + Left: number; + + /** Gets the short (UI-friendly) name of the URL/file currently viewed. */ + readonly LocationName: string; + + /** Gets the full URL/path currently viewed. */ + readonly LocationURL: string; + + /** Controls whether menubar is shown. */ + MenuBar: boolean; + + /** Returns name of the application. */ + readonly Name: string; + + /** Navigates to a URL or file. */ + Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void; + + /** Navigates to a URL or file or pidl. */ + Navigate2(URL: any, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void; + + /** Controls if the frame is offline (read from cache) */ + Offline: boolean; + + /** Returns the automation object of the container/parent if one exists or this automation object. */ + readonly Parent: any; + + /** Returns the path to the application. */ + readonly Path: string; + + /** Associates vtValue with the name szProperty in the context of the object. */ + PutProperty(Property: string, vtValue: any): void; + + /** IOleCommandTarget::QueryStatus */ + QueryStatusWB(cmdID: OLECMDID): OLECMDF; + + /** Exits application and closes the open document. */ + Quit(): void; + readonly ReadyState: tagREADYSTATE; + + /** Refresh the currently viewed page. */ + Refresh(): void; + + /** Refresh the currently viewed page. */ + Refresh2(Level?: RefreshConstants): void; + + /** Registers OC as a top-level browser (for target name resolution) */ + RegisterAsBrowser: boolean; + + /** Registers OC as a drop target for navigation */ + RegisterAsDropTarget: boolean; + + /** Controls whether the window is resizable */ + Resizable: boolean; + + /** Set BrowserBar to Clsid */ + ShowBrowserBar(pvaClsid: string | BrowserBarConstants, pvarShow?: boolean): void; + + /** Controls if any dialog boxes can be shown */ + Silent: boolean; + + /** Turn on or off the statusbar. */ + StatusBar: boolean; + + /** Text of Status window. */ + StatusText: string; + + /** Stops opening a file. */ + Stop(): void; + + /** Controls if the browser is in theater mode */ + TheaterMode: boolean; + + /** Controls which toolbar is shown. */ + ToolBar: number; + + /** The vertical position (pixels) of the frame window relative to the screen/container. */ + Top: number; + + /** Returns True if this is the top level object. */ + readonly TopLevelContainer: boolean; + + /** Returns the type of the contained document object. */ + readonly Type: string; + + /** Determines whether the application is visible or hidden. */ + Visible: boolean; + + /** The horizontal dimension (pixels) of the frame window/object. */ + Width: number; + } + + class ShellNameSpace { + private 'SHDocVw.ShellNameSpace_typekey': ShellNameSpace; + private constructor(); + Columns: string; + + /** number of view types */ + readonly CountViewTypes: number; + + /** method CreateSubscriptionForSelection */ + CreateSubscriptionForSelection(): boolean; + + /** method DeleteSubscriptionForSelection */ + DeleteSubscriptionForSelection(): boolean; + Depth: number; + + /** options */ + EnumOptions: number; + + /** expands item specified depth */ + Expand(var_0: any, iDepth: number): void; + + /** method Export */ + Export(): void; + Flags: number; + + /** method Import */ + Import(): void; + + /** method InvokeContextMenuCommand */ + InvokeContextMenuCommand(strCommand: string): void; + Mode: number; + + /** method MoveSelectionDown */ + MoveSelectionDown(): void; + + /** method MoveSelectionTo */ + MoveSelectionTo(): void; + + /** method MoveSelectionUp */ + MoveSelectionUp(): void; + + /** method NewFolder */ + NewFolder(): void; + + /** method ResetSort */ + ResetSort(): void; + + /** get the root item */ + Root: any; + + /** get the selected item */ + SelectedItem: any; + + /** collection of selected items */ + SelectedItems(): any; + + /** old, use put_Root() instead */ + SetRoot(bstrFullPath: string): void; + + /** set view type */ + SetViewType(iType: number): void; + + /** Query to see if subscriptions are enabled */ + readonly SubscriptionsEnabled: boolean; + + /** method Synchronize */ + Synchronize(): void; + TVFlags: number; + + /** unselects all items */ + UnselectAll(): void; + } + + class ShellUIHelper { + private 'SHDocVw.ShellUIHelper_typekey': ShellUIHelper; + private constructor(); + AddChannel(URL: string): void; + AddDesktopComponent(URL: string, Type: string, Left?: any, Top?: any, Width?: any, Height?: any): void; + AddFavorite(URL: string, Title?: any): void; + AddSearchProvider(URL: string): void; + AddService(URL: string): void; + AddToFavoritesBar(URL: string, Title: string, Type?: any): void; + AutoCompleteAttach(Reserved?: any): void; + AutoCompleteSaveForm(Form?: any): void; + AutoScan(strSearch: string, strFailureUrl: string, pvarTargetFrame?: any): void; + BrandImageUri(): string; + BuildNewTabPage(): void; + ContentDiscoveryReset(): void; + CustomizeClearType(fSet: boolean): void; + CustomizeSettings(fSQM: boolean, fPhishing: boolean, bstrLocale: string): void; + DefaultSearchProvider(): string; + DiagnoseConnection(): void; + EnableSuggestedSites(fEnable: boolean): void; + GetCVListData(): string; + GetCVListLocalData(): string; + GetEMIEListData(): string; + GetEMIEListLocalData(): string; + GetExperimentalFlag(bstrFlagString: string): boolean; + GetExperimentalValue(bstrValueString: string): number; + GetNeedIEAutoLaunchFlag(bstrUrl: string): boolean; + HasNeedIEAutoLaunchFlag(bstrUrl: string): boolean; + ImportExportFavorites(fImport: boolean, strImpExpPath: string): void; + InPrivateFilteringEnabled(): boolean; + IsSearchMigrated(): boolean; + IsSearchProviderInstalled(URL: string): number; + IsServiceInstalled(URL: string, Verb: string): number; + IsSubscribed(URL: string): boolean; + IsSuggestedSitesEnabled(): boolean; + LaunchIE(bstrUrl: string, automated: boolean): void; + LaunchInHVSI(bstrUrl: string): void; + msActiveXFilteringEnabled(): boolean; + msAddSiteMode(): void; + msAddTrackingProtectionList(URL: string, bstrFilterName: string): void; + msChangeDefaultBrowser(fChange: boolean): void; + msClearTile(): void; + msDiagnoseConnectionUILess(): void; + msEnableTileNotificationQueue(fChange: boolean): void; + msEnableTileNotificationQueueForSquare150x150(fChange: boolean): void; + msEnableTileNotificationQueueForSquare310x310(fChange: boolean): void; + msEnableTileNotificationQueueForWide310x150(fChange: boolean): void; + msIsSiteMode(): boolean; + msIsSiteModeFirstRun(fPreserveState: boolean): any; + msLaunchInternetOptions(): void; + msLaunchNetworkClientHelp(): void; + msPinnedSiteState(): any; + msProvisionNetworks(bstrProvisioningXml: string): any; + msRemoveScheduledTileNotification(bstrNotificationId: string): void; + msReportSafeUrl(): void; + msScheduledTileNotification(bstrNotificationXml: string, bstrNotificationId: string, bstrNotificationTag: string, startTime?: any, expirationTime?: any): void; + msSiteModeActivate(): void; + msSiteModeAddButtonStyle(uiButtonID: any, bstrIconURL: string, bstrTooltip: string): any; + msSiteModeAddJumpListItem(bstrName: string, bstrActionUri: string, bstrIconUri: string, pvarWindowType?: any): void; + msSiteModeAddThumbBarButton(bstrIconURL: string, bstrTooltip: string): any; + msSiteModeClearBadge(): void; + msSiteModeClearIconOverlay(): void; + msSiteModeClearJumpList(): void; + msSiteModeCreateJumpList(bstrHeader: string): void; + msSiteModeRefreshBadge(): void; + msSiteModeSetIconOverlay(IconUrl: string, pvarDescription?: any): void; + msSiteModeShowButtonStyle(uiButtonID: any, uiStyleID: any): void; + msSiteModeShowJumpList(): void; + msSiteModeShowThumbBar(): void; + msSiteModeUpdateThumbBarButton(ButtonID: any, fEnabled: boolean, fVisible: boolean): void; + msStartPeriodicBadgeUpdate(pollingUri: string, startTime?: any, uiUpdateRecurrence?: any): void; + msStartPeriodicTileUpdate(pollingUris: any, startTime?: any, uiUpdateRecurrence?: any): void; + msStartPeriodicTileUpdateBatch(pollingUris: any, startTime?: any, uiUpdateRecurrence?: any): void; + msStopPeriodicBadgeUpdate(): void; + msStopPeriodicTileUpdate(): void; + msTrackingProtectionEnabled(): boolean; + NavigateAndFind(URL: string, strQuery: string, varTargetFrame: any): void; + NavigateToSuggestedSites(bstrRelativeUrl: string): void; + OpenFavoritesPane(): void; + OpenFavoritesSettings(): void; + PhishingEnabled(): boolean; + RefreshOfflineDesktop(): void; + ResetAllExperimentalFlagsAndValues(): void; + ResetFirstBootMode(): void; + ResetSafeMode(): void; + RunOnceHasShown(): boolean; + RunOnceRequiredSettingsComplete(fComplete: boolean): void; + RunOnceShown(): void; + SearchGuideUrl(): string; + SetActivitiesVisible(fVisible: boolean): void; + SetExperimentalFlag(bstrFlagString: string, vfFlag: boolean): void; + SetExperimentalValue(bstrValueString: string, dwValue: number): void; + SetNeedIEAutoLaunchFlag(bstrUrl: string, flag: boolean): void; + SetRecentlyClosedVisible(fVisible: boolean): void; + ShowBrowserUI(bstrName: string, pvarIn: any): any; + ShowInPrivateHelp(): void; + ShowTabsHelp(): void; + SkipRunOnce(): void; + SkipTabsWelcome(): void; + SqmEnabled(): boolean; + } + + /** ShellDispatch Load in Shell Context */ + class ShellWindows { + private 'SHDocVw.ShellWindows_typekey': ShellWindows; + private constructor(); + + /** Get count of open Shell windows */ + readonly Count: number; + + /** Find the window based on the location */ + FindWindowSW(pvarloc: any, pvarlocRoot: any, swClass: number, pHWND: number, swfwOptions: number): any; + + /** Return the shell window for the given index */ + Item(index?: any): any; + + /** Notifies the activation */ + OnActivated(lCookie: number, fActive: boolean): void; + + /** Notifies on creation and frame name set */ + OnCreated(lCookie: number, punk: any): void; + + /** Notifies the new location */ + OnNavigate(lCookie: number, pvarloc: any): void; + + /** Used by IExplore to register different processes */ + ProcessAttachDetach(fAttach: boolean): void; + + /** Register a window with the list */ + Register(pid: any, HWND: number, swClass: number, plCookie: number): void; + + /** Register a pending open with the list */ + RegisterPending(lThreadId: number, pvarloc: any, pvarlocRoot: any, swClass: number, plCookie: number): void; + + /** Remove a window from the list */ + Revoke(lCookie: number): void; + } + + /** WebBrowser Control */ + class WebBrowser { + private 'SHDocVw.WebBrowser_typekey': WebBrowser; + private constructor(); + + /** Controls whether address bar is shown (ignored by WebBrowser) */ + AddressBar: boolean; + + /** Returns the application automation object if accessible, this automation object otherwise.. */ + readonly Application: any; + + /** Query to see if something is still in progress. */ + readonly Busy: boolean; + + /** Converts client sizes into window sizes. */ + ClientToWindow(pcx: number, pcy: number): void; + + /** Returns the container/parent automation object, if any. */ + readonly Container: any; + + /** Returns the active Document automation object, if any. */ + readonly Document: any; + + /** IOleCommandTarget::Exec */ + ExecWB(cmdID: OLECMDID, cmdexecopt: OLECMDEXECOPT, pvaIn?: any, pvaOut?: any): void; + + /** Returns file specification of the application, including path. */ + readonly FullName: string; + + /** Maximizes window and turns off statusbar, toolbar, menubar, and titlebar. */ + FullScreen: boolean; + + /** Retrieve the Associated value for the property vtValue in the context of the object. */ + GetProperty(Property: string): any; + + /** Navigates to the previous item in the history list. */ + GoBack(): void; + + /** Navigates to the next item in the history list. */ + GoForward(): void; + + /** Go home/start page. */ + GoHome(): void; + + /** Go Search Page. */ + GoSearch(): void; + + /** The vertical dimension (pixels) of the frame window/object. */ + Height: number; + + /** Returns the HWND of the current IE window. */ + readonly HWND: number; + + /** The horizontal position (pixels) of the frame window relative to the screen/container. */ + Left: number; + + /** Gets the short (UI-friendly) name of the URL/file currently viewed. */ + readonly LocationName: string; + + /** Gets the full URL/path currently viewed. */ + readonly LocationURL: string; + + /** Controls whether menubar is shown. */ + MenuBar: boolean; + + /** Returns name of the application. */ + readonly Name: string; + + /** Navigates to a URL or file. */ + Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void; + + /** Navigates to a URL or file or pidl. */ + Navigate2(URL: any, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void; + + /** Controls if the frame is offline (read from cache) */ + Offline: boolean; + + /** Returns the automation object of the container/parent if one exists or this automation object. */ + readonly Parent: any; + + /** Returns the path to the application. */ + readonly Path: string; + + /** Associates vtValue with the name szProperty in the context of the object. */ + PutProperty(Property: string, vtValue: any): void; + + /** IOleCommandTarget::QueryStatus */ + QueryStatusWB(cmdID: OLECMDID): OLECMDF; + + /** Exits application and closes the open document. */ + Quit(): void; + readonly ReadyState: tagREADYSTATE; + + /** Refresh the currently viewed page. */ + Refresh(): void; + + /** Refresh the currently viewed page. */ + Refresh2(Level?: RefreshConstants): void; + + /** Registers OC as a top-level browser (for target name resolution) */ + RegisterAsBrowser: boolean; + + /** Registers OC as a drop target for navigation */ + RegisterAsDropTarget: boolean; + + /** Controls whether the window is resizable */ + Resizable: boolean; + + /** Set BrowserBar to Clsid */ + ShowBrowserBar(pvaClsid: string | BrowserBarConstants, pvarShow?: boolean): void; + + /** Controls if any dialog boxes can be shown */ + Silent: boolean; + + /** Turn on or off the statusbar. */ + StatusBar: boolean; + + /** Text of Status window. */ + StatusText: string; + + /** Stops opening a file. */ + Stop(): void; + + /** Controls if the browser is in theater mode */ + TheaterMode: boolean; + + /** Controls which toolbar is shown. */ + ToolBar: number; + + /** The vertical position (pixels) of the frame window relative to the screen/container. */ + Top: number; + + /** Returns True if this is the top level object. */ + readonly TopLevelContainer: boolean; + + /** Returns the type of the contained document object. */ + readonly Type: string; + + /** Determines whether the application is visible or hidden. */ + Visible: boolean; + + /** The horizontal dimension (pixels) of the frame window/object. */ + Width: number; + } + + /** WebBrowser Control */ + class WebBrowser_V1 { + private 'SHDocVw.WebBrowser_V1_typekey': WebBrowser_V1; + private constructor(); + + /** Returns the application automation object if accessible, this automation object otherwise.. */ + readonly Application: any; + + /** Query to see if something is still in progress. */ + readonly Busy: boolean; + + /** Returns the container/parent automation object, if any. */ + readonly Container: any; + + /** Returns the active Document automation object, if any. */ + readonly Document: any; + + /** Navigates to the previous item in the history list. */ + GoBack(): void; + + /** Navigates to the next item in the history list. */ + GoForward(): void; + + /** Go home/start page. */ + GoHome(): void; + + /** Go Search Page. */ + GoSearch(): void; + + /** The vertical dimension (pixels) of the frame window/object. */ + Height: number; + + /** The horizontal position (pixels) of the frame window relative to the screen/container. */ + Left: number; + + /** Gets the short (UI-friendly) name of the URL/file currently viewed. */ + readonly LocationName: string; + + /** Gets the full URL/path currently viewed. */ + readonly LocationURL: string; + + /** Navigates to a URL or file. */ + Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void; + + /** Returns the automation object of the container/parent if one exists or this automation object. */ + readonly Parent: any; + + /** Refresh the currently viewed page. */ + Refresh(): void; + + /** Refresh the currently viewed page. */ + Refresh2(Level?: RefreshConstants): void; + + /** Stops opening a file. */ + Stop(): void; + + /** The vertical position (pixels) of the frame window relative to the screen/container. */ + Top: number; + + /** Returns True if this is the top level object. */ + readonly TopLevelContainer: boolean; + + /** Returns the type of the contained document object. */ + readonly Type: string; + + /** The horizontal dimension (pixels) of the frame window/object. */ + Width: number; + } + + namespace EventHelperTypes { + type InternetExplorer_BeforeNavigate2_ArgNames = ['pDisp', 'URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel']; + + type InternetExplorerMedium_BeforeNavigate2_ArgNames = ['pDisp', 'URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel']; + + type ShellBrowserWindow_BeforeNavigate2_ArgNames = ['pDisp', 'URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel']; + + type ShellNameSpace_FavoritesSelectionChange_ArgNames = ['cItems', 'hItem', 'strName', 'strUrl', 'cVisits', 'strDate', 'fAvailableOffline']; + + type WebBrowser_BeforeNavigate2_ArgNames = ['pDisp', 'URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel']; + + type WebBrowser_V1_BeforeNavigate_ArgNames = ['URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel']; + + type WebBrowser_V1_FrameBeforeNavigate_ArgNames = ['URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel']; + + type WebBrowser_V1_FrameNewWindow_ArgNames = ['URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Processed']; + + type WebBrowser_V1_NewWindow_ArgNames = ['URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Processed']; + + interface InternetExplorer_BeforeNavigate2_Parameter { + Cancel: boolean; + readonly Flags: any; + readonly Headers: any; + readonly pDisp: any; + readonly PostData: any; + readonly TargetFrameName: any; + readonly URL: any; + } + + interface InternetExplorerMedium_BeforeNavigate2_Parameter { + Cancel: boolean; + readonly Flags: any; + readonly Headers: any; + readonly pDisp: any; + readonly PostData: any; + readonly TargetFrameName: any; + readonly URL: any; + } + + interface ShellBrowserWindow_BeforeNavigate2_Parameter { + Cancel: boolean; + readonly Flags: any; + readonly Headers: any; + readonly pDisp: any; + readonly PostData: any; + readonly TargetFrameName: any; + readonly URL: any; + } + + interface ShellNameSpace_FavoritesSelectionChange_Parameter { + readonly cItems: number; + readonly cVisits: number; + readonly fAvailableOffline: number; + readonly hItem: number; + readonly strDate: string; + readonly strName: string; + readonly strUrl: string; + } + + interface WebBrowser_BeforeNavigate2_Parameter { + Cancel: boolean; + readonly Flags: any; + readonly Headers: any; + readonly pDisp: any; + readonly PostData: any; + readonly TargetFrameName: any; + readonly URL: any; + } + + interface WebBrowser_V1_BeforeNavigate_Parameter { + Cancel: boolean; + readonly Flags: number; + readonly Headers: string; + readonly PostData: any; + readonly TargetFrameName: string; + readonly URL: string; + } + + interface WebBrowser_V1_FrameBeforeNavigate_Parameter { + Cancel: boolean; + readonly Flags: number; + readonly Headers: string; + readonly PostData: any; + readonly TargetFrameName: string; + readonly URL: string; + } + + interface WebBrowser_V1_FrameNewWindow_Parameter { + readonly Flags: number; + readonly Headers: string; + readonly PostData: any; + Processed: boolean; + readonly TargetFrameName: string; + readonly URL: string; + } + + interface WebBrowser_V1_NewWindow_Parameter { + readonly Flags: number; + readonly Headers: string; + readonly PostData: any; + Processed: boolean; + readonly TargetFrameName: string; + readonly URL: string; + } + } +} + +interface ActiveXObject { + on( + obj: SHDocVw.InternetExplorer, event: 'BeforeNavigate2', argNames: SHDocVw.EventHelperTypes.InternetExplorer_BeforeNavigate2_ArgNames, + handler: (this: SHDocVw.InternetExplorer, parameter: SHDocVw.EventHelperTypes.InternetExplorer_BeforeNavigate2_Parameter) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'BeforeScriptExecute', argNames: ['pDispWindow'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly pDispWindow: any }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'ClientToHostWindow', argNames: ['CX', 'CY'], handler: (this: SHDocVw.InternetExplorer, parameter: { CX: number, CY: number }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'DocumentComplete' | 'NavigateComplete2', argNames: ['pDisp', 'URL'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any, readonly URL: any }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'FileDownload', argNames: ['ActiveDocument', 'Cancel'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly ActiveDocument: boolean, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'NavigateError', argNames: ['pDisp', 'URL', 'Frame', 'StatusCode', 'Cancel'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any, readonly URL: any, readonly Frame: any, readonly StatusCode: any, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'NewProcess', argNames: ['lCauseFlag', 'pWB2', 'Cancel'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly lCauseFlag: number, readonly pWB2: any, Cancel: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'NewWindow2', argNames: ['ppDisp', 'Cancel'], handler: (this: SHDocVw.InternetExplorer, parameter: { ppDisp: any, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'NewWindow3', argNames: ['ppDisp', 'Cancel', 'dwFlags', 'bstrUrlContext', 'bstrUrl'], + handler: (this: SHDocVw.InternetExplorer, parameter: { ppDisp: any, Cancel: boolean, readonly dwFlags: number, readonly bstrUrlContext: string, readonly bstrUrl: string }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'OnFullScreen', argNames: ['FullScreen'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly FullScreen: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'OnMenuBar', argNames: ['MenuBar'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly MenuBar: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'OnStatusBar', argNames: ['StatusBar'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly StatusBar: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'OnTheaterMode', argNames: ['TheaterMode'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly TheaterMode: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'OnToolBar', argNames: ['ToolBar'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly ToolBar: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'OnVisible', argNames: ['Visible'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Visible: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'PrintTemplateInstantiation' | 'PrintTemplateTeardown', argNames: ['pDisp'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'PrivacyImpactedStateChange', argNames: ['bImpacted'], handler: (this: SHDocVw.InternetExplorer, + parameter: { readonly bImpacted: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'PropertyChange', argNames: ['szProperty'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly szProperty: string }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'RedirectXDomainBlocked', argNames: ['pDisp', 'StartURL', 'RedirectURL', 'Frame', 'StatusCode'], + handler: (this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any, readonly StartURL: any, readonly RedirectURL: any, readonly Frame: any, readonly StatusCode: any }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'SetPhishingFilterStatus', argNames: ['PhishingFilterStatus'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly PhishingFilterStatus: number }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'SetSecureLockIcon', argNames: ['SecureLockIcon'], handler: (this: SHDocVw.InternetExplorer, + parameter: { readonly SecureLockIcon: number }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Text: string }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'ThirdPartyUrlBlocked', argNames: ['URL', 'dwCount'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly URL: any, readonly dwCount: number }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'UpdatePageStatus', argNames: ['pDisp', 'nPage', 'fDone'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any, readonly nPage: any, readonly fDone: any }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'WebWorkerFinsihed', argNames: ['dwUniqueID'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly dwUniqueID: number }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'WebWorkerStarted', argNames: ['dwUniqueID', 'bstrWorkerLabel'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly dwUniqueID: number, readonly bstrWorkerLabel: string }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'WindowClosing', argNames: ['IsChildWindow', 'Cancel'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly IsChildWindow: boolean, Cancel: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'WindowSetHeight', argNames: ['Height'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Height: number }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'WindowSetLeft', argNames: ['Left'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Left: number }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'WindowSetResizable', argNames: ['Resizable'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Resizable: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'WindowSetTop', argNames: ['Top'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Top: number }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'WindowSetWidth', argNames: ['Width'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Width: number }) => void): void; + on( + obj: SHDocVw.InternetExplorer, event: 'WindowStateChanged', argNames: ['dwWindowStateFlags', 'dwValidFlagsMask'], handler: ( + this: SHDocVw.InternetExplorer, parameter: { readonly dwWindowStateFlags: number, readonly dwValidFlagsMask: number }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'BeforeNavigate2', argNames: SHDocVw.EventHelperTypes.InternetExplorerMedium_BeforeNavigate2_ArgNames, + handler: (this: SHDocVw.InternetExplorerMedium, parameter: SHDocVw.EventHelperTypes.InternetExplorerMedium_BeforeNavigate2_Parameter) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'BeforeScriptExecute', argNames: ['pDispWindow'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDispWindow: any }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'ClientToHostWindow', argNames: ['CX', 'CY'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { CX: number, CY: number }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'DocumentComplete' | 'NavigateComplete2', argNames: ['pDisp', 'URL'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any, readonly URL: any }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'FileDownload', argNames: ['ActiveDocument', 'Cancel'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly ActiveDocument: boolean, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'NavigateError', argNames: ['pDisp', 'URL', 'Frame', 'StatusCode', 'Cancel'], + handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any, readonly URL: any, readonly Frame: any, readonly StatusCode: any, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'NewProcess', argNames: ['lCauseFlag', 'pWB2', 'Cancel'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly lCauseFlag: number, readonly pWB2: any, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'NewWindow2', argNames: ['ppDisp', 'Cancel'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { ppDisp: any, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'NewWindow3', argNames: ['ppDisp', 'Cancel', 'dwFlags', 'bstrUrlContext', 'bstrUrl'], + handler: (this: SHDocVw.InternetExplorerMedium, parameter: { + ppDisp: any, Cancel: boolean, readonly dwFlags: number, readonly bstrUrlContext: string, + readonly bstrUrl: string + }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'OnFullScreen', argNames: ['FullScreen'], handler: (this: SHDocVw.InternetExplorerMedium, + parameter: { readonly FullScreen: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'OnMenuBar', argNames: ['MenuBar'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly MenuBar: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'OnStatusBar', argNames: ['StatusBar'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly StatusBar: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'OnTheaterMode', argNames: ['TheaterMode'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly TheaterMode: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'OnToolBar', argNames: ['ToolBar'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly ToolBar: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'OnVisible', argNames: ['Visible'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Visible: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'PrintTemplateInstantiation' | 'PrintTemplateTeardown', argNames: ['pDisp'], + handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'PrivacyImpactedStateChange', argNames: ['bImpacted'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly bImpacted: boolean }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'PropertyChange', argNames: ['szProperty'], handler: (this: SHDocVw.InternetExplorerMedium, + parameter: { readonly szProperty: string }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'RedirectXDomainBlocked', argNames: ['pDisp', 'StartURL', 'RedirectURL', 'Frame', 'StatusCode'], + handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any, readonly StartURL: any, readonly RedirectURL: any, readonly Frame: any, readonly StatusCode: any }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'SetPhishingFilterStatus', argNames: ['PhishingFilterStatus'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly PhishingFilterStatus: number }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'SetSecureLockIcon', argNames: ['SecureLockIcon'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly SecureLockIcon: number }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly Text: string }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'ThirdPartyUrlBlocked', argNames: ['URL', 'dwCount'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly URL: any, readonly dwCount: number }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'UpdatePageStatus', argNames: ['pDisp', 'nPage', 'fDone'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any, readonly nPage: any, readonly fDone: any }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'WebWorkerFinsihed', argNames: ['dwUniqueID'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly dwUniqueID: number }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'WebWorkerStarted', argNames: ['dwUniqueID', 'bstrWorkerLabel'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly dwUniqueID: number, readonly bstrWorkerLabel: string }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'WindowClosing', argNames: ['IsChildWindow', 'Cancel'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly IsChildWindow: boolean, Cancel: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetHeight', argNames: ['Height'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Height: number }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetLeft', argNames: ['Left'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Left: number }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetResizable', argNames: ['Resizable'], handler: ( + this: SHDocVw.InternetExplorerMedium, parameter: { readonly Resizable: boolean }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetTop', argNames: ['Top'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Top: number }) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetWidth', argNames: ['Width'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Width: number }) => void): void; + on( + obj: SHDocVw.InternetExplorerMedium, event: 'WindowStateChanged', argNames: ['dwWindowStateFlags', 'dwValidFlagsMask'], + handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly dwWindowStateFlags: number, readonly dwValidFlagsMask: number }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'BeforeNavigate2', argNames: SHDocVw.EventHelperTypes.ShellBrowserWindow_BeforeNavigate2_ArgNames, + handler: (this: SHDocVw.ShellBrowserWindow, parameter: SHDocVw.EventHelperTypes.ShellBrowserWindow_BeforeNavigate2_Parameter) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'BeforeScriptExecute', argNames: ['pDispWindow'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDispWindow: any }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'ClientToHostWindow', argNames: ['CX', 'CY'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { CX: number, CY: number }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'DocumentComplete' | 'NavigateComplete2', argNames: ['pDisp', 'URL'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDisp: any, readonly URL: any }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'FileDownload', argNames: ['ActiveDocument', 'Cancel'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly ActiveDocument: boolean, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'NavigateError', argNames: ['pDisp', 'URL', 'Frame', 'StatusCode', 'Cancel'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDisp: any, readonly URL: any, readonly Frame: any, readonly StatusCode: any, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'NewProcess', argNames: ['lCauseFlag', 'pWB2', 'Cancel'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly lCauseFlag: number, readonly pWB2: any, Cancel: boolean }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'NewWindow2', argNames: ['ppDisp', 'Cancel'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { ppDisp: any, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'NewWindow3', argNames: ['ppDisp', 'Cancel', 'dwFlags', 'bstrUrlContext', 'bstrUrl'], + handler: (this: SHDocVw.ShellBrowserWindow, parameter: { ppDisp: any, Cancel: boolean, readonly dwFlags: number, readonly bstrUrlContext: string, readonly bstrUrl: string }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'OnFullScreen', argNames: ['FullScreen'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly FullScreen: boolean }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'OnMenuBar', argNames: ['MenuBar'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly MenuBar: boolean }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'OnStatusBar', argNames: ['StatusBar'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly StatusBar: boolean }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'OnTheaterMode', argNames: ['TheaterMode'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly TheaterMode: boolean }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'OnToolBar', argNames: ['ToolBar'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly ToolBar: boolean }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'OnVisible', argNames: ['Visible'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Visible: boolean }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'PrintTemplateInstantiation' | 'PrintTemplateTeardown', argNames: ['pDisp'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDisp: any }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'PrivacyImpactedStateChange', argNames: ['bImpacted'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly bImpacted: boolean }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'PropertyChange', argNames: ['szProperty'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly szProperty: string }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'RedirectXDomainBlocked', argNames: ['pDisp', 'StartURL', 'RedirectURL', 'Frame', 'StatusCode'], + handler: (this: SHDocVw.ShellBrowserWindow, parameter: { + readonly pDisp: any, readonly StartURL: any, readonly RedirectURL: any, readonly Frame: any, + readonly StatusCode: any + }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'SetPhishingFilterStatus', argNames: ['PhishingFilterStatus'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly PhishingFilterStatus: number }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'SetSecureLockIcon', argNames: ['SecureLockIcon'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly SecureLockIcon: number }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Text: string }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'ThirdPartyUrlBlocked', argNames: ['URL', 'dwCount'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly URL: any, readonly dwCount: number }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'UpdatePageStatus', argNames: ['pDisp', 'nPage', 'fDone'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDisp: any, readonly nPage: any, readonly fDone: any }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'WebWorkerFinsihed', argNames: ['dwUniqueID'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly dwUniqueID: number }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'WebWorkerStarted', argNames: ['dwUniqueID', 'bstrWorkerLabel'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly dwUniqueID: number, readonly bstrWorkerLabel: string }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'WindowClosing', argNames: ['IsChildWindow', 'Cancel'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly IsChildWindow: boolean, Cancel: boolean }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetHeight', argNames: ['Height'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Height: number }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetLeft', argNames: ['Left'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Left: number }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetResizable', argNames: ['Resizable'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Resizable: boolean }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetTop', argNames: ['Top'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Top: number }) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetWidth', argNames: ['Width'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Width: number }) => void): void; + on( + obj: SHDocVw.ShellBrowserWindow, event: 'WindowStateChanged', argNames: ['dwWindowStateFlags', 'dwValidFlagsMask'], handler: ( + this: SHDocVw.ShellBrowserWindow, parameter: { readonly dwWindowStateFlags: number, readonly dwValidFlagsMask: number }) => void): void; + on( + obj: SHDocVw.ShellNameSpace, event: 'FavoritesSelectionChange', argNames: SHDocVw.EventHelperTypes.ShellNameSpace_FavoritesSelectionChange_ArgNames, + handler: (this: SHDocVw.ShellNameSpace, parameter: SHDocVw.EventHelperTypes.ShellNameSpace_FavoritesSelectionChange_Parameter) => void): void; + on(obj: SHDocVw.ShellWindows, event: 'WindowRegistered' | 'WindowRevoked', argNames: ['lCookie'], handler: (this: SHDocVw.ShellWindows, parameter: { readonly lCookie: number }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'BeforeNavigate2', argNames: SHDocVw.EventHelperTypes.WebBrowser_BeforeNavigate2_ArgNames, handler: ( + this: SHDocVw.WebBrowser, parameter: SHDocVw.EventHelperTypes.WebBrowser_BeforeNavigate2_Parameter) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'BeforeScriptExecute', argNames: ['pDispWindow'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly pDispWindow: any }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'ClientToHostWindow', argNames: ['CX', 'CY'], handler: (this: SHDocVw.WebBrowser, parameter: { CX: number, CY: number }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'DocumentComplete' | 'NavigateComplete2', argNames: ['pDisp', 'URL'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any, readonly URL: any }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'FileDownload', argNames: ['ActiveDocument', 'Cancel'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly ActiveDocument: boolean, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'NavigateError', argNames: ['pDisp', 'URL', 'Frame', 'StatusCode', 'Cancel'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any, readonly URL: any, readonly Frame: any, readonly StatusCode: any, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'NewProcess', argNames: ['lCauseFlag', 'pWB2', 'Cancel'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly lCauseFlag: number, readonly pWB2: any, Cancel: boolean }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'NewWindow2', argNames: ['ppDisp', 'Cancel'], handler: (this: SHDocVw.WebBrowser, parameter: { ppDisp: any, Cancel: boolean }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'NewWindow3', argNames: ['ppDisp', 'Cancel', 'dwFlags', 'bstrUrlContext', 'bstrUrl'], handler: ( + this: SHDocVw.WebBrowser, parameter: { ppDisp: any, Cancel: boolean, readonly dwFlags: number, readonly bstrUrlContext: string, readonly bstrUrl: string }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'OnFullScreen', argNames: ['FullScreen'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly FullScreen: boolean }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'OnMenuBar', argNames: ['MenuBar'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly MenuBar: boolean }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'OnStatusBar', argNames: ['StatusBar'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly StatusBar: boolean }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'OnTheaterMode', argNames: ['TheaterMode'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly TheaterMode: boolean }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'OnToolBar', argNames: ['ToolBar'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly ToolBar: boolean }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'OnVisible', argNames: ['Visible'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Visible: boolean }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'PrintTemplateInstantiation' | 'PrintTemplateTeardown', argNames: ['pDisp'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'PrivacyImpactedStateChange', argNames: ['bImpacted'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly bImpacted: boolean }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'PropertyChange', argNames: ['szProperty'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly szProperty: string }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'RedirectXDomainBlocked', argNames: ['pDisp', 'StartURL', 'RedirectURL', 'Frame', 'StatusCode'], + handler: (this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any, readonly StartURL: any, readonly RedirectURL: any, readonly Frame: any, readonly StatusCode: any }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'SetPhishingFilterStatus', argNames: ['PhishingFilterStatus'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly PhishingFilterStatus: number }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'SetSecureLockIcon', argNames: ['SecureLockIcon'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly SecureLockIcon: number }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Text: string }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'ThirdPartyUrlBlocked', argNames: ['URL', 'dwCount'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly URL: any, readonly dwCount: number }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'UpdatePageStatus', argNames: ['pDisp', 'nPage', 'fDone'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any, readonly nPage: any, readonly fDone: any }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'WebWorkerFinsihed', argNames: ['dwUniqueID'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly dwUniqueID: number }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'WebWorkerStarted', argNames: ['dwUniqueID', 'bstrWorkerLabel'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly dwUniqueID: number, readonly bstrWorkerLabel: string }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'WindowClosing', argNames: ['IsChildWindow', 'Cancel'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly IsChildWindow: boolean, Cancel: boolean }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'WindowSetHeight', argNames: ['Height'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Height: number }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'WindowSetLeft', argNames: ['Left'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Left: number }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'WindowSetResizable', argNames: ['Resizable'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Resizable: boolean }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'WindowSetTop', argNames: ['Top'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Top: number }) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'WindowSetWidth', argNames: ['Width'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Width: number }) => void): void; + on( + obj: SHDocVw.WebBrowser, event: 'WindowStateChanged', argNames: ['dwWindowStateFlags', 'dwValidFlagsMask'], handler: ( + this: SHDocVw.WebBrowser, parameter: { readonly dwWindowStateFlags: number, readonly dwValidFlagsMask: number }) => void): void; + on( + obj: SHDocVw.WebBrowser_V1, event: 'BeforeNavigate', argNames: SHDocVw.EventHelperTypes.WebBrowser_V1_BeforeNavigate_ArgNames, + handler: (this: SHDocVw.WebBrowser_V1, parameter: SHDocVw.EventHelperTypes.WebBrowser_V1_BeforeNavigate_Parameter) => void): void; + on( + obj: SHDocVw.WebBrowser_V1, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: ( + this: SHDocVw.WebBrowser_V1, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void; + on( + obj: SHDocVw.WebBrowser_V1, event: 'FrameBeforeNavigate', argNames: SHDocVw.EventHelperTypes.WebBrowser_V1_FrameBeforeNavigate_ArgNames, + handler: (this: SHDocVw.WebBrowser_V1, parameter: SHDocVw.EventHelperTypes.WebBrowser_V1_FrameBeforeNavigate_Parameter) => void): void; + on(obj: SHDocVw.WebBrowser_V1, event: 'FrameNavigateComplete' | 'NavigateComplete', argNames: ['URL'], handler: (this: SHDocVw.WebBrowser_V1, parameter: { readonly URL: string }) => void): void; + on( + obj: SHDocVw.WebBrowser_V1, event: 'FrameNewWindow', argNames: SHDocVw.EventHelperTypes.WebBrowser_V1_FrameNewWindow_ArgNames, + handler: (this: SHDocVw.WebBrowser_V1, parameter: SHDocVw.EventHelperTypes.WebBrowser_V1_FrameNewWindow_Parameter) => void): void; + on( + obj: SHDocVw.WebBrowser_V1, event: 'NewWindow', argNames: SHDocVw.EventHelperTypes.WebBrowser_V1_NewWindow_ArgNames, handler: ( + this: SHDocVw.WebBrowser_V1, parameter: SHDocVw.EventHelperTypes.WebBrowser_V1_NewWindow_Parameter) => void): void; + on( + obj: SHDocVw.WebBrowser_V1, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: ( + this: SHDocVw.WebBrowser_V1, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void; + on(obj: SHDocVw.WebBrowser_V1, event: 'PropertyChange', argNames: ['Property'], handler: (this: SHDocVw.WebBrowser_V1, parameter: { readonly Property: string }) => void): void; + on(obj: SHDocVw.WebBrowser_V1, event: 'Quit', argNames: ['Cancel'], handler: (this: SHDocVw.WebBrowser_V1, parameter: { Cancel: boolean }) => void): void; + on(obj: SHDocVw.WebBrowser_V1, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: (this: SHDocVw.WebBrowser_V1, parameter: { readonly Text: string }) => void): void; + on(obj: SHDocVw.InternetExplorer, event: 'DownloadBegin' | 'DownloadComplete' | 'OnQuit', handler: (this: SHDocVw.InternetExplorer, parameter: {}) => void): void; + on(obj: SHDocVw.InternetExplorerMedium, event: 'DownloadBegin' | 'DownloadComplete' | 'OnQuit', handler: (this: SHDocVw.InternetExplorerMedium, parameter: {}) => void): void; + on(obj: SHDocVw.ShellBrowserWindow, event: 'DownloadBegin' | 'DownloadComplete' | 'OnQuit', handler: (this: SHDocVw.ShellBrowserWindow, parameter: {}) => void): void; + on(obj: SHDocVw.ShellNameSpace, event: 'DoubleClick' | 'Initialized' | 'SelectionChange', handler: (this: SHDocVw.ShellNameSpace, parameter: {}) => void): void; + on(obj: SHDocVw.WebBrowser, event: 'DownloadBegin' | 'DownloadComplete' | 'OnQuit', handler: (this: SHDocVw.WebBrowser, parameter: {}) => void): void; + on(obj: SHDocVw.WebBrowser_V1, event: 'DownloadBegin' | 'DownloadComplete' | 'WindowActivate' | 'WindowMove' | 'WindowResize', handler: (this: SHDocVw.WebBrowser_V1, parameter: {}) => void): void; + new (progid: K): ActiveXObjectNameMap[K]; +} + +interface ActiveXObjectNameMap { + 'InternetExplorer.Application': SHDocVw.InternetExplorer; + 'Shell.Explorer': SHDocVw.WebBrowser; + 'Shell.UIHelper': SHDocVw.ShellUIHelper; + 'ShellNameSpace.ShellNameSpace': SHDocVw.ShellNameSpace; +} + +interface EnumeratorConstructor { + new(col: SHDocVw.ShellWindows): Enumerator; +} diff --git a/types/activex-shdocvw/package.json b/types/activex-shdocvw/package.json new file mode 100644 index 0000000000..d9b1031263 --- /dev/null +++ b/types/activex-shdocvw/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "activex-helpers": "*" + } +} \ No newline at end of file diff --git a/types/activex-shdocvw/tsconfig.json b/types/activex-shdocvw/tsconfig.json new file mode 100644 index 0000000000..1907cb1ef6 --- /dev/null +++ b/types/activex-shdocvw/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "scripthost" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "activex-shdocvw-tests.ts" + ] +} \ No newline at end of file diff --git a/types/activex-shdocvw/tslint.json b/types/activex-shdocvw/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/activex-shdocvw/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/activex-shell/activex-shell-tests.ts b/types/activex-shell/activex-shell-tests.ts new file mode 100644 index 0000000000..f236f6e592 --- /dev/null +++ b/types/activex-shell/activex-shell-tests.ts @@ -0,0 +1,489 @@ +/// + +const shell = new ActiveXObject('Shell.Application'); + +const getWindowsFolder = () => shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfWINDOWS); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537735(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + if (!folder) { return; } + const folderItem = folder.ParseName('system.ini'); + if (!folderItem) { return; } + shell.AddToRecent(folderItem.Path); +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774065(v=vs.85).aspx +(() => { + const folder = shell.BrowseForFolder(0, 'Example', 0, Shell32.ShellSpecialFolderConstants.ssfWINDOWS); +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537736(v=vs.85).aspx +const canStartStop = shell.CanStartStopService('service name'); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774069(v=vs.85).aspx +shell.ControlPanelItem('desk.cpl'); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774073(v=vs.85).aspx +shell.Explore('C:\\'); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537737(v=vs.85).aspx +const explorerPolicy = shell.ExplorerPolicy('ValueName'); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537739(v=vs.85).aspx +const settingValue = shell.GetSetting(Shell32.SettingKey.SSF_SHOWALLOBJECTS); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537740(v=vs.85).aspx +const processorLevel = shell.GetSystemInformation('ProcessorLevel'); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537741(v=vs.85).aspx +const isRestricted = shell.IsRestricted('system', 'undockwithoutlogon'); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537742(v=vs.85).aspx +const isServiceRunning = shell.IsServiceRunning('Themes'); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774086(v=vs.85).aspx +shell.Open(Shell32.ShellSpecialFolderConstants.ssfWINDOWS); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537743(v=vs.85).aspx +shell.ServiceStart('Messenger', true); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537744(v=vs.85).aspx +shell.ServiceStop('Messenger', true); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537745(v=vs.85).aspx +shell.ShellExecute("notepad.exe", "", "", "open", Shell32.ShellExecuteShow.Normal); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537746(v=vs.85).aspx?cs-save-lang=1&cs-lang=jscript#code-snippet-1 +shell.ShowBrowserBar(Shell32.ExplorerBarCLSID.Favorites, true); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774107(v=vs.85).aspx +const wshShell = new ActiveXObject('WScript.Shell'); +wshShell.Popup(shell.Windows().Count.toString()); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787866(v=vs.85).aspx +shell.NameSpace(`c:\\windows`)!.CopyHere('c:\\autoexec.bat'); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx +(() => { + const folder = shell.NameSpace('c:\\windows'); + const folderItem = folder ? folder.ParseName('clock.avi') : undefined; + if (folder && folderItem) { + const info = folder.GetDetailsOf(folderItem, Shell32.FileSystemDetails.Type); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787874(v=vs.85).aspx +shell.NameSpace('c:\\windows')!.MoveHere('c:\\temp.txt', Shell32.FileOperationFlag.FOF_NOCONFIRMATION); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787876(v=vs.85).aspx +shell.NameSpace('c:\\')!.NewFolder('TestFolder'); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787858(v=vs.85).aspx +(() => { + const folder = shell.NameSpace("\\\\server\\share\\folder"); + const offlineStatus = folder ? folder.OfflineStatus : undefined; +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787880(v=vs.85).aspx +(() => { + const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS); + WScript.Echo(folder!.ParentFolder.Title); +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787860(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787816(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787850(v=vs.85).aspx +(() => { + const folder = shell.NameSpace('C:\\WINDOWS'); + const folderItem = folder ? folder.Self : undefined; + if (folderItem) { + const verbs = folderItem.Verbs(); + folderItem.InvokeVerb(); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787812(v=vs.85).aspx +(() => { + const parentFolder = getWindowsFolder(); + const folderItem = parentFolder ? parentFolder.ParseName('system32') : undefined; + const folder = folderItem ? folderItem.GetFolder : undefined; +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787814(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787824(v=vs.85).aspx +(() => { + const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS); + const folderItem = folder ? folder.ParseName('Internet Explorer.lnk') : undefined; + if (folderItem && folderItem.IsLink) { + const link = folderItem.GetLink; + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787818(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787819(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787821(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + const folderItem = folder ? folder.Self : undefined; + if (folderItem) { + const isBrowsable = folderItem.IsBrowsable; + const isFileSystem = folderItem.IsFileSystem; + const isFolder = folderItem.IsFolder; + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787825(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + const folderItem = folder!.ParseName('notepad.exe'); + if (folderItem) { + const oldDate = folderItem.ModifyDate; + folderItem.ModifyDate = new Date(1900, 1, 1, 18, 5).getVarDate(); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787827(v=vs.85).aspx +(() => { + const rootFolder = shell.NameSpace('C:\\'); + const folderItem = rootFolder ? rootFolder.ParseName('autoexec.bat') : undefined; + if (folderItem) { + const oldName = folderItem.Name; + folderItem.Name = 'test.bat'; + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787829(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + const folderItem = folder ? folder.Self : undefined; + const parent = folderItem ? folderItem.Parent : undefined; + if (parent) { + WScript.Echo('Got parent object'); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787844(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + const folderItem = folder ? folder.Self : undefined; + const path = folderItem ? folderItem.Path : ''; +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787846(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + const folderItem = folder!.ParseName('notepad.exe'); + const size = folderItem ? folderItem.Size : undefined; +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787848(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + if (folder) { + WScript.Echo(folder.Self.Type); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787798(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + const folderItems = folder ? folder.Items() : undefined; + const count = folderItems ? folderItems.Count : undefined; +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787794(v=vs.85).aspx +(() => { + const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfDRIVES); + if (folder) { + folder.Items().InvokeVerbEx(); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774170(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774174(v=vs.85).aspx +(() => { + const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS); + const verbs = folder ? folder.Self.Verbs() : undefined; + if (verbs) { + const verb = verbs.Item(0); + WScript.Echo(verb.Name); + verb.DoIt(); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787787(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + if (folder) { + const folderItems = folder.Items(); + WScript.Echo(folderItems.Count); + folderItems.Filter(Shell32.ShellFolderEnumerationFlags.SHCONTF_NONFOLDERS, '*.txt'); + WScript.Echo(folderItems.Count); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787791(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774162(v=vs.85).aspx +(() => { + const echoFirstVerbName = (folder: Shell32.Folder3 | null) => { + if (!folder) { return; } + const verbs = folder.Items().Verbs; + WScript.Echo(verbs.Item(0).Name); + }; + + let folder = getWindowsFolder(); + echoFirstVerbName(folder); + + folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS); + echoFirstVerbName(folder); +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774158(v=vs.85).aspx +(() => { + const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS); + if (folder) { + const verbs = folder.Self.Verbs(); + WScript.Echo(verbs.Count); + } +})(); + +const getIELink = () => { + const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS); + const folderItem = folder ? folder.ParseName('Internet Explorer.lnk') : undefined; + return { + link: folderItem ? folderItem.GetLink : undefined, + folderItem + }; +}; + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773990(v=vs.85).aspx +(() => { + const { link, folderItem } = getIELink(); + if (link && folderItem) { + WScript.Echo(link.GetIconLocation(folderItem.Path)); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773996(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + link.Resolve(Shell32.ShellLinkResolveFlags.NoUI); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773998(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + link.Description = 'New Description'; + link.Save(); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774002(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + link.SetIconLocation(link.Path, 1); + link.Save(); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773986(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + WScript.Echo(link.Arguments); + link.Arguments = '/s'; + link.Save(); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773988(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + WScript.Echo(link.Description); + link.Description = 'Test'; + link.Save(); + } +})(); + +const parseHotkey = (hotkey: number) => { + // missing implementation + return { + shift: false, + ctrl: false, + alt: false, + extended: false, + hotkey + }; +}; +const buildHotkey = (hotkey: number, shift: boolean = false, ctrl: boolean = false, alt: boolean = false, extended: boolean = false) => { + // missing implementation + return 0; +}; + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773992(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + const { hotkey } = parseHotkey(link.Hotkey); + WScript.Echo(hotkey); + link.Hotkey = buildHotkey(4); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773994(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + WScript.Echo(link.Path); + link.Path = 'C:\\Program Files\\IE\\IEXPLORE.EXE'; + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774006(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + WScript.Echo(link.ShowCommand); + link.ShowCommand = Shell32.LinkShowWindowState.Normal; + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774008(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + WScript.Echo(link.WorkingDirectory); + link.WorkingDirectory = ''; + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774115(v=vs.85).aspx +(() => { + const { link } = getIELink(); + if (link) { + const target = link.Target; + if (target) { + WScript.Echo(target.Size); + } + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774055(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + const folderItem = folder ? folder.ParseName('notepad.exe') : undefined; + if (folderItem) { + WScript.Echo(folderItem.ExtendedProperty('infotip')); + } + + const wordDoc = shell.NameSpace('C:\\')!.ParseName('test.doc'); + if (wordDoc) { + const FMTID_SummaryInfo = "{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"; + const PID_TITLE = "2"; + const PID_AUTHOR = "4"; + const SCID_TITLE = `${FMTID_SummaryInfo} ${PID_TITLE}`; + const SCID_AUTHOR = `${FMTID_SummaryInfo} ${PID_AUTHOR}`; + const docTitle = wordDoc.ExtendedProperty(SCID_TITLE); + const docAuthor = wordDoc.ExtendedProperty(SCID_AUTHOR); + } +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774057(v=vs.85).aspx +(() => { + const folder = getWindowsFolder(); + const folderItem = folder ? folder.ParseName('notepad.exe') : undefined; + if (folderItem) { + folderItem.InvokeVerbEx("open", "c:\\autoexec.bat"); + } +})(); + +const collectionToArray = (col: any): T[] => { // tslint:disable-line no-unnecessary-generics + const results: T[] = []; + const enumerator = new Enumerator(col); + enumerator.moveFirst(); + while (!enumerator.atEnd()) { + results.push(enumerator.item()); + enumerator.moveNext(); + } + return results; +}; + +interface String { + endsWith(searchString: string, length?: number): boolean; +} +if (!String.prototype.endsWith) { + String.prototype.endsWith = function(search, this_len) { + if (this_len === undefined || this_len > this.length) { + this_len = this.length; + } + return this.substring(this_len - search.length, this_len) === search; + }; +} + +// shell.Windows() includes items other than Explorer windows, such as Internet Explorer tabs +const getExplorerWindows = () => + collectionToArray(shell.Windows()) + .filter(x => x.FullName.toLowerCase().endsWith('explorer.exe')); + +const getFolderViews = () => + getExplorerWindows() + .map(x => x.Document as Shell32.ShellFolderView); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774045(v=vs.85).aspx +(() => { + getFolderViews().forEach(x => + ActiveXObject.on(x, 'SelectionChanged', function(this: Shell32.ShellFolderView) { + WScript.Echo(`Selection change in ${this.Folder.Title} -- count: ${this.SelectedItems().Count}`); + }) + ); +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773970(v=vs.85).aspx +WScript.Echo(shell.Windows().Item().Path); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773969(v=vs.85).aspx +WScript.Echo(shell.Windows().Count); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774043(v=vs.85).aspx +(() => { + getFolderViews().forEach(x => + WScript.Echo(`${x.Folder.Title} -- ${x.SelectedItems().Count} selected items`) + ); +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774047(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774022(v=vs.85).aspx +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774053(v=vs.85).aspx +(() => { + const folderView = getExplorerWindows()[0].Document as Shell32.ShellFolderView; + const folder = folderView.Folder; + if (folder) { + const folderItem = folder.Self; + folderView.SelectItem(folder.Self, Shell32.ShellFolderViewSelectItem.Focus); + } + WScript.Echo(folderView.ViewOptions); +})(); + +// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774020(v=vs.85).aspx +(() => { + const folderView = getExplorerWindows()[0].Document as Shell32.ShellFolderView; + const focusedItem = folderView.FocusedItem; + if (focusedItem) { + WScript.Echo(`Focused item in first Excplorer window -- ${focusedItem.Path}`); + } +})(); + +(() => { + const router = new ActiveXObject('Shell.FolderView'); + const folder = getFolderViews()[0]; + router.SetFolderView(folder); + ActiveXObject.on(router, 'EnumDone', () => WScript.Echo('Current folder view was finisehd enumerating')); + ActiveXObject.on(router, 'SelectionChanged', () => WScript.Echo('Selection changed in current folder view')); + // the folder view monitored by the ShellFolderViewOC object can be changed via SetFolderView without disconnecting and reconnecting the handlers +})(); diff --git a/types/activex-shell/index.d.ts b/types/activex-shell/index.d.ts new file mode 100644 index 0000000000..cb59a11c5e --- /dev/null +++ b/types/activex-shell/index.d.ts @@ -0,0 +1,1016 @@ +// Type definitions for Microsoft Shell Controls And Automation - Shell32 1.0 +// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx +// Definitions by: Zev Spitz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/// + +declare namespace Shell32 { + // tslint:disable-next-line no-const-enum + const enum BrowseInfoFlags { + /** + * Allow folder junctions such as a library or a compressed file with a .zip file name extension to be browsed. + * + * _Windows 7 and later._ + */ + BIF_BROWSEFILEJUNCTIONS = 0x00010000, + + /** Only return computers. If the user selects anything other than a computer, the **OK** button is grayed. */ + BIF_BROWSEFORCOMPUTER = 0x00001000, + + /** + * Only allow the selection of printers. If the user selects anything other than a printer, the **OK** button is grayed. + * + * In Windows XP and later systems, the best practice is to use a Windows XP-style dialog, setting the root of the dialog to the **Printers and Faxes** folder (`CSIDL_PRINTERS`). + */ + BIF_BROWSEFORPRINTER = 0x00002000, + + /** + * The browse dialog box displays files as well as folders. + * + * _[Version 4.7.1](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + BIF_BROWSEINCLUDEFILES = 0x00004000, + + /** + * The browse dialog box can display URLs. The `BIF_USENEWUI` and `BIF_BROWSEINCLUDEFILES` flags must also be set. If any of these three flags are not set, the browser dialog box rejects URLs. + * Even when these flags are set, the browse dialog box displays URLs only if the folder that contains the selected item supports URLs. + * + * When the folder's [IShellFolder::GetAttributesOf](https://msdn.microsoft.com/en-us/library/windows/desktop/bb775068.aspx) method is called to request the selected item's attributes, the + * folder must set the `SFGAO_FOLDER` attribute flag. Otherwise, the browse dialog box will not display the URL. + * + * _[Version 5.0](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + BIF_BROWSEINCLUDEURLS = 0x00000080, + + /** Do not include network folders below the domain level in the dialog box's tree view control. */ + BIF_DONTGOBELOWDOMAIN = 0x00000002, + + /** + * Include an edit control in the browse dialog box that allows the user to type the name of an item. + * + * _[Version 4.7.1](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + BIF_EDITBOX = 0x00000010, + + /** + * Use the new user interface. Setting this flag provides the user with a larger dialog box that can be resized. The dialog box has several new capabilities, including: drag-and-drop + * capability within the dialog box, reordering, shortcut menus, new folders, delete, and other shortcut menu commands. + * + * _[Version 5.0](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + BIF_NEWDIALOGSTYLE = 0x00000040, + + /** + * Do not include the **New Folder** button in the browse dialog box. + * + * _[Version 6.0](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + BIF_NONEWFOLDERBUTTON = 0x00000200, + + /** + * When the selected item is a shortcut, return the PIDL of the shortcut itself rather than its target. + * + * _[Version 6.0](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + BIF_NOTRANSLATETARGETS = 0x00000400, + + /** + * Only return file system ancestors. An ancestor is a subfolder that is beneath the root folder in the namespace hierarchy. If the user selects an ancestor of the root folder that is not + * part of the file system, the **OK** button is grayed. + */ + BIF_RETURNFSANCESTORS = 0x00000008, + + /** + * Only return file system directories. If the user selects folders that are not part of the file system, the **OK** button is grayed. + * + * **Note** The **OK** button remains enabled for `\\server` items, as well as `\\server\share` and directory items. However, if the user selects a `\\server` item, passing the PIDL + * returned by [SHBrowseForFolder](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762115.aspx) to + * [SHGetPathFromIDList](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762194.aspx) fails. + */ + BIF_RETURNONLYFSDIRS = 0x00000001, + + /** + * The browse dialog box can display sharable resources on remote systems. This is intended for applications that want to expose remote shares on a local system. The BIF_NEWDIALOGSTYLE flag + * must also be set. + * + * _[Version 5.0](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + BIF_SHAREABLE = 0x00008000, + + /** + * Include a status area in the dialog box. The callback function can set the status text by sending messages to the dialog box. This flag is not supported when BIF_NEWDIALOGSTYLE + * is specified. + */ + BIF_STATUSTEXT = 0x00000004, + + /** + * When combined with `BIF_NEWDIALOGSTYLE`, adds a usage hint to the dialog box, in place of the edit box. `BIF_EDITBOX` overrides this flag. + * + * _[Version 6.0](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + BIF_UAHINT = 0x00000100, + + /** + * Use the new user interface, including an edit box. This flag is equivalent to `BIF_EDITBOX | BIF_NEWDIALOGSTYLE`. + * + * _[Version 5.0](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + BIF_USENEWUI = 0x00000090, + + /** + * If the user types an invalid name into the edit box, the browse dialog box calls the application's + * [BrowseCallbackProc](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762598.aspx) with the **BFFM_VALIDATEFAILED** message. This flag is ignored if BIF_EDITBOX is not specified. + * + * _[Version 4.71](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779)_ + */ + BIF_VALIDATE = 0x00000020, + } + + // tslint:disable-next-line no-const-enum + const enum ExplorerBarCLSID { + Favorites = '{EFA24E61-B078-11d0-89E4-00C04FC9E26E}', + Folders = '{EFA24E64-B078-11d0-89E4-00C04FC9E26E}', + History = '{EFA24E62-B078-11d0-89E4-00C04FC9E26E}', + Search = '{30D02401-6A81-11d0-8274-00C04FD5AE38}', + } + + // tslint:disable-next-line no-const-enum + const enum FileOperationFlag { + /** Preserve undo information, if possible. */ + FOF_ALLOWUNDO = 64, + + /** Perform the operation on files only if a wildcard file name (*.*) is specified. */ + FOF_FILESONLY = 128, + + /** Respond with "Yes to All" for any dialog box that is displayed. */ + FOF_NOCONFIRMATION = 16, + + /** Do not confirm the creation of a new directory if the operation requires one to be created. */ + FOF_NOCONFIRMMKDIR = 512, + + /** + * Do not copy connected files as a group. Only copy the specified files. + * + * _[Version 5.0](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + FOF_NO_CONNECTED_ELEMENTS = 8192, + + /** + * Do not copy the security attributes of the file. + * + * _[Version 4.7.1](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776779.aspx)_ + */ + FOF_NOCOPYSECURITYATTRIBS = 2048, + + /** Do not display a user interface if an error occurs. */ + FOF_NOERRORUI = 1024, + + /** Only operate in the local directory. Do not operate recursively into subdirectories. */ + FOF_NORECURSION = 4096, + + /** Give the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists. */ + FOF_RENAMEONCOLLISION = 8, + + /** Do not display a progress dialog box. */ + FOF_SILENT = 4, + + /** Display a progress dialog box but do not show the file names. */ + FOF_SIMPLEPROGRESS = 256, + } + + // tslint:disable-next-line no-const-enum + const enum FileSystemDetails { + Name = 0, + Size = 1, + Type = 2, + LastModified = 3, + Attributes = 4, + InfoTip = -1, + } + + // tslint:disable-next-line no-const-enum + const enum HotkeyModifiers { + SHIFT = 1, + CTRL = 2, + ALT = 4, + Extended = 8 + } + + // tslint:disable-next-line no-const-enum + const enum LinkShowWindowState { + /** Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. */ + Normal = 1, + + /** Activates the window and displays it as a minimized window. */ + Minimized = 2, + + /** Activates the window and displays it as a maximized window. */ + Maximized = 3 + } + + /** Constants for Folder2.OfflineStatus */ + // tslint:disable-next-line no-const-enum + const enum OfflineFolderStatus { + OFS_DIRTYCACHE = 3, + OFS_INACTIVE = -1, + OFS_OFFLINE = 1, + OFS_ONLINE = 0, + OFS_SERVERBACK = 2, + } + + // tslint:disable-next-line no-const-enum + const enum ShellFolderEnumerationFlags { + /** **Windows 7 and later** The calling application is checking for the existence of child items in the folder. */ + SHCONTF_CHECKING_FOR_CHILDREN = 0x00010, + + /** Include items that are folders in the enumeration. */ + SHCONTF_FOLDERS = 0x00020, + + /** Include items that are not folders in the enumeration. */ + SHCONTF_NONFOLDERS = 0x00040, + + /** Include hidden items in the enumeration. This does not include hidden system items. (To include hidden system items, use SHCONTF_INCLUDESUPERHIDDEN.) */ + SHCONTF_INCLUDEHIDDEN = 0x00080, + + /** The calling application is looking for printer objects. */ + SHCONTF_NETPRINTERSRCH = 0x00200, + + /** The calling application is looking for resources that can be shared. */ + SHCONTF_SHAREABLE = 0x00400, + + /** Include items with accessible storage and their ancestors, including hidden items. */ + SHCONTF_STORAGE = 0x00800, + + /** **Windows 7 and later**. Child folders should provide a navigation enumeration. */ + SHCONTF_NAVIGATION_ENUM = 0x01000, + + /** **Windows Vista and later**. The calling application is looking for resources that can be enumerated quickly. */ + SHCONTF_FASTITEMS = 0x02000, + + /** **Windows Vista and later**. Enumerate items as a simple list even if the folder itself is not structured in that way. */ + SHCONTF_FLATLIST = 0x04000, + + /** + * **Windows Vista and later**. The calling application is monitoring for change notifications.This means that the enumerator does not have to return all results. + * Items can be reported through change notifications. + */ + SHCONTF_ENABLE_ASYNC = 0x08000, + + /** + * **Windows 7 and later**. Include hidden system items in the enumeration. This value does not include hidden non-system items. + * (To include hidden non-system items, use SHCONTF_INCLUDEHIDDEN.) + */ + SHCONTF_INCLUDESUPERHIDDEN = 0x10000, + } + + // tslint:disable-next-line no-const-enum + const enum ShellFolderViewOptions { + /** The **Show All Files** option is enabled. */ + SFVVO_SHOWALLOBJECTS = 0x00000001, + + /** The **Hide extensions for known file types** option is disabled. */ + SFVVO_SHOWEXTENSIONS = 0x00000002, + + /** The **Display Compressed Files and Folders with Alternate Color** option is enabled. */ + SFVVO_SHOWCOMPCOLOR = 0x00000008, + + /** The **Do Not Show Hidden Files** option is enabled. */ + SFVVO_SHOWSYSFILES = 0x00000020, + + /** The **Classic Style** option is enabled. */ + SFVVO_WIN95CLASSIC = 0x00000040, + + /** The **Double-Click to Open an Item** option is enabled. */ + SFVVO_DOUBLECLICKINWEBVIEW = 0x00000080, + + /** The **Active Desktop – View as Web Page** option is enabled. */ + SFVVO_DESKTOPHTML = 0x00000200 + } + + // tslint:disable-next-line no-const-enum + const enum ShellFolderViewSelectItem { + Deselect = 0, + Select = 1, + EditMode = 3, + DeselectAllButThis = 4, + ScrollIntoView = 8, + Focus = 16 + } + + // tslint:disable-next-line no-const-enum + const enum ShellLinkResolveFlags { + /** + * Do not display a dialog box if the link cannot be resolved. When this flag is set, the high-order word of _fFlags_ specifies a time-out duration, in milliseconds. + * The method returns if the link cannot be resolved within the time-out duration. If the high-order word is set to zero, the time-out duration defaults to 3000 milliseconds (3 seconds). + */ + NoUI = 1, + + /** If the link has changed, update its path and list of identifiers. */ + Update = 4, + + /** Do not update the link information. */ + NoUpdate = 8, + + /** Do not execute the search heuristics. */ + NoSearch = 16, + + /** Do not use distributed link tracking. */ + NoTrack = 32, + + /** + * Disable distributed link tracking. By default, distributed link tracking tracks removable media across multiple devices based on the volume name. + * It also uses the UNC path to track remote file systems whose drive letter has changed. Setting this flag disables both types of tracking. + */ + NoLinkInfo = 64, + + /** Call the Windows Installer. */ + InvokeMSI = 128 + } + + // tslint:disable-next-line no-const-enum + const enum SettingKey { + /** + * The state of the **Use check boxes to select items** option. This option is enabled automatically when the system has a pen input device configured. + * + * _Windows Vista and later_ + */ + SSF_AUTOCHECKSELECT = 0x00800000, + + /** Not used. */ + SSF_DESKTOPHTML = 0x00000200, + + /** The state of the **Allow all uppercase names** option. As of Windows Vista, this folder option is no longer available. */ + SSF_DONTPRETTYPATH = 0x00000800, + + /** The state of the **Double-click to open an item (single-click to select)** option. */ + SSF_DOUBLECLICKINWEBVIEW = 0x00000080, + + /** Not used. */ + SSF_FILTER = 0x00010000, + + /** Not used. */ + SSF_HIDDENFILEEXTS = 0x00000004, + + /** The state of icon display in the Windows Explorer list view. If this option is active, no icons are displayed in the list view. */ + SSF_HIDEICONS = 0x00004000, + + /** + * The state of display name display in the Windows Explorer list view. If this option is active, icons are displayed in the list view, but display names are not. + * + * _Windows Vista and later_ + */ + SSF_ICONSONLY = 0x01000000, + + /** The state of the **Show map network drive button in toolbar** option. As of Windows Vista, this option is no longer available. */ + SSF_MAPNETDRVBUTTON = 0x00001000, + + /** The state of the Recycle Bin's **Display delete confirmation dialog** option. */ + SSF_NOCONFIRMRECYCLE = 0x00008000, + + /** The state of the **Automatically search for network folders and printers** option. As of Windows Vista, this option is no longer available. */ + SSF_NONETCRAWLING = 0x00100000, + + /** The state of the **Launch folder windows in a separate process** option. */ + SSF_SEPPROCESS = 0x00080000, + + /** Not used. */ + SSF_SERVERADMINUI = 0x00000004, + + /** The state of the **Hidden files and folders** option. */ + SSF_SHOWALLOBJECTS = 0x00000001, + + /** The state of the **Show File Attributes in Detail View** option. As of Windows Vista, this option is no longer available. */ + SSF_SHOWATTRIBCOL = 0x00000100, + + /** The state of the **Show encrypted or compressed NTFS files in color** option. */ + SSF_SHOWCOMPCOLOR = 0x00000008, + + /** The state of the **Hide extensions for known file types** option. */ + SSF_SHOWEXTENSIONS = 0x00000002, + + /** The state of the **Show pop-up description for folder and desktop items** option. */ + SSF_SHOWINFOTIP = 0x00002000, + + /** Not used. */ + SSF_SHOWSTARTPAGE = 0x00400000, + + /** The state of the **Hide protected operating system files** option. */ + SSF_SHOWSUPERHIDDEN = 0x00040000, + + /** + * The state of the **Hidden files and folders** option. In Windows Vista and later, this is equivalent to `SSF_SHOWALLOBJECTS`. In versions of Windows before Windows Vista, this value + * referred to the state of the **Do not show hidden files and folders** option. + */ + SSF_SHOWSYSFILES = 0x00000020, + + /** + * The state of the **Display file icon on thumbnails** option. If this option is active, a file type overlay is applied when a file supplies a thumbnail representation. + * + * _Windows Vista and later_ + */ + SSF_SHOWTYPEOVERLAY = 0x02000000, + + /** Not used. */ + SSF_SORTCOLUMNS = 0x00000010, + + /** The state of the Windows XP display option, which selects between the Windows XP style and the classic style. As of Windows Vista, this option is no longer available. */ + SSF_STARTPANELON = 0x00200000, + + /** The state of the **Display as a web view option**. As of Windows Vista, this option is no longer available. */ + SSF_WEBVIEW = 0x00020000, + + /** The state of the **Classic Style** option. As of Windows Vista, this option is no longer available. */ + SSF_WIN95CLASSIC = 0x00000400, + } + + // tslint:disable-next-line no-const-enum + const enum ShellExecuteShow { + /** Open the application with a hidden window. */ + Hidden = 0, + + /** Open the application with a normal window. If the window is minimized or maximized, the system restores it to its original size and position. */ + Normal = 1, + + /** Open the application with a minimized window. */ + Minimized = 2, + + /** Open the application with a maximized window. */ + Maximized = 3, + + /** Open the application with its window at its most recent size and position. The active window remains active. */ + Last = 4, + + /** Open the application with its window at its current size and position. */ + Current = 5, + + /** Open the application with a minimized window. The active window remains active. */ + MinimizedNotActivated = 7, + + /** Open the application with its window in the default state specified by the application. */ + Application = 10, + } + + /** Constants for Special Folders for open/Explore */ + // tslint:disable-next-line no-const-enum + const enum ShellSpecialFolderConstants { + ssfALTSTARTUP = 29, + ssfAPPDATA = 26, + ssfBITBUCKET = 10, + ssfCOMMONALTSTARTUP = 30, + ssfCOMMONAPPDATA = 35, + ssfCOMMONDESKTOPDIR = 25, + ssfCOMMONFAVORITES = 31, + ssfCOMMONPROGRAMS = 23, + ssfCOMMONSTARTMENU = 22, + ssfCOMMONSTARTUP = 24, + ssfCONTROLS = 3, + ssfCOOKIES = 33, + ssfDESKTOP = 0, + ssfDESKTOPDIRECTORY = 16, + ssfDRIVES = 17, + ssfFAVORITES = 6, + ssfFONTS = 20, + ssfHISTORY = 34, + ssfINTERNETCACHE = 32, + ssfLOCALAPPDATA = 28, + ssfMYPICTURES = 39, + ssfNETHOOD = 19, + ssfNETWORK = 18, + ssfPERSONAL = 5, + ssfPRINTERS = 4, + ssfPRINTHOOD = 27, + ssfPROFILE = 40, + ssfPROGRAMFILES = 38, + ssfPROGRAMFILESx86 = 48, + ssfPROGRAMS = 2, + ssfRECENT = 8, + ssfSENDTO = 9, + ssfSTARTMENU = 11, + ssfSTARTUP = 7, + ssfSYSTEM = 37, + ssfSYSTEMx86 = 41, + ssfTEMPLATES = 21, + ssfWINDOWS = 36, + } + + /** FileSearchBand Class */ + class FileSearchBand { + private 'Shell32.FileSearchBand_typekey': FileSearchBand; + private constructor(); + + /** Retrieve the file from which the search was restored. */ + readonly QueryFile: any; + + /** Get the search scope */ + readonly Scope: any; + + /** Retrieve the guid of the currently active search. */ + readonly SearchID: string; + + /** method SetFocus */ + SetFocus(): void; + + /** method SetSearchParameters */ + SetSearchParameters(pbstrSearchID: string, bNavToResults: boolean, pvarScope?: any, pvarQueryFile?: any): void; + } + + /** Definition of interface Folder version 3 */ + class Folder3 { + private 'Shell32.Folder3_typekey': Folder3; + private constructor(); + + /** Get Application object */ + readonly Application: any; + + /** Copy Items to this folder. */ + CopyHere(vItem: string | ShellFolderItem | FolderItems3, vOptions?: FileOperationFlag): void; + + /** Call this after the WebView barricade is dismissed by the user */ + DismissedWebViewBarricade(): void; + + /** + * Get the details about an item. + * @param vItem The item for which to retrieve the information. + * @param iColumn An integer value that specifies the information to be retrieved. The information available for an item depends on the folder in which it is displayed. This value + * corresponds to the zero-based column number that is displayed in a Shell view. + */ + GetDetailsOf(vItem: ShellFolderItem, iColumn: number): string; + + /** Should the WebView barricade be shown? */ + readonly HaveToShowWebViewBarricade: boolean; + + /** The collection of Items in folder */ + Items(): FolderItems3; + + /** Move Items to this folder. */ + MoveHere(vItem: string | ShellFolderItem | FolderItems3, vOptions?: FileOperationFlag): void; + + /** Create a new sub folder in this folder. */ + NewFolder(bName: string): void; + + /** Offline status of the server? */ + readonly OfflineStatus: OfflineFolderStatus; + + /** Get Parent object */ + readonly ParentFolder: Folder3; + + /** Parse the name to get an item. */ + ParseName(bName: string): ShellFolderItem | null; + + /** Folder's FolderItem interface */ + readonly Self: ShellFolderItem; + + /** Ask if the WebView barricade should be shown or not */ + ShowWebViewBarricade: boolean; + + /** Synchronize all offline files */ + Synchronize(): void; + + /** Get the display name for the window */ + readonly Title: string; + } + + /** Definition of interface FolderItems3 */ + class FolderItems3 { + private 'Shell32.FolderItems3_typekey': FolderItems3; + private constructor(); + + /** Get Application object */ + readonly Application: any; + + /** Get count of items in the folder */ + readonly Count: number; + + /** Set a wildcard filter to apply to the items returned */ + Filter(grfFlags: ShellFolderEnumerationFlags, bstrFileSpec: string): void; + + /** + * Executes a verb on a collection of `FolderItem` objects + * @param vVerb String that corresponds to the command to be executed. If no verb is specified, the default verb is executed. + * @param vArgs String with one or more arguments to the command specified by vVerb. The format of this string depends on the particular verb. + */ + InvokeVerbEx(vVerb?: string, vArgs?: string): void; + + /** Return the figure for the given index */ + Item(index?: any): ShellFolderItem; + + /** Get the list of verbs common to all the items */ + readonly Verbs: FolderItemVerbs; + } + + /** Definition of interface FolderItemVerb */ + class FolderItemVerb { + private 'Shell32.FolderItemVerb_typekey': FolderItemVerb; + private constructor(); + + /** Execute the verb */ + DoIt(): void; + + /** Get display name for item */ + readonly Name: string; + } + + /** Definition of interface FolderItemVerbs */ + class FolderItemVerbs { + private 'Shell32.FolderItemVerbs_typekey': FolderItemVerbs; + private constructor(); + + /** Get count of open folder windows */ + readonly Count: number; + + /** Return the specified verb */ + Item(index?: any): FolderItemVerb; + } + + /** Shell Object Type Information */ + class Shell { + private 'Shell32.Shell_typekey': Shell; + private constructor(); + + /** Add an object to the Recent Docuements */ + AddToRecent(varFile: string | null, bstrCategory?: string): void; + + /** Get Application object */ + readonly Application: any; + + /** Browse the name space for a Folder */ + BrowseForFolder(Hwnd: number, Title: string, Options: number | BrowseInfoFlags, RootFolder?: string | ShellSpecialFolderConstants): Folder3; + + /** Determine if the current user can start/stop the named service. */ + CanStartStopService(ServiceName: string): boolean; + + /** Cascade Windows */ + CascadeWindows(): void; + + /* + * Runs the specified Control Panel (*.cpl) application. If the application is already open, it will activate the running instance. + * + * **Note** As of Windows Vista, most Control Panel applications are Shell items and cannot be opened with this function. To open those Control Panel applications, pass the canonical name to + * `control.exe`. For example: + * + * `control.exe /name Microsoft.Personalization` + */ + ControlPanelItem(bstrDir: string): void; + + /** Eject the pc */ + EjectPC(): void; + + /** Explore a folder */ + Explore(vDir: string | ShellSpecialFolderConstants): void; + + /** + * Return explorer policy value + * + * The specified value name must be within the **HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer** subkey. + * If the value name does not exist then the method returns null. + */ + ExplorerPolicy(bstrPolicyName: string): any; + + /** Bring up the file run dialog box */ + FileRun(): void; + + /** Find a computer */ + FindComputer(): void; + + /** Find Files */ + FindFiles(): void; + + /** Find a Printer in the Directory Service */ + FindPrinter(Name?: string, location?: string, model?: string): void; + + /** Return shell global setting */ + GetSetting(lSetting: number | SettingKey): boolean; + + /** + * `DirectoryServiceAvailable` -- Returns **true** if the directory service is available + * + * `IsOS_DomainMember` -- Returns **true** if the computer is a member of a domain (_Windows XP and later_) + * + * `IsOS_Personal` -- Returns **true** if the operating system is Windows XP Home Edition (_Windows XP only_) + * + * `IsOS_Professional` -- Returns **true** if the operating system is Windows XP Professional Edition (_Windows XP only_) + */ + GetSystemInformation(Name: 'DirectoryServiceAvailable' | 'IsOS_DomainMember' | 'IsOS_Personal' | 'IsOS_Professional'): boolean; + + /** + * `DoubleClickTime` -- The double-click time, in milliseconds + * + * `PhysicalMemoryInstalled` -- The amount of physical memory installed, in bytes + * + * `ProcessorArchitecture` -- The processor architecture. For details, see the discussion of the **wProcessorArchitecture** member of the + * [`SYSTEM_INFO`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724958.aspx) structure + * + * `ProcessorLevel` -- The processor level. Returns 3, 4, or 5, for x386, x486, and Pentium-level processors, respectively (_Windows Vista and later_) + * + * `ProcessorSpeed` -- The processor speed, in megahertz (MHz) + */ + GetSystemInformation(Name: 'DoubleClickTime' | 'PhysicalMemoryInstalled' | 'ProcessorArchitecture' | 'ProcessorLevel' | 'ProcessorSpeed'): number; + + /** Display shell help */ + Help(): void; + + /** get restriction settings */ + IsRestricted(Group: string, Restriction: string): number; + + /** Determine if a service is running by name. */ + IsServiceRunning(ServiceName: string): any; + + /** Minimize all windows */ + MinimizeAll(): void; + + /** Get special folder from ShellSpecialFolderConstants */ + NameSpace(vDir: string | ShellSpecialFolderConstants): Folder3 | null; + + /** Open a folder */ + Open(vDir: string | ShellSpecialFolderConstants): void; + + /** Get Parent object */ + readonly Parent: any; + + /** Refresh the menu */ + RefreshMenu(): void; + + /** Immersive Search */ + SearchCommand(): void; + + /** + * Start a service by name, and optionally set it to autostart. + * + * The method returns `false` if the service has already been started. Before calling this method, you can call + * [Shell.IsServiceRunning](https://msdn.microsoft.com/en-us/library/windows/desktop/gg537742.aspx) to ascertain the status of the service. + */ + ServiceStart(ServiceName: string, Persistent?: boolean): boolean; + + /** + * Stop a service by name, and optionally disable autostart. + * + * The method returns `false` if the service has already been stopped. Before calling this method, you can call + * [Shell.IsServiceRunning](https://msdn.microsoft.com/en-us/library/windows/desktop/gg537742.aspx) to ascertain the status of the service. + */ + ServiceStop(ServiceName: string, Persistent?: boolean): boolean; + + /** Displays the **Date and Time Properties** dialog box. */ + SetTime(): void; + + /** + * Execute generic command + * @param sFile A string that contains the name of the file on which `ShellExecute` will perform the action specified by `vOperation`. + * @param [vArgs] A string that contains parameter values for the operation. + * @param [vDir] The fully qualified path of the directory that contains the file specified by `sFile`. If this parameter is not specified, the current working directory is used. + * @param [vOperation] The operation to be performed. This value is set to one of the verb strings that is supported by the file. If this parameter is not specified, the default operation is + * performed. + * @param [vShow] A recommendation as to how the application window should be displayed initially. The application can ignore this recommendation. + */ + ShellExecute(File: string, vArgs?: string, vDir?: string, vOperation?: string, vShow?: ShellExecuteShow): void; + + /** Show/Hide browser bar. */ + ShowBrowserBar(bstrClsid: ExplorerBarCLSID, bShow: boolean): any; + + /** Exit Windows */ + ShutdownWindows(): void; + + /** Tile windows horizontally */ + TileHorizontally(): void; + + /** Tile windows vertically */ + TileVertically(): void; + + /** Raise/lower the desktop */ + ToggleDesktop(): void; + + /** Displays the **Taskbar and Start Menu Properties** dialog box. */ + TrayProperties(): void; + + /** Undo Minimize All */ + UndoMinimizeALL(): void; + + /** The collection of open folder windows */ + Windows(): ShellWindows; + + /** Displays the **Windows Security** dialog box. */ + WindowsSecurity(): void; + + /** Displays your open windows in a 3D stack that you can flip through. */ + WindowSwitcher(): void; + } + + /** ShellDispatch Load in Shell Context */ + class ShellDispatchInproc { + private 'Shell32.ShellDispatchInproc_typekey': ShellDispatchInproc; + private constructor(); + } + + /** Shell Folder Item */ + class ShellFolderItem { + private 'Shell32.ShellFolderItem_typekey': ShellFolderItem; + private constructor(); + + /** Get Application object */ + readonly Application: any; + + /** Access an extended property */ + ExtendedProperty(bstrPropName: string): any; + + /** If item is a folder return folder object */ + readonly GetFolder: Folder3 | null; + + /** If item is link return link object */ + readonly GetLink: ShellLinkObject | null; + + /** + * Execute a command on the item. + * Must be one of the values returned by the item's `FolderItemVerb.Name` property. + * If no verb is specified, the default verb will be invoked. + */ + InvokeVerb(vVerb?: string): void; + + /** + * Extended version of InvokeVerb + * @param vVerb String that corresponds to the command to be executed. If no verb is specified, the default verb is executed. + * @param vArgs String with one or more arguments to the command specified by vVerb. The format of this string depends on the particular verb. + */ + InvokeVerbEx(vVerb?: string, vArgs?: string): void; + + /** Indicates if the item can be hosted inside a browser or Windows Explorer frame. */ + readonly IsBrowsable: boolean; + + /** Is the item a file system object? */ + readonly IsFileSystem: boolean; + + /** Is the item a Folder? */ + readonly IsFolder: boolean; + + /** Is the item a link? */ + readonly IsLink: boolean; + + /** Modification Date? */ + ModifyDate: VarDate; + + /** Get display name for item */ + Name: string; + + /** Get Parent object */ + readonly Parent: any; + + /** Get the pathname to the item */ + readonly Path: string; + + /** Size */ + readonly Size: number; + + /** Contains a string representation of the item's type */ + readonly Type: string; + + /** Get the list of verbs for the object */ + Verbs(): FolderItemVerbs; + } + + /** Shell Folder View Object */ + class ShellFolderView { + private 'Shell32.ShellFolderView_typekey': ShellFolderView; + private constructor(); + + /** Get Application object */ + readonly Application: any; + + /** Get Current View Mode */ + CurrentViewMode: number; + + /** Filter View */ + FilterView(bstrFilterText: string): void; + + /** The currently focused item in the folder */ + readonly FocusedItem: ShellFolderItem; + + /** Get the folder being viewed */ + readonly Folder: Folder3; + + /** Get Folder Flags */ + FolderFlags: number; + + /** Get Group By Column */ + GroupBy: string; + + /** Set Icon Size */ + IconSize: number; + + /** Show items menu and return command selected */ + PopupItemMenu(pfi: ShellFolderItem, vx?: any, vy?: any): string; + + /** The collection of Selected Items in folder */ + SelectedItems(): FolderItems3; + + /** Select the item */ + SelectItem(pvfi: ShellFolderItem, dwFlags: ShellFolderViewSelectItem): void; + + /** Select Item relative to the Current Item */ + SelectItemRelative(iRelative: number): void; + + /** Get Sorting Columns */ + SortColumns: string; + + /** Returns the view options for showing a folder. */ + readonly ViewOptions: ShellFolderViewOptions; + } + + /** + * The **ShellFolderView** object fires two events, **EnumDone** and **SelectionChanged**, that are typically handled by applications. However, some applications + * must handle events from a series of **ShellFolderView** objects. For example, an application might host a **WebBrowser** control that allows users to navigate through + * a series of folders. Each folder has its own **ShellFolderView** object with its associated events. Handling these events can be difficult. + * + * The **ShellFolderViewOC** object simplifies event handling for such scenarios. It allows applications to handle events for all ShellFolderView objects with a single + * pair of **ShellFolderViewOC** event handlers. Each time the user navigates to a new folder, the application passes the associated **ShellFolderView** object to the + * **ShellFolderViewOC** object by calling **SetFolderView**. Then, when an **EnumDone** or **SelectionChanged** event is fired, the **ShellFolderViewOC** object + * forwards the event to its own handler for processing. + */ + class ShellFolderViewOC { + private 'Shell32.ShellFolderViewOC_typekey': ShellFolderViewOC; + private constructor(); + + /** Set the ShellFolderView object to monitor events of. */ + SetFolderView(pdisp: ShellFolderView): void; + } + + /** Shell Link object */ + class ShellLinkObject { + private 'Shell32.ShellLinkObject_typekey': ShellLinkObject; + private constructor(); + + /** Arguments for the link */ + Arguments: string; + + /** Description of the link */ + Description: string; + + /** Get the IconLocation for the link */ + GetIconLocation(pbs: string): number; + + /** Hotkey for the link */ + Hotkey: number; + + /** Fully qualified path of the link */ + Path: string; + + /** Tell the link to resolve itself */ + Resolve(fFlags: ShellLinkResolveFlags): void; + + /** + * Tell the link to save the changes + * @param sFile The fully qualified path of the file where the new link information is to be saved. If no file is specified, the current file is used. + */ + Save(vWhere?: string): void; + + /** + * Set the IconLocation for the link + * @param sPath The fully qualified path of the file that contains the icon. + * @param iIcon The index of the icon in the file specified by _sPath_. + */ + SetIconLocation(sPath: string, iIcon: number): void; + + /** Get the Show Command for the link */ + ShowCommand: LinkShowWindowState; + + /** Get the target of a link object */ + readonly Target: ShellFolderItem | null; + + /** Get the working directory for the link */ + WorkingDirectory: string; + } + + class ShellWindows { + private 'Shell32.ShellWindows_typekey': ShellWindows; + private constructor(); + + /** + * Retrieves an InternetExplorer object that represents the Shell window. + * @param index Default is 0 + */ + Item(index?: number): SHDocVw.InternetExplorer; + + /** Contains the number of items in the collection. */ + readonly Count: number; + } +} + +interface ActiveXObject { + on( + obj: Shell32.ShellFolderView, event: 'BeginDrag' | 'DefaultVerbInvoked' | 'EnumDone' | 'SelectionChanged' | 'VerbInvoked', handler: ( + this: Shell32.ShellFolderView, parameter: {}) => void): void; + on( + obj: Shell32.ShellFolderViewOC, event: 'BeginDrag' | 'DefaultVerbInvoked' | 'EnumDone' | 'SelectionChanged' | 'VerbInvoked', + handler: (this: Shell32.ShellFolderViewOC, parameter: {}) => void): void; + new (progid: K): ActiveXObjectNameMap[K]; +} + +interface ActiveXObjectNameMap { + 'Shell.Application': Shell32.Shell; + 'Shell.FolderView': Shell32.ShellFolderViewOC; +} + +interface EnumeratorConstructor { + new(col: Shell32.FolderItems3): Enumerator; + new(col: Shell32.FolderItemVerbs): Enumerator; + new(col: Shell32.ShellWindows): Enumerator; +} diff --git a/types/activex-shell/package.json b/types/activex-shell/package.json new file mode 100644 index 0000000000..d9b1031263 --- /dev/null +++ b/types/activex-shell/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "activex-helpers": "*" + } +} \ No newline at end of file diff --git a/types/activex-shell/tsconfig.json b/types/activex-shell/tsconfig.json new file mode 100644 index 0000000000..f4b549f649 --- /dev/null +++ b/types/activex-shell/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "scripthost" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "activex-shell-tests.ts" + ] +} \ No newline at end of file diff --git a/types/activex-shell/tslint.json b/types/activex-shell/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/activex-shell/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/activex-stdole/tslint.json b/types/activex-stdole/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-stdole/tslint.json +++ b/types/activex-stdole/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-vbide/tslint.json b/types/activex-vbide/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-vbide/tslint.json +++ b/types/activex-vbide/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/activex-wia/activex-wia-tests.ts b/types/activex-wia/activex-wia-tests.ts index d8046ef319..c33385af14 100644 --- a/types/activex-wia/activex-wia-tests.ts +++ b/types/activex-wia/activex-wia-tests.ts @@ -1,79 +1,505 @@ +// Note -- running these tests under cscript requires some ES5 polyfills + +const collectionToArray = (col: { Item(key: any): T }): T[] => { + const results: T[] = []; + const enumerator = new Enumerator(col); + enumerator.moveFirst(); + while (!enumerator.atEnd()) { + results.push(enumerator.item()); + enumerator.moveNext(); + } + return results; +}; + // source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx +{ + const cd = new ActiveXObject('WIA.CommonDialog'); + const dm = new ActiveXObject('WIA.DeviceManager'); -// Convert a file -let commonDialog = new ActiveXObject('WIA.CommonDialog'); -let img = commonDialog.ShowAcquireImage(); + // Download new items as they are created + { + dm.RegisterEvent(WIA.EventID.wiaEventItemCreated, WIA.Miscellaneous.wiaAnyDeviceID); + ActiveXObject.on(dm, 'OnEvent', ['EventID', 'DeviceID', 'ItemID'], x => { + const dev = dm.DeviceInfos(x.DeviceID).Connect(); + const itm = dev.GetItem(x.ItemID); + const img = cd.ShowTransfer(itm); + const v = img.FileData; + // Picture type not available in Javascript + }); + } -// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these: -let jpegFormatID = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}'; -if (img.FormatID !== jpegFormatID) { - const ip = new ActiveXObject('WIA.ImageProcess'); - ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID); - ip.Filters.Item(1).Properties.Item('FormatID').Value = jpegFormatID; - img = ip.Apply(img); -} -// with this: -/*if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) { - let ip = new ActiveXObject('WIA.ImageProcess'); - ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID); - ip.Filters.Item(1).Properties.Item('FormatID').Value = WIA.FormatID.wiaFormatJPEG; - img = ip.Apply(img); -}*/ - -// Take a picture -let dev = commonDialog.ShowSelectDevice(); -if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) { - // when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these: - const commandID = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'; - const itm = dev.ExecuteCommand(commandID); - - // with this: - // let itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); -} - -// Display detailed property information -dev = commonDialog.ShowSelectDevice(); -let e = new Enumerator(dev.Properties); // no foreach over ActiveX collections -e.moveFirst(); -while (!e.atEnd()) { - const p = e.item(); - let s = `${p.Name} (${p.PropertyID}) = `; - if (p.IsVector) { - s += '[vector of data]'; - } else { - s += p.Value; - if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType) { - if (p.Value !== p.SubTypeDefault) { - s += ` (Default = ${p.SubTypeDefault})`; - } + // Convert a file + { + let img = cd.ShowAcquireImage(); + if (img && img.FormatID !== WIA.FormatID.wiaFormatJPEG) { + const ip = new ActiveXObject('WIA.ImageProcess'); + ip.Filters.Add(ip.FilterInfos('Convert').FilterID); + ip.Filters(1).Properties('FormatID').Value = WIA.FormatID.wiaFormatJPEG; + img = ip.Apply(img); } } - if (p.IsReadOnly) { - s += ' [READ ONLY]'; - } else { - switch (p.SubType) { - case WIA.WiaSubType.FlagSubType: - case WIA.WiaSubType.ListSubType: - if (p.SubType === WIA.WiaSubType.FlagSubType) { - s += ' [valid flags include: '; + // Take a picture + { + const dev = cd.ShowSelectDevice(); + if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) { + const item = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); + } + } + + // Display detailed property information + { + const dev = cd.ShowSelectDevice(); + if (dev) { + collectionToArray(dev.Properties).forEach(p => { + let s = `${p.Name} (${p.PropertyID}) = `; + if (p.IsVector) { + s += '[vector of data]'; } else { - s += ' [valid values include: '; - } - const count = p.SubTypeValues.Count; - for (let i = 1; i <= count; i++) { - s += p.SubTypeValues.Item(i); - if (i < count) { - s += ', '; + s += p.Value; + if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType + && p.Value !== p.SubTypeDefault) { + s += ` (Default = ${p.SubTypeDefault})`; } } - s += ']'; - break; - case WIA.WiaSubType.RangeSubType: - s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`; - break; + + if (p.IsReadOnly) { + s += ' [READ ONLY]'; + } else { + switch (p.SubType) { + case WIA.WiaSubType.FlagSubType: + case WIA.WiaSubType.ListSubType: + const count = p.SubTypeValues.Count; + const items: string[] = []; + for (let i = 1; i <= count; i++) { + items.push(p.SubTypeValues(i)); + } + const descr = p.SubType === WIA.WiaSubType.FlagSubType ? 'flags' : 'values'; + s += ` [valid ${descr} include: ${items.join(',')}]`; + break; + case WIA.WiaSubType.RangeSubType: + s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`; + break; + } + } + + WScript.Echo(s); + }); } } - WScript.Echo(s); + // Determine whether the selected device is a camera + { + const dev = cd.ShowSelectDevice(); + if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) { + WScript.Echo('Selectd device is a camera'); + } + } + + // Count root - level images for transfer + { + const dev = cd.ShowSelectDevice(); + if (dev) { + const count = collectionToArray(dev.Items).filter(f => { + const imageFlag = WIA.WiaItemFlag.ImageItemFlag; + return (f.Properties('Item Flags').Value & imageFlag) === imageFlag; + }).length; + WScript.Echo(`Selected device has ${count} top-level images`); + } + } + + // Display all imagefile properties + { + const img = cd.ShowAcquireImage(); + if (img) { + collectionToArray(img.Properties).forEach(p => { + let contents = ''; + if (p.IsVector) { + contents = '[vector data not emitted]'; + } else if (p.Type === WIA.WiaImagePropertyType.RationalImagePropertyType) { + contents = `${p.Value.Nunerator}/${p.Value.Denominator}`; + } else if (p.Type === WIA.WiaImagePropertyType.StringImagePropertyType) { + contents = `"${p.Value}"`; + } else { + contents = p.Value; + } + WScript.Echo(`${p.Name} (${p.PropertyID}) = ${contents}`); + }); + } + } + + // Determine the event type + { + const dev = cd.ShowSelectDevice(); + if (dev) { + const actionEvent = WIA.WiaEventFlag.ActionEvent; + collectionToArray(dev.Events).forEach(e => { + const msg = (e.Type & actionEvent) === actionEvent ? + `${e.Name} is an Action event` : + `${e.Name} is not an Action event`; + WScript.Echo(msg); + }); + } + } + + // Set rational numerator and denominator + { + const r = new ActiveXObject('WIA.Rational'); + r.Numerator = 1; + r.Denominator = 3; + WScript.Echo(`1/3 = ${r.Value}`); + r.Numerator = 2; + r.Denominator = 6; + WScript.Echo(`2/6 = ${r.Value}`); + } + + // Create and initialize a vector object + { + const v: WIA.Vector = new ActiveXObject('WIA.Vector'); + v.SetFromString('This is a test', true, false); + + // when iterated using Enumerator / collectionToArray, each item comes back as an Automation Byte + // https://stackoverflow.com/questions/48757982/wia-vector-returns-something-which-is-not-a-number + // so the following falls, because fromCharCode is expecting a number + // collectionToArray(v).forEach(item => WScript.Echo(String.fromCharCode(item))); + + // Instead, use the Vector's Item method, or the Vector's default property: + for (let i = 1; i <= v.Count; i++) { + WScript.Echo(String.fromCharCode(v(i))); + } + } + + // Display detailed image information + { + const img = new ActiveXObject('WIA.ImageFile'); + img.LoadFile('c:\\windows\\web\\Screen\\img102.jpg'); + + let s = ` +Width = ${img.Width} +Height = ${img.Height} +Depth = ${img.PixelDepth} +Horizontal resolution = ${img.HorizontalResolution} +Vertical resolution = ${img.VerticalResolution} +Frame count = ${img.FrameCount}} + `.trim(); + + let arr: string[] = []; + + if (img.IsIndexedPixelFormat) { arr.push('Pixel data contains palette indexes'); } + if (img.IsAlphaPixelFormat) { arr.push('Pixel data has alpha information'); } + if (img.IsExtendedPixelFormat) { arr.push('Pixel data has extended color information (16 bit/channel)'); } + if (img.IsAnimated) { arr.push('Image is animated'); } + + const propertyTests = [40091, 40092, 40093, 40094, 40095] + .filter(n => img.Properties.Exists(n)) + .map(n => { + const prp = img.Properties(n); + return `${prp.Name} = ${prp.Value.String}`; + }); + arr = arr.concat(propertyTests); + + if (arr.length) { + s += '\n' + arr.join('\n'); + } + + WScript.Echo(s); + } + + // Create an imageprocess object and enumerate filters + { + const ip = new ActiveXObject('WIA.ImageProcess'); + collectionToArray(ip.FilterInfos).forEach(fi => { + const s = [ + fi.Name, + new Array(51).join('='), + fi.Description + ].join('\n'); + WScript.Echo(s); + }); + } + + // Create an imageprocess object and create one of each available filter + { + const ip = new ActiveXObject('WIA.ImageProcess'); + + const stringValue = (v: any) => { + if (typeof v === 'string') { return `"${v}"`; } + return v; + }; + + const listValues = (v: any) => collectionToArray(v).join(', '); + + const listProperties = (filter: WIA.Filter) => { + let s = [ + `${filter.Name} (${filter.FilterID})`, + new Array(51).join('='), + filter.Description, + new Array(51).join('=') + ].map(line => line + '\n').join(''); + + s += collectionToArray(filter.Properties).map(p => { + let contents: string; + + switch (typeof p.Value) { + // these case clauses replace the IsObject function in VB6/VBScript + case 'boolean': + case 'string': + case 'number': + contents = stringValue(p.Value); + default: + switch (p.SubType) { + case WIA.WiaSubType.FlagSubType: + contents = ` // [valid values formed by using the OR operator with the following bit flags: ${listValues(p.SubTypeValues)}]`; + break; + case WIA.WiaSubType.ListSubType: + contents = ` // [valid values from the following list: ${listValues(p.SubTypeValues)}]`; + break; + case WIA.WiaSubType.RangeSubType: + contents = ` // [valid values between ${p.SubTypeMin} and ${p.SubTypeMax}, with a step of ${p.SubTypeStep}]`; + break; + default: + contents = ''; + break; + } + } + + return `ip.Filters(1).Properties("${p.Name}") = ${contents}`; + }).join('\n'); + + WScript.Echo(s); + }; + + collectionToArray(ip.FilterInfos).forEach(fi => { + ip.Filters.Add(fi.FilterID); + listProperties(ip.Filters(1)); + ip.Filters.Remove(1); + }); + } + + // List the supported transfer formats + { + const stringFormat = (fld: string) => { + switch (fld) { + case WIA.FormatID.wiaFormatBMP: return 'BMP'; + case WIA.FormatID.wiaFormatPNG: return 'PNG'; + case WIA.FormatID.wiaFormatGIF: return 'GIF'; + case WIA.FormatID.wiaFormatJPEG: return 'JPEG'; + case WIA.FormatID.wiaFormatTIFF: return 'TIFF'; + default: return 'Unknown'; + } + }; + + const dev = cd.ShowSelectDevice(); + const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true); + if (items) { + WScript.Echo(collectionToArray(items(1).Formats).map(stringFormat).join(', ')); + } + } + + // Enumerate supported commands in commands collection + { + const dev = cd.ShowSelectDevice(); + if (dev && collectionToArray(dev.Commands).some(dc => dc.CommandID === WIA.CommandID.wiaCommandTakePicture)) { + WScript.Echo('Selected device supports the TakePicture command'); + } + } + + // Enumerate root - level items and display their names + { + const dev = cd.ShowSelectDevice(); + if (dev) { + collectionToArray(dev.Items).forEach(item => { + let s: string = item.Properties("Item Name").Value; + if (item.Properties.Exists("Item Time Stamp")) { + const v: WIA.Vector = item.Properties("Item Time Stamp").Value; + if (v.Count === 8) { s += ` (${v.Date})`; } + } + WScript.Echo(s); + }); + } + } + + // Determine the number of items returned by ShowSelectItems + { + const dev = cd.ShowSelectDevice(); + const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true); + if (items) { + WScript.Echo(`You selected ${items.Count} items`); + } + } + + // Enumerate all the supported events for the selected device + { + const dev = cd.ShowSelectDevice(); + if (dev) { + const msg = collectionToArray(dev.Events) + .map(e => `\n${e.Name} (${e.EventID}): ${e.Description}`) + .join(''); + WScript.Echo('The selected device supports the following events: ' + msg); + } + } + + // List all available devices by name and deviceid + collectionToArray(dm.DeviceInfos).forEach(di => { + const name: string = di.Properties("Name").Value; + WScript.Echo(`${name} (${di.DeviceID})`); + }); + + // Display all the properties for the selected device + { + const dev = cd.ShowSelectDevice(); + if (dev) { + collectionToArray(dev.Properties).forEach(p => { + const name = `${p.Name} (${p.PropertyID})`; + let contents: string; + if (p.IsVector) { + contents = '[vector of data]'; + } else if (p.Type === WIA.WiaPropertyType.StringPropertyType) { + contents = `"${p.Value}"`; + } else { + contents = p.Value; + } + WScript.Echo(`${name} = ${contents}`); + }); + } + } + + // Enumerate the supported commands + { + const dev = cd.ShowSelectDevice(); + const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true); + if (items) { + const msg = collectionToArray(items(1).Commands) + .map(c => `${c.Name}: ${c.Description}\n`) + .join(''); + WScript.Echo(`The selected item supports the following commands:\n${msg}`); + } + } + + // Create an imagefile object that contains a blank page + { + // This fails with the error: `The Vector's Type is not compatible with this operation` + /*const c = 0xFF0000FF; + const v: WIA.Vector = new ActiveXObject('WIA.Vector'); + for (let i = 0; i < 4; i++) { + v.Add(c); + } + const img = v.ImageFile(2, 2); + img.SaveFile('C:\\test.' + img.FileExtension);*/ + } + + interface WshArgumentsBase { + Item(index: TKey): string; + (index: TKey): string; + length: number; + Count(): number; + } + + interface WshArguments extends WshArgumentsBase { // not sure if WshArguments takes a string as well, or only a number + Named: WshArgumentsBase; + Unnamed: WshArgumentsBase; + ShowUsage(): void; + } + + // Implement a windows script host script that runs automatically + { + const args = collectionToArray(WScript.Arguments as WshArguments) + .map(arg => arg.toLowerCase()); + + switch (args.length) { + case 1: + case 2: + const command = `${WScript.FullName} "${WScript.ScriptFullName}" connect`; + const name = 'QuickTransfer'; + const title = 'Quick Scripting Transfer'; + const icon = `${WScript.FullName}, 0`; + const eventID = WIA.EventID.wiaEventDeviceConnected; + const deviceID = args.length === 2 ? args[1] : WIA.Miscellaneous.wiaAnyDeviceID; + + if (args[0] === 'register') { + WScript.Echo('Registering event handler'); + dm.RegisterPersistentEvent(command, name, title, icon, eventID, deviceID); + WScript.Quit(); + } else if (args[0] === 'unregister') { + WScript.Echo('Unregistering event handler'); + dm.UnregisterPersistentEvent(command, name, title, icon, eventID, deviceID); + WScript.Quit(); + } + break; + case 3: + if (args[0] === 'connect') { + const deviceID = args[1].substr(12); + const device = dm.DeviceInfos(deviceID).Connect(); + collectionToArray(device.Items).forEach(item => { + const img = item.Transfer(); + img.SaveFile(`C:\\${item.Properties('Item Name').Value}.${img.FileExtension}`); + + // Uncomment the following lines to remove the picture from the camera after transfer + for (let i = 1; i < device.Items.Count; i++) { + const item2 = device.Items(i); + if (item2.ItemID !== item.ItemID) { continue; } + try { + // some cameras don't support deleting a picture + device.Items.Remove(i); + } catch (error) { + WScript.Echo(error); + } + } + }); + WScript.Quit(); + } + break; + } + + const usage = ` +Usage: + +To register, type: + + ${WScript.ScriptName} register [] + +To unregister, type: + + ${WScript.ScriptName} unregister [] + +Available device ids: +${collectionToArray(dm.DeviceInfos) + .map(device => `${device.DeviceID} '${device.Properties("Name").Value}'`) + .join('\n')} + `.trim(); + + WScript.Echo(usage); + } + + // Count the number of child items available for transfer + { + const device = cd.ShowSelectDevice(); + const items = device && cd.ShowSelectItems(device, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true); + const item = items && items(1); + if (item) { + const count = collectionToArray(item.Items).filter(childItem => { + const flags = childItem.Properties('Item Flags').Value as number; + return (flags & WIA.WiaItemFlag.TransferItemFlag) === WIA.WiaItemFlag.TransferItemFlag; + }).length; + WScript.Echo(`Selected device has ${count} child items that can be transferred.`); + } + } + + // Use a vector object + { + const v: WIA.Vector = new ActiveXObject('WIA.Vector'); + v.Add(1); + v.Add(42); + v.Add(3); + v.Remove(1); + v.Remove(2); + WScript.Echo(`v(1) = ${v(1)}`); + v.Clear(); + v.Add('This'); + v.Add('is'); + v.Add('Cool'); + v.Remove(1); + v.Remove(2); + WScript.Echo(`v(1) = ${v(1)}`); + } } diff --git a/types/activex-wia/index.d.ts b/types/activex-wia/index.d.ts index 7d7cbae727..18e474e09c 100644 --- a/types/activex-wia/index.d.ts +++ b/types/activex-wia/index.d.ts @@ -2,22 +2,20 @@ // Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx // Definitions by: Zev Spitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Typescript Version: 2.4 +// TypeScript Version: 2.6 declare namespace WIA { /** String versions of globally unique identifiers (GUIDs) that identify common Device and Item commands. */ - // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) - /*const enum CommandID { + const enum CommandID { wiaCommandChangeDocument = '{04E725B0-ACAE-11D2-A093-00C04F72DC3C}', wiaCommandDeleteAllItems = '{E208C170-ACAD-11D2-A093-00C04F72DC3C}', wiaCommandSynchronize = '{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}', wiaCommandTakePicture = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}', - wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}' - }*/ + wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}', + } /** String versions of globally unique identifiers (GUIDs) that identify DeviceManager events. */ - // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) - /*const enum EventID { + const enum EventID { wiaEventDeviceConnected = '{A28BBADE-64B6-11D2-A231-00C04FA31809}', wiaEventDeviceDisconnected = '{143E4E83-6497-11D2-A231-00C04FA31809}', wiaEventItemCreated = '{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}', @@ -30,50 +28,48 @@ declare namespace WIA { wiaEventScanImage3 = '{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}', wiaEventScanImage4 = '{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}', wiaEventScanOCRImage = '{9D095B89-37D6-4877-AFED-62A297DC6DBE}', - wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}' - }*/ + wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}', + } /** String versions of globally unique identifiers (GUIDs) that indicate the file format of an image. */ - // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) - /*const enum FormatID { + const enum FormatID { wiaFormatBMP = '{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}', wiaFormatGIF = '{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}', wiaFormatJPEG = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}', wiaFormatPNG = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}', - wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}' - }*/ + wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}', + } /** Miscellaneous string constants */ - // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) - /*const enum Miscellaneous { + const enum Miscellaneous { wiaAnyDeviceID = '*', - wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}' - }*/ + wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}', + } /** * The WiaDeviceType enumeration specifies the type of device attached to a user's computer. Use the Type property on the DeviceInfo object or the Device - * object to obtain these values from the device. + * object to obtain these values from the device. */ const enum WiaDeviceType { CameraDeviceType = 2, ScannerDeviceType = 1, UnspecifiedDeviceType = 0, - VideoDeviceType = 3 + VideoDeviceType = 3, } /** - * A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with DeviceEv - * ent.Type and a member from the WiaEventFlags enumeration. + * A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with + * DeviceEvent.Type and a member from the WiaEventFlags enumeration. */ const enum WiaEventFlag { ActionEvent = 2, - NotificationEvent = 1 + NotificationEvent = 1, } /** The WiaImageBias enumeration helps specify what type of data the image is intended to represent. */ const enum WiaImageBias { MaximizeQuality = 131072, - MinimizeSize = 65536 + MinimizeSize = 65536, } /** The WiaImageIntent enumeration helps specify what type of data the image is intended to represent. */ @@ -81,12 +77,12 @@ declare namespace WIA { ColorIntent = 1, GrayscaleIntent = 2, TextIntent = 4, - UnspecifiedIntent = 0 + UnspecifiedIntent = 0, } /** - * The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection o - * f an ImageFile object. + * The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection + * of an ImageFile object. */ const enum WiaImagePropertyType { ByteImagePropertyType = 1001, @@ -103,12 +99,12 @@ declare namespace WIA { VectorOfUndefinedImagePropertyType = 1100, VectorOfUnsignedIntegersImagePropertyType = 1102, VectorOfUnsignedLongsImagePropertyType = 1104, - VectorOfUnsignedRationalsImagePropertyType = 1106 + VectorOfUnsignedRationalsImagePropertyType = 1106, } /** - * An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with Item.Properties("Item - * Flags") and a member from the WiaItemFlags enumeration. + * An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with + * Item.Properties("Item Flags") and a member from the WiaItemFlags enumeration. */ const enum WiaItemFlag { AnalyzeItemFlag = 16, @@ -129,12 +125,12 @@ declare namespace WIA { StorageItemFlag = 4096, TransferItemFlag = 8192, VideoItemFlag = 65536, - VPanoramaItemFlag = 1024 + VPanoramaItemFlag = 1024, } /** - * The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a Dev - * ice or Item object. + * The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a + * Device or Item object. */ const enum WiaPropertyType { BooleanPropertyType = 1, @@ -173,28 +169,31 @@ declare namespace WIA { VectorOfUnsignedIntegersPropertyType = 104, VectorOfUnsignedLargeIntegersPropertyType = 109, VectorOfUnsignedLongsPropertyType = 106, - VectorOfVariantsPropertyType = 119 + VectorOfVariantsPropertyType = 119, } /** - * The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for t - * he property. + * The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for + * the property. */ const enum WiaSubType { FlagSubType = 3, ListSubType = 2, RangeSubType = 1, - UnspecifiedSubType = 0 + UnspecifiedSubType = 0, } /** * The CommonDialog control is an invisible-at-runtime control that contains all the methods that display a User Interface. A CommonDialog control can be - * created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form. + * created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form. */ - interface CommonDialog { + class CommonDialog { + private constructor(); + private 'WIA.CommonDialog_typekey': CommonDialog; + /** - * Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile object - * on success, otherwise Nothing + * Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile + * object on success, otherwise Nothing * @param WIA.WiaDeviceType [DeviceType=0] * @param WIA.WiaImageIntent [Intent=0] * @param WIA.WiaImageBias [Bias=131072] @@ -203,11 +202,11 @@ declare namespace WIA { * @param boolean [UseCommonUI=true] * @param boolean [CancelError=false] */ - ShowAcquireImage( - DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean): ImageFile; + ShowAcquireImage(DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, + CancelError?: boolean): ImageFile | null; /** Launches the Windows Scanner and Camera Wizard and returns Nothing. Future versions may return a collection of ImageFile objects. */ - ShowAcquisitionWizard(Device: Device): any; + ShowAcquisitionWizard(Device: Device): null; /** * Displays the properties dialog box for the specified Device @@ -222,38 +221,41 @@ declare namespace WIA { ShowItemProperties(Item: Item, CancelError?: boolean): void; /** Launches the Photo Printing Wizard with the absolute path of a specific file or Vector of absolute paths to files */ - ShowPhotoPrintingWizard(Files: any): void; + ShowPhotoPrintingWizard(Files: string | Vector): void; /** - * Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success, otherwise - * Nothing + * Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success, + * otherwise Nothing * @param WIA.WiaDeviceType [DeviceType=0] * @param boolean [AlwaysSelectDevice=false] * @param boolean [CancelError=false] */ - ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device; + ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device | null; /** - * Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an It - * ems collection on success, otherwise Nothing + * Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an + * Items collection on success, otherwise Nothing * @param WIA.WiaImageIntent [Intent=0] * @param WIA.WiaImageBias [Bias=131072] * @param boolean [SingleSelect=true] * @param boolean [UseCommonUI=true] * @param boolean [CancelError=false] */ - ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items; + ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items | null; /** * Displays a progress dialog box while transferring the specified Item to the local machine. See Item.Transfer for additional information. * @param string [FormatID='{00000000-0000-0000-0000-000000000000}'] * @param boolean [CancelError=false] */ - ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): any; + ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): ImageFile; } /** The Device object represents an active connection to an imaging device. */ - interface Device { + class Device { + private constructor(); + private 'WIA.Device_typekey': Device; + /** A collection of all commands for this imaging device */ readonly Commands: DeviceCommands; @@ -264,8 +266,8 @@ declare namespace WIA { readonly Events: DeviceEvents; /** - * Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in the - * Commands collection. + * Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in + * the Commands collection. */ ExecuteCommand(CommandID: string): Item; @@ -280,13 +282,13 @@ declare namespace WIA { /** Returns the Type of Device */ readonly Type: WiaDeviceType; - - /** Returns the underlying IWiaItem interface for this Device object */ - readonly WiaItem: any; } /** The DeviceCommand object describes a CommandID that can be used when calling ExecuteCommand on a Device or Item object. */ - interface DeviceCommand { + class DeviceCommand { + private constructor(); + private 'WIA.DeviceCommand_typekey': DeviceCommand; + /** Returns the commandID for this Command */ readonly CommandID: string; @@ -298,8 +300,8 @@ declare namespace WIA { } /** - * The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item obje - * ct for more details on determining the collection of supported device commands. + * The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item + * object for more details on determining the collection of supported device commands. */ interface DeviceCommands { /** Returns the number of members in the collection */ @@ -307,10 +309,16 @@ declare namespace WIA { /** Returns the specified item in the collection by position */ Item(Index: number): DeviceCommand; + + /** Returns the specified item in the collection by position */ + (Index: number): DeviceCommand; } /** The DeviceEvent object describes an EventID that can be used when calling RegisterEvent or RegisterPersistentEvent on a DeviceManager object. */ - interface DeviceEvent { + class DeviceEvent { + private constructor(); + private 'WIA.DeviceEvent_typekey': DeviceEvent; + /** Returns the event Description */ readonly Description: string; @@ -325,8 +333,8 @@ declare namespace WIA { } /** - * The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more det - * ails on determining the collection of supported device events. + * The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more + * details on determining the collection of supported device events. */ interface DeviceEvents { /** Returns the number of members in the collection */ @@ -334,13 +342,19 @@ declare namespace WIA { /** Returns the specified item in the collection by position */ Item(Index: number): DeviceEvent; + + /** Returns the specified item in the collection by position */ + (Index: number): DeviceEvent; } /** - * The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the computer - * . + * The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the + * computer. */ - interface DeviceInfo { + class DeviceInfo { + private constructor(); + private 'WIA.DeviceInfo_typekey': DeviceInfo; + /** Establish a connection with this device and return a Device object */ Connect(): Device; @@ -355,59 +369,68 @@ declare namespace WIA { } /** - * The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the DeviceManage - * r object for detail on accessing the DeviceInfos object. + * The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the + * DeviceManager object for detail on accessing the DeviceInfos object. */ interface DeviceInfos { /** Returns the number of members in the collection */ readonly Count: number; /** Returns the specified item in the collection either by position or Device ID */ - Item(Index: any): DeviceInfo; + Item(Index: number | string): DeviceInfo; + + /** Returns the specified item in the collection either by position or Device ID */ + (Index: number | string): DeviceInfo; } /** - * The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can be - * created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form. + * The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can + * be created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form. */ - interface DeviceManager { + class DeviceManager { + private constructor(); + private 'WIA.DeviceManager_typekey': DeviceManager; + /** A collection of all imaging devices connected to this computer */ readonly DeviceInfos: DeviceInfos; /** * Registers the specified EventID for the specified DeviceID. If DeviceID is "*" then OnEvent will be called whenever the event specified occurs for any - * device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified. + * device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified. * @param string [DeviceID='*'] */ RegisterEvent(EventID: string, DeviceID?: string): void; /** - * Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full pat - * h name and the appropriate command-line arguments needed to invoke the application. + * Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full + * path name and the appropriate command-line arguments needed to invoke the application. * @param string [DeviceID='*'] */ RegisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void; /** - * Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called Regis - * terEvent. + * Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called + * RegisterEvent. * @param string [DeviceID='*'] */ UnregisterEvent(EventID: string, DeviceID?: string): void; /** - * Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the Command - * , Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent. + * Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the + * Command, Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent. * @param string [DeviceID='*'] */ UnregisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void; } /** - * The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's propertie - * s and finally use the Apply method of the ImageProcess object to filter an ImageFile. + * The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's + * properties and finally use the Apply method of the ImageProcess object to filter an ImageFile. */ - interface Filter { + class Filter { + private constructor(); + private 'WIA.Filter_typekey': Filter; + /** Returns a Description of what the filter does */ readonly Description: string; @@ -422,10 +445,13 @@ declare namespace WIA { } /** - * The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos pr - * operty on the ImageProcess object for details on accessing FilterInfo objects. + * The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos + * property on the ImageProcess object for details on accessing FilterInfo objects. */ - interface FilterInfo { + class FilterInfo { + private constructor(); + private 'WIA.FilterInfo_typekey': FilterInfo; + /** Returns a technical Description of what the filter does and how to use it in a filter chain */ readonly Description: string; @@ -437,15 +463,18 @@ declare namespace WIA { } /** - * The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on a - * ccessing the FilterInfos object. + * The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on + * accessing the FilterInfos object. */ interface FilterInfos { /** Returns the number of members in the collection */ readonly Count: number; /** Returns the specified item in the collection either by position or name */ - Item(Index: any): FilterInfo; + Item(Index: number | string): FilterInfo; + + /** Returns the specified item in the collection either by position or name */ + (Index: number | string): FilterInfo; } /** The Filters object is a collection of the Filters that will be applied to an ImageFile when you call the Apply method on the ImageProcess object. */ @@ -464,11 +493,14 @@ declare namespace WIA { /** Removes the designated filter */ Remove(Index: number): void; + + /** Returns the specified item in the collection by position or FilterID */ + (Index: number): Filter; } /** - * The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog ob - * ject for this Item. + * The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog + * object for this Item. */ interface Formats { /** Returns the number of members in the collection */ @@ -476,13 +508,19 @@ declare namespace WIA { /** Returns the specified item in the collection by position */ Item(Index: number): string; + + /** Returns the specified item in the collection by position */ + (Index: number): string; } /** - * The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files throug - * h LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject. + * The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files + * through LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject. */ - interface ImageFile { + class ImageFile { + private constructor(); + private 'WIA.ImageFile_typekey': ImageFile; + /** Returns/Sets the current frame in the image */ ActiveFrame: number; @@ -539,7 +577,10 @@ declare namespace WIA { } /** The ImageProcess object manages the filter chain. An ImageProcess object can be created using "WIA.ImageProcess" in a call to CreateObject. */ - interface ImageProcess { + class ImageProcess { + private constructor(); + private 'WIA.ImageProcess_typekey': ImageProcess; + /** Takes the specified ImageFile and returns the new ImageFile with all the filters applied on success */ Apply(Source: ImageFile): ImageFile; @@ -551,10 +592,13 @@ declare namespace WIA { } /** - * The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing It - * em objects. + * The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing + * Item objects. */ - interface Item { + class Item { + private constructor(); + private 'WIA.Item_typekey': Item; + /** A collection of all commands for this item */ readonly Commands: DeviceCommands; @@ -574,17 +618,15 @@ declare namespace WIA { readonly Properties: Properties; /** - * Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging d - * evice. Future versions may return a collection of ImageFile objects. + * Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging + * device. Future versions may return a collection of ImageFile objects. * @param string [FormatID='{00000000-0000-0000-0000-000000000000}'] */ - Transfer(FormatID?: string): any; - - /** Returns the underlying IWiaItem interface for this Item object */ - readonly WiaItem: any; + Transfer(FormatID?: string): ImageFile; } /** The Items object contains a collection of Item objects. See the Items property on the Device or Item object for details on accessing the Items object. */ + // tslint:disable-next-line interface-name interface Items { /** Adds a new Item with the specified Name and Flags. The Flags value is created by using the OR operation with members of the WiaItemFlags enumeration. */ Add(Name: string, Flags: number): void; @@ -597,28 +639,37 @@ declare namespace WIA { /** Removes the designated Item */ Remove(Index: number): void; + + /** Returns the specified item in the collection by position */ + (Index: number): Item; } /** - * The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See the - * Properties property on any of these objects for detail on accessing the Properties object. + * The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See + * the Properties property on any of these objects for detail on accessing the Properties object. */ interface Properties { /** Returns the number of members in the collection */ readonly Count: number; /** Indicates whether the specified Property exists in the collection */ - Exists(Index: any): boolean; + Exists(Index: number | string): boolean; /** Returns the specified item in the collection either by position or name. */ - Item(Index: any): Property; + Item(Index: number | string): Property; + + /** Returns the specified item in the collection either by position or name. */ + (Index: number | string): Property; } /** - * The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property o - * n any of these objects for details on accessing Property objects. + * The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property + * on any of these objects for details on accessing Property objects. */ - interface Property { + class Property { + private constructor(); + private 'WIA.Property_typekey': Property; + /** Indicates whether the Property Value is read only */ readonly IsReadOnly: boolean; @@ -657,10 +708,13 @@ declare namespace WIA { } /** - * The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created u - * sing "WIA.Rational" in a call to CreateObject. + * The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created + * using "WIA.Rational" in a call to CreateObject. */ - interface Rational { + class Rational { + private constructor(); + private 'WIA.Rational_typekey': Rational; + /** Returns/Sets the Rational Value Denominator */ Denominator: number; @@ -672,19 +726,19 @@ declare namespace WIA { } /** - * The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be create - * d using "WIA.Vector" in a call to CreateObject. + * The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be + * created using "WIA.Vector" in a call to CreateObject. */ - interface Vector { + interface Vector { /** - * If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the Vecto - * r collection. + * If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the + * Vector collection. * @param number [Index=0] */ - Add(Value: any, Index?: number): void; + Add(Value: TItem, Index?: number): void; /** Returns/Sets the Vector of Bytes as an array of bytes */ - BinaryData: any; + BinaryData: SafeArray; /** Removes all elements. */ Clear(): void; @@ -696,30 +750,30 @@ declare namespace WIA { Date: VarDate; /** - * Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an ImageFil - * e from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details. + * Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an + * ImageFile from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details. * @param number [Width=0] * @param number [Height=0] */ ImageFile(Width?: number, Height?: number): ImageFile; - /** Returns/Sets the specified item in the vector by position */ - Item(Index: number): any; + /** Returns the specified item in the vector by position */ + Item(Index: number): TItem; /** - * If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs mu - * st be ARGB data. Returns a Picture object on success. See the ImageFile method for more details. + * If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs + * must be ARGB data. Returns a Picture object on success. See the ImageFile method for more details. * @param number [Width=0] * @param number [Height=0] */ Picture(Width?: number, Height?: number): any; /** Removes the designated element and returns it if successful */ - Remove(Index: number): any; + Remove(Index: number): TItem | null; /** - * Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be sto - * red as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string. + * Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be + * stored as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string. * @param boolean [Resizable=true] * @param boolean [Unicode=true] */ @@ -730,30 +784,24 @@ declare namespace WIA { * @param boolean [Unicode=true] */ String(Unicode?: boolean): string; + + /** Returns the specified item in the vector by position */ + (Index: number): TItem; } } interface ActiveXObject { + new(progid: K): ActiveXObjectNameMap[K]; on(obj: WIA.DeviceManager, event: 'OnEvent', argNames: ['EventID', 'DeviceID', 'ItemID'], handler: ( - this: WIA.DeviceManager, parameter: { - EventID: string, DeviceID: string, ItemID: string}) => void): void; - set(obj: WIA.Vector, propertyName: 'Item', parameterTypes: [number], newValue: any): void; - new(progid: 'WIA.CommonDialog'): WIA.CommonDialog; - new(progid: 'WIA.DeviceManager'): WIA.DeviceManager; - new(progid: 'WIA.ImageFile'): WIA.ImageFile; - new(progid: 'WIA.ImageProcess'): WIA.ImageProcess; - new(progid: 'WIA.Rational'): WIA.Rational; - new(progid: 'WIA.Vector'): WIA.Vector; + this: WIA.DeviceManager, parameter: { readonly EventID: string, readonly DeviceID: string, readonly ItemID: string }) => void): void; + set(obj: WIA.Vector, propertyName: 'Item', parameterTypes: [number], newValue: TItem): void; } -interface EnumeratorConstructor { - new(col: WIA.DeviceCommands): WIA.DeviceCommand; - new(col: WIA.DeviceEvents): WIA.DeviceEvent; - new(col: WIA.DeviceInfos): WIA.DeviceInfo; - new(col: WIA.FilterInfos): WIA.FilterInfo; - new(col: WIA.Filters): WIA.Filter; - new(col: WIA.Formats): string; - new(col: WIA.Items): WIA.Item; - new(col: WIA.Properties): WIA.Property; - new(col: WIA.Vector): any; +interface ActiveXObjectNameMap { + 'WIA.CommonDialog': WIA.CommonDialog; + 'WIA.DeviceManager': WIA.DeviceManager; + 'WIA.ImageFile': WIA.ImageFile; + 'WIA.ImageProcess': WIA.ImageProcess; + 'WIA.Rational': WIA.Rational; + 'WIA.Vector': WIA.Vector; } diff --git a/types/activex-wia/tslint.json b/types/activex-wia/tslint.json index 2750cc0197..457cebbb55 100644 --- a/types/activex-wia/tslint.json +++ b/types/activex-wia/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } \ No newline at end of file +{ + "extends": "dtslint/dt.json", + "rules":{ + "no-const-enum": false + } +} diff --git a/types/activex-word/tslint.json b/types/activex-word/tslint.json index 4ac54521fe..3224b40b8b 100644 --- a/types/activex-word/tslint.json +++ b/types/activex-word/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [false] + "no-const-enum": false } -} \ No newline at end of file +} diff --git a/types/add-zero/tsconfig.json b/types/add-zero/tsconfig.json index e71d235cdf..d7645a2e3c 100644 --- a/types/add-zero/tsconfig.json +++ b/types/add-zero/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "add-zero-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/adone/adone.d.ts b/types/adone/adone.d.ts index 34540761b5..91ebc4db7c 100644 --- a/types/adone/adone.d.ts +++ b/types/adone/adone.d.ts @@ -7,16 +7,15 @@ declare namespace adone { export function identity(x: T): T; export function truly(): true; export function falsely(): false; - export const ok: "OK"; - export const bad: "BAD"; - export const exts: [".js", ".tjs", ".ajs"]; + export const ok: "ok"; + export const bad: "bad"; export function log(...args: any[]): void; - export function fatal(...args: any[]): void; - export function error(...args: any[]): void; - export function warn(...args: any[]): void; - export function info(...args: any[]): void; - export function debug(...args: any[]): void; - export function trace(...args: any[]): void; + export function logFatal(...args: any[]): void; + export function logError(...args: any[]): void; + export function logWarn(...args: any[]): void; + export function logInfo(...args: any[]): void; + export function logDebug(...args: any[]): void; + export function logTrace(...args: any[]): void; export function o(...props: any[]): object; export const Date: typeof global.Date; export const hrtime: typeof global.process.hrtime; @@ -76,40 +75,16 @@ declare namespace adone { set(Class: object, tag: string): void; has(obj: object, tag: string): boolean; define(tag: string, predicate?: string): void; - SUBSYSTEM: symbol; - APPLICATION: symbol; - TRANSFORM: symbol; - CORE_STREAM: symbol; - LOGGER: symbol; - LONG: symbol; - BIGNUMBER: symbol; - EXBUFFER: symbol; - EXDATE: symbol; - CONFIGURATION: symbol; - GENESIS_NETRON: symbol; - GENESIS_PEER: symbol; - NETRON: symbol; - NETRON_PEER: symbol; - NETRON_ADAPTER: symbol; - NETRON_DEFINITION: symbol; - NETRON_DEFINITIONS: symbol; - NETRON_REFERENCE: symbol; - NETRON_INTERFACE: symbol; - NETRON_STUB: symbol; - NETRON_REMOTESTUB: symbol; - NETRON_STREAM: symbol; - FAST_STREAM: symbol; - FAST_FS_STREAM: symbol; - FAST_FS_MAP_STREAM: symbol; } } export const tag: I.Tag; - export function bind(libName: string): object; export function getAssetAbsolutePath(relPath: string): string; export function loadAsset(relPath: string): string | Buffer; export function require(path: string): object; export const package: object; + export function sprintf(format: string, ...args: any[]): string; + namespace I { interface Runtime { term: object; // TODO @@ -120,11 +95,10 @@ declare namespace adone { export const runtime: I.Runtime; - export const homePath: string; - export const rootPath: string; - export const etcPath: string; - export const config: object; - export const emptyBuffer: Buffer; + export const ROOT_PATH: string; + export const ETC_PATH: string; + export const configuration: object; + export const EMPTY_BUFFER: Buffer; export const assert: assertion.I.AssertFunction; export const expect: assertion.I.ExpectFunction; diff --git a/types/adone/glosses/application.d.ts b/types/adone/glosses/application.d.ts index 6b2b783d68..4c9661843a 100644 --- a/types/adone/glosses/application.d.ts +++ b/types/adone/glosses/application.d.ts @@ -1,5 +1,275 @@ declare namespace adone { namespace application { - function run(app: object, ignoreArgs?: boolean): Promise; + namespace I { + type ArgumentType = ((x: string, index: number) => any) | RegExp; + + interface ArgumentInfo { + name: string | string[]; + action?: "store" + | "store_const" + | "store_true" + | "store_false" + | "append" + | "count" + | "set"; + nargs?: number | "+" | "*" | "?" + type?: ArgumentType | ArgumentType[]; + verify?: (args: any, opts: any) => boolean; // TODO + required?: boolean; + description?: string; + help?: string; + holder?: string | string[]; + appendDefaultMessage?: boolean; + appendChoicesHelpMessage?: boolean; + default?: any; + enabled?: boolean; + } + + interface Group { + name: string; + description?: string; + } + + interface MainCommandInfo { + arguments?: Array; + options?: Array; + description?: string; + optionsGroups?: Group[]; + blindMode?: boolean; + match?: (name: string) => boolean; + handler?: (args: object, opts: object) => void; + } + + interface CommandInfo extends MainCommandInfo { + name?: string | string[]; + group?: string; + } + + interface ApplicationInfo { + name?: string; + description?: string; + subsystems?: SubsystemInfo[]; + commandsGroups?: Group[] + } + + interface SubsystemInfo { + name: string; + description?: string; + subsystem: string; + transpile?: boolean; + group?: string; + } + } + + function DSubsystem(info?: I.ApplicationInfo): (...args: any[]) => void; + + function DApplication(info?: I.ApplicationInfo): (...args: any[]) => void; + + function DCliCommand(info?: I.CommandInfo): (...args: any[]) => void; + + function DMainCliCommand(info?: I.MainCommandInfo): (...args: any[]) => void; + + namespace I { + interface LoadSubsystemOptions { + name?: string, + description?: string, + group?: string, + transpile?: boolean + } + + interface CommonAddSubsystemInfo { + name?: string, + useFilename?: boolean + description?: string, + group?: string, + configureArgs?: any[] + transpile?: boolean, + bind?: boolean | string + } + + interface AddSubsystemInfo extends CommonAddSubsystemInfo { + subsystem: Subsystem | string, + } + + interface SysInfo { + name: string; + description: string; + group: string; + configureArgs: any[]; + instance: Subsystem; + path: string | null; + } + + interface SysInfoWithPath extends SysInfo { + path: string; + } + + interface SysInfoNoPath extends SysInfo { + path: null; + } + + interface AddSubsystemsFromOptions extends CommonAddSubsystemInfo { + filter?: string[] | ((file: string) => boolean | Promise) + } + } + + class Subsystem extends event.AsyncEmitter { + constructor(options?: { name?: string }); + + readonly name?: string; + + readonly root?: Subsystem; + + setRoot(root: Subsystem): void; + + readonly parent?: Subsystem; + + readonly state: number; + + readonly isOwned: boolean; + + setState(state: number): void; + + waitForState(expectedState: number, timeout?: number): Promise; + + configure(): void; + + initialize(): void; + + uninitialize(): void; + + configureSubsystems(): Promise; + + uninitializeSubsystems(): Promise; + + reinitializeSubsystems(): Promise; + + configureSubsystem(name: string): Promise; + + loadSubsystem(subsystem: string | Subsystem, options?: I.LoadSubsystemOptions): Promise; + + unloadSubsystem(name: string): Promise; + + initializeSubsystem(name: string): Promise; + + uninitializeSubsystem(name: string): Promise; + + reinitializeSubsystem(name: string): Promise; + + getSubsystem(name: string): Subsystem; + + hasSubsystem(name: string): boolean; + + hasSubsystems(): boolean; + + addSubsystem(info: I.AddSubsystemInfo & { subsystem: Subsystem }): I.SysInfoNoPath; + addSubsystem(info: I.AddSubsystemInfo & { subsystem: string }): I.SysInfoWithPath; + + addSubsystemsFrom(path: string, options?: I.AddSubsystemsFromOptions): I.SysInfoWithPath; + + instantiateSubsystem(subsystem: string | Subsystem, options?: { + transpile?: boolean + }): Subsystem; + + deleteSubsystem(name: string, force?: boolean): void; + + getSubsystemInfo(name: string): I.SysInfo; + + getSubsystems(): I.SysInfo[]; + } + + namespace I { + interface ReportOptions { + events?: string; + signal?: string; + filename?: string; + directory?: string; + } + } + + class Application extends Subsystem { + readonly isMain: boolean; + + main(): void; + + enableReport(opts?: I.ReportOptions): void; + + reportEnabled(): boolean; + + run(): Promise; + + exit(code?: number): Promise; + + exitOnSignal(...names: string[]): void; + + removeProcesshandlers(): void; + + _uncaughtException(err: any): void; + + _unhandledRejection(reson: any, p: Promise): void; + + _rejectionHandled(p: Promise): void; + + _signalExit(sigName: string): void; + + } + + namespace I { + interface Command { + // ? + } + + interface Argument { + // ? + } + + interface PositionalArgument extends Argument { + // ? + } + + interface OptionalArgument extends Argument { + // ? + } + + interface DefineCommandFromSubsystemOptions { + name?: string; + description?: string; + group?: string; + subsystem: string | Subsystem; + configureArgs?: any[]; + lazily?: boolean; + transpile?: boolean; + } + } + + class CliApplication extends Application { + run(options?: { ignoreArgs?: boolean }): Promise; + + getVersion(): Promise; + + exposeCliInterface(ctxId?: string): void; + + readonly mainCommand: I.Command; + + defineMainCommand(schema: I.MainCommandInfo): this; + + defineArguments(schema: I.MainCommandInfo): this; + + defineCommand(schema: I.CommandInfo): I.Command; + + defineCommandFromSubsystem(options?: I.DefineCommandFromSubsystemOptions): void; + + defineOption(schema: I.ArgumentInfo): void; + + defineOptionsGroup(schema: I.Group): void; + + defineCommandsGroup(schema: I.Group): void; + + option(path: string, options?: { value?: boolean }): any; + } + + function run(app: Application, ignoreArgs?: boolean): Promise; + + function runCli(app: CliApplication, ignoreArgs?: boolean): Promise; } } diff --git a/types/adone/glosses/archives.d.ts b/types/adone/glosses/archives.d.ts index 3f059ff14d..ddeb25d891 100644 --- a/types/adone/glosses/archives.d.ts +++ b/types/adone/glosses/archives.d.ts @@ -448,7 +448,7 @@ declare namespace adone { isCompressed(): boolean; } - interface ZipFile extends event.EventEmitter { + interface ZipFile extends event.Emitter { /** * true until close() is called; then it's false */ diff --git a/types/adone/glosses/assertion.d.ts b/types/adone/glosses/assertion.d.ts index e7ba662791..f0cf377a21 100644 --- a/types/adone/glosses/assertion.d.ts +++ b/types/adone/glosses/assertion.d.ts @@ -38,7 +38,7 @@ declare namespace adone { proxyExcludedKeys: string[]; } - type PossibleTypes = util.I.PossibleTypes | "array"; + type PossibleTypes = meta.I.PossibleTypes | "array"; type UseFunction = (fn: () => void) => assertion; @@ -53,18 +53,10 @@ declare namespace adone { * Throws an AssertionError, like node.js */ fail(actual?: any, expected?: any, message?: string, operator?: any): void; - /** - * Asserts that value is truthy - */ - isOk(value: any, message?: string): void; /** * Asserts that value is truthy */ ok(value: any, message?: string): void; - /** - * Asserts that value is falsy - */ - isNotOk(value: any, message?: string): void; /** * Asserts that value is falsy */ @@ -104,51 +96,51 @@ declare namespace adone { /** * Asserts that value > above */ - isAbove(value: any, above: any, message?: string): void; + above(value: any, above: any, message?: string): void; /** * Asserts that value >= atLeast */ - isAtLeast(value: any, atLeast: any, message?: string): void; + atLeast(value: any, atLeast: any, message?: string): void; /** * Asserts that value < below */ - isBelow(value: any, below: any, message?: string): void; + below(value: any, below: any, message?: string): void; /** * Asserts that value <= atMost */ - isAtMost(value: any, atMost: any, message?: string): void; + atMost(value: any, atMost: any, message?: string): void; /** * Asserts that value is true */ - isTrue(value: any, message?: string): void; + true(value: any, message?: string): void; /** * Asserts that value is not true */ - isNotTrue(value: any, message?: string): void; + notTrue(value: any, message?: string): void; /** * Asserts that value is false */ - isFalse(value: any, message?: string): void; + false(value: any, message?: string): void; /** * Asserts that value is not false */ - isNotFalse(value: any, message?: string): void; + notFalse(value: any, message?: string): void; /** * Asserts that value is null */ - isNull(value: any, message?: string): void; + null(value: any, message?: string): void; /** * Asserts that valus is not null */ - isNotNull(value: any, message?: string): void; + notNull(value: any, message?: string): void; /** * Asserts that value is NaN */ - isNaN(value: any, message?: string): void; + NaN(value: any, message?: string): void; /** * Asserts that value is not NaN */ - isNotNaN(value: any, message?: string): void; + NotNaN(value: any, message?: string): void; /** * Asserts that value is neither null nor undefined */ @@ -160,63 +152,63 @@ declare namespace adone { /** * Asserts that value is undefined */ - isUndefined(value: any, message?: string): void; + undefined(value: any, message?: string): void; /** * Asserts that value is not undefined */ - isDefined(value: any, message?: string): void; + defined(value: any, message?: string): void; /** * Asserts that value is a function */ - isFunction(value: any, message?: string): void; + function(value: any, message?: string): void; /** * Asserts that value is not a function */ - isNotFunction(value: any, message?: string): void; + notFunction(value: any, message?: string): void; /** * Asserts that value is an object of type Object */ - isObject(value: any, message?: string): void; + object(value: any, message?: string): void; /** * Asserts that value is not an object of type Object */ - isNotObject(value: any, message?: string): void; + notObject(value: any, message?: string): void; /** * Asserts that value is an array */ - isArray(value: any, message?: string): void; + array(value: any, message?: string): void; /** * Asserts that value is not an array */ - isNotArray(value: any, message?: string): void; + notArray(value: any, message?: string): void; /** * Asserts that value is a string */ - isString(value: any, message?: string): void; + string(value: any, message?: string): void; /** * Asserts that value is not a string */ - isNotString(value: any, message?: string): void; + notString(value: any, message?: string): void; /** * Asserts that value is a number */ - isNumber(value: any, message?: string): void; + number(value: any, message?: string): void; /** * Asserts that value is not a number */ - isNotNumber(value: any, message?: string): void; + notNumber(value: any, message?: string): void; /** * Asserts that value is a finite number */ - isFinite(value: any, message?: string): void; + finite(value: any, message?: string): void; /** * Asserts that value is a boolean */ - isBoolean(value: any, message?: string): void; + boolean(value: any, message?: string): void; /** * Asserts that value is not a boolean */ - isNotBoolean(value: any, message?: string): void; + notBoolean(value: any, message?: string): void; /** * Asserts that value's type is `type` */ @@ -562,66 +554,34 @@ declare namespace adone { * Throws an error if value is truthy */ ifError(value: any): void; - /** - * Asserts that object is extensible - */ - isExtensible(object: object, message?: string): void; /** * Asserts that object is extensible */ extensible(object: object, message?: string): void; - /** - * Asserts that object is not extensible - */ - isNotExtensible(object: object, message?: string): void; /** * Asserts that object is not extensible */ notExtensible(object: object, message?: string): void; - /** - * Asserts that object is sealed - */ - isSealed(object: object, message?: string): void; /** * Asserts that object is sealed */ sealed(object: object, message?: string): void; - /** - * Asserts that object is not sealed - */ - isNotSealed(object: object, message?: string): void; /** * Asserts that object is not sealed */ notSealed(object: object, message?: string): void; - /** - * Asserts that object is frozen - */ - isFrozen(object: object, message?: string): void; /** * Asserts that object is frozen */ frozen(object: object, message?: string): void; - /** - * Asserts that object is not frozen - */ - isNotFrozen(object: object, message?: string): void; /** * Asserts that object is not frozen */ notFrozen(object: object, message?: string): void; - /** - * Asserts that value is empty - */ - isEmpty(value: any, message?: string): void; /** * Asserts that value is empty */ empty(value: any, message?: string): void; - /** - * Asserts that value is not empty - */ - isNotEmpty(value: any, message?: string): void; /** * Asserts that value is not empty */ @@ -710,43 +670,43 @@ declare namespace adone { /** * Asserts that the target is non-strictly equal to true */ - ok: this; + ok(): this; /** * Asserts that the target is true */ - true: this; + true(): this; /** * Asserts that the target is false */ - false: this; + false(): this; /** * Asserts that the target is null */ - null: this; + null(): this; /** * Asserts that the target is undefined */ - undefined: this; + undefined(): this; /** * Asserts that the target is NaN */ - NaN: this; + NaN(): this; /** * Asserts that the target is neither null nor undefined */ - exist: this; + exist(): this; /** * Asserts that the target is empty */ - empty: this; + empty(): this; /** * Asserts that the target is an arguments object */ - arguments: this; + arguments(): this; /** * Asserts that the target is an arguments object */ - Arguments: this; + Arguments(): this; /** * Asserts that the target is strictly equal to value(===) */ @@ -976,26 +936,26 @@ declare namespace adone { /** * Asserts that the target is extensible */ - extensible: this; + extensible(): this; /** * Asserts that the target is sealed */ - sealed: this; + sealed(): this; /** * Asserts that the target is frozen */ - frozen: this; + frozen(): this; /** * Asserts that the target is a finite number */ - finite: this; + finite(): this; } interface MockAssertions extends Assertion { /** * Asserts that the spy has been called */ - called: this; + called(): this; /** * Asserts that the spy has been called n times */ @@ -1003,15 +963,15 @@ declare namespace adone { /** * Asserts that the spy has been called once */ - calledOnce: this; + calledOnce(): this; /** * Asserts that the spy has been called twice */ - calledTwice: this; + calledTwice(): this; /** * Asserts that the spy has been been called with `new` */ - calledThrice: this; + calledThrice(): this; /** * Asserts that the spy has been called before anotherSpy */ @@ -1059,7 +1019,7 @@ declare namespace adone { } } - class AssertionError extends x.Exception { + class AssertionError extends error.Exception { constructor(message?: string, props?: object, ssf?: object) } diff --git a/types/adone/glosses/collections.d.ts b/types/adone/glosses/collections.d.ts deleted file mode 100644 index 178921136d..0000000000 --- a/types/adone/glosses/collections.d.ts +++ /dev/null @@ -1,1965 +0,0 @@ -declare namespace adone { - namespace collection { - namespace I.LinkedList { - /** - * Represents the node of a linked list - */ - interface Node { - /** - * The next node - */ - next?: Node; - - /** - * The previous node - */ - prev?: Node; - - /** - * The value this node contains - */ - value: T; - } - } - - /** - * Represents a linked list - */ - class LinkedList { - /** - * The maximum length of the list - */ - readonly maxLength: number; - - /** - * Current length of the list - */ - readonly length: number; - - /** - * Whether the list is autoresizable - */ - readonly autoresize: boolean; - - /** - * @param maxLength Maximum length of the linked list - */ - constructor(maxLength?: number); - - /** - * Whether the list is full - */ - readonly full: boolean; - - /** - * Whether the list is empty - */ - readonly empty: boolean; - - /** - * Resizes the list - */ - resize(newLength: number): this; - - /** - * Adds a new node to the end - * - * @returns Added node - */ - push(value: T): I.LinkedList.Node; - - /** - * Removes the last node, returns undefined if the list is empty - */ - pop(): T | undefined; - - /** - * Removes the first node, returns undefined if the list is empty - */ - shift(): T | undefined; - - /** - * Inserts a new node at the beginning of the list - * - * @returns Added node - */ - unshift(value: T): I.LinkedList.Node; - - /** - * Moves the given node to the end of the list - */ - pushNode(node: I.LinkedList.Node): void; - - /** - * Moved the given node to the beginning of the list - */ - unshiftNode(node: I.LinkedList.Node): void; - - /** - * Removes the given node from the list - */ - removeNode(node: I.LinkedList.Node): void; - - /** - * Clears the list - * - * @param strong Whether to reset all the node's values - */ - clear(strong?: boolean): void; - - /** - * Convers the list to an array - */ - toArray(): T[]; - - /** - * The first element of the list - */ - readonly front: T; - - /** - * The last element of the list - */ - readonly back: T; - - /** - * Returns an iterator over the list elements - */ - [Symbol.iterator](): IterableIterator; - - /** - * Returns the next node for the given node - */ - nextNode(node: I.LinkedList.Node): I.LinkedList.Node; - - /** - * Maps this linked list to a new one using the given function - */ - map(fn: (value: T, index: number) => R): LinkedList; - - /** - * Invokes the given callback for each value from the beginning to the end (much faster than for-of). - * If the given function returns false it stops iterating. - */ - forEach(callback: (value: T, index: number) => void | boolean): void; - - /** - * Default length of a new created linked list - */ - static DEFAULT_LENGTH: number; - } - - namespace I { - type Long = math.Long; - - type Longable = math.I.Longable; - - namespace ByteArray { - interface Varint32 { - value: number; - length: number; - } - - interface Varint64 { - value: Long; - length: number; - } - - interface String { - string: string; - length: number; - } - - type Wrappable = string | ByteArray | Buffer | Uint8Array | ArrayBuffer; - - type Metrics = "b" | "c"; - } - } - - /** - * Represents an array of bytes, enhanced Node.js Buffer - */ - class ByteArray { - /** - * Constructs a new ByteArray - * - * @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64) - * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) - */ - constructor(capacity?: number, noAssert?: boolean); - - /** - * Reads a BitSet as an array of booleans. - * - * @param offset Offset to read from. Will use and increase offset by length if omitted. - */ - readBitSet(offset?: number): boolean[]; - - /** - * Reads the specified number of bytes. - * - * @param length Number of bytes to read - * @param offset Offset to read from. Will use and increase offset by length if omitted. - */ - read(length: number, offset?: number): ByteArray; - - /** - * Reads an 8bit signed integer - * - * @param offset Offset to read from - */ - readInt8(offset?: number): number; - - /** - * Reads an 8bit unsigned integer - * - * @param offset Offset to read from - */ - readUInt8(offset?: number): number; - - /** - * Reads a 16bit signed le integer - * - * @param offset Offset to read from - */ - readInt16LE(offset?: number): number; - - /** - * Reads a 16bit unsigned le integer - * - * @param offset Offset to read from - */ - readUInt16LE(offset?: number): number; - - /** - * Reads a 16bit signed be integer - * - * @param offset Offset to read from - */ - readInt16BE(offset?: number): number; - - /** - * Reads a 16bit unsigned be integer - * - * @param offset Offset to read from - */ - readUInt16BE(offset?: number): number; - - /** - * Reads a 32bit signed le integer - * - * @param offset Offset to read from - */ - readInt32LE(offset?: number): number; - - /** - * Reads a 32bit unsigned le integer - * - * @param offset Offset to read from - */ - readUInt32LE(offset?: number): number; - - /** - * Reads a 32bit signed be integer - * - * @param offset Offset to read from - */ - readInt32BE(offset?: number): number; - - /** - * Reads a 32bit unsigned be integer - * - * @param offset Offset to read from - */ - readUInt32BE(offset?: number): number; - - /** - * Reads a 64bit signed le integer as math.Long - * - * @param offset Offset to read from - */ - readInt64LE(offset?: number): math.Long; - - /** - * Reads a 64bit unsigned le integer as math.Long - * - * @param offset Offset to read from - */ - readUInt64LE(offset?: number): math.Long; - - /** - * Reads a 64bit signed be integer as math.Long - * - * @param offset Offset to read from - */ - readInt64BE(offset?: number): math.Long; - - /** - * Reads a 64bit unsigned be integer as math.Long - * - * @param offset Offset to read from - */ - readUInt64BE(offset?: number): math.Long; - - /** - * Reads a 32bit le float - * - * @param offset Offset to read from - */ - readFloatLE(offset?: number): number; - - /** - * Reads a 32bit be float - * - * @param offset Offset to read from - */ - readFloatBE(offset?: number): number; - - /** - * Reads a 64bit le float - * - * @param offset Offset to read from - */ - readDoubleLE(offset?: number): number; - - /** - * Reads a 64bit be float - * - * @param offset Offset to read from - */ - readDoubleBE(offset?: number): number; - - /** - * Appends some data to this ByteArray. - * This will overwrite any contents behind the specified offset up to the appended data's length. - * - * @param source The source write from - * @param offset Offset to write to - * @param length length to read from the source - * @param encoding encoding to use for wrapping the source in bytearray - */ - write(source: I.ByteArray.Wrappable, offset?: number, length?: number, encoding?: string): this; - - /** - * Writes the array as a bitset. - * @param value Array of booleans to write - */ - writeBitSet(value: number[]): this; - - /** - * Writes the array as a bitset. - * @param value Array of booleans to write - * @param offset Offset to write to - */ - writeBitSet(value: number[], offset: number): number; - - /** - * Writes an 8bit signed integer - * - * @param offset Offset to write to - */ - writeInt8(value: number, offset?: number): this; - - /** - * Writes an 8bit unsigned integer - * - * @param offset Offset to write to - */ - writeUInt8(value: number, offset?: number): this; - - /** - * Writes a 16bit signed le integer - * - * @param offset Offset to write to - */ - writeInt16LE(value: number, offset?: number): this; - - /** - * Writes a 16bit signed be integer - * - * @param offset Offset to write to - */ - writeInt16BE(value: number, offset?: number): this; - - /** - * Writes a 16bit unsigned le integer - * - * @param offset Offset to write to - */ - writeUInt16LE(value: number, offset?: number): this; - - /** - * Writes a 16bit unsigned be integer - * - * @param offset Offset to write to - */ - writeUInt16BE(value: number, offset?: number): this; - - /** - * Writes a 32bit signed le integer - * - * @param offset Offset to write to - */ - writeInt32LE(value: number, offset?: number): this; - - /** - * Writes a 32bit signed be integer - * - * @param offset Offset to write to - */ - writeInt32BE(value: number, offset?: number): this; - - /** - * Writes a 32bit unsigned le integer - * - * @param offset Offset to write to - */ - writeUInt32LE(value: number, offset?: number): this; - - /** - * Writes a 32bit unsigned be integer - * - * @param offset Offset to write to - */ - writeUInt32BE(value: number, offset?: number): this; - - /** - * Writes a 64bit signed le long integer - * - * @param offset Offset to write to - */ - writeInt64LE(value: math.Long | string | number, offset?: number): this; - - /** - * Writes a 64bit signed be long integer - * - * @param offset Offset to write to - */ - writeInt64BE(value: math.Long | string | number, offset?: number): this; - - /** - * Writes a 64bit unsigned le long integer - * - * @param offset Offset to write to - */ - writeUInt64LE(value: math.Long | string | number, offset?: number): this; - - /** - * Writes a 64bit unsigned be long integer - * - * @param offset Offset to write to - */ - writeUInt64BE(value: math.Long | string | number, offset?: number): this; - - /** - * Writes a 32bit le float - * - * @param offset Offset to write to - */ - writeFloatLE(value: number, offset?: number): this; - - /** - * Writes a 32bit be float - * - * @param offset Offset to write to - */ - writeFloatBE(value: number, offset?: number): this; - - /** - * Writes a 64bit le float - * - * @param offset Offset to write to - */ - writeDoubleLE(value: number, offset?: number): this; - - /** - * Writes a 64bit be float - * - * @param offset Offset to write to - */ - writeDoubleBE(value: number, offset?: number): this; - - /** - * Writes a 32bit base 128 variable-length integer - */ - writeVarint32(value: number): this; - - /** - * Writes a 32bit base 128 variable-length integer - * - * @param offset Offset to write to - */ - writeVarint32(value: number, offset: number): number; - - /** - * Writes a zig-zag encoded 32bit base 128 variable-length integer - */ - writeVarint32ZigZag(value: number): this; - - /** - * Writes a zig-zag encoded 32bit base 128 variable-length integer - * - * @param offset Offset to write to - */ - writeVarint32ZigZag(value: number, offset: number): number; - - /** - * Reads a 32bit base 128 variable-length integer - */ - readVarint32(): number; - - /** - * Reads a 32bit base 128 variable-length integer - * - * @param offset Offset to read from - */ - readVarint32(offset: number): I.ByteArray.Varint32; - - /** - * Reads a zig-zag encoded 32bit base 128 variable-length integer - */ - readVarint32ZigZag(): number; - - /** - * Reads a zig-zag encoded 32bit base 128 variable-length integer - * - * @param offset Offset to read from - */ - readVarint32ZigZag(offset: number): I.ByteArray.Varint32; - - /** - * Writes a 64bit base 128 variable-length integer - */ - writeVarint64(value: math.Long | string | number): this; - - /** - * Writes a 64bit base 128 variable-length integer - * - * @param offset Offset to write to - */ - writeVarint64(value: math.Long | string | number, offset: number): number; - - /** - * Writes a zig-zag encoded 64bit base 128 variable-length integer - */ - writeVarint64ZigZag(value: math.Long | string | number): this; - - /** - * Writes a zig-zag encoded 64bit base 128 variable-length integer - * - * @param offset Offset to write to - */ - writeVarint64ZigZag(value: math.Long | string | number, offset: number): number; - - /** - * Reads a 64bit base 128 variable-length integer - */ - readVarint64(): I.Long; - - /** - * Reads a 64bit base 128 variable-length integer - * - * @param offset Offset to read from - */ - readVarint64(offset: number): I.ByteArray.Varint64; - - /** - * Reads a zig-zag encoded 64bit base 128 variable-length integer - */ - readVarint64ZigZag(): math.Long; - - /** - * Reads a zig-zag encoded 64bit base 128 variable-length integer - * - * @param offset Offset to read from - */ - readVarint64ZigZag(offset: number): I.ByteArray.Varint64; - - /** - * Writes a NULL-terminated UTF8 encoded string. - * For this to work the specified string must not contain any NULL characters itself - */ - writeCString(str: string): this; - - /** - * Writes a NULL-terminated UTF8 encoded string. - * For this to work the specified string must not contain any NULL characters itself - * - * @param offset Offset to write to - */ - writeCString(str: string, offset: number): number; - - /** - * Reads a NULL-terminated UTF8 encoded string. - * For this to work the string read must not contain any NULL characters itself - */ - readCString(): string; - - /** - * Reads a NULL-terminated UTF8 encoded string. - * For this to work the string read must not contain any NULL characters itself - * - * @param offset Offset to read from - */ - readCString(offset: number): I.ByteArray.String; - - /** - * Writes an UTF8 encoded string - */ - writeString(str: string): this; - - /** - * Writes an UTF8 encoded string - * - * @param offset Offset to write to - */ - writeString(str: string, offset: number): number; - - /** - * Reads an UTF8 encoded string - * - * @param length Number of characters or bytes to read - * @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c") - */ - readString(length: number, metrics?: I.ByteArray.Metrics): string; - - /** - * Reads an UTF8 encoded string - * - * @param length Number of characters or bytes to read - * @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c") - * @param offset Offset to read from - */ - readString(length: number, metrics: I.ByteArray.Metrics, offset: number): I.ByteArray.String; - - /** - * Reads an UTF8 encoded string - * - * @param length Number of characters or bytes to read - * @param offset Offset to read from - */ - readString(length: number, offset: number): I.ByteArray.String; - - /** - * Writes a length as varint32 prefixed UTF8 encoded string - */ - writeVString(str: string): this; - - /** - * Writes a length as varint32 prefixed UTF8 encoded string - * - * @param offset Offset to read from - */ - writeVString(str: string, offset: number): number; - - /** - * Reads a length as varint32 prefixed UTF8 encoded string - */ - readVString(): string; - - /** - * Reads a length as varint32 prefixed UTF8 encoded string - * - * @param offset Offset to read from - */ - readVString(offset: number): I.ByteArray.String; - - /** - * Appends this ByteArray's contents to another ByteArray. - * This will overwrite any contents behind the specified offset up to the length of this ByteArray's data - * - * @param offset Offset to append to - */ - appendTo(target: ByteArray, offset?: number): this; - - /** - * Enables or disables assertions of argument types and offsets. - * Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid - */ - assert(assert?: boolean): this; - - /** - * Gets the capacity of this ByteArray's backing buffer - */ - capacity(): number; - - /** - * Clears this ByteArray's offsets by setting offset to 0 and limit to the backing buffer's capacity - */ - clear(): this; - - /** - * Creates a cloned instance of this ByteArray, - * preset with this ByteArray's values for offset, markedOffset and limit - * - * @param copy Whether to copy the backing buffer or to return another view on the same, false by default - */ - clone(copy?: boolean): ByteArray; - - /** - * Compacts this ByteArray to be backed by a buffer of its contents' length. - * Will set offset = 0 and limit = capacity and adapt markedOffset to the same relative position if set - * - * @param begin Offset to start at, buffer offset by default - * @param end Offset to end at, buffer limit by default - */ - compact(begin?: number, end?: number): this; - - /** - * Creates a copy of this ByteArray's contents. - * - * @param begin Begin offset, buffer offset by default - * @param end End offset, buffer limit by default - */ - copy(begin?: number, end?: number): ByteArray; - - /** - * Copies this ByteArray's contents to another ByteArray. - * - * @param targetOffset Offset to copy to. Will use and increase the target's offset by the number of bytes copied if omitted - * @param sourceOffset Offset to start copying from. Will use and increase offset by the number of bytes copied if omitted - * @param sourceLimit Offset to end copying from, defaults to the buffer limit - */ - copyTo(target: ByteArray, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ByteArray; - - /** - * Makes sure that this ByteArray is backed by a ByteArray#buffer of at least the specified capacity. - * If the current capacity is exceeded, it will be doubled. - * If double the current capacity is less than the required capacity, the required capacity will be used instead - */ - ensureCapacity(capacity: number): this; - - /** - * Overwrites this ByteArray's contents with the specified value. - * - * @param value Byte value to fill with. If given as a string, the first character is used - * @param begin Begin offset. Will use and increase offset by the number of bytes written if omitted. defaults to offset - * @param end End offset, defaults to limit. - */ - fill(value: string | number, begin?: number, end?: number): this; - - /** - * Makes this ByteArray ready for a new sequence of write or relative read operations. - * Sets limit = offset and offset = 0. - * Make sure always to flip a ByteArray when all relative read or write operations are complete - */ - flip(): this; - - /** - * Marks an offset on this ByteArray to be used later - * - * @param offset Offset to mark. Defaults to offset. - */ - mark(offset?: number): this; - - /** - * Prepends some data to this ByteArray. - * This will overwrite any contents before the specified offset up to the prepended data's length. - * If there is not enough space available before the specified offset, - * the backing buffer will be resized and its contents moved accordingly - * - * @param source Data to prepend - * @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted. - */ - prepend(source: I.ByteArray.Wrappable, offset: number): this; - - /** - * Prepends some data to this ByteArray. - * This will overwrite any contents before the specified offset up to the prepended data's length. - * If there is not enough space available before the specified offset, - * the backing buffer will be resized and its contents moved accordingly - * - * @param source Data to prepend - * @param encoding Encoding if data is a string - * @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted. - */ - prepend(source: I.ByteArray.Wrappable, encoding?: string, offset?: number): this; - - /** - * Prepends this ByteArray to another ByteArray. - * This will overwrite any contents before the specified offset up to the prepended data's length. - * If there is not enough space available before the specified offset, - * the backing buffer will be resized and its contents moved accordingly - * - * @param offset Offset to prepend at - */ - prependTo(target: ByteArray, offset?: number): this; - - /** - * Gets the number of remaining readable bytes - */ - remaining(): number; - - /** - * Resets this ByteArray's offset. - * If an offset has been marked through mark before, offset will be set to markedOffset, which will then be discarded. - * If no offset has been marked, sets offset = 0 - */ - reset(): this; - - /** - * Resizes this ByteArray to be backed by a buffer of at least the given capacity. - * Will do nothing if already that large or larger. - * - * @param capacity Capacity required - */ - resize(capacity: number): this; - - /** - * Reverses this ByteArray's contents. - * - * @param begin Offset to start at, defaults to offset - * @param end Offset to end at, defaults to limit - */ - reverse(begin?: number, end?: number): this; - - /** - * Skips the next length bytes. This will just advance - */ - skip(length: number): this; - - /** - * Slices this ByteArray by creating a cloned instance with offset = begin and limit = end - * - * @param begin Begin offset, defaults to offset - * @param end End offset, defaults to limit - */ - slice(begin?: number, end?: number): ByteArray; - - /** - * Returns a copy of the backing buffer that contains this ByteArray's contents. - * - * @param forceCopy If true returns a copy, otherwise returns a view referencing the same memory if possible, false by default - * @param begin Begin offset, offset by default - * @param end End offset, limit by default - */ - toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer; - - /** - * Returns a raw buffer compacted to contain this ByteArray's contents - */ - toArrayBuffer(): ArrayBuffer; - - /** - * Converts the ByteArray's contents to a string - * - * @param encoding Output encoding - * @param begin Begin offset, offset by default - * @param end End offset, limit by default - */ - toString(encoding?: string, begin?: number, end?: number): string; - - /** - * Encodes this ByteArray's contents to a base64 encoded string - * - * @param begin Begin offset, offset by default - * @param end End offset, limit by default - */ - toBase64(begin?: number, end?: number): string; - - /** - * Encodes this ByteArray to a binary encoded string, that is using only characters 0x00-0xFF as bytes - * - * @param begin Begin offset, offset by default - * @param end End offset, limit by default - */ - toBinary(begin?: number, end?: number): string; - - /** - * Encodes this ByteArray to a hex encoded string with marked offsets - * - * @param columns If true returns two columns hex + ascii, defaults to false - */ - toDebug(columns?: boolean): string; - - /** - * Encodes this ByteArray's contents to a hex encoded string - * - * @param begin Begin offset, offset by default - * @param end End offset, limit by default - */ - toHex(begin?: number, end?: number): string; - - /** - * Encodes this ByteArray's contents to an UTF8 encoded string - * - * @param begin Begin offset, offset by default - * @param end End offset, limit by default - */ - toUTF8(begin?: number, end?: number): string; - - static accessor(): typeof Buffer; - - /** - * Allocates a new ByteArray backed by a buffer of the specified capacity. - * - * @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64) - * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) - */ - static allocate(capacity?: number, noAssert?: boolean): ByteArray; - - /** - * Concatenates multiple ByteArrays into one - * - * @param encoding Encoding for strings - * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) - */ - static concat(buffers: I.ByteArray.Wrappable[], encoding?: string, noAssert?: boolean): ByteArray; - - static type(): typeof Buffer; - - /** - * Wraps a buffer or a string. - * Sets the allocated ByteArray's offset to 0 and its limit to the length of the wrapped data - * - * @param encoding Encoding for strings - * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) - */ - static wrap(buffer: I.ByteArray.Wrappable, encoding?: string, noAssert?: boolean): ByteArray; - - /** - * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer - */ - static calculateVarint32(value: number): number; - - /** - * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding - */ - static zigZagEncode32(n: number): number; - - /** - * Decodes a zigzag encoded signed 32bit integer - */ - static zigZagDecode32(n: number): number; - - /** - * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer - */ - static calculateVarint64(value: number | string): number; - - /** - * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding - */ - static zigZagEncode64(value: number | string | I.Long): I.Long; - - /** - * Decodes a zigzag encoded signed 64bit integer. - */ - static zigZagDecode64(value: number | string | I.Long): I.Long; - - /** - * 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. - */ - static calculateString(str: string): number; - - /** - * Decodes a base64 encoded string to a ByteArray - */ - static fromBase64(str: string): ByteArray; - - /** - * Encodes a binary string to base64 like window.btoa does - */ - static btoa(str: string): string; - - /** - * Decodes a base64 encoded string to binary like window.atob does - */ - static atob(b64: string): string; - - /** - * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteArray - */ - static fromBinary(str: string): ByteArray; - - /** - * Decodes a hex encoded string with marked offsets to a ByteArray - */ - static fromDebug(str: string, noAssert?: boolean): ByteArray; - - /** - * Decodes a hex encoded string to a ByteArray - */ - static fromHex(str: string, noAssert?: boolean): ByteArray; - - /** - * Decodes an UTF8 encoded string to a ByteArray - */ - static fromUTF8(str: string, noAssert?: boolean): ByteArray; - - /** - * Default initial capacity - */ - static DEFAULT_CAPACITY: number; - - /** - * Default no assertions flag - */ - static DEFAULT_NOASSERT: boolean; - - /** - * Maximum number of bytes required to store a 32bit base 128 variable-length integer - */ - static MAX_VARINT32_BYTES: number; - - /** - * Maximum number of bytes required to store a 64bit base 128 variable-length integer - */ - static MAX_VARINT64_BYTES: number; - - /** - * Metrics representing number of UTF8 characters. Evaluates to `c`. - */ - static METRICS_CHARS: string; - - /** - * Metrics representing number of bytes. Evaluates to `b`. - */ - static METRICS_BYTES: string; - } - - /** - * Represents a queue - */ - class Queue { - /** - * Whether the queue is full - */ - readonly full: boolean; - - /** - * The length of the queue - */ - readonly length: number; - - /** - * Whether the queue is empty - */ - readonly empty: boolean; - - /** - * Inserts a new element at the end - */ - push(x: S): this; - - /** - * Removes and returns an element from the beginning - */ - pop(): T | undefined; - } - - /** - * Represents an asynchronous queue, each pop is a promise - * that is resolved with an existing element or an element that will be pushed in the future - */ - class AsyncQueue extends Queue> { - /** - * Returns a promise that will be resolved with an existing element or an element that will be pushed in the future - */ - pop(): Promise; - } - - namespace I.PriorityQueue { - interface ConstructorOptions { - /** - * Function that compares objects. - * - * Must return a positive value if a > b, a negative if a < b, and zero for equal objects - */ - compare?(a: T, b: T): number; - - /** - * Function that evaluates the priority value by the given objects, - * if the returned value > 0, then the first argument has higher priority, - * = 0 same priority, < 0 lower priority. - * By default the top element is an element that has the highest priority, - * the default priority function is equal to the compare function - */ - priority?(a: T, b: T): number; - } - } - - /** - * Represents a priority queue - */ - class PriorityQueue { - /** - * Whether the queue is empty - */ - readonly empty: boolean; - - /** - * The length of the queue - */ - readonly length: number; - - constructor(options?: I.PriorityQueue.ConstructorOptions); - - /** - * Clones the queue - */ - clone(): PriorityQueue; - - /** - * Inserts a new element - */ - push(x: T): this; - - /** - * Removes the top element (that has the highest priority) - */ - pop(): T | undefined; - - /** - * Deletes the given element from the queue - */ - delete(x: T): this; - - /** - * Replaces the top element (pop + push) - */ - replace(x: T): T; - - /** - * Faster push + pop - */ - pushpop(x: T): T; - - /** - * Converts the queue to an array, it works with a clone of the queue, so the original queue is untouched - */ - toArray(): T[]; - - /** - * Creates a queue object from the given iterable - */ - static from(iterable: Iterable, options?: I.PriorityQueue.ConstructorOptions): PriorityQueue; - } - - /** - * Represents a faster LRU cache but with less functionality - */ - class FastLRU { - /** - * @param size Cache size, unlimited by default - */ - constructor(size?: number, options?: { - /** - * Function that is called when a value is deleted - */ - dispose?(key: K, value: V): void - }); - - /** - * The actual size of the cache - */ - readonly size: number; - - /** - * Gets the value by the given key - */ - get(key: K): V | undefined; - - /** - * Sets a new value for the given key - */ - set(key: K, value: V): void; - - /** - * Deletes the given key from the cache - */ - delete(key: K): boolean; - - /** - * Checks whether the cache has an element with the given key - */ - has(key: K): boolean; - - /** - * Returns the keys iterator - */ - keys(): IterableIterator; - - /** - * Returns the values iterator - */ - values(): IterableIterator; - - /** - * Returns the entries iterator - */ - entries(): IterableIterator<[K, V]>; - - /** - * Clears the cache - */ - clear(): void; - } - - /** - * Represents a stack - */ - class Stack { - /** - * Whether the stack is empty - */ - readonly empty: boolean; - - /** - * The top element of the stack - */ - readonly top: T; - - /** - * Inserts a new element - */ - push(x: T): this; - - /** - * Removes the top element - */ - pop(): T | undefined; - - /** - * Returns an iterator over the values - */ - [Symbol.iterator](): IterableIterator; - - /** - * Creates a stack and pushed all the values from the given iterable object - */ - static from(iterable: Iterable): Stack; - } - - namespace I.BinarySearchTree { - interface ConstructorOptions { - /** - * The parent tree - */ - parent?: Tree; - - /** - * Value to keep in this node - */ - value?: V; - - /** - * WHether the values must be unique, false by default. - * If false you can store many values for same keys, otherwise only one - */ - unique?: boolean; - - /** - * Custom keys comparator, by default if a > b => -1, a < b -1, a === b => 0 - */ - compareKeys?(a: K, b: K): number; - - /** - * Function that defines whether 2 values are the same, by default a === b - */ - checkValueEquality?(a: V, b: V): boolean; - } - - interface Query { - $lt?: K; - $lte?: K; - $gt?: K; - $gte?: K; - } - } - - /** - * Represents a binary search tree - */ - class BinarySearchTree { - constructor(options?: I.BinarySearchTree.ConstructorOptions>); - - /** - * Returns the max descendant tree - */ - getMaxKeyDescendant(): BinarySearchTree; - - /** - * Returns the maximum key - */ - getMaxKey(): K; - - /** - * Returns the min descendant tree - */ - getMinKeyDescendant(): BinarySearchTree; - - /** - * Returns the minumum key - */ - getMinKey(): K; - - /** - * Traverses the tree and calls the given function for each node - */ - checkAllNodesFullfillCondition(test: (key: K, value: V) => void): void; - - /** - * Checks whether the tree is a binary search tree - */ - checkIsBST(): void; - - /** - * Returns the of keys in the tree - */ - getNumberOfKeys(): number; - - /** - * Inserts a new key/value - */ - insert(key: K, value: V): void; - - /** - * Searches the given key in the tree - */ - search(key: K): V[]; - - /** - * Returns all the values from the given key bounds - */ - betweenBounds(query: I.BinarySearchTree.Query): V[]; - - /** - * Deletes the given key/value from the tree - */ - delete(key: K, value?: V): void; - - /** - * Executed the given callback for each node from left to right - */ - executeOnEveryNode(fn: (tree: BinarySearchTree) => void): void; - - /** - * Prints the tree - */ - prettyPrint(printData?: boolean, spacing?: string): void; - } - - /** - * Represents an AVL tree, a self-balancing binary search tree - */ - class AVLTree { - constructor(options?: I.BinarySearchTree.ConstructorOptions>); - - /** - * Checks whether the tree is an avl tree - */ - checkIsAVLT(): void; - - /** - * Inserts a new key/value - */ - insert(key: K, value: V): void; - - /** - * Deletes the given key/value from the tree - */ - delete(key: K, value?: V): void; - - /** - * Returns the of keys in the tree - */ - getNumberOFKeys(): number; - - /** - * Searches the given key in the tree - */ - search(key: K): V[]; - - /** - * Returns all the values from the given key bounds - */ - betweenBounds(query: I.BinarySearchTree.Query): V[]; - - /** - * Executed the given callback for each node from left to right - */ - executeOnEveryNode(fn: (tree: AVLTree) => void): void; - - /** - * Prints the tree - */ - prettyPrint(printDate?: boolean, spacing?: string): void; - } - - namespace I.RedBlackTree { - interface Node { - /** - * The key associated to the node - */ - key: K; - - /** - * The value associated to the node - */ - value: V; - - /** - * The left subtree of the node - */ - left?: Node; - - /** - * The right subtree of the node - */ - right?: Node; - } - - interface Iterator { - /** - * Checks if the iterator is valid - */ - readonly valid: boolean; - - /** - * The value of the node at the iterator's current position, null if invalid - */ - readonly node: Node | null; - - /** - * The key of the item referenced by the iterator, undefined if invalid - */ - readonly key?: K; - - /** - * The value of the item referenced by the iterator, undefined if invalid - */ - readonly value?: V; - - /** - * Returns the position of this iterator in the sequence - */ - readonly index: number; - - /** - * If true, then the iterator is not at the end of the sequence - */ - readonly hasNext: boolean; - - /** - * If true, then the iterator is not at the beginning of the sequence - */ - readonly hasPrev: boolean; - - /** - * The tree associated to the iterator - */ - tree: RedBlackTree; - - /** - * Makes a copy of the iterator - */ - clone(): Iterator; - - /** - * Removes the item at the position of the iterator and returns a new rb-tree - */ - remove(): RedBlackTree; - - /** - * Advances the iterator to the next position - */ - next(): void; - - /** - * Updates the value of the node in the tree at this iterator and returns a new rb-tree - */ - update(value: V): RedBlackTree; - - /** - * Moves the iterator backward one element - */ - prev(): void; - } - } - - /** - * Represents a fully persistent red-black tree - */ - class RedBlackTree { - /** - * The root node of the tree - */ - root: I.RedBlackTree.Node; - - constructor(compare?: (a: K, b: K) => number, root?: RedBlackTree); - - /** - * A sorted array of all the keys in the tree - */ - readonly keys: K[]; - - /** - * An array of all the values in the tree - */ - readonly values: V[]; - - /** - * The number of items in the tree - */ - readonly length: number; - - /** - * An iterator pointing to the first element in the tree - */ - readonly begin: I.RedBlackTree.Iterator; - - /** - * An iterator pointing to the last element in the tree - */ - readonly end: I.RedBlackTree.Iterator; - - /** - * Creates a new tree with the new pair inserted - */ - insert(key: K, value: V): RedBlackTree; - - /** - * Walks a visitor function over the nodes of the tree in order - * - * @param visit A callback that gets executed on each node. - * If a truthy value is returned from the visitor, then iteration is stopped. - * @param lo An optional start of the range to visit (inclusive) - * @param hi An optional end of the range to visit (non-inclusive) - */ - forEach(visit: (key: K, value: V) => T, lo?: K, hi?: K): T; - - /** - * Finds an iterator starting at the given element - */ - at(idx: number): I.RedBlackTree.Iterator; - - /** - * Finds the first item in the tree whose key is >= key - */ - ge(key: K): I.RedBlackTree.Iterator; - - /** - * Finds the first item in the tree whose key is > key - */ - gt(key: K): I.RedBlackTree.Iterator; - - /** - * Finds the first item in the tree whose key is < key - */ - lt(key: K): I.RedBlackTree.Iterator; - - /** - * Finds the first item in the tree whose key is <= key - */ - le(key: K): I.RedBlackTree.Iterator; - - /** - * Returns an iterator pointing to the first item in the tree with key, otherwise null - */ - find(key: K): I.RedBlackTree.Iterator | null; - - /** - * Removes the first item with key in the tree - */ - remove(key: K): RedBlackTree; - - /** - * Retrieves the value associated to the given key - */ - get(key: K): V | undefined; - } - - /** - * Respresetns a data structure which is a combination of an array and a set. - * Adding a new member is O(1), testing for membership is O(1), - * and finding the index of an element is O(1). - */ - class ArraySet { - /** - * The number of unique items in this ArraySet. - * If duplicates have been added, than those do not count towards the size. - */ - readonly length: number; - - /** - * Adds the given value to this set. - * - * @param allowDuplicates Whether to allow duplicates in the set, false by default - */ - add(value: T, allowDuplicates?: boolean): this; - - /** - * Checks whether the given value is a member of the set - */ - has(value: T): boolean; - - /** - * Returns the index of the given element. - * If the value is not present it will return -1 - */ - indexOf(value: T): number; - - /** - * Converts the set to an array - */ - toArray(): T[]; - - /** - * Creates an ArraySet from the given iterable object - * - * @param allowDuplicates Whether to allow duplicates in the set, false by default - */ - static from(iterable: Iterable, allowDuplicates?: boolean): ArraySet; - } - - namespace I.BufferList { - type Appendable = Buffer | BufferList | string | number | Array; - } - - /** - * Represents a Node.js Buffer list collector, reader and streamer with callback/promise interface support - */ - class BufferList extends std.stream.Duplex implements PromiseLike { - /** - * Creates a new buffer list - */ - constructor(); - - /** - * Creates a new buffer list and initiates with the given value - */ - constructor(buffer: I.BufferList.Appendable); - - /** - * Creates a new buffer list and subscribes the given callback on the end/error event - */ - constructor(callback: (err: any, data: Buffer) => void); - - /** - * Adds an additional buffer or BufferList to the internal list - */ - append(buf: I.BufferList.Appendable): this; - - /** - * Ends the stream - */ - end(chunk?: Buffer): void; - end(chunk?: () => void): void; - - /** - * Returns the byte at the specified index - */ - get(idx: number): number; - - /** - * Returns a new Buffer object containing the bytes within the range specified. - */ - slice(start?: number, end?: number): Buffer; - - /** - * Copies the content of the list in the dest buffer - * starting from destStart and containing the bytes within the range specified with srcStart to srcEnd - * - * @param dstStart writes from this position - * @param srcStart reads bytes from this position - * @param srcEnd read bytes to this position - */ - copy(dst: T, dstStart?: number, srcStart?: number, srcEnd?: number): T; - - /** - * Returns a new BufferList object containing the bytes within the range specified. - * No copies will be performed. All buffers in the result share memory with the original list. - * - * @param start slice from - * @param end slice to - */ - shallowSlice(start?: number, end?: number): BufferList; - - /** - * Return a string representation of the buffer - */ - toString(encoding?: fs.I.Encoding, start?: number, end?: number): string; - - /** - * Shifts bytes off the start of the list - */ - consume(bytes: number): this; - - /** - * Performs a shallow-copy of the list. - */ - duplicate(): BufferList; - - /** - * Destroys the stream - */ - destroy(): void; - - then( - onfulfilled?: ((value: Buffer) => T1 | PromiseLike) | null, - onrejected?: ((reason: any) => T2 | PromiseLike) | null - ): PromiseLike; - - catch(onrejected?: ((reason: any) => T | PromiseLike) | null): PromiseLike; - } - - /** - * Represents a Map that has a default values factory object or function. - * Each get of non-existent key goes through the factory - */ - class DefaultMap extends Map { - constructor(factory?: ((key: K) => V) | { [key: string]: V }, iterable?: Iterable<[K, V]>); - } - - namespace I.LRU { - type LengthCalculator = (value: V, key: K) => number; - interface ConstructorOptions { - /** - * The maximum size of the cache, checked by applying the length function to all values in the cache. - * Default is Infinity - */ - max?: number; - - /** - * Maximum age in ms. Items are not pro-actively pruned out as they age, - * but if you try to get an item that is too old, - * it'll drop it and return undefined instead of giving it to you - */ - maxAge?: number; - - /** - * Function that is used to calculate the length of stored items - */ - length?: LengthCalculator; - - /** - * Function that is called on items when they are dropped from the cache - */ - dispose?(key: K, value: V): void; - - /** - * Whether to return the stale value before deleting it - */ - stale?: boolean; - - /** - * Dispose will only be called when a key falls out of the cache, not when it is overwritten - */ - noDisposeOnSet?: boolean; - } - - interface SerializedEntry { - /** - * key - */ - key: K; - - /** - * value - */ - value: V; - - /** - * when it becomes expired - */ - e: number; - } - - interface Entry { - /** - * key - */ - key: K; - - /** - * value - */ - value: V; - - /** - * entry length - */ - length: number; - - /** - * Timestamp when the entry was created - */ - now: number; - - /** - * Maximum live time - */ - maxAge: number; - } - } - - /** - * Represent an LRU cache - */ - class LRU { - /** - * Creates an LRU cache of the given size - */ - constructor(max: number); - - /** - * Creates an LRU cache with the given options - */ - constructor(options?: I.LRU.ConstructorOptions); - - /** - * The length of the cache, setter resizes the cache - */ - max: number; - - /** - * stale setting - */ - allowStale: boolean; - - /** - * maxAge setting - */ - maxAge: number; - - /** - * length setting - */ - lengthCalculator: I.LRU.LengthCalculator; - - /** - * Total length of objects in cache taking into account length options function - */ - readonly length: number; - - /** - * Total quantity of objects currently in cache. - * Note, that stale items are returned as part of this item count. - */ - readonly itemCount: number; - - /** - * Iterates over all the keys in the cache, in reverse recent-ness order. (ie, less recently used items are iterated over first.) - */ - rforEach(fn: (this: T, value: V, key: K, cache: LRU) => void, thisp?: T): void; - - /** - * Iterates over all the keys in the cache, in order of recent-ness - */ - forEach(fn: (this: T, value: V, key: K, cache: LRU) => void, thisp?: T): void; - - /** - * Returns an array of the keys in the cache - */ - keys(): K[]; - - /** - * Returns an array of the values in the cache - */ - values(): V[]; - - /** - * Clears the cache entirely, throwing away all values - */ - reset(): void; - - /** - * Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)` - */ - dump(): Array>; - - /** - * Returns an internal lru list of entries - */ - dumpLru(): LinkedList>; - - /** - * @param opts std.util.inspect options - */ - inspect(opts?: object): string; - - /** - * Sets a new value for the given key. Updates the "recently used"-ness of the key - * - * @param maxAge maxAge option specific for this key - * @returns Whether the key was set - */ - set(key: K, value: V, maxAge?: number): boolean; - - /** - * Check if a key is in the cache, without updating the recent-ness or deleting it for being stale - */ - has(key: K): boolean; - - /** - * Gets the value of the given key. Updates the "recently used"-ness of the key - */ - get(key: K): V | undefined; - - /** - * Returns the key value without updating the "recently used"-ness of the key - */ - peek(key: K): V | undefined; - - /** - * Deletes the less recently used element - */ - pop(): I.LRU.Entry; - - /** - * Deletes a key out of the cache - */ - del(key: K): void; - - /** - * Loads another cache entries array, obtained with sourceCache.dump(), into the cache. - * The destination cache is reset before loading new entries - */ - load(arr: Array>): void; - - /** - * Manually iterates over the entire cache proactively pruning old entries - */ - prune(): void; - } - - /** - * Represents a Map that keeps keys only for a specified interval of time - */ - class TimedoutMap extends Map { - /** - * @param timeout maximum age of the keys, 1000 by default - * @param callback callback that is called with each key when the timeout is passed - */ - constructor(timeout?: number, callback?: (key: K) => void); - - /** - * Gets the timeout - */ - getTimeout(): number; - - /** - * Sets the timeout - */ - setTimeout(ms: number): void; - - /** - * Iterates over the map and calls the callback for each element - */ - forEach(callback: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): this; - - /** - * Deletes the given key - */ - delete(key: K): boolean; - } - } -} diff --git a/types/adone/glosses/collections/array_set.d.ts b/types/adone/glosses/collections/array_set.d.ts new file mode 100644 index 0000000000..c13d8769f1 --- /dev/null +++ b/types/adone/glosses/collections/array_set.d.ts @@ -0,0 +1,44 @@ +declare namespace adone.collection { + /** + * Respresetns a data structure which is a combination of an array and a set. + * Adding a new member is O(1), testing for membership is O(1), + * and finding the index of an element is O(1). + */ + class ArraySet { + /** + * The number of unique items in this ArraySet. + * If duplicates have been added, than those do not count towards the size. + */ + readonly length: number; + + /** + * Adds the given value to this set. + * + * @param allowDuplicates Whether to allow duplicates in the set, false by default + */ + add(value: T, allowDuplicates?: boolean): this; + + /** + * Checks whether the given value is a member of the set + */ + has(value: T): boolean; + + /** + * Returns the index of the given element. + * If the value is not present it will return -1 + */ + indexOf(value: T): number; + + /** + * Converts the set to an array + */ + toArray(): T[]; + + /** + * Creates an ArraySet from the given iterable object + * + * @param allowDuplicates Whether to allow duplicates in the set, false by default + */ + static from(iterable: Iterable, allowDuplicates?: boolean): ArraySet; + } +} diff --git a/types/adone/glosses/collections/async_queue.d.ts b/types/adone/glosses/collections/async_queue.d.ts new file mode 100644 index 0000000000..9a575a33be --- /dev/null +++ b/types/adone/glosses/collections/async_queue.d.ts @@ -0,0 +1,12 @@ +declare namespace adone.collection { + /** + * Represents an asynchronous queue, each pop is a promise + * that is resolved with an existing element or an element that will be pushed in the future + */ + class AsyncQueue extends Queue> { + /** + * Returns a promise that will be resolved with an existing element or an element that will be pushed in the future + */ + pop(): Promise; + } +} diff --git a/types/adone/glosses/collections/avl_tree.d.ts b/types/adone/glosses/collections/avl_tree.d.ts new file mode 100644 index 0000000000..2b5dc132b6 --- /dev/null +++ b/types/adone/glosses/collections/avl_tree.d.ts @@ -0,0 +1,48 @@ +declare namespace adone.collection { + /** + * Represents an AVL tree, a self-balancing binary search tree + */ + class AVLTree { + constructor(options?: I.BinarySearchTree.ConstructorOptions>); + + /** + * Checks whether the tree is an avl tree + */ + checkIsAVLT(): void; + + /** + * Inserts a new key/value + */ + insert(key: K, value: V): void; + + /** + * Deletes the given key/value from the tree + */ + delete(key: K, value?: V): void; + + /** + * Returns the of keys in the tree + */ + getNumberOFKeys(): number; + + /** + * Searches the given key in the tree + */ + search(key: K): V[]; + + /** + * Returns all the values from the given key bounds + */ + betweenBounds(query: I.BinarySearchTree.Query): V[]; + + /** + * Executed the given callback for each node from left to right + */ + executeOnEveryNode(fn: (tree: AVLTree) => void): void; + + /** + * Prints the tree + */ + prettyPrint(printDate?: boolean, spacing?: string): void; + } +} diff --git a/types/adone/glosses/collections/binary_search_tree.d.ts b/types/adone/glosses/collections/binary_search_tree.d.ts new file mode 100644 index 0000000000..878bd7e6a4 --- /dev/null +++ b/types/adone/glosses/collections/binary_search_tree.d.ts @@ -0,0 +1,110 @@ +declare namespace adone.collection { + namespace I.BinarySearchTree { + interface ConstructorOptions { + /** + * The parent tree + */ + parent?: Tree; + + /** + * Value to keep in this node + */ + value?: V; + + /** + * WHether the values must be unique, false by default. + * If false you can store many values for same keys, otherwise only one + */ + unique?: boolean; + + /** + * Custom keys comparator, by default if a > b => -1, a < b -1, a === b => 0 + */ + compareKeys?(a: K, b: K): number; + + /** + * Function that defines whether 2 values are the same, by default a === b + */ + checkValueEquality?(a: V, b: V): boolean; + } + + interface Query { + $lt?: K; + $lte?: K; + $gt?: K; + $gte?: K; + } + } + + /** + * Represents a binary search tree + */ + class BinarySearchTree { + constructor(options?: I.BinarySearchTree.ConstructorOptions>); + + /** + * Returns the max descendant tree + */ + getMaxKeyDescendant(): BinarySearchTree; + + /** + * Returns the maximum key + */ + getMaxKey(): K; + + /** + * Returns the min descendant tree + */ + getMinKeyDescendant(): BinarySearchTree; + + /** + * Returns the minumum key + */ + getMinKey(): K; + + /** + * Traverses the tree and calls the given function for each node + */ + checkAllNodesFullfillCondition(test: (key: K, value: V) => void): void; + + /** + * Checks whether the tree is a binary search tree + */ + checkIsBST(): void; + + /** + * Returns the of keys in the tree + */ + getNumberOfKeys(): number; + + /** + * Inserts a new key/value + */ + insert(key: K, value: V): void; + + /** + * Searches the given key in the tree + */ + search(key: K): V[]; + + /** + * Returns all the values from the given key bounds + */ + betweenBounds(query: I.BinarySearchTree.Query): V[]; + + /** + * Deletes the given key/value from the tree + */ + delete(key: K, value?: V): void; + + /** + * Executed the given callback for each node from left to right + */ + executeOnEveryNode(fn: (tree: BinarySearchTree) => void): void; + + /** + * Prints the tree + */ + prettyPrint(printData?: boolean, spacing?: string): void; + } +} diff --git a/types/adone/glosses/collections/buffer_list.d.ts b/types/adone/glosses/collections/buffer_list.d.ts new file mode 100644 index 0000000000..b2a4157385 --- /dev/null +++ b/types/adone/glosses/collections/buffer_list.d.ts @@ -0,0 +1,92 @@ +declare namespace adone.collection { + namespace I.BufferList { + type Appendable = Buffer | BufferList | string | number | Array; + } + + /** + * Represents a Node.js Buffer list collector, reader and streamer with callback/promise interface support + */ + class BufferList extends std.stream.Duplex implements PromiseLike { + /** + * Creates a new buffer list + */ + constructor(); + + /** + * Creates a new buffer list and initiates with the given value + */ + constructor(buffer: I.BufferList.Appendable); + + /** + * Creates a new buffer list and subscribes the given callback on the end/error event + */ + constructor(callback: (err: any, data: Buffer) => void); + + /** + * Adds an additional buffer or BufferList to the internal list + */ + append(buf: I.BufferList.Appendable): this; + + /** + * Ends the stream + */ + end(chunk?: Buffer): void; + end(chunk?: () => void): void; + + /** + * Returns the byte at the specified index + */ + get(idx: number): number; + + /** + * Returns a new Buffer object containing the bytes within the range specified. + */ + slice(start?: number, end?: number): Buffer; + + /** + * Copies the content of the list in the dest buffer + * starting from destStart and containing the bytes within the range specified with srcStart to srcEnd + * + * @param dstStart writes from this position + * @param srcStart reads bytes from this position + * @param srcEnd read bytes to this position + */ + copy(dst: T, dstStart?: number, srcStart?: number, srcEnd?: number): T; + + /** + * Returns a new BufferList object containing the bytes within the range specified. + * No copies will be performed. All buffers in the result share memory with the original list. + * + * @param start slice from + * @param end slice to + */ + shallowSlice(start?: number, end?: number): BufferList; + + /** + * Return a string representation of the buffer + */ + toString(encoding?: fs.I.Encoding, start?: number, end?: number): string; + + /** + * Shifts bytes off the start of the list + */ + consume(bytes: number): this; + + /** + * Performs a shallow-copy of the list. + */ + duplicate(): BufferList; + + /** + * Destroys the stream + */ + destroy(): void; + + then( + onfulfilled?: ((value: Buffer) => T1 | PromiseLike) | null, + onrejected?: ((reason: any) => T2 | PromiseLike) | null + ): PromiseLike; + + catch(onrejected?: ((reason: any) => T | PromiseLike) | null): PromiseLike; + } +} diff --git a/types/adone/glosses/collections/byte_array.d.ts b/types/adone/glosses/collections/byte_array.d.ts new file mode 100644 index 0000000000..1dc3080fb3 --- /dev/null +++ b/types/adone/glosses/collections/byte_array.d.ts @@ -0,0 +1,892 @@ +declare namespace adone.collection { + namespace I { + type Long = math.Long; + + type Longable = math.I.Longable; + + namespace ByteArray { + interface Varint32 { + value: number; + length: number; + } + + interface Varint64 { + value: Long; + length: number; + } + + interface String { + string: string; + length: number; + } + + type Wrappable = string | ByteArray | Buffer | Uint8Array | ArrayBuffer; + + type Metrics = "b" | "c"; + } + } + + /** + * Represents an array of bytes, enhanced Node.js Buffer + */ + class ByteArray { + readonly woffset: number; + + readonly roffset: number; + + readonly buffer: Buffer; + + readonly noAssert: boolean; + + /** + * Constructs a new ByteArray + * + * @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64) + * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) + */ + constructor(capacity?: number, noAssert?: boolean); + + /** + * Reads a BitSet as an array of booleans. + * + * @param offset Offset to read from. Will use and increase offset by length if omitted. + */ + readBitSet(offset?: number): boolean[]; + + /** + * Reads the specified number of bytes. + * + * @param length Number of bytes to read + * @param offset Offset to read from. Will use and increase offset by length if omitted. + */ + read(length: number, offset?: number): ByteArray; + + /** + * Reads an 8bit signed integer + * + * @param offset Offset to read from + */ + readInt8(offset?: number): number; + + /** + * Reads an 8bit unsigned integer + * + * @param offset Offset to read from + */ + readUInt8(offset?: number): number; + + /** + * Reads a 16bit signed le integer + * + * @param offset Offset to read from + */ + readInt16LE(offset?: number): number; + + /** + * Reads a 16bit unsigned le integer + * + * @param offset Offset to read from + */ + readUInt16LE(offset?: number): number; + + /** + * Reads a 16bit signed be integer + * + * @param offset Offset to read from + */ + readInt16BE(offset?: number): number; + + /** + * Reads a 16bit unsigned be integer + * + * @param offset Offset to read from + */ + readUInt16BE(offset?: number): number; + + /** + * Reads a 32bit signed le integer + * + * @param offset Offset to read from + */ + readInt32LE(offset?: number): number; + + /** + * Reads a 32bit unsigned le integer + * + * @param offset Offset to read from + */ + readUInt32LE(offset?: number): number; + + /** + * Reads a 32bit signed be integer + * + * @param offset Offset to read from + */ + readInt32BE(offset?: number): number; + + /** + * Reads a 32bit unsigned be integer + * + * @param offset Offset to read from + */ + readUInt32BE(offset?: number): number; + + /** + * Reads a 64bit signed le integer as math.Long + * + * @param offset Offset to read from + */ + readInt64LE(offset?: number): math.Long; + + /** + * Reads a 64bit unsigned le integer as math.Long + * + * @param offset Offset to read from + */ + readUInt64LE(offset?: number): math.Long; + + /** + * Reads a 64bit signed be integer as math.Long + * + * @param offset Offset to read from + */ + readInt64BE(offset?: number): math.Long; + + /** + * Reads a 64bit unsigned be integer as math.Long + * + * @param offset Offset to read from + */ + readUInt64BE(offset?: number): math.Long; + + /** + * Reads a 32bit le float + * + * @param offset Offset to read from + */ + readFloatLE(offset?: number): number; + + /** + * Reads a 32bit be float + * + * @param offset Offset to read from + */ + readFloatBE(offset?: number): number; + + /** + * Reads a 64bit le float + * + * @param offset Offset to read from + */ + readDoubleLE(offset?: number): number; + + /** + * Reads a 64bit be float + * + * @param offset Offset to read from + */ + readDoubleBE(offset?: number): number; + + /** + * Appends some data to this ByteArray. + * This will overwrite any contents behind the specified offset up to the appended data's length. + * + * @param source The source write from + * @param offset Offset to write at + * @param length length to read from the source + * @param encoding encoding to use for wrapping the source in bytearray + */ + write(source: I.ByteArray.Wrappable, offset?: number, length?: number, encoding?: string): this; + + /** + * Writes the array as a bitset. + * @param value Array of booleans to write + */ + writeBitSet(value: number[]): this; + + /** + * Writes the array as a bitset. + * @param value Array of booleans to write + * @param offset Offset to write at + */ + writeBitSet(value: number[], offset: number): number; + + /** + * Writes a buffer at the given offset + * @param buf Buffer to write + * @param offset Offset to write at + */ + writeBuffer(buf: Buffer, offset?: number): this; + + /** + * Writes an 8bit signed integer + * + * @param offset Offset to write at + */ + writeInt8(value: number, offset?: number): this; + + /** + * Writes an 8bit unsigned integer + * + * @param offset Offset to write at + */ + writeUInt8(value: number, offset?: number): this; + + /** + * Writes a 16bit signed le integer + * + * @param offset Offset to write at + */ + writeInt16LE(value: number, offset?: number): this; + + /** + * Writes a 16bit signed be integer + * + * @param offset Offset to write at + */ + writeInt16BE(value: number, offset?: number): this; + + /** + * Writes a 16bit unsigned le integer + * + * @param offset Offset to write at + */ + writeUInt16LE(value: number, offset?: number): this; + + /** + * Writes a 16bit unsigned be integer + * + * @param offset Offset to write at + */ + writeUInt16BE(value: number, offset?: number): this; + + /** + * Writes a 32bit signed le integer + * + * @param offset Offset to write at + */ + writeInt32LE(value: number, offset?: number): this; + + /** + * Writes a 32bit signed be integer + * + * @param offset Offset to write at + */ + writeInt32BE(value: number, offset?: number): this; + + /** + * Writes a 32bit unsigned le integer + * + * @param offset Offset to write at + */ + writeUInt32LE(value: number, offset?: number): this; + + /** + * Writes a 32bit unsigned be integer + * + * @param offset Offset to write at + */ + writeUInt32BE(value: number, offset?: number): this; + + /** + * Writes a 64bit signed le long integer + * + * @param offset Offset to write at + */ + writeInt64LE(value: math.Long | string | number, offset?: number): this; + + /** + * Writes a 64bit signed be long integer + * + * @param offset Offset to write at + */ + writeInt64BE(value: math.Long | string | number, offset?: number): this; + + /** + * Writes a 64bit unsigned le long integer + * + * @param offset Offset to write at + */ + writeUInt64LE(value: math.Long | string | number, offset?: number): this; + + /** + * Writes a 64bit unsigned be long integer + * + * @param offset Offset to write at + */ + writeUInt64BE(value: math.Long | string | number, offset?: number): this; + + /** + * Writes a 32bit le float + * + * @param offset Offset to write at + */ + writeFloatLE(value: number, offset?: number): this; + + /** + * Writes a 32bit be float + * + * @param offset Offset to write at + */ + writeFloatBE(value: number, offset?: number): this; + + /** + * Writes a 64bit le float + * + * @param offset Offset to write at + */ + writeDoubleLE(value: number, offset?: number): this; + + /** + * Writes a 64bit be float + * + * @param offset Offset to write at + */ + writeDoubleBE(value: number, offset?: number): this; + + /** + * Writes a 32bit base 128 variable-length integer + */ + writeVarint32(value: number): this; + + /** + * Writes a 32bit base 128 variable-length integer + * + * @param offset Offset to write at + */ + writeVarint32(value: number, offset: number): number; + + /** + * Writes a zig-zag encoded 32bit base 128 variable-length integer + */ + writeVarint32ZigZag(value: number): this; + + /** + * Writes a zig-zag encoded 32bit base 128 variable-length integer + * + * @param offset Offset to write at + */ + writeVarint32ZigZag(value: number, offset: number): number; + + /** + * Reads a 32bit base 128 variable-length integer + */ + readVarint32(): number; + + /** + * Reads a 32bit base 128 variable-length integer + * + * @param offset Offset to read from + */ + readVarint32(offset: number): I.ByteArray.Varint32; + + /** + * Reads a zig-zag encoded 32bit base 128 variable-length integer + */ + readVarint32ZigZag(): number; + + /** + * Reads a zig-zag encoded 32bit base 128 variable-length integer + * + * @param offset Offset to read from + */ + readVarint32ZigZag(offset: number): I.ByteArray.Varint32; + + /** + * Writes a 64bit base 128 variable-length integer + */ + writeVarint64(value: math.Long | string | number): this; + + /** + * Writes a 64bit base 128 variable-length integer + * + * @param offset Offset to write at + */ + writeVarint64(value: math.Long | string | number, offset: number): number; + + /** + * Writes a zig-zag encoded 64bit base 128 variable-length integer + */ + writeVarint64ZigZag(value: math.Long | string | number): this; + + /** + * Writes a zig-zag encoded 64bit base 128 variable-length integer + * + * @param offset Offset to write at + */ + writeVarint64ZigZag(value: math.Long | string | number, offset: number): number; + + /** + * Reads a 64bit base 128 variable-length integer + */ + readVarint64(): I.Long; + + /** + * Reads a 64bit base 128 variable-length integer + * + * @param offset Offset to read from + */ + readVarint64(offset: number): I.ByteArray.Varint64; + + /** + * Reads a zig-zag encoded 64bit base 128 variable-length integer + */ + readVarint64ZigZag(): math.Long; + + /** + * Reads a zig-zag encoded 64bit base 128 variable-length integer + * + * @param offset Offset to read from + */ + readVarint64ZigZag(offset: number): I.ByteArray.Varint64; + + /** + * Writes a NULL-terminated UTF8 encoded string. + * For this to work the specified string must not contain any NULL characters itself + */ + writeCString(str: string): this; + + /** + * Writes a NULL-terminated UTF8 encoded string. + * For this to work the specified string must not contain any NULL characters itself + * + * @param offset Offset to write at + */ + writeCString(str: string, offset: number): number; + + /** + * Reads a NULL-terminated UTF8 encoded string. + * For this to work the string read must not contain any NULL characters itself + */ + readCString(): string; + + /** + * Reads a NULL-terminated UTF8 encoded string. + * For this to work the string read must not contain any NULL characters itself + * + * @param offset Offset to read from + */ + readCString(offset: number): I.ByteArray.String; + + /** + * Writes an UTF8 encoded string + */ + writeString(str: string): this; + + /** + * Writes an UTF8 encoded string + * + * @param offset Offset to write at + */ + writeString(str: string, offset: number): number; + + /** + * Reads an UTF8 encoded string + * + * @param length Number of characters or bytes to read + * @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c") + */ + readString(length: number, metrics?: I.ByteArray.Metrics): string; + + /** + * Reads an UTF8 encoded string + * + * @param length Number of characters or bytes to read + * @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c") + * @param offset Offset to read from + */ + readString(length: number, metrics: I.ByteArray.Metrics, offset: number): I.ByteArray.String; + + /** + * Reads an UTF8 encoded string + * + * @param length Number of characters or bytes to read + * @param offset Offset to read from + */ + readString(length: number, offset: number): I.ByteArray.String; + + /** + * Writes a length as varint32 prefixed UTF8 encoded string + */ + writeVString(str: string): this; + + /** + * Writes a length as varint32 prefixed UTF8 encoded string + * + * @param offset Offset to read from + */ + writeVString(str: string, offset: number): number; + + /** + * Reads a length as varint32 prefixed UTF8 encoded string + */ + readVString(): string; + + /** + * Reads a length as varint32 prefixed UTF8 encoded string + * + * @param offset Offset to read from + */ + readVString(offset: number): I.ByteArray.String; + + /** + * Appends this ByteArray's contents to another ByteArray. + * This will overwrite any contents behind the specified offset up to the length of this ByteArray's data + * + * @param offset Offset to append to + */ + appendTo(target: ByteArray, offset?: number): this; + + /** + * Enables or disables assertions of argument types and offsets. + * Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid + */ + assert(assert?: boolean): this; + + /** + * Gets the capacity of this ByteArray's backing buffer + */ + capacity(): number; + + /** + * Clears this ByteArray's offsets by setting offset to 0 and limit to the backing buffer's capacity + */ + clear(): this; + + /** + * Creates a cloned instance of this ByteArray, + * preset with this ByteArray's values for offset, markedOffset and limit + * + * @param copy Whether to copy the backing buffer or to return another view on the same, false by default + */ + clone(copy?: boolean): ByteArray; + + /** + * Compacts this ByteArray to be backed by a buffer of its contents' length. + * Will set offset = 0 and limit = capacity and adapt markedOffset to the same relative position if set + * + * @param begin Offset to start at, buffer offset by default + * @param end Offset to end at, buffer limit by default + */ + compact(begin?: number, end?: number): this; + + /** + * Creates a copy of this ByteArray's contents. + * + * @param begin Begin offset, buffer offset by default + * @param end End offset, buffer limit by default + */ + copy(begin?: number, end?: number): ByteArray; + + /** + * Copies this ByteArray's contents to another ByteArray. + * + * @param targetOffset Offset to copy to. Will use and increase the target's offset by the number of bytes copied if omitted + * @param sourceOffset Offset to start copying from. Will use and increase offset by the number of bytes copied if omitted + * @param sourceLimit Offset to end copying from, defaults to the buffer limit + */ + copyTo(target: ByteArray, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ByteArray; + + /** + * Makes sure that this ByteArray is backed by a ByteArray#buffer of at least the specified capacity. + * If the current capacity is exceeded, it will be doubled. + * If double the current capacity is less than the required capacity, the required capacity will be used instead + */ + ensureCapacity(capacity: number): this; + + /** + * Overwrites this ByteArray's contents with the specified value. + * + * @param value Byte value to fill with. If given as a string, the first character is used + * @param begin Begin offset. Will use and increase offset by the number of bytes written if omitted. defaults to offset + * @param end End offset, defaults to limit. + */ + fill(value: string | number, begin?: number, end?: number): this; + + /** + * Makes this ByteArray ready for a new sequence of write or relative read operations. + * Sets limit = offset and offset = 0. + * Make sure always to flip a ByteArray when all relative read or write operations are complete + */ + flip(): this; + + /** + * Marks an offset on this ByteArray to be used later + * + * @param offset Offset to mark. Defaults to offset. + */ + mark(offset?: number): this; + + /** + * Prepends some data to this ByteArray. + * This will overwrite any contents before the specified offset up to the prepended data's length. + * If there is not enough space available before the specified offset, + * the backing buffer will be resized and its contents moved accordingly + * + * @param source Data to prepend + * @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted. + */ + prepend(source: I.ByteArray.Wrappable, offset: number): this; + + /** + * Prepends some data to this ByteArray. + * This will overwrite any contents before the specified offset up to the prepended data's length. + * If there is not enough space available before the specified offset, + * the backing buffer will be resized and its contents moved accordingly + * + * @param source Data to prepend + * @param encoding Encoding if data is a string + * @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted. + */ + prepend(source: I.ByteArray.Wrappable, encoding?: string, offset?: number): this; + + /** + * Prepends this ByteArray to another ByteArray. + * This will overwrite any contents before the specified offset up to the prepended data's length. + * If there is not enough space available before the specified offset, + * the backing buffer will be resized and its contents moved accordingly + * + * @param offset Offset to prepend at + */ + prependTo(target: ByteArray, offset?: number): this; + + /** + * Gets the number of remaining readable bytes + */ + remaining(): number; + + /** + * Resets this ByteArray's offset. + * If an offset has been marked through mark before, offset will be set to markedOffset, which will then be discarded. + * If no offset has been marked, sets offset = 0 + */ + reset(): this; + + /** + * Resizes this ByteArray to be backed by a buffer of at least the given capacity. + * Will do nothing if already that large or larger. + * + * @param capacity Capacity required + */ + resize(capacity: number): this; + + /** + * Reverses this ByteArray's contents. + * + * @param begin Offset to start at, defaults to offset + * @param end Offset to end at, defaults to limit + */ + reverse(begin?: number, end?: number): this; + + /** + * Skips the next length bytes. This will just advance + */ + skip(length: number): this; + + /** + * Slices this ByteArray by creating a cloned instance with offset = begin and limit = end + * + * @param begin Begin offset, defaults to offset + * @param end End offset, defaults to limit + */ + slice(begin?: number, end?: number): ByteArray; + + /** + * Returns a copy of the backing buffer that contains this ByteArray's contents. + * + * @param forceCopy If true returns a copy, otherwise returns a view referencing the same memory if possible, false by default + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer; + + /** + * Returns a raw buffer compacted to contain this ByteArray's contents + */ + toArrayBuffer(): ArrayBuffer; + + /** + * Converts the ByteArray's contents to a string + * + * @param encoding Output encoding + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toString(encoding?: string, begin?: number, end?: number): string; + + /** + * Encodes this ByteArray's contents to a base64 encoded string + * + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toBase64(begin?: number, end?: number): string; + + /** + * Encodes this ByteArray to a binary encoded string, that is using only characters 0x00-0xFF as bytes + * + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toBinary(begin?: number, end?: number): string; + + /** + * Encodes this ByteArray to a hex encoded string with marked offsets + * + * @param columns If true returns two columns hex + ascii, defaults to false + */ + toDebug(columns?: boolean): string; + + /** + * Encodes this ByteArray's contents to a hex encoded string + * + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toHex(begin?: number, end?: number): string; + + /** + * Encodes this ByteArray's contents to an UTF8 encoded string + * + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toUTF8(begin?: number, end?: number): string; + + static accessor(): typeof Buffer; + + /** + * Allocates a new ByteArray backed by a buffer of the specified capacity. + * + * @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64) + * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) + */ + static allocate(capacity?: number, noAssert?: boolean): ByteArray; + + /** + * Concatenates multiple ByteArrays into one + * + * @param encoding Encoding for strings + * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) + */ + static concat(buffers: I.ByteArray.Wrappable[], encoding?: string, noAssert?: boolean): ByteArray; + + static type(): typeof Buffer; + + /** + * Wraps a buffer or a string. + * Sets the allocated ByteArray's offset to 0 and its limit to the length of the wrapped data + * + * @param encoding Encoding for strings + * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) + */ + static wrap(buffer: I.ByteArray.Wrappable, encoding?: string, noAssert?: boolean): ByteArray; + + /** + * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer + */ + static calculateVarint32(value: number): number; + + /** + * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding + */ + static zigZagEncode32(n: number): number; + + /** + * Decodes a zigzag encoded signed 32bit integer + */ + static zigZagDecode32(n: number): number; + + /** + * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer + */ + static calculateVarint64(value: number | string): number; + + /** + * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding + */ + static zigZagEncode64(value: number | string | I.Long): I.Long; + + /** + * Decodes a zigzag encoded signed 64bit integer. + */ + static zigZagDecode64(value: number | string | I.Long): I.Long; + + /** + * 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. + */ + static calculateString(str: string): number; + + /** + * Decodes a base64 encoded string to a ByteArray + */ + static fromBase64(str: string): ByteArray; + + /** + * Encodes a binary string to base64 like window.btoa does + */ + static btoa(str: string): string; + + /** + * Decodes a base64 encoded string to binary like window.atob does + */ + static atob(b64: string): string; + + /** + * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteArray + */ + static fromBinary(str: string): ByteArray; + + /** + * Decodes a hex encoded string with marked offsets to a ByteArray + */ + static fromDebug(str: string, noAssert?: boolean): ByteArray; + + /** + * Decodes a hex encoded string to a ByteArray + */ + static fromHex(str: string, noAssert?: boolean): ByteArray; + + /** + * Decodes an UTF8 encoded string to a ByteArray + */ + static fromUTF8(str: string, noAssert?: boolean): ByteArray; + + /** + * Default initial capacity + */ + static DEFAULT_CAPACITY: number; + + /** + * Default no assertions flag + */ + static DEFAULT_NOASSERT: boolean; + + /** + * Maximum number of bytes required to store a 32bit base 128 variable-length integer + */ + static MAX_VARINT32_BYTES: number; + + /** + * Maximum number of bytes required to store a 64bit base 128 variable-length integer + */ + static MAX_VARINT64_BYTES: number; + + /** + * Metrics representing number of UTF8 characters. Evaluates to `c`. + */ + static METRICS_CHARS: string; + + /** + * Metrics representing number of bytes. Evaluates to `b`. + */ + static METRICS_BYTES: string; + } +} diff --git a/types/adone/glosses/collections/default_map.d.ts b/types/adone/glosses/collections/default_map.d.ts new file mode 100644 index 0000000000..46b8ccebfe --- /dev/null +++ b/types/adone/glosses/collections/default_map.d.ts @@ -0,0 +1,9 @@ +declare namespace adone.collection { + /** + * Represents a Map that has a default values factory object or function. + * Each get of non-existent key goes through the factory + */ + class DefaultMap extends Map { + constructor(factory?: ((key: K) => V) | { [key: string]: V }, iterable?: Iterable<[K, V]>); + } +} diff --git a/types/adone/glosses/collections/fast_lru.d.ts b/types/adone/glosses/collections/fast_lru.d.ts new file mode 100644 index 0000000000..e991322bc0 --- /dev/null +++ b/types/adone/glosses/collections/fast_lru.d.ts @@ -0,0 +1,61 @@ +declare namespace adone.collection { + /** + * Represents a faster LRU cache but with less functionality + */ + class FastLRU { + /** + * @param size Cache size, unlimited by default + */ + constructor(size?: number, options?: { + /** + * Function that is called when a value is deleted + */ + dispose?(key: K, value: V): void + }); + + /** + * The actual size of the cache + */ + readonly size: number; + + /** + * Gets the value by the given key + */ + get(key: K): V | undefined; + + /** + * Sets a new value for the given key + */ + set(key: K, value: V): void; + + /** + * Deletes the given key from the cache + */ + delete(key: K): boolean; + + /** + * Checks whether the cache has an element with the given key + */ + has(key: K): boolean; + + /** + * Returns the keys iterator + */ + keys(): IterableIterator; + + /** + * Returns the values iterator + */ + values(): IterableIterator; + + /** + * Returns the entries iterator + */ + entries(): IterableIterator<[K, V]>; + + /** + * Clears the cache + */ + clear(): void; + } +} diff --git a/types/adone/glosses/collections/index.d.ts b/types/adone/glosses/collections/index.d.ts new file mode 100644 index 0000000000..234ffe85f4 --- /dev/null +++ b/types/adone/glosses/collections/index.d.ts @@ -0,0 +1,28 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +declare namespace adone { + /** + * Data structures + */ + namespace collection { + // + } +} diff --git a/types/adone/glosses/collections/linked_list.d.ts b/types/adone/glosses/collections/linked_list.d.ts new file mode 100644 index 0000000000..69ffa4da4b --- /dev/null +++ b/types/adone/glosses/collections/linked_list.d.ts @@ -0,0 +1,150 @@ +declare namespace adone.collection { + namespace I.LinkedList { + /** + * Represents the node of a linked list + */ + interface Node { + /** + * The next node + */ + next?: Node; + + /** + * The previous node + */ + prev?: Node; + + /** + * The value this node contains + */ + value: T; + } + } + + /** + * Represents a linked list + */ + class LinkedList { + /** + * The maximum length of the list + */ + readonly maxLength: number; + + /** + * Current length of the list + */ + readonly length: number; + + /** + * Whether the list is autoresizable + */ + readonly autoresize: boolean; + + /** + * @param maxLength Maximum length of the linked list + */ + constructor(maxLength?: number); + + /** + * Whether the list is full + */ + readonly full: boolean; + + /** + * Whether the list is empty + */ + readonly empty: boolean; + + /** + * Resizes the list + */ + resize(newLength: number): this; + + /** + * Adds a new node to the end + * + * @returns Added node + */ + push(value: T): I.LinkedList.Node; + + /** + * Removes the last node, returns undefined if the list is empty + */ + pop(): T | undefined; + + /** + * Removes the first node, returns undefined if the list is empty + */ + shift(): T | undefined; + + /** + * Inserts a new node at the beginning of the list + * + * @returns Added node + */ + unshift(value: T): I.LinkedList.Node; + + /** + * Moves the given node to the end of the list + */ + pushNode(node: I.LinkedList.Node): void; + + /** + * Moved the given node to the beginning of the list + */ + unshiftNode(node: I.LinkedList.Node): void; + + /** + * Removes the given node from the list + */ + removeNode(node: I.LinkedList.Node): void; + + /** + * Clears the list + * + * @param strong Whether to reset all the node's values + */ + clear(strong?: boolean): void; + + /** + * Convers the list to an array + */ + toArray(): T[]; + + /** + * The first element of the list + */ + readonly front: T; + + /** + * The last element of the list + */ + readonly back: T; + + /** + * Returns an iterator over the list elements + */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns the next node for the given node + */ + nextNode(node: I.LinkedList.Node): I.LinkedList.Node; + + /** + * Maps this linked list to a new one using the given function + */ + map(fn: (value: T, index: number) => R): LinkedList; + + /** + * Invokes the given callback for each value from the beginning to the end (much faster than for-of). + * If the given function returns false it stops iterating. + */ + forEach(callback: (value: T, index: number) => void | boolean): void; + + /** + * Default length of a new created linked list + */ + static DEFAULT_LENGTH: number; + } +} diff --git a/types/adone/glosses/collections/lru.d.ts b/types/adone/glosses/collections/lru.d.ts new file mode 100644 index 0000000000..7d41e32cd5 --- /dev/null +++ b/types/adone/glosses/collections/lru.d.ts @@ -0,0 +1,213 @@ +declare namespace adone.collection { + namespace I.LRU { + type LengthCalculator = (value: V, key: K) => number; + interface ConstructorOptions { + /** + * The maximum size of the cache, checked by applying the length function to all values in the cache. + * Default is Infinity + */ + max?: number; + + /** + * Maximum age in ms. Items are not pro-actively pruned out as they age, + * but if you try to get an item that is too old, + * it'll drop it and return undefined instead of giving it to you + */ + maxAge?: number; + + /** + * Function that is used to calculate the length of stored items + */ + length?: LengthCalculator; + + /** + * Function that is called on items when they are dropped from the cache + */ + dispose?(key: K, value: V): void; + + /** + * Whether to return the stale value before deleting it + */ + stale?: boolean; + + /** + * Dispose will only be called when a key falls out of the cache, not when it is overwritten + */ + noDisposeOnSet?: boolean; + } + + interface SerializedEntry { + /** + * key + */ + key: K; + + /** + * value + */ + value: V; + + /** + * when it becomes expired + */ + e: number; + } + + interface Entry { + /** + * key + */ + key: K; + + /** + * value + */ + value: V; + + /** + * entry length + */ + length: number; + + /** + * Timestamp when the entry was created + */ + now: number; + + /** + * Maximum live time + */ + maxAge: number; + } + } + + /** + * Represent an LRU cache + */ + class LRU { + /** + * Creates an LRU cache of the given size + */ + constructor(max: number); + + /** + * Creates an LRU cache with the given options + */ + constructor(options?: I.LRU.ConstructorOptions); + + /** + * The length of the cache, setter resizes the cache + */ + max: number; + + /** + * stale setting + */ + allowStale: boolean; + + /** + * maxAge setting + */ + maxAge: number; + + /** + * length setting + */ + lengthCalculator: I.LRU.LengthCalculator; + + /** + * Total length of objects in cache taking into account length options function + */ + readonly length: number; + + /** + * Total quantity of objects currently in cache. + * Note, that stale items are returned as part of this item count. + */ + readonly itemCount: number; + + /** + * Iterates over all the keys in the cache, in reverse recent-ness order. (ie, less recently used items are iterated over first.) + */ + rforEach(fn: (this: T, value: V, key: K, cache: LRU) => void, thisp?: T): void; + + /** + * Iterates over all the keys in the cache, in order of recent-ness + */ + forEach(fn: (this: T, value: V, key: K, cache: LRU) => void, thisp?: T): void; + + /** + * Returns an array of the keys in the cache + */ + keys(): K[]; + + /** + * Returns an array of the values in the cache + */ + values(): V[]; + + /** + * Clears the cache entirely, throwing away all values + */ + reset(): void; + + /** + * Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)` + */ + dump(): Array>; + + /** + * Returns an internal lru list of entries + */ + dumpLru(): LinkedList>; + + /** + * @param opts std.util.inspect options + */ + inspect(opts?: object): string; + + /** + * Sets a new value for the given key. Updates the "recently used"-ness of the key + * + * @param maxAge maxAge option specific for this key + * @returns Whether the key was set + */ + set(key: K, value: V, maxAge?: number): boolean; + + /** + * Check if a key is in the cache, without updating the recent-ness or deleting it for being stale + */ + has(key: K): boolean; + + /** + * Gets the value of the given key. Updates the "recently used"-ness of the key + */ + get(key: K): V | undefined; + + /** + * Returns the key value without updating the "recently used"-ness of the key + */ + peek(key: K): V | undefined; + + /** + * Deletes the less recently used element + */ + pop(): I.LRU.Entry; + + /** + * Deletes a key out of the cache + */ + del(key: K): void; + + /** + * Loads another cache entries array, obtained with sourceCache.dump(), into the cache. + * The destination cache is reset before loading new entries + */ + load(arr: Array>): void; + + /** + * Manually iterates over the entire cache proactively pruning old entries + */ + prune(): void; + } +} diff --git a/types/adone/glosses/collections/map_cache.d.ts b/types/adone/glosses/collections/map_cache.d.ts new file mode 100644 index 0000000000..55bbb6e05f --- /dev/null +++ b/types/adone/glosses/collections/map_cache.d.ts @@ -0,0 +1,13 @@ +declare namespace adone.collection { + class MapCache { + has(key: string): boolean; + + get(key: string): T; + + set(key: string, value: T): void; + + delete(key: string): void; + + clear(): void; + } +} diff --git a/types/adone/glosses/collections/ns_cache.d.ts b/types/adone/glosses/collections/ns_cache.d.ts new file mode 100644 index 0000000000..5630c295d3 --- /dev/null +++ b/types/adone/glosses/collections/ns_cache.d.ts @@ -0,0 +1,17 @@ +declare namespace adone.collection { + class NSCache { + constructor(size: number, namespaces: string[]); + + resize(newSize: number): void; + + set(ns: string, key: string, value: T): void; + + get(ns: string, key: string): T; + + has(ns: string, key: string): boolean; + + delete(ns: string, key: string): void; + + clear(): void; + } +} diff --git a/types/adone/glosses/collections/priority_queue.d.ts b/types/adone/glosses/collections/priority_queue.d.ts new file mode 100644 index 0000000000..0fb1e92814 --- /dev/null +++ b/types/adone/glosses/collections/priority_queue.d.ts @@ -0,0 +1,78 @@ +declare namespace adone.collection { + namespace I.PriorityQueue { + interface ConstructorOptions { + /** + * Function that compares objects. + * + * Must return a positive value if a > b, a negative if a < b, and zero for equal objects + */ + compare?(a: T, b: T): number; + + /** + * Function that evaluates the priority value by the given objects, + * if the returned value > 0, then the first argument has higher priority, + * = 0 same priority, < 0 lower priority. + * By default the top element is an element that has the highest priority, + * the default priority function is equal to the compare function + */ + priority?(a: T, b: T): number; + } + } + + /** + * Represents a priority queue + */ + class PriorityQueue { + /** + * Whether the queue is empty + */ + readonly empty: boolean; + + /** + * The length of the queue + */ + readonly length: number; + + constructor(options?: I.PriorityQueue.ConstructorOptions); + + /** + * Clones the queue + */ + clone(): PriorityQueue; + + /** + * Inserts a new element + */ + push(x: T): this; + + /** + * Removes the top element (that has the highest priority) + */ + pop(): T | undefined; + + /** + * Deletes the given element from the queue + */ + delete(x: T): this; + + /** + * Replaces the top element (pop + push) + */ + replace(x: T): T; + + /** + * Faster push + pop + */ + pushpop(x: T): T; + + /** + * Converts the queue to an array, it works with a clone of the queue, so the original queue is untouched + */ + toArray(): T[]; + + /** + * Creates a queue object from the given iterable + */ + static from(iterable: Iterable, options?: I.PriorityQueue.ConstructorOptions): PriorityQueue; + } +} diff --git a/types/adone/glosses/collections/queue.d.ts b/types/adone/glosses/collections/queue.d.ts new file mode 100644 index 0000000000..8a0832a7e6 --- /dev/null +++ b/types/adone/glosses/collections/queue.d.ts @@ -0,0 +1,33 @@ +declare namespace adone.collection { + /** + * Represents a queue + */ + class Queue { + /** + * Whether the queue is full + */ + readonly full: boolean; + + /** + * The length of the queue + */ + readonly length: number; + + /** + * Whether the queue is empty + */ + readonly empty: boolean; + + /** + * Inserts a new element at the end + */ + push(x: S): this; + + /** + * Removes and returns an element from the beginning + */ + pop(): T | undefined; + + static from(iterable: Iterable, length?: number): Queue; + } +} diff --git a/types/adone/glosses/collections/rb_tree.d.ts b/types/adone/glosses/collections/rb_tree.d.ts new file mode 100644 index 0000000000..2ed7a81323 --- /dev/null +++ b/types/adone/glosses/collections/rb_tree.d.ts @@ -0,0 +1,184 @@ +declare namespace adone.collection { + namespace I.RedBlackTree { + interface Node { + /** + * The key associated to the node + */ + key: K; + + /** + * The value associated to the node + */ + value: V; + + /** + * The left subtree of the node + */ + left?: Node; + + /** + * The right subtree of the node + */ + right?: Node; + } + + interface Iterator { + /** + * Checks if the iterator is valid + */ + readonly valid: boolean; + + /** + * The value of the node at the iterator's current position, null if invalid + */ + readonly node: Node | null; + + /** + * The key of the item referenced by the iterator, undefined if invalid + */ + readonly key?: K; + + /** + * The value of the item referenced by the iterator, undefined if invalid + */ + readonly value?: V; + + /** + * Returns the position of this iterator in the sequence + */ + readonly index: number; + + /** + * If true, then the iterator is not at the end of the sequence + */ + readonly hasNext: boolean; + + /** + * If true, then the iterator is not at the beginning of the sequence + */ + readonly hasPrev: boolean; + + /** + * The tree associated to the iterator + */ + tree: RedBlackTree; + + /** + * Makes a copy of the iterator + */ + clone(): Iterator; + + /** + * Removes the item at the position of the iterator and returns a new rb-tree + */ + remove(): RedBlackTree; + + /** + * Advances the iterator to the next position + */ + next(): void; + + /** + * Updates the value of the node in the tree at this iterator and returns a new rb-tree + */ + update(value: V): RedBlackTree; + + /** + * Moves the iterator backward one element + */ + prev(): void; + } + } + + /** + * Represents a fully persistent red-black tree + */ + class RedBlackTree { + /** + * The root node of the tree + */ + root: I.RedBlackTree.Node; + + constructor(compare?: (a: K, b: K) => number, root?: RedBlackTree); + + /** + * A sorted array of all the keys in the tree + */ + readonly keys: K[]; + + /** + * An array of all the values in the tree + */ + readonly values: V[]; + + /** + * The number of items in the tree + */ + readonly length: number; + + /** + * An iterator pointing to the first element in the tree + */ + readonly begin: I.RedBlackTree.Iterator; + + /** + * An iterator pointing to the last element in the tree + */ + readonly end: I.RedBlackTree.Iterator; + + /** + * Creates a new tree with the new pair inserted + */ + insert(key: K, value: V): RedBlackTree; + + /** + * Walks a visitor function over the nodes of the tree in order + * + * @param visit A callback that gets executed on each node. + * If a truthy value is returned from the visitor, then iteration is stopped. + * @param lo An optional start of the range to visit (inclusive) + * @param hi An optional end of the range to visit (non-inclusive) + */ + forEach(visit: (key: K, value: V) => T, lo?: K, hi?: K): T; + + /** + * Finds an iterator starting at the given element + */ + at(idx: number): I.RedBlackTree.Iterator; + + /** + * Finds the first item in the tree whose key is >= key + */ + ge(key: K): I.RedBlackTree.Iterator; + + /** + * Finds the first item in the tree whose key is > key + */ + gt(key: K): I.RedBlackTree.Iterator; + + /** + * Finds the first item in the tree whose key is < key + */ + lt(key: K): I.RedBlackTree.Iterator; + + /** + * Finds the first item in the tree whose key is <= key + */ + le(key: K): I.RedBlackTree.Iterator; + + /** + * Returns an iterator pointing to the first item in the tree with key, otherwise null + */ + find(key: K): I.RedBlackTree.Iterator | null; + + /** + * Removes the first item with key in the tree + */ + remove(key: K): RedBlackTree; + + /** + * Retrieves the value associated to the given key + */ + get(key: K): V | undefined; + } +} diff --git a/types/adone/glosses/collections/refcounted_cache.d.ts b/types/adone/glosses/collections/refcounted_cache.d.ts new file mode 100644 index 0000000000..79410423a4 --- /dev/null +++ b/types/adone/glosses/collections/refcounted_cache.d.ts @@ -0,0 +1,9 @@ +declare namespace adone.collection { + class RefcountedCache extends MapCache { + ref(key: string): void; + + unref(key: string): void; + + references(key: string): number; + } +} diff --git a/types/adone/glosses/collections/set.d.ts b/types/adone/glosses/collections/set.d.ts new file mode 100644 index 0000000000..f1a6bae96d --- /dev/null +++ b/types/adone/glosses/collections/set.d.ts @@ -0,0 +1,17 @@ +declare namespace adone.collection { + class Set { + constructor(key?: (x: T) => any); + + has(value: T): boolean; + + add(value: T): void; + + delete(value: T): void; + + get(value: T): T; // ??? + + readonly size: number; + + only(): T; + } +} diff --git a/types/adone/glosses/collections/stack.d.ts b/types/adone/glosses/collections/stack.d.ts new file mode 100644 index 0000000000..90fe35b99b --- /dev/null +++ b/types/adone/glosses/collections/stack.d.ts @@ -0,0 +1,36 @@ +declare namespace adone.collection { + /** + * Represents a stack + */ + class Stack { + /** + * Whether the stack is empty + */ + readonly empty: boolean; + + /** + * The top element of the stack + */ + readonly top: T; + + /** + * Inserts a new element + */ + push(x: T): this; + + /** + * Removes the top element + */ + pop(): T | undefined; + + /** + * Returns an iterator over the values + */ + [Symbol.iterator](): IterableIterator; + + /** + * Creates a stack and pushed all the values from the given iterable object + */ + static from(iterable: Iterable): Stack; + } +} diff --git a/types/adone/glosses/collections/timedout_map.d.ts b/types/adone/glosses/collections/timedout_map.d.ts new file mode 100644 index 0000000000..fedcf79fa2 --- /dev/null +++ b/types/adone/glosses/collections/timedout_map.d.ts @@ -0,0 +1,32 @@ +declare namespace adone.collection { + /** + * Represents a Map that keeps keys only for a specified interval of time + */ + class TimedoutMap extends Map { + /** + * @param timeout maximum age of the keys, 1000 by default + * @param callback callback that is called with each key when the timeout is passed + */ + constructor(timeout?: number, callback?: (key: K) => void); + + /** + * Gets the timeout + */ + getTimeout(): number; + + /** + * Sets the timeout + */ + setTimeout(ms: number): void; + + /** + * Iterates over the map and calls the callback for each element + */ + forEach(callback: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): this; + + /** + * Deletes the given key + */ + delete(key: K): boolean; + } +} diff --git a/types/adone/glosses/crypto/asn1.d.ts b/types/adone/glosses/crypto/asn1.d.ts new file mode 100644 index 0000000000..2c4f2134a0 --- /dev/null +++ b/types/adone/glosses/crypto/asn1.d.ts @@ -0,0 +1,597 @@ +declare namespace adone.crypto { + namespace asn1 { + namespace I { + interface LocalBaseBlockParams { + blockLength?: number; + error?: string; + warnings?: string[]; + valueBeforeDecode?: ArrayBuffer; + } + + interface JsonLocalBaseBlock { + blockName: string; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + } + + class LocalBaseBlock { + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + + constructor(params?: LocalBaseBlockParams); + /** + * Aux function, need to get a block name. Need to have it here for inhiritence + */ + static blockName(): string; + /** + * Convertion for the block to JSON object + */ + toJSON(): JsonLocalBaseBlock; + } + + interface LocalHexBlockParams extends LocalBaseBlockParams { + isHexOnly?: boolean; + valueHex?: ArrayBuffer; + } + + class LocalHexBlock { + isHexOnly: boolean; + + valueHex: ArrayBuffer; + + constructor(params: any); + + /** + * Aux function, need to get a block name. Need to have it here for inhiritence + */ + static blockName(): string; + + /** + * Base function for converting block from BER encoded array of bytes + * + * @param inputBuffer ASN.1 BER encoded array + * @param inputOffset Offset in ASN.1 BER encoded array where decoding should be started + * @param inputLength Maximum length of array of bytes which can be using in this function + */ + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + + /** + * Encoding of current ASN.1 block into ASN.1 encoded array (BER rules) + * + * @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes + */ + toBER(sizeOnly?: boolean): ArrayBuffer; + + /** + * Convertion for the block to JSON object + */ + toJSON(): any; + } + + interface LocalIdentificationBlockParams { + idBlock?: LocalHexBlockParams & { + isConstructed?: boolean; + tagClass?: number; + tagNumber?: number; + }; + } + + class LocalIdentificationBlock extends LocalBaseBlock { + isConstructed: boolean; + + tagClass: number; + + tagNumber: number; + + constructor(params?: LocalIdentificationBlockParams); + + // ILocalHexBlock implementation + isHexOnly: boolean; + valueHex: ArrayBuffer; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalLengthBlockParams { + lenBlock?: { + isIndefiniteForm?: boolean; + longFormUsed?: boolean; + length: number; + }; + } + + class LocalLengthBlock extends LocalBaseBlock { + isIndefiniteForm: boolean; + longFormUsed: boolean; + length: number; + constructor(params?: LocalLengthBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): void; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + class LocalValueBlock extends LocalBaseBlock { + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): void; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface BaseBlockParams extends LocalBaseBlockParams { + name?: string; + optional?: boolean; + primitiveSchema?: object; + } + + interface LocalPrimitiveValueBlockParams extends LocalBaseBlockParams { + valueHex?: ArrayBuffer; + isHexOnly?: boolean; + } + + class LocalPrimitiveValueBlock extends LocalValueBlock { + valueHex: ArrayBuffer; + isHexOnly: boolean; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalConstructedValueBlockParams extends LocalBaseBlockParams { + value?: LocalValueBlock; + isIndefiniteForm?: boolean; + } + + class LocalConstructedValueBlock extends LocalValueBlock { + value: LocalValueBlock[]; + isIndefiniteForm: boolean; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + class LocalEndOfContentValueBlock extends LocalValueBlock { + constructor(params?: LocalBaseBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalBooleanValueBlockParams extends LocalBaseBlockParams { + value?: boolean; + isHexOnly?: boolean; + valueHex?: ArrayBuffer; + } + + class LocalBooleanValueBlock extends LocalValueBlock { + value: boolean; + isHexOnly: boolean; + valueHex: ArrayBuffer; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalOctetStringValueBlockParams extends LocalConstructedValueBlockParams, LocalHexBlockParams { + isConstructed?: boolean; + } + + class LocalOctetStringValueBlock extends LocalConstructedValueBlock { + isConstructed: boolean; + isHexOnly: boolean; + valueHex: ArrayBuffer; + + constructor(params?: LocalOctetStringValueBlockParams); + } + + interface LocalBitStringValueBlockParams extends LocalConstructedValueBlockParams, LocalHexBlockParams { + unusedBits?: number; + isConstructed?: boolean; + blockLength?: number; + } + + class LocalBitStringValueBlock extends LocalConstructedValueBlock implements LocalHexBlock { + unusedBits: number; + isConstructed: boolean; + blockLength: number; + isHexOnly: boolean; + valueHex: ArrayBuffer; + constructor(params?: LocalBitStringValueBlockParams); + } + + interface LocalIntegerValueBlockParams extends LocalBaseBlockParams, LocalHexBlockParams { + } + + class LocalIntegerValueBlock extends LocalValueBlock implements LocalHexBlock { + valueDec: number; + isHexOnly: boolean; + valueHex: ArrayBuffer; + constructor(params?: LocalIntegerValueBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + /** + * Base function for converting block from DER encoded array of bytes + * + * @param inputBuffer ASN.1 DER encoded array + * @param inputOffset Offset in ASN.1 DER encoded array where decoding should be started + * @param inputLength Maximum length of array of bytes which can be using in this function + * @param expectedLength Expected length of converted "valueHex" buffer + */ + fromDER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number, expectedLength?: number): number; + /** + * Encoding of current ASN.1 block into ASN.1 encoded array (DER rules) + * + * @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes + */ + toDER(sizeOnly?: boolean): ArrayBuffer; + } + + interface IntegerParams { + value?: number; + } + + interface LocalSidValueBlockParams extends LocalBaseBlockParams, LocalHexBlockParams { + valueDec?: number; + isFirstSid?: boolean; + } + + class LocalSidValueBlock extends LocalBaseBlock implements LocalHexBlock { + valueDec: number; + isFirstSid: boolean; + isHexOnly: boolean; + valueHex: ArrayBuffer; + constructor(params?: LocalSidValueBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toString(): string; + } + + interface LocalObjectIdentifierValueBlockParams extends LocalBaseBlockParams { + value?: string; + } + + class LocalObjectIdentifierValueBlock extends LocalValueBlock { + constructor(params?: LocalObjectIdentifierValueBlockParams); + + /** + * Create "LocalObjectIdentifierValueBlock" class from string + * + * @param string Input string to convert from + */ + fromString(data: string): boolean; + /** + * Converts "LocalObjectIdentifierValueBlock" class to string + */ + toString(): string; + } + + interface LocalUtf8StringValueBlockParams extends LocalBaseBlockParams, LocalHexBlock { + } + + class LocalUtf8StringValueBlock extends LocalBaseBlock implements LocalHexBlock { + isHexOnly: boolean; + valueHex: ArrayBuffer; + constructor(params?: LocalSidValueBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toString(): string; + } + + interface Utf8StringParams { + value?: string; + } + + interface LocalBmpStringValueBlockParams extends LocalHexBlockParams, LocalBaseBlockParams { + } + + class LocalBmpStringValueBlock extends LocalBaseBlock implements LocalHexBlock { + value: string; + isHexOnly: boolean; + valueHex: ArrayBuffer; + + constructor(params?: LocalBmpStringValueBlockParams); + + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalUniversalStringValueParams extends LocalHexBlockParams, LocalBaseBlockParams { + } + + class LocalUniversalStringValueBlock extends LocalBaseBlock implements LocalHexBlock { + value: string; + isHexOnly: boolean; + valueHex: ArrayBuffer; + + constructor(params?: LocalUniversalStringValueParams); + + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalSimpleLocalSimpleStringValueBlockParams extends LocalHexBlockParams, LocalBaseBlockParams { + } + + class LocalSimpleLocalSimpleStringValueBlock extends LocalBaseBlock implements LocalHexBlock { + value: string; + isHexOnly: boolean; + valueHex: ArrayBuffer; + + constructor(params?: LocalSimpleLocalSimpleStringValueBlockParams); + + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalSimpleStringBlockParams { + value?: string; + } + + class LocalSimpleStringBlock extends BaseBlock { + constructor(params?: LocalSimpleStringBlockParams); + /** + * Function converting ArrayBuffer into ASN.1 internal string + * + * @param inputBuffer ASN.1 BER encoded array + */ + fromBuffer(inputBuffer: ArrayBuffer): void; + /** + * Function converting JavaScript string into ASN.1 internal class + * + * @param inputString ASN.1 BER encoded array + */ + fromString(inputString: string): void; + } + + interface BmpStringParams { + value?: string; + } + + interface UniversalStringParams { + value?: string; + } + + interface UTCTimeParams extends LocalSimpleLocalSimpleStringValueBlockParams { + value?: string; + valueDate?: Date; + } + + interface ChoiceParams { + value?: LocalValueBlock[]; + optional?: boolean; + } + + interface AnyParams { + name?: string; + optional?: boolean; + } + + interface RepeatedParams { + name?: string; + optional?: boolean; + value?: Any; + local?: boolean; + } + + interface RawDataParams { + data?: ArrayBuffer; + } + } + + class BaseBlock extends I.LocalBaseBlock { + constructor(parameters?: I.BaseBlockParams, valueBlockType?: typeof I.LocalValueBlock); + idBlock: I.LocalIdentificationBlock; + lenBlock: I.LocalLengthBlock; + valueBlock: T; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + class Primitive extends BaseBlock { + } + + class Constructed extends BaseBlock { } + + class EndOfContent extends BaseBlock { } + + class Boolean extends BaseBlock { } + + class Sequence extends Constructed { } + + class Set extends Constructed { } + + class Null extends BaseBlock { } + + class OctetString extends BaseBlock { + constructor(params?: I.LocalOctetStringValueBlockParams); + /** + * Checking that two OCTETSTRINGs are equal + */ + isEqual(octetString: OctetString): boolean; + } + + class BitString extends BaseBlock { + constructor(params?: I.LocalBitStringValueBlockParams); + /** + * Checking that two BITSTRINGs are equal + * @param bitString + */ + isEqual(bitString: BitString): boolean; + } + + class Integer extends BaseBlock { + constructor(params?: I.IntegerParams) + /** + * Compare two Integer object, or Integer and ArrayBuffer objects + */ + isEqual(otherValue: Integer | ArrayBuffer): boolean; + /** + * Convert current Integer value from BER into DER format + */ + convertToDER(): Integer; + /** + * Convert current Integer value from DER to BER format + */ + convertFromDER(): Integer; + } + + class Enumerated extends Integer { } + + class ObjectIdentifier extends BaseBlock { + constructor(params?: I.LocalObjectIdentifierValueBlockParams); + } + + class Utf8String extends BaseBlock { + constructor(params?: I.Utf8StringParams); + /** + * Function converting ArrayBuffer into ASN.1 internal string + * + * @param inputBuffer ASN.1 BER encoded array + */ + fromBuffer(inputBuffer: ArrayBuffer): void; + /** + * Function converting JavaScript string into ASN.1 internal class + * + * @param inputString ASN.1 BER encoded array + */ + fromString(inputString: string): void; + } + + class BmpString extends BaseBlock { + constructor(params?: I.BmpStringParams); + /** + * Function converting ArrayBuffer into ASN.1 internal string + * + * @param inputBuffer ASN.1 BER encoded array + */ + fromBuffer(inputBuffer: ArrayBuffer): void; + /** + * Function converting JavaScript string into ASN.1 internal class + * + * @param inputString ASN.1 BER encoded array + */ + fromString(inputString: string): void; + } + + class UniversalString extends BaseBlock { + constructor(params?: I.UniversalStringParams); + /** + * Function converting ArrayBuffer into ASN.1 internal string + * + * @param inputBuffer ASN.1 BER encoded array + */ + fromBuffer(inputBuffer: ArrayBuffer): void; + /** + * Function converting JavaScript string into ASN.1 internal class + * + * @param inputString ASN.1 BER encoded array + */ + fromString(inputString: string): void; + } + + class NumericString extends I.LocalSimpleStringBlock { } + + class PrintableString extends I.LocalSimpleStringBlock { } + + class TeletexString extends I.LocalSimpleStringBlock { } + + class VideotexString extends I.LocalSimpleStringBlock { } + + class IA5String extends I.LocalSimpleStringBlock { } + + class GraphicString extends I.LocalSimpleStringBlock { } + + class VisibleString extends I.LocalSimpleStringBlock { } + + class GeneralString extends I.LocalSimpleStringBlock { } + + class CharacterString extends I.LocalSimpleStringBlock { } + + class UTCTime extends VisibleString { + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; + constructor(params?: I.UTCTimeParams); + /** + * Function converting ASN.1 internal string into ArrayBuffer + */ + toBuffer(): ArrayBuffer; + /** + * Function converting "Date" object into ASN.1 internal string + * + * @param inputDate JavaScript "Date" object + */ + fromDate(inputDate: Date): void; + /** + * Function converting ASN.1 internal string into "Date" object + */ + toDate(): Date; + } + + class GeneralizedTime extends UTCTime { + millisecond: number; + } + + class DATE extends Utf8String { } + + class TimeOfDay extends Utf8String { } + + class DateTime extends Utf8String { } + + class Duration extends Utf8String { } + + class TIME extends Utf8String { } + + class Choice { + value: I.LocalValueBlock[]; + optional: boolean; + constructor(params?: I.ChoiceParams); + } + + class Any { + name: string; + optional: boolean; + constructor(params?: I.AnyParams); + } + + class Repeated { + name: string; + optional: boolean; + value: Any; + local: boolean; + constructor(params?: I.RepeatedParams); + } + + class RawData { + data: ArrayBuffer; + + constructor(params?: I.RawDataParams); + + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + /** + * Major function for decoding ASN.1 BER array into internal library structuries + * + * @param inputBuffer ASN.1 BER encoded array of bytes + */ + function fromBER(inputBuffer: ArrayBuffer): { offset: number; result: I.LocalBaseBlock }; + + /** + * Compare of two ASN.1 object trees + * + * @param root Root of input ASN.1 object tree + * @param inputData Input ASN.1 object tree + * @param inputSchema Input ASN.1 schema to compare with + */ + function compareSchema(root: any, inputData: any, inputSchema: any): { verified: boolean, result?: any }; + + /** + * ASN.1 schema verification for ArrayBuffer data + * + * @param inputBuffer Input BER-encoded ASN.1 data + * @param inputSchema Input ASN.1 schema to verify against to + */ + function verifySchema(inputBuffer: ArrayBuffer, inputSchema: any): { verified: boolean, result?: any }; + } +} diff --git a/types/adone/glosses/crypto/ed25519.d.ts b/types/adone/glosses/crypto/ed25519.d.ts new file mode 100644 index 0000000000..7e4f6e2f33 --- /dev/null +++ b/types/adone/glosses/crypto/ed25519.d.ts @@ -0,0 +1,20 @@ +declare namespace adone.crypto { + namespace ed25519 { + const publicKeyLength: number; + + const privateKeyLength: number; + + namespace I { + interface KeyPair { + publicKey: Buffer; + privateKey: Buffer; + } + } + + function generateKeyPair(seed: Buffer): I.KeyPair; + + function sign(message: Buffer, seed: Buffer | I.KeyPair): Buffer; + + function verify(message: Buffer, signature: Buffer, publicKey: Buffer): boolean; + } +} diff --git a/types/adone/glosses/crypto/index.d.ts b/types/adone/glosses/crypto/index.d.ts new file mode 100644 index 0000000000..ea4b76967f --- /dev/null +++ b/types/adone/glosses/crypto/index.d.ts @@ -0,0 +1,9 @@ +/// +/// +/// + +declare namespace adone { + namespace crypto { + // + } +} diff --git a/types/adone/glosses/crypto/secp256k1.d.ts b/types/adone/glosses/crypto/secp256k1.d.ts new file mode 100644 index 0000000000..87167cc441 --- /dev/null +++ b/types/adone/glosses/crypto/secp256k1.d.ts @@ -0,0 +1,127 @@ +declare namespace adone.crypto { + namespace secp256k1 { + /** + * Verifies an ECDSA privateKey + */ + function privateKeyVerify(privateKey: Buffer): boolean; + + /** + * Exports a privateKey in DER format + */ + function privateKeyExport(privateKey: Buffer, compressed?: boolean): Buffer; + + /** + * Imports a privateKey in DER format + */ + function privateKeyImport(privateKey: Buffer): Buffer; + + /** + * Negates a privateKey by subtracting it from the order of the curve's base point + */ + function privateKeyNegate(privateKey: Buffer): Buffer; + + /** + * Computes the inverse of a privateKey (modulo the order of the curve's base point) + */ + function privateKeyModInverse(privateKey: Buffer): Buffer; + + /** + * Tweaks a privateKey by adding tweak to it + */ + function privateKeyTweakAdd(privateKey: Buffer, tweak: Buffer): Buffer; + + /** + * Tweaks a privateKey by multiplying it by a tweak + */ + function privateKeyTweakMul(privateKey: Buffer, tweak: Buffer): Buffer; + + /** + * Computes the public key for a privateKey + */ + function publicKeyCreate(privateKey: Buffer, compressed?: boolean): Buffer; + + /** + * Converts a publicKey to compressed or uncompressed form + */ + function publicKeyConvert(publicKey: Buffer, compressed?: boolean): Buffer; + + /** + * Verifies an ECDSA publicKey + */ + function publicKeyVerify(publicKey: Buffer): boolean; + + /** + * Tweaks a publicKey by adding tweak times the generator to it + */ + function publicKeyTweakAdd(publicKey: Buffer, tweak: Buffer, compressed?: boolean): Buffer; + + /** + * Tweaks a publicKey by multiplying it by a tweak value + */ + function publicKeyTweakMul(publicKey: Buffer, tweak: Buffer, compressed?: boolean): Buffer; + + /** + * Adds a given publicKeys together + */ + function publicKeyCombine(publicKeys: Buffer[], compressed?: boolean): Buffer; + + /** + * Converts a signature to a normalized lower-S form + */ + function signatureNormalize(signature: Buffer): Buffer; + + /** + * Serializes an ECDSA signature in DER format + */ + function signatureExport(signature: Buffer): Buffer; + + /** + * Parse a DER ECDSA signature (follow by BIP66) + */ + function signatureImport(signature: Buffer): Buffer; + + /** + * Same as signatureImport but not follow by BIP66 + */ + function signatureImportLax(signature: Buffer): Buffer; + + namespace I { + interface SignOptions { + noncefn?: (message: Buffer, privateKey: Buffer, algo: Buffer, data: Buffer, attempt: number) => Buffer; + data?: Buffer | null; + } + + interface SignResult { + signature: Buffer; + recovery: number; + } + } + + /** + * Creates an ECDSA signature. Always return low-S signature. + */ + function sign(message: Buffer, privateKey: Buffer, options?: I.SignOptions): I.SignResult; + + /** + * Verifies an ECDSA signature + * + * Note: return false for high signatures! + */ + function verify(message: Buffer, signature: Buffer, publicKey: Buffer): boolean; + + /** + * Recovers an ECDSA public key from a signature + */ + function recover(message: Buffer, signature: Buffer, recovery: number, compressed?: boolean): Buffer; + + /** + * Computes an EC Diffie-Hellman secret and applied sha256 to compressed public key + */ + function ecdh(publicKey: Buffer, privateKey: Buffer): Buffer; + + /** + * Computes an EC Diffie-Hellman secret and return public key as result + */ + function ecdhUnsafe(publicKey: Buffer, privateKey: Buffer, compressed?: boolean): Buffer; + } +} diff --git a/types/adone/glosses/data.d.ts b/types/adone/glosses/data.d.ts index f711836bdd..3a979cae98 100644 --- a/types/adone/glosses/data.d.ts +++ b/types/adone/glosses/data.d.ts @@ -30,7 +30,12 @@ declare namespace adone { * or an array of String and Number objects that serve as a whitelist * for selecting/filtering the properties of the value object to be included in the JSON string */ - replacer?: I.Replacer + replacer?: I.Replacer, + + /** + * Wheter to append a newline + */ + newline?: boolean }): Buffer; /** @@ -84,6 +89,8 @@ declare namespace adone { */ function decode(buf: collection.I.ByteArray.Wrappable): any; + function tryDecode(buf: collection.ByteArray): any; + namespace I { type Type = string | number; // ? type DecodeFunction = (buf: collection.ByteArray) => any; @@ -153,6 +160,8 @@ declare namespace adone { * Represents a MessagePack serializer */ class Serializer { + constructor(initialCapacity?: number); + /** * Encoder instance */ @@ -211,6 +220,8 @@ declare namespace adone { * x.Exception, Error, Date, Map, Set, math.Long */ const serializer: Serializer; + + function registerCommonTypesFor(s: Serializer): void; } /** @@ -244,21 +255,32 @@ declare namespace adone { * Base64 encoder */ namespace base64 { + namespace I { + interface DecodeOptions { + buffer?: boolean; + encoding?: string; + } + + interface EncodeOptions { + buffer?: boolean; + } + } + /** * Encodes a string/Buffer to base64 */ - function encode(str: string | Buffer, options: { buffer: false }): string; - function encode(str: string | Buffer, options?: { buffer?: true }): Buffer; + function encode(str: string | Buffer, options: I.EncodeOptions & { buffer: false }): string; + function encode(str: string | Buffer, options?: I.EncodeOptions): Buffer; /** * Decodes base64 string/buffer into a buffer */ - function decode(str: string | Buffer, options: { buffer: true }): Buffer; + function decode(str: string | Buffer, options: I.DecodeOptions & { buffer: true }): Buffer; /** * Decodes base64 string/buffer into a string */ - function decode(str: string | Buffer, options?: { buffer?: false }): string; + function decode(str: string | Buffer, options?: I.DecodeOptions): string; function encodeVLQ(value: number): string; @@ -560,7 +582,7 @@ declare namespace adone { /** * Represents a YAML exception */ - class Exception extends adone.x.Exception { + class Exception extends adone.error.Exception { reason: string; mark: Mark; @@ -1028,5 +1050,183 @@ declare namespace adone { */ function decode(buf: Buffer, options?: I.DeserializeOptions): any; } + + namespace protobuf { + namespace schema { + namespace I { + interface Field { + name: string | null; + type: string | null; + tag: number; + map: { + from: string; + to: string; + } | null; + oneof: string | null; + required: boolean; + repeated: boolean; + options: object; + } + + interface Enum { + name: string; + values: object; + options: object; + } + + interface Extend { + name: string; + message: Message; + } + + interface Message { + name: string; + enums: Enum[]; + extends: Extend[]; + messages: Message[]; + fields: Field[]; + extensions: { + from: number, + to: number + } | null; + } + + interface RPCMethod { + name: string; + input_type: string | null; + output_type: string | null; + client_streaming: boolean; + server_streaming: boolean; + options: object; + } + + interface Service { + name: string; + methods: RPCMethod[]; + options: object; + } + + interface Schema { + syntax: any; // ?? + package: string | null; + imports: string[]; + enums: Enum[]; + messages: Message[]; + options: object; + extends: Extend[]; + services?: Service[]; + } + } + + function parse(buf: Buffer | string): I.Schema; + + function stringify(schema: object): string; + } + + function create(proto: Buffer | string | object, opts?: object): object; + } + + namespace base32 { + function charmap(alphabet: string, mappings?: T): T; + + namespace I { + interface Spec { + alphabet: string; + charmap: { + [c: string]: number; + }; + } + } + + const rfc4648: I.Spec; + + const crockford: I.Spec; + + const base32hex: I.Spec; + + namespace I { + interface DecoderOptions { + type: "rfc4648" | "crockford" | "base32hex"; + charmap?: object; + } + + interface EncoderOptions { + type: "rfc4648" | "crockford" | "base32hex"; + alphabet?: string; + } + } + + class Decoder { + constructor(options?: I.DecoderOptions); + + write(str: string): this; + + finalize(str?: string): Buffer; + } + + class Encoder { + constructor(options?: I.EncoderOptions); + + write(buf: Buffer): this; + + finalize(buf?: Buffer): string; + } + + function encode(buf: Buffer, options?: I.EncoderOptions): string; + + function decode(str: string, options?: I.DecoderOptions): Buffer; + } + + namespace I { + interface BaseX { + encode(buf: Buffer): string; + + decode(str: string): Buffer; + + decodeUnsafe(str: string): Buffer; + } + } + + function basex(alphabet: string): I.BaseX; + + const base58: I.BaseX; + + namespace base64url { + function unescape(str: string): string; + + function escape(str: string): string; + + namespace I { + interface EncodeOptions { + encoding?: string; + } + + interface DecodeOptions { + encoding?: string; + buffer?: boolean; + } + } + + function encode(str: Buffer | string, options?: I.EncodeOptions): string; + + function decode(str: string, options: I.DecodeOptions & { buffer: true }): Buffer; + function decode(str: string, options?: I.DecodeOptions): string; + } + + namespace varint { + function encode(num: number, out?: T[], offset?: number): T[]; + + function decode(buf: Buffer, offset?: number): number; + + function encodingLength(value: number): number; + } + + namespace varintSigned { + function encode(num: number, out?: T[], offset?: number): T[]; + + function decode(buf: Buffer, offset?: number): number; + + function encodingLength(value: number): number; + } } } diff --git a/types/adone/glosses/exceptions.d.ts b/types/adone/glosses/errors.d.ts similarity index 98% rename from types/adone/glosses/exceptions.d.ts rename to types/adone/glosses/errors.d.ts index 347a3c632d..c3d9e1f632 100644 --- a/types/adone/glosses/exceptions.d.ts +++ b/types/adone/glosses/errors.d.ts @@ -1,5 +1,5 @@ declare namespace adone { - namespace x { + namespace error { class Exception extends Error { constructor(message?: string | Error, captureStackTrace?: boolean); } diff --git a/types/adone/glosses/events.d.ts b/types/adone/glosses/events.d.ts index ecb323f925..e812624aa9 100644 --- a/types/adone/glosses/events.d.ts +++ b/types/adone/glosses/events.d.ts @@ -1,25 +1,48 @@ declare namespace adone { namespace event { - class EventEmitter { - static listenerCount(emitter: EventEmitter, event: string | symbol): number; + namespace I { + interface PropagateEventsEnder { + end(): void; + } + } + + class Emitter { + static listenerCount(emitter: Emitter, event: string | symbol): number; + static defaultMaxListeners: number; addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Array<(...args: any[]) => any>; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array; + listenerCount(type: string | symbol): number; + + propagateEvents(dest: Emitter, events: string[]): I.PropagateEventsEnder; + + static propagateEvents(source: Emitter, dest: Emitter, events: string[]): I.PropagateEventsEnder; } - class AsyncEmitter extends EventEmitter { + class AsyncEmitter extends Emitter { constructor(concurrency?: number); setConcurrency(max?: number): this; diff --git a/types/adone/glosses/fake.d.ts b/types/adone/glosses/fake.d.ts new file mode 100644 index 0000000000..0c403747e4 --- /dev/null +++ b/types/adone/glosses/fake.d.ts @@ -0,0 +1,337 @@ +declare namespace adone { + namespace fake { + namespace I { + interface Card { + name: string; + username: string; + email: string; + address: FullAddress; + phone: string; + website: string; + company: Company; + posts: Post[]; + accountHistory: string[]; + } + + interface FullAddress { + streetA: string; + streetB: string; + streetC: string; + streetD: string; + city: string; + state: string; + county: string; + zipcode: string; + geo: Geo; + } + + interface Geo { + lat: string; + lng: string; + } + + interface Company { + name: string; + catchPhrase: string; + bs: string; + } + + interface Post { + words: string; + sentence: string; + sentences: string; + paragraph: string; + } + + interface ContextualCard { + name: string; + username: string; + email: string; + dob: Date; + phone: string; + address: Address; + website: string; + company: Company; + } + + interface Address { + street: string; + suite: string; + city: string; + state: string; + zipcode: string; + geo: Geo; + } + + interface UserCard { + name: string; + username: string; + email: string; + address: Address; + phone: string; + website: string; + company: Company; + } + + interface Transaction { + amount: string; + date: Date; + business: string; + name: string; + type: string; + account: string; + } + } + + namespace address { + function zipCode(format?: string): string; + function city(format?: number): string; + function cityPrefix(): string; + function citySuffix(): string; + function streetName(): string; + function streetAddress(useFullAddress?: boolean): string; + function streetSuffix(): string; + function streetPrefix(): string; + function secondaryAddress(): string; + function county(): string; + function country(): string; + function countryCode(): string; + function state(useAbbr?: boolean): string; + function stateAbbr(): string; + function latitude(): string; + function longitude(): string; + } + + namespace commerce { + function color(): string; + function department(): string; + function productName(): string; + function price(min?: number, max?: number, dec?: number, symbol?: string): string; + function productAdjective(): string; + function productMaterial(): string; + function product(): string; + } + + namespace company { + function suffixes(): string[]; + function companyName(format?: number): string; + function companySuffix(): string; + function catchPhrase(): string; + function bs(): string; + function catchPhraseAdjective(): string; + function catchPhraseDescriptor(): string; + function catchPhraseNoun(): string; + function bsAdjective(): string; + function bsBuzz(): string; + function bsNoun(): string; + } + + namespace database { + function column(): string; + function type(): string; + function collation(): string; + function engine(): string; + } + + namespace date { + function past(years?: number, refDate?: string|Date): Date; + function future(years?: number, refDate?: string|Date): Date; + function between(from: string|number|Date, to: string|Date): Date; + function recent(days?: number): Date; + function soon(days?: number): Date; + function month(options?: { abbr?: boolean, context?: boolean }): string; + function weekday(options?: { abbr?: boolean, context?: boolean }): string; + } + + function fake(str: string): string; + + namespace finance { + function account(length?: number): string; + function accountName(): string; + function mask(length?: number, parens?: boolean, elipsis?: boolean): string; + function amount(min?: number, max?: number, dec?: number, symbol?: string): string; + function transactionType(): string; + function currencyCode(): string; + function currencyName(): string; + function currencySymbol(): string; + function bitcoinAddress(): string; + function ethereumAddress(): string; + function iban(formatted?: boolean): string; + function bic(): string; + } + + namespace hacker { + function abbreviation(): string; + function adjective(): string; + function noun(): string; + function verb(): string; + function ingverb(): string; + function phrase(): string; + } + + namespace helpers { + function randomize(array: T[]): T; + function randomize(): string; + function slugify(string?: string): string; + function replaceSymbolWithNumber(string?: string, symbol?: string): string; + function replaceSymbols(string?: string): string; + function shuffle(o: T[]): T[]; + function shuffle(): string[]; + function mustache(str: string, data: { [key: string]: string|((substring: string, ...args: any[]) => string) }): string; + function createCard(): I.Card; + function contextualCard(): I.ContextualCard; + function userCard(): I.UserCard; + function createTransaction(): I.Transaction; + } + + namespace image { + function image(): string; + function avatar(): string; + function imageUrl(width?: number, height?: number, category?: string): string; + function abstract(width?: number, height?: number): string; + function animals(width?: number, height?: number): string; + function business(width?: number, height?: number): string; + function cats(width?: number, height?: number): string; + function city(width?: number, height?: number): string; + function food(width?: number, height?: number): string; + function nightlife(width?: number, height?: number): string; + function fashion(width?: number, height?: number): string; + function people(width?: number, height?: number): string; + function nature(width?: number, height?: number): string; + function sports(width?: number, height?: number): string; + function technics(width?: number, height?: number): string; + function transport(width?: number, height?: number): string; + function dataUri(width?: number, height?: number): string; + } + + namespace internet { + function avatar(): string; + function email(firstName?: string, lastName?: string, provider?: string): string; + function exampleEmail(firstName?: string, lastName?: string): string; + function userName(firstName?: string, lastName?: string): string; + function protocol(): string; + function url(): string; + function domainName(): string; + function domainSuffix(): string; + function domainWord(): string; + function ip(): string; + function ipv6(): string; + function userAgent(): string; + function color(baseRed255?: number, baseGreen255?: number, baseBlue255?: number): string; + function mac(): string; + function password(len?: number, memorable?: boolean, pattern?: string|RegExp, prefix?: string): string; + } + + namespace lorem { + function word(): string; + function words(num?: number): string; + function sentence(wordCount?: number, range?: number): string; + function slug(wordCount?: number): string; + function sentences(sentenceCount?: number): string; + function paragraph(sentenceCount?: number): string; + function paragraphs(paragraphCount?: number, separator?: string): string; + function text(times?: number): string; + function lines(lineCount?: number): string; + } + + namespace name { + function firstName(gender?: number): string; + function lastName(gender?: number): string; + function findName(firstName?: string, lastName?: string, gender?: number): string; + function jobTitle(): string; + function prefix(): string; + function suffix(): string; + function title(): string; + function jobDescriptor(): string; + function jobArea(): string; + function jobType(): string; + } + + namespace phone { + function phoneNumber(format?: string): string; + function phoneNumberFormat(phoneFormatsArrayIndex?: number): string; + function phoneFormats(): string; + } + + namespace random { + function number(max: number): number; + function number(options?: { min?: number, max?: number, precision?: number }): number; + function arrayElement(): string; + function arrayElement(array: T[]): T; + function objectElement(object?: { [key: string]: any }, field?: "key"): string; + function objectElement(object?: { [key: string]: T }, field?: any): T; + function uuid(): string; + function boolean(): boolean; + function word(type?: string): string; + function words(count?: number): string; + function image(): string; + function locale(): string; + function alphaNumeric(count?: number): string; + function hexaDecimal(count?: number): string; + } + + namespace system { + function fileName(ext: string, type: string): string; + function commonFileName(ext: string, type: string): string; + function mimeType(): string; + function commonFileType(): string; + function commonFileExt(): string; + function fileType(): string; + function fileExt(mimeType: string): string; + function directoryPath(): string; + function filePath(): string; + function semver(): string; + } + + function seed(value: number): void; + + namespace I { + type Locale = + | "az" + | "cz" + | "de" + | "de_AT" + | "de_CH" + | "el" + | "en" + | "en_AU" + | "en_BORK" + | "en_CA" + | "en_GB" + | "en_IE" + | "en_IND" + | "en_US" + | "en_au_ocker" + | "es" + | "es_MX" + | "fa" + | "fr" + | "fr_CA" + | "ge" + | "id_ID" + | "it" + | "ja" + | "ko" + | "lv" + | "nb_NO" + | "nep" + | "nl" + | "nl_BE" + | "pl" + | "pt_BR" + | "ro" + | "ru" + | "sk" + | "sv" + | "tr" + | "uk" + | "vi" + | "zh_CN" + | "zh_TW"; + } + + function getLocale(): I.Locale; + + function setLocale(locale: I.Locale): void; + } +} diff --git a/types/adone/glosses/fast.d.ts b/types/adone/glosses/fast.d.ts index 725e0e9db3..1b04bec6d3 100644 --- a/types/adone/glosses/fast.d.ts +++ b/types/adone/glosses/fast.d.ts @@ -152,7 +152,7 @@ declare namespace adone { type SymbolicFile = File; /* tslint:disable-next-line:no-empty-interface */ - interface Stream extends stream.CoreStream { + interface Stream extends stream.core.Stream { // } } @@ -160,7 +160,7 @@ declare namespace adone { export const File: I.FileConstructor; namespace I { - type CoreStreamSource = stream.I.CoreStream.Source; + type CoreStreamSource = stream.core.I.Source; interface LocalStreamConstructorOptions { /** @@ -586,7 +586,7 @@ declare namespace adone { /** * Read JSON manifests written out by revisionHash */ - manifest?: File[] | stream.CoreStream, + manifest?: File[] | stream.core.Stream, /** * Modify the name of the unreved files before using them diff --git a/types/adone/glosses/fs.d.ts b/types/adone/glosses/fs.d.ts index 7fa8f51593..7517764faf 100644 --- a/types/adone/glosses/fs.d.ts +++ b/types/adone/glosses/fs.d.ts @@ -22,6 +22,14 @@ declare namespace adone { function readlink(path: string | Buffer | I.URL, options: { encoding: null }): Promise; function readlink(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): Promise; + /** + * Reads the value of a symbolic link + */ + function readlinkSync(path: string | Buffer | I.URL, encoding: null): Buffer; + function readlinkSync(path: string | Buffer | I.URL, encoding: I.Encoding): string; + function readlinkSync(path: string | Buffer | I.URL, options: { encoding: null }): Buffer; + function readlinkSync(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): string; + /** * Deletes a name and possibly the file it refers to */ @@ -32,6 +40,21 @@ declare namespace adone { */ function unlinkSync(path: string | Buffer | I.URL): void; + /** + * Changes the file system timestamps of the object referenced by path + */ + function utimes(path: string | Buffer | I.URL, atime: number | string | Date, mtime: number | string | Date): Promise; + + /** + * Changes the file system timestamps of the object referenced by path + */ + function utimesSync(path: string | Buffer | I.URL, atime: number | string | Date, mtime: number | string | Date): void; + + /** + * Changes the file system timestamps of the object referenced by path + */ + function utimesMillis(path: string | Buffer | I.URL, atime: number, mtime: number): Promise; + /** * Changes permissions of a file */ @@ -42,6 +65,11 @@ declare namespace adone { */ function chown(path: string | Buffer | I.URL, uid: number, gid: number): Promise; + /** + * Changes ownership recursively for a given path + */ + function chownr(path: string | Buffer | I.URL, uid: number, gid: number): Promise; + /** * Deletes a directory */ @@ -63,6 +91,87 @@ declare namespace adone { function readdirSync(path: string | Buffer | I.URL, options: { encoding: null }): Buffer[]; function readdirSync(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): string[]; + namespace I { + interface ReaddirpEntry { + /** + * filename + */ + name: string; + + /** + * full path to a file + */ + fullPath: string; + + /** + * relative path to a file + */ + path: string; + + /** + * relative path to the parent dir + */ + parentDir: string; + + /** + * full path to the parent dir + */ + fullParentDir: string; + + /** + * file stats + */ + stat: fs.I.Stats; + } + + type ReaddirpFilter = string | ((entry: ReaddirpEntry) => boolean); + + interface ReaddirpOptions { + /** + * filter for files + */ + fileFilter?: ReaddirpFilter | ReaddirpFilter[]; + + /** + * filter for directories + */ + directoryFilter?: ReaddirpFilter | ReaddirpFilter[]; + + /** + * maximum recursion depth + * + * Infinity by default + */ + depth?: number; + + /** + * whether to emit files + * + * true by default + */ + files?: boolean; + + /** + * whether to emit directories + * + * true by default + */ + directories?: boolean; + + /** + * whether to use lstat for stating + * + * false by default + */ + lstat?: boolean; + } + } + + /** + * Traverses the given path + */ + function readdirp(root: string | Buffer | I.URL, options?: I.ReaddirpOptions): stream.core.Stream; + /** * Gets file status, identical to stat, except that if pathname is a symbolic link, * then it returns information about the link itself, not the file that it refers to @@ -117,6 +226,15 @@ declare namespace adone { flag?: I.Flag }): Promise; + /** + * Appends data to a file, creating the file if it does not yet exist + */ + function appendFileSync(file: string | Buffer | number, data: string | Buffer, options?: { + encoding?: I.Encoding, + mode?: number, + flag?: I.Flag + }): void; + /** * Tests a user's permissions for the file or directory specified by path */ @@ -154,6 +272,14 @@ declare namespace adone { cwd?: string }): Promise; + /** + * Recursively deletes empty directiries inside the given directory + */ + function rmEmpty(path: string, options?: { + cwd?: string; + filter?: (filename: string) => boolean + }): Promise; + namespace I { interface Access { read: boolean; @@ -460,12 +586,12 @@ declare namespace adone { /** * Copies this from this directory to the given path */ - copyTo(destPath: string, options?: I.CopyOptions): Promise; + copyTo(destPath: string, options?: I.CopyToOptions): Promise; /** * Copies files from the given path to this directory */ - copyFrom(srcPath: string, options?: I.CopyOptions): Promise; + copyFrom(srcPath: string, options?: I.CopyToOptions): Promise; /** * Creates a new directory with the given path @@ -560,7 +686,7 @@ declare namespace adone { /** * Represents a file that supports random access */ - class RandomAccessFile extends event.EventEmitter { + class RandomAccessFile extends event.Emitter { constructor(filename: string, options?: I.RandomAccessFile.ConstructorOptions); /** @@ -602,7 +728,7 @@ declare namespace adone { /** * Represents an abstract random access reader */ - class AbstractRandomAccessReader extends event.EventEmitter { + class AbstractRandomAccessReader extends event.Emitter { /** * Increments the reference counter */ @@ -826,7 +952,7 @@ declare namespace adone { }>; } - type Stream = stream.CoreStream; + type Stream = stream.core.Stream; interface EmitterConstructor { new(pattern: string, optons: Options, callback?: (error: any, matches: string[]) => void): Emitter; @@ -835,7 +961,7 @@ declare namespace adone { prototype: Emitter; } - interface Emitter extends event.EventEmitter { + interface Emitter extends event.Emitter { isIgnored(path: string): boolean; /** @@ -999,7 +1125,7 @@ declare namespace adone { /** * Represents a file watcher */ - class Watcher extends event.EventEmitter { + class Watcher extends event.Emitter { constructor(options?: I.Watcher.ConstructorOptions); /** @@ -1128,214 +1254,209 @@ declare namespace adone { function whichSync(cmd: string, options?: I.Which.Options): string; /** - * Functions to work with files using file descriptors + * Opens and possibly creates a file */ - namespace fd { - /** - * Opens and possibly create a file - */ - function open(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): Promise; + function open(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): Promise; - /** - * Opens and possibly create a file - */ - function openSync(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): I.FD; + /** + * Opens and possibly creates a file + */ + function openSync(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): I.FD; - /** - * Closes a file descriptor - */ - function close(fd: I.FD): Promise; + /** + * Closes a file descriptor + */ + function close(fd: I.FD): Promise; - /** - * Closes a file descriptor - */ - function closeSync(fd: I.FD): void; + /** + * Closes a file descriptor + */ + function closeSync(fd: I.FD): void; - /** - * Changes the file timestamps of a file referenced by the supplied file descriptor - */ - function utimes(fd: I.FD, atime: number, mtime: number): Promise; + /** + * Changes the file timestamps of a file referenced by the supplied file descriptor + */ + function futimes(fd: I.FD, atime: number, mtime: number): Promise; - /** - * Changes the file timestamps of a file referenced by the supplied file descriptor - */ - function utimesSync(fd: I.FD, atime: number, mtime: number): void; + /** + * Changes the file timestamps of a file referenced by the supplied file descriptor + */ + function futimesSync(fd: I.FD, atime: number, mtime: number): void; - /** - * Gets file status - */ - function stat(fd: I.FD): Promise; + /** + * Gets file status + */ + function fstat(fd: I.FD): Promise; - /** - * Gets file status - */ - function statSync(fd: I.FD): I.Stats; + /** + * Gets file status + */ + function fstatSync(fd: I.FD): I.Stats; - /** - * Truncates a file to a specified length - */ - function truncate(fd: I.FD, length?: number): Promise; + /** + * Truncates a file to a specified length + */ + function ftruncate(fd: I.FD, length?: number): Promise; - /** - * Truncates a file to a specified length - */ - function truncateSync(fd: I.FD, length?: number): void; + /** + * Truncates a file to a specified length + */ + function ftruncateSync(fd: I.FD, length?: number): void; + /** + * Read data from the file specified by fd + */ + function read( + fd: I.FD, /** - * Read data from the file specified by fd + * The buffer that the data will be written to */ - function read( - fd: I.FD, - /** - * The buffer that the data will be written to - */ - buffer: Buffer | Uint8Array, - /** - * The offset in the buffer to start writing at - */ - offset: number, - /** - * An integer specifying the number of bytes to read - */ - length: number, - /** - * An argument specifying where to begin reading from in the file - */ - position: number - ): Promise; - - function readSync( - fd: I.FD, - /** - * The buffer that the data will be written to - */ - buffer: Buffer | Uint8Array, - /** - * The offset in the buffer to start writing at - */ - offset: number, - /** - * An integer specifying the number of bytes to read - */ - length: number, - /** - * An argument specifying where to begin reading from in the file - */ - position: number - ): number; - + buffer: Buffer | Uint8Array, /** - * Writes buffer to the file specified by fd + * The offset in the buffer to start writing at */ - function write( - fd: I.FD, - buffer: Buffer | Uint8Array, - /** - * Determines the part of the buffer to be written - */ - offset?: number, - /** - * An integer specifying the number of bytes to write - */ - length?: number, - /** - * The offset from the beginning of the file where this data should be written - */ - position?: number - ): Promise; - + offset: number, /** - * Writes string to the file specified by fd + * An integer specifying the number of bytes to read */ - function write( - fd: I.FD, - string: string, - /** - * The offset from the beginning of the file where this data should be written - */ - position?: number, - /** - * The expected string encoding - */ - encoding?: I.Encoding - ): Promise; - + length: number, /** - * Writes buffer to the file specified by fd + * An argument specifying where to begin reading from in the file */ - function writeSync( - fd: I.FD, - buffer: Buffer | Uint8Array, - /** - * Determines the part of the buffer to be written - */ - offset?: number, - /** - * An integer specifying the number of bytes to write - */ - length?: number, - /** - * The offset from the beginning of the file where this data should be written - */ - position?: number - ): number; + position: number + ): Promise; + function readSync( + fd: I.FD, /** - * Writes string to the file specified by fd + * The buffer that the data will be written to */ - function writeSync( - fd: I.FD, - string: string, - /** - * The offset from the beginning of the file where this data should be written - */ - position?: number, - /** - * The expected string encoding - */ - encoding?: I.Encoding - ): number; + buffer: Buffer | Uint8Array, + /** + * The offset in the buffer to start writing at + */ + offset: number, + /** + * An integer specifying the number of bytes to read + */ + length: number, + /** + * An argument specifying where to begin reading from in the file + */ + position: number + ): number; + /** + * Writes buffer to the file specified by fd + */ + function write( + fd: I.FD, + buffer: Buffer | Uint8Array, /** - * Synchronizes a file's in-core state with storage + * Determines the part of the buffer to be written */ - function sync(fd: I.FD): Promise; + offset?: number, + /** + * An integer specifying the number of bytes to write + */ + length?: number, + /** + * The offset from the beginning of the file where this data should be written + */ + position?: number + ): Promise; + /** + * Writes string to the file specified by fd + */ + function write( + fd: I.FD, + string: string, /** - * Synchronizes a file's in-core state with storage + * The offset from the beginning of the file where this data should be written */ - function syncSync(fd: I.FD): void; + position?: number, + /** + * The expected string encoding + */ + encoding?: I.Encoding + ): Promise; + /** + * Writes buffer to the file specified by fd + */ + function writeSync( + fd: I.FD, + buffer: Buffer | Uint8Array, /** - * Changes ownership of a file + * Determines the part of the buffer to be written */ - function chown(fd: I.FD, uid: number, gid: number): Promise; + offset?: number, + /** + * An integer specifying the number of bytes to write + */ + length?: number, + /** + * The offset from the beginning of the file where this data should be written + */ + position?: number + ): number; + /** + * Writes string to the file specified by fd + */ + function writeSync( + fd: I.FD, + string: string, /** - * Changes ownership of a file + * The offset from the beginning of the file where this data should be written */ - function chownSync(fd: I.FD, uid: number, gid: number): void; + position?: number, + /** + * The expected string encoding + */ + encoding?: I.Encoding + ): number; - /** - * Changes permissions of a file - */ - function chmod(fd: I.FD, mode: number): Promise; + /** + * Synchronizes a file's in-core state with storage + */ + function fsync(fd: I.FD): Promise; - /** - * Changes permissions of a file - */ - function chmodSync(fd: I.FD, mode: number): void; + /** + * Synchronizes a file's in-core state with storage + */ + function fsyncSync(fd: I.FD): void; - /** - * Repositions read/write file offset - */ - function seek(fd: I.FD, offset: number, whence: number): Promise; + /** + * Changes ownership of a file + */ + function fchown(fd: I.FD, uid: number, gid: number): Promise; - /** - * Applies or removes an advisory lock on an open file - */ - function lock(fd: I.FD, flags: "sh" | "ex" | "shnb" | "exnb" | "un" | number): Promise; - } + /** + * Changes ownership of a file + */ + function fchownSync(fd: I.FD, uid: number, gid: number): void; + + /** + * Changes permissions of a file + */ + function fchmod(fd: I.FD, mode: number): Promise; + + /** + * Changes permissions of a file + */ + function fchmodSync(fd: I.FD, mode: number): void; + + /** + * Repositions read/write file offset + */ + function seek(fd: I.FD, offset: number, whence: number): Promise; + + /** + * Applies or removes an advisory lock on an open file + */ + function flock(fd: I.FD, flags: "sh" | "ex" | "shnb" | "exnb" | "un" | number): Promise; namespace constants { const F_OK: number; @@ -1475,12 +1596,63 @@ declare namespace adone { function existsSync(path: string | Buffer | I.URL): boolean; /** - * Creates a new directory and any necessary subdirectories + * Creates a new directory */ function mkdir(path: string, mode?: number): Promise; + /** + * Creates a new directory + */ + function mkdirSync(path: string, mode?: number): Promise; + + /** + * Creates a new directory and any necessary subdirectories + */ + function mkdirp(path: string, mode?: number): Promise; + + /** + * Creates a new directory and any necessary subdirectories + */ + function mkdirpSync(path: string, mode?: number): Promise; + namespace I { interface CopyOptions { + /** + * regexp or function against which each filename is tested whether to copy it or not + */ + filter?: RegExp | ((src: string, dst: string) => boolean); + + /** + * transform function which applies when files are streamed + */ + transform?( + readStream: NodeJS.ReadableStream, + writeStream: NodeJS.WritableStream, + file: { + name: string, + mode: number, + mtime: Date, + atime: Date, + stats: adone.fs.I.Stats + } + ): void; + + /** + * Whether to overwrite destination files if they exist. + * + * true by default + */ + clobber?: boolean; // ??? + + /** + * Whether to overwrite destination files if they exist. + * + * true by default + */ + overwrite?: boolean; + } + + interface CopyToOptions { /** * Do not replace existing files */ @@ -1494,10 +1666,15 @@ declare namespace adone { } /** - * Copies all files from src to dst + * Recursively copies all the files from src to dst */ function copy(src: string, dst: string, options?: I.CopyOptions): Promise; + /** + * Copies all files from src to dst + */ + function copyTo(src: string, dst: string, options?: I.CopyToOptions): Promise; + /** * Renames a file */ @@ -1514,8 +1691,32 @@ declare namespace adone { /** * Returns the last lines of a file + * + * @param path path to a file + * @param n number of lines to return */ - function tail(path: string, n: number, options?: { separator?: string, chunkLength?: number }): Promise; + function tail(path: string, n: number, options?: { + /** + * Line separator + * + * By default "\r\n" for windows and "\n" for others + */ + separator?: string, + + /** + * The number of bytes to read at once + * + * By default 4096 + */ + chunkLength?: number + + /** + * Position from which to start reading (from the end) + * + * By default stats.size of the file + */ + pos?: number + }): Promise; namespace I { interface StatVFS { @@ -1667,11 +1868,6 @@ declare namespace adone { */ function lookup(path: string): Promise; - /** - * Recursively changes ownership of files - */ - function chownr(path: string, uid: number, gid: number): Promise; - namespace I.TailWatcher { interface ConstructorOptions { /** @@ -1709,7 +1905,7 @@ declare namespace adone { * Represents an event emitter that watches for a file growing, * emits "line" event for each new line in a file */ - class TailWatcher extends event.EventEmitter { + class TailWatcher extends event.Emitter { constructor(filename: string, options?: I.TailWatcher.ConstructorOptions); /** diff --git a/types/adone/glosses/is.d.ts b/types/adone/glosses/is.d.ts index 335439a0bf..20d898ca7b 100644 --- a/types/adone/glosses/is.d.ts +++ b/types/adone/glosses/is.d.ts @@ -6,13 +6,13 @@ declare namespace adone { /** * Checks whether the given object is `null` */ - function _null(obj: any): boolean; + function _null(obj: any): obj is null; export { _null as null }; /** * Checks whether the given object is `undefined` */ - export function undefined(obj: any): boolean; + export function undefined(obj: any): obj is undefined; /** * Checks whether the given object is nither `undefined` nor `null` @@ -22,52 +22,54 @@ declare namespace adone { /** * Checks whether the given object is either `undefined` or `null` */ - export function nil(obj: any): boolean; + export function nil(obj: any): obj is undefined | null; /** * Checks whether the given object is a number */ - export function number(obj: any): boolean; + export function number(obj: any): obj is number; /** * Checks whether the given object is a finite number or a string represents a finite number */ - export function numeral(obj: any): boolean; + export function numeral(obj: number): obj is number; + export function numeral(obj: string): obj is string; + export function numeral(obj: any): obj is number | string; /** * Checks whether the given object is either +Infinity or -Inginity */ - export function infinite(obj: any): boolean; + export function infinite(obj: any): obj is number; /** * Checks whether the given object is an odd number */ - export function odd(obj: any): boolean; + export function odd(obj: any): obj is number; /** * Checks whether the given object is an even number */ - export function even(obj: any): boolean; + export function even(obj: any): obj is number; /** * Checks whether the given object is a float */ - export function float(obj: any): boolean; + export function float(obj: any): obj is number; /** * Checks whether the given object is -0 */ - export function negativeZero(obj: any): boolean; + export function negativeZero(obj: any): obj is number; /** * Checks whether the given object is a string */ - export function string(obj: any): boolean; + export function string(obj: any): obj is string; /** - * Checks whether the given object is an empty string + * Checks whether the given object is an empty string, i.e. a string with only whitespace characters */ - export function emptyString(obj: any): boolean; + export function emptyString(obj: any): obj is string; /** * Checks whether the first string is a substring of the second string from the given offset @@ -87,7 +89,7 @@ declare namespace adone { /** * Checks whether the given object is a boolean */ - export function boolean(obj: any): boolean; + export function boolean(obj: any): obj is boolean; /** * Checks whether the given object is a string with ".json" extension or an object @@ -97,12 +99,12 @@ declare namespace adone { /** * Checks whether the given object is not a primitive, i.e. neither `undefined` nor `null` nor number nor string nor boolean nor symbol) */ - export function object(obj: any): boolean; + export function object(obj: any): obj is object; /** * Checks whether the given object is a plain object, i.e. created by Object */ - export function plainObject(obj: any): boolean; + export function plainObject(obj: any): obj is object; /** * Checks whether the given object is an adone namespace @@ -118,7 +120,7 @@ declare namespace adone { /** * Checks whether the given object is empty, i.e. it is an object(not a primitive), and Object.keys returns an empty array */ - export function emptyObject(obj: any): boolean; + export function emptyObject(obj: any): obj is object; /** * Checks whether the given object has the given owned property @@ -138,7 +140,7 @@ declare namespace adone { /** * Checks whether the given object is like an array, i.e. it is not a primitive, not a function and has length */ - export function arrayLikeObject(obj: any): boolean; + export function arrayLikeObject(obj: any): obj is ArrayLike; /** * Checks whether the given array has the given value @@ -215,7 +217,7 @@ declare namespace adone { /** * Checks whether the given string is a glob */ - export function glob(str: string): boolean; + export function glob(str: any): str is string; /** * Checks whether the given path is not a dot-file path (.secret) @@ -225,18 +227,18 @@ declare namespace adone { /** * Checks whether the given object is a function */ - function _function(obj: any): boolean; + function _function(obj: any): obj is (...args: any[]) => any; export { _function as function }; /** * Checks whether the given object is an async function */ - export function asyncFunction(obj: any): boolean; + export function asyncFunction(obj: any): obj is (...args: any[]) => Promise; /** * Checks whether the given object is a promise */ - export function promise(obj: any): boolean; + export function promise(obj: any): obj is PromiseLike; /** * Checks whether the given string is a valid date-string @@ -246,7 +248,7 @@ declare namespace adone { /** * Checks whether the given object is a buffer */ - export function buffer(obj: any): boolean; + export function buffer(obj: any): obj is Buffer; /** * Checks whether the given object is a callback function, i.e. it has a common function name @@ -256,7 +258,7 @@ declare namespace adone { /** * Checks whether the given object is a generator function */ - export function generator(obj: any): boolean; + export function generator(obj: any): obj is GeneratorFunction; /** * Checks whether the given object is NaN @@ -266,27 +268,27 @@ declare namespace adone { /** * Checks whether the given object is a finite number */ - export function finite(obj: any): boolean; + export function finite(obj: any): obj is number; /** * Checks whether the given object is an integer */ - export function integer(obj: any): boolean; + export function integer(obj: any): obj is number; /** * Checks whether the given object is a safe integer */ - export function safeInteger(obj: any): boolean; + export function safeInteger(obj: any): obj is number; /** * Checks whether the given object is an array */ - export function array(obj: any): boolean; + export function array(obj: any): obj is any[]; /** * Checks whether the given object is a Uint8 array */ - export function uint8Array(obj: any): boolean; + export function uint8Array(obj: any): obj is Uint8Array; /** * Checks whether the given object is an adone configuration @@ -296,34 +298,34 @@ declare namespace adone { /** * Checks whether the given object is an instance of adone.math.Long */ - export function long(obj: any): boolean; + export function long(obj: any): obj is adone.math.Long; /** * Checks whether the given object is an instance of adone.math.BigNumber */ - export function bigNumber(obj: any): boolean; + export function bigNumber(obj: any): obj is adone.math.BigNumber; /** * Checks whether the given object is an instance of adone.collection.ByteArray */ - export function byteArray(obj: any): boolean; + export function byteArray(obj: any): obj is adone.collection.ByteArray; /** * Checks whether the given object is an instance of adone.datetime */ - export function datetime(obj: any): boolean; + export function datetime(obj: any): obj is adone.I.datetime.Datetime; export function transform(obj: any): boolean; /** * Checks whether the given object is an adone subsystem */ - export function subsystem(obj: any): boolean; + export function subsystem(obj: any): obj is adone.application.Subsystem; /** * Checks whether the given object is an adone application */ - export function application(obj: any): boolean; + export function application(obj: any): obj is adone.application.Application; /** * Checks whether the given object is an adone logger @@ -333,22 +335,22 @@ declare namespace adone { /** * Checks whether the given object is a core stream */ - export function coreStream(obj: any): boolean; + export function coreStream(obj: any): obj is adone.stream.core.Stream; /** * Checks whether the given object is a fast local map stream */ - export function fastLocalMapStream(obj: any): boolean; + export function fastLocalMapStream(obj: any): obj is adone.fast.I.LocalMapStream; /** * Checks whether the given object is a fast local stream */ - export function fastLocalStream(obj: any): boolean; + export function fastLocalStream(obj: any): obj is adone.fast.I.LocalStream; /** * Checks whether the given object is a fast stream */ - export function fastStream(obj: any): boolean; + export function fastStream(obj: any): obj is adone.fast.I.Stream; /** * Checks whether the given object is a genesis netron @@ -428,7 +430,7 @@ declare namespace adone { /** * Checks whether the given object is iterable, has defined Symbol.iterator property */ - export function iterable(obj: any): boolean; + export function iterable(obj: any): obj is Iterable; /** * true if the OS is Windows @@ -498,17 +500,17 @@ declare namespace adone { /** * Checks whether the given object is an array buffer */ - export function arrayBuffer(obj: any): boolean; + export function arrayBuffer(obj: any): obj is ArrayBuffer; /** * Checks whether the given object is an array buffer view */ - export function arrayBufferView(obj: any): boolean; + export function arrayBufferView(obj: any): obj is ArrayBufferView; /** * Checks whether the given object is a date */ - export function date(obj: any): boolean; + export function date(obj: any): obj is Date; /** * Checks whether the given object is an error, instance of Error @@ -518,27 +520,22 @@ declare namespace adone { /** * Checks whether the given object is a map */ - export function map(obj: any): boolean; + export function map(obj: any): obj is Map; /** * Checks whether the given object is a regexp */ - export function regexp(obj: any): boolean; + export function regexp(obj: any): obj is RegExp; /** * Checks whether the given object is a set */ - export function set(obj: any): boolean; + export function set(obj: any): obj is Set; /** * Checks whether the given object is a symbol */ - export function symbol(obj: any): boolean; - - /** - * Checks whether the given buffer a valid UTF-8 encoded text - */ - export function validUTF8(obj: Buffer): boolean; + export function symbol(obj: any): obj is symbol; /** * Checks whether the given object is a vault valuable @@ -549,5 +546,135 @@ declare namespace adone { * Checks whether the given object is an adone task */ export function task(obj: any): boolean; + + namespace I { + interface FQDNOptions { + /** + * Whether to require top-level domain, default `true` + */ + requireTld?: boolean; + + /** + * Whether to allow underscores("_"), default `false` + */ + allowUnderscores?: boolean; + + /** + * Whether to allow trailing dot, default `false` + */ + allowTrailingDot?: boolean; + } + } + + /** + * Checks whether the given object(string) is a fully qualified domain name (e.g. domain.com). + */ + export function fqdn(obj: any, options?: I.FQDNOptions): obj is string; + + /** + * Checks whether the given object(string) is a url + */ + export function url(obj: any, options?: I.FQDNOptions & { + /** + * List of valid protocols. + * Used when requireValidProtocol is `true`. + * Default ["http", "https", "ftp"] + */ + protocols?: string[], + + /** + * Whether to require protocol, default `true` + */ + requireProtocol?: boolean, + + /** + * Whether to require host, default `true` + */ + requireHost?: boolean, + + /** + * Whether to require valid protocol defined in `protocols` options, default `true` + */ + requireValidProtocol?: boolean, + + /** + * Whether to allow urls like "//example.com", default `false` + */ + allowProtocolRelativeUrls?: boolean + }): obj is string; + + /** + * Checks whether the given object(string) is a valid email address + */ + export function email(obj: any, options?: { + /** + * Whether to allow email addresses with display names ("Name "") + */ + allowDisplayName?: boolean, + + /** + * Whether to require display name + */ + requireDisplayName?: boolean, + + /** + * Whether to allow UTF8 characters in the local part + */ + allowUtf8LocalPart?: boolean, + + /** + * Whether to require top-level domain, default `true` + */ + requireTld?: boolean + }): obj is string; + + /** + * Checks whether the given object is a valid IPv4 address + */ + export function ip(obj: any, version: 4): boolean; + + /** + * Checks whether the given object is a valid IPv6 address + */ + export function ip(obj: any, version: 6): boolean; + + /** + * Checks whether the given object in a valid IPv4 or IPv6 address + */ + export function ip(obj: any): boolean; + + /** + * Checks whether the given object is a valid UUIDv1 identifier + */ + export function uuid(obj: any, version: 1): obj is string; + + /** + * Checks whether the given object is a valid UUIDv2 identifier + */ + export function uuid(obj: any, version: 2): obj is string; + + /** + * Checks whether the given object is a valid UUIDv3 identifier + */ + export function uuid(obj: any, version: 3): obj is string; + + /** + * Checks whether the given object is a valid UUIDv4 identifier + */ + export function uuid(obj: any, version: 4): obj is string; + + /** + * Checks whether the given object is a valid UUIDv5 identifier + */ + export function uuid(obj: any, version: 5): obj is string; + + /** + * Checks whether the given object is a valid UUID identifier (v1, v2, v3, v4 or v5) + */ + export function uuid(obj: any, version?: "all"): obj is string; + + export function emitter(obj: any): obj is event.Emitter; + + export function asyncEmitter(obj: any): obj is event.AsyncEmitter; } } diff --git a/types/adone/glosses/meta.d.ts b/types/adone/glosses/meta.d.ts new file mode 100644 index 0000000000..bc96c1e148 --- /dev/null +++ b/types/adone/glosses/meta.d.ts @@ -0,0 +1,13 @@ +declare namespace adone { + namespace meta { + namespace I { + type PossibleTypes = "object" | "class" | "null" | "global" | "Array" | "RegExp" | "Date" + | "Promise" | "Set" | "Map" | "WeakSet" | "DataView" | "Map Iterator" | "Set Iterator" + | "Array Iterator" | "String Iterator" | "Object" | "function" | "boolean" | "number" + | "undefined" | "string" | "symbol"; + } + + function typeOf(obj: any): I.PossibleTypes; + function typeOf(obj: any): string; + } +} diff --git a/types/adone/glosses/net/http/client.d.ts b/types/adone/glosses/net/http/client.d.ts new file mode 100644 index 0000000000..33bccc95ac --- /dev/null +++ b/types/adone/glosses/net/http/client.d.ts @@ -0,0 +1,275 @@ +declare namespace adone.net.http { + namespace client { + namespace I { + interface RequestHeaders { + "Accept"?: string; + "Accept-Charset"?: string; + "Accept-Encoding"?: string; + "Accept-Language"?: string; + "Accept-Datetime"?: string; + "Access-Control-Request-Method"?: string; + "Access-Control-Request-Headers"?: string; + "Authorization"?: string; + "Cache-Control"?: string; + "Connection"?: string; + "Cookie"?: string; + "Content-Length"?: string; + "Content-MD5"?: string; + "Content-Type"?: string; + "Date"?: string; + "Expect"?: string; + "Forwarded"?: string; + "From"?: string; + "Host"?: string; + "If-Match"?: string; + "If-Modified-Since"?: string; + "If-None-Match"?: string; + "If-Range"?: string; + "If-Unmodified-Since"?: string; + "Max-Forwards"?: string; + "Origin"?: string; + "Pragma"?: string; + "Proxy-Authorization"?: string; + "Range"?: string; + "Referer"?: string; + "TE"?: string; + "User-Agent"?: string; + "Upgrade"?: string; + "Via"?: string; + "Warning"?: string; + "X-Requested-With"?: string; + "DNT"?: string; + "X-Forwarded-For"?: string; + "X-Forwarded-Host"?: string; + "X-Forwarded-Proto"?: string; + "Front-End-Https"?: string; + "X-Http-Method-Override"?: string; + "X-ATT-DeviceId"?: string; + "X-Wap-Profile"?: string; + "Proxy-Connection"?: string; + "X-UIDH"?: string; + "X-Csrf-Token"?: string; + "X-Request-ID"?: string; + "X-Correlation-ID"?: string; + + [name: string]: string | undefined; + } + + interface ResponseHeaders { + "accept-patch": string | undefined; + "accept-ranges": string | undefined; + "access-control-allow-credentials": string | undefined; + "access-control-allow-headers": string | undefined; + "access-control-allow-methods": string | undefined; + "access-control-allow-origin": string | undefined; + "access-control-expose-headers": string | undefined; + "access-control-max-age": string | undefined; + "age": string | undefined; + "allow": string | undefined; + "alt-svc": string | undefined; + "cache-control": string | undefined; + "connection": string| undefined; + "content-disposition": string | undefined; + "content-encoding": string| undefined; + "content-language": string | undefined; + "content-length": string| undefined; + "content-location": string| undefined; + "content-md5": string| undefined; + "content-range": string| undefined; + "content-security-policy": string | undefined; + "content-type": string| undefined; + "date": string| undefined; + "etag": string| undefined; + "expires": string| undefined; + "keep-alive": string | undefined; + "last-modified": string | undefined; + "link": string| undefined; + "location": string| undefined; + "p3p": string| undefined; + "pragma": string| undefined; + "proxy-authenticate": string | undefined; + "public-key-pins": string| undefined; + "referer-policy": string | undefined; + "refresh": string | undefined; + "retry-after": string | undefined; + "server": string | undefined; + "set-cookie": string | undefined; + "status": string | undefined; + "strict-transport-security": string| undefined; + "timing-allow-origin": string | undefined; + "tk": string| undefined; + "transfer-encoding": string | undefined; + "upgrade-insecure-requests": string | undefined; + "upgrade": string| undefined; + "vary": string | undefined; + "via": string| undefined; + "warning": string| undefined; + "www-authenticate": string | undefined; + "x-content-duration": string | undefined; + "x-content-security-policy": string | undefined; + "x-content-type-options": string | undefined; + "x-correlation-id": string | undefined; + "x-frame-options": string| undefined; + "x-powered-by": string | undefined; + "x-request-id": string | undefined; + "x-ua-compatible": string | undefined; + "x-webkit-csp": string | undefined; + "x-xss-protection": string | undefined; + + [header: string]: string | undefined; + } + + interface Response { + status: number; + statusText: string; + headers: ResponseHeaders; + data: T; + } + + type Transformer = (data: Data, headers: object, config: I.Options) => Data; + + interface FormValueOptions { + header?: string | { [key: string]: string }; + knownLength?: number; + filename?: string; + filepath?: string; + contentType?: string; + } + + type FormValue = string | Buffer | nodestd.stream.Readable | { + value: string | Buffer | nodestd.stream.Readable; + options: FormValueOptions + }; + + interface UploadProgressEvent { + lengthComputable: boolean; + loaded: number; + total: number; + } + + interface ProxyObject { + protocol?: string; + host?: string; + port?: number; + auth?: { + username?: string; + password?: string; + }; + } + + interface Config { + adapter(config: I.Config): Promise>; + transformRequest: Transformer[]; + transformResponse: Transformer[]; + timeout: number; + xsrfCookieName: string; + xsrfHeaderName: string; + maxContentLength: number; + validateStatus: (status: number) => boolean; + responseType: "buffer" | "string" | "stream" | "json"; + responseEncoding: adone.util.iconv.I.SupportedEncoding; + method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS"; + headers: RequestHeaders; + data: Data; + formData: { + [formKey: string]: FormValue | FormValue[]; + }; + auth: { + username?: string; + password?: string; + }; + httpsAgent: object; + httpAgent: object; + params: object; + rejectUnauthorized: boolean; + proxy: string | ProxyObject | false; + transport: object; + maxRedirects: number; + cancelToken: CancelToken; + onUploadProgress(event: UploadProgressEvent): void; + baseURL: string; + paramsSerializer(params: object): string; + } + + type Options = Partial; + + type Data = string | Buffer | ArrayBuffer | nodestd.stream.Readable | ArrayBufferView | object | undefined; + + interface Request extends Client { + (config: I.Options, ...args: any[]): Promise; + } + } + + class Client { + constructor(options?: I.Options); + + request(config: I.Options & { responseType: "json" }, ...args: any[]): Promise>; + request(config: I.Options & { responseType: "string" }, ...args: any[]): Promise>; + request(config: I.Options & { responseType: "buffer" }, ...args: any[]): Promise>; + request(config: I.Options & { responseType: "stream" }, ...args: any[]): Promise>; + request(config: I.Options, ...args: any[]): Promise>; + + get(url: string, options: I.Options & { responseType: "string" }): Promise>; + get(url: string, options: I.Options & { responseType: "buffer" }): Promise>; + get(url: string, options: I.Options & { responseType: "stream" }): Promise>; + get(url: string, options?: I.Options): Promise>; + + post(url: string, data: I.Data, options: I.Options & { responseType: "string" }): Promise>; + post(url: string, data: I.Data, options: I.Options & { responseType: "buffer" }): Promise>; + post(url: string, data: I.Data, options: I.Options & { responseType: "stream" }): Promise>; + post(url: string, data?: I.Data, options?: I.Options): Promise>; + + put(url: string, data: I.Data, options: I.Options & { responseType: "string" }): Promise>; + put(url: string, data: I.Data, options: I.Options & { responseType: "buffer" }): Promise>; + put(url: string, data: I.Data, options: I.Options & { responseType: "stream" }): Promise>; + put(url: string, data?: I.Data, options?: I.Options): Promise>; + + patch(url: string, data: I.Data, options: I.Options & { responseType: "string" }): Promise>; + patch(url: string, data: I.Data, options: I.Options & { responseType: "buffer" }): Promise>; + patch(url: string, data: I.Data, options: I.Options & { responseType: "stream" }): Promise>; + patch(url: string, data?: I.Data, options?: I.Options): Promise>; + + delete(url: string, options: I.Options & { responseType: "string" }): Promise>; + delete(url: string, options: I.Options & { responseType: "buffer" }): Promise>; + delete(url: string, options: I.Options & { responseType: "stream" }): Promise>; + delete(url: string, options?: I.Options): Promise>; + + options(url: string, options: I.Options & { responseType: "string" }): Promise>; + options(url: string, options: I.Options & { responseType: "buffer" }): Promise>; + options(url: string, options: I.Options & { responseType: "stream" }): Promise>; + options(url: string, options?: I.Options): Promise>; + } + + class Cancel { + message: string; + + constructor(message: string); + } + + namespace I { + type Canceller = (message?: string) => void; + + interface CancelTokenSource { + token: CancelToken; + cancel: Canceller; + } + } + + class CancelToken { + promise: Promise; + reason?: Cancel; + + constructor(executor: I.Canceller); + + throwIfRequested(): void; + + static source(): I.CancelTokenSource; + } + + const request: I.Request; + + function create(options?: I.Options): I.Request; + + function isCancel(obj: any): obj is Cancel; + } +} diff --git a/types/adone/glosses/net/http/index.d.ts b/types/adone/glosses/net/http/index.d.ts new file mode 100644 index 0000000000..a4fbe478d8 --- /dev/null +++ b/types/adone/glosses/net/http/index.d.ts @@ -0,0 +1,7 @@ +/// + +declare namespace adone.net { + namespace http { + // + } +} diff --git a/types/adone/glosses/net/index.d.ts b/types/adone/glosses/net/index.d.ts new file mode 100644 index 0000000000..5e773e4601 --- /dev/null +++ b/types/adone/glosses/net/index.d.ts @@ -0,0 +1,7 @@ +/// + +declare namespace adone { + namespace net { + // + } +} diff --git a/types/adone/glosses/pretty/index.d.ts b/types/adone/glosses/pretty/index.d.ts new file mode 100644 index 0000000000..ca2bc125f6 --- /dev/null +++ b/types/adone/glosses/pretty/index.d.ts @@ -0,0 +1,10 @@ +/// +/// +/// +/// + +declare namespace adone { + namespace pretty { + // + } +} diff --git a/types/adone/glosses/pretty/json.d.ts b/types/adone/glosses/pretty/json.d.ts new file mode 100644 index 0000000000..0c86d4fa49 --- /dev/null +++ b/types/adone/glosses/pretty/json.d.ts @@ -0,0 +1,16 @@ +declare namespace adone.pretty { + namespace I { + interface JSONOptions { + emptyArrayMsg?: string; + keysColor?: string; + dashColor?: string; + numberColor?: string; + stringColor?: string; + defaultIndentation?: number; + noColor?: boolean; + noAlign?: boolean; + } + } + + function json(data: any, options?: I.JSONOptions, indentation?: number): string; +} diff --git a/types/adone/glosses/pretty/size.d.ts b/types/adone/glosses/pretty/size.d.ts new file mode 100644 index 0000000000..2ff1c1c4b5 --- /dev/null +++ b/types/adone/glosses/pretty/size.d.ts @@ -0,0 +1,3 @@ +declare namespace adone.pretty { + function size(num: number, space?: string): string; +} diff --git a/types/adone/glosses/pretty/table.d.ts b/types/adone/glosses/pretty/table.d.ts new file mode 100644 index 0000000000..b71ce18d2c --- /dev/null +++ b/types/adone/glosses/pretty/table.d.ts @@ -0,0 +1,38 @@ +declare namespace adone.pretty { + namespace I { + interface TableColumn { + id: string; + header?: string; + align?: "right" | "center" | "left"; + width?: string | number; + maxWidth?: number | string; + wordwrap?: "soft" | "hard" | adone.text.I.WordWrapOptions; + handle?: (item: object) => string; + format?: string | ((val: any, item: object) => string); + style?: string | ((val: any, str: string) => string); + } + + type TableModel = TableColumn[]; + + interface TableStyle { + "padding-left"?: number; + "padding-right"?: number; + head?: string[]; + broder?: string[]; + compact?: boolean; + } + + interface TableOptions { + model: TableModel; + noHeader?: boolean; + borderless?: boolean; + style?: TableStyle; + width?: number | string; + countAnsiEscapeCodes?: boolean; + } + + type TableData = Array<{ [id: string]: any }>; + } + + function table(data: I.TableData, options: I.TableOptions): string; +} diff --git a/types/adone/glosses/pretty/time.d.ts b/types/adone/glosses/pretty/time.d.ts new file mode 100644 index 0000000000..3732c16640 --- /dev/null +++ b/types/adone/glosses/pretty/time.d.ts @@ -0,0 +1,11 @@ +declare namespace adone.pretty { + namespace I { + interface TimeOptions { + msDecimalDigits?: number; + secDecimalDigits?: number; + verbose?: boolean; + compact?: boolean; + } + } + function time(ms: number, options?: I.TimeOptions): string; +} diff --git a/types/adone/glosses/promise.d.ts b/types/adone/glosses/promise.d.ts index cdfe0ec2f5..cc0eac9c73 100644 --- a/types/adone/glosses/promise.d.ts +++ b/types/adone/glosses/promise.d.ts @@ -125,5 +125,36 @@ declare namespace adone { */ function _finally(promise: Promise, onFinally?: (...args: any[]) => void): Promise; export { _finally as finally }; + + namespace I { + type ResolvableProps = object & {[K in keyof T]: PromiseLike | T[K]}; + } + + /** + * Returns a promise that is fulfilled when all the object's values are fulfilled + */ + export function props(obj: I.ResolvableProps): Promise; + + namespace I { + interface _RetryOptions { + max: number; + + timeout: number; + + match: (string | RegExp | Error) | Array; + + backOffBase: number; + + backOffExponent: number; + + report: (message: string, options: _RetryOptions, err: any) => void; + + name: string; + } + + type RetryOptions = Partial<_RetryOptions>; + } + + export function retry(fn: (info: { current: number }) => PromiseLike | T, options?: number | I.RetryOptions): Promise; } } diff --git a/types/adone/glosses/regex.d.ts b/types/adone/glosses/regex.d.ts new file mode 100644 index 0000000000..e5c3be642a --- /dev/null +++ b/types/adone/glosses/regex.d.ts @@ -0,0 +1,25 @@ +declare namespace adone { + namespace regex { + function filename(): RegExp; + + function ip4(): RegExp; + + function ip6(): RegExp; + + function protocol(): RegExp; + + function idn(): RegExp; + + function punycode(): RegExp; + + function uri(): RegExp; + + function uuid4(): RegExp; + + function uuid5(): RegExp; + + function ansi(): RegExp; + + function shebang(): RegExp; + } +} diff --git a/types/adone/glosses/semver.d.ts b/types/adone/glosses/semver.d.ts new file mode 100644 index 0000000000..6c78695600 --- /dev/null +++ b/types/adone/glosses/semver.d.ts @@ -0,0 +1,237 @@ +declare namespace adone { + namespace semver { + const SEMVER_SPEC_VERSION: "2.0.0"; + + namespace I { + type ReleaseType = "major" + | "premajor" + | "minor" + | "preminor" + | "patch" + | "prepatch" + | "prerelease"; + + type Operator = '===' + | "!==" + | "" + | "=" + | "==" + | "!=" + | ">" + | ">=" + | "<" + | "<="; + } + + /** + * Returns the parsed version as a SemVer object, or null if it's not valid. + */ + function parse(v: string | SemVer, loose?: boolean): SemVer | null; + + /** + * Returns the parsed version, or null if it's not valid. + */ + function valid(v: string | SemVer, loose?: boolean): string | null; + + /** + * Returns cleaned (removed leading/trailing whitespace, remove '=v' prefix) and parsed version, or null if version is invalid. + */ + function clean(version: string, loose?: boolean): string | null; + + /** + * Returns the version incremented by the release type (major, minor, patch, or prerelease), or null if it's not valid. + */ + function inc(v: string | SemVer, release: I.ReleaseType, loose?: boolean, identifier?: string): string | null; + + /** + * Returns the major version number. + */ + function major(v: string | SemVer, loose?: boolean): number; + + /** + * Returns the minor version number. + */ + function minor(v: string | SemVer, loose?: boolean): number; + + /** + * Returns the patch version number. + */ + function patch(v: string | SemVer, loose?: boolean): number; + + /** + * Returns an array of prerelease components, or null if none exist. + */ + function prerelease(v: string | SemVer, loose?: boolean): string[] | null; + + // Comparison + + /** + * v1 > v2 + */ + function gt(v1: string | SemVer, v2: string | SemVer, loose?: boolean): boolean; + + /** + * v1 >= v2 + */ + function gte(v1: string | SemVer, v2: string | SemVer, loose?: boolean): boolean; + + /** + * v1 < v2 + */ + function lt(v1: string | SemVer, v2: string | SemVer, loose?: boolean): boolean; + + /** + * v1 <= v2 + */ + function lte(v1: string | SemVer, v2: string | SemVer, loose?: boolean): boolean; + + /** + * v1 == v2 This is true if they're logically equivalent, even if they're not the exact same string. You already know how to compare strings. + */ + function eq(v1: string | SemVer, v2: string | SemVer, loose?: boolean): boolean; + + /** + * v1 != v2 The opposite of eq. + */ + function neq(v1: string | SemVer, v2: string | SemVer, loose?: boolean): boolean; + + /** + * Pass in a comparison string, and it'll call the corresponding semver comparison function. + * "===" and "!==" do simple string comparison, but are included for completeness. + * Throws if an invalid comparison string is provided. + */ + function cmp(v1: string | SemVer, operator: I.Operator, v2: string | SemVer, loose?: boolean): boolean; + + /** + * Returns 0 if v1 == v2, or 1 if v1 is greater, or -1 if v2 is greater. Sorts in ascending order if passed to Array.sort(). + */ + function compare(v1: string | SemVer, v2: string | SemVer, loose?: boolean): 1 | 0 | -1; + + /** + * The reverse of compare. Sorts an array of versions in descending order when passed to Array.sort(). + */ + function rcompare(v1: string | SemVer, v2: string | SemVer, loose?: boolean): 1 | 0 | -1; + + /** + * Compares two identifiers, must be numeric strings or truthy/falsy values. Sorts in ascending order if passed to Array.sort(). + */ + function compareIdentifiers(a: string | null, b: string | null): 1 | 0 | -1; + + /** + * The reverse of compareIdentifiers. Sorts in descending order when passed to Array.sort(). + */ + function rcompareIdentifiers(a: string | null, b: string | null): 1 | 0 | -1; + + /** + * Sorts an array of semver entries in ascending order. + */ + function sort(list: Array, loose?: boolean): Array; + + /** + * Sorts an array of semver entries in descending order. + */ + function rsort(list: Array, loose?: boolean): Array; + + /** + * Returns difference between two versions by the release type (major, premajor, minor, preminor, patch, prepatch, or prerelease), or null if the versions are the same. + */ + function diff(v1: string, v2: string, loose?: boolean): I.ReleaseType | null; + + // Ranges + + /** + * Returns the valid range or null if it's not valid + */ + function validRange(range: string | Range, loose?: boolean): string; + + /** + * Returns true if the version satisfies the range. + */ + function satisfies(version: string | SemVer, range: string | Range, loose?: boolean): boolean; + + /** + * Returns the highest version in the list that satisfies the range, or null if none of them do. + */ + function maxSatisfying(versions: Array, range: string | Range, loose?: boolean): string; + + /** + * Returns the lowest version in the list that satisfies the range, or null if none of them do. + */ + function minSatisfying(versions: Array, range: string, loose?: boolean): string; + + /** + * Returns true if version is greater than all the versions possible in the range. + */ + function gtr(version: string | SemVer, range: string | Range, loose?: boolean): boolean; + + /** + * Returns true if version is less than all the versions possible in the range. + */ + function ltr(version: string | SemVer, range: string | Range, loose?: boolean): boolean; + + /** + * Returns true if the version is outside the bounds of the range in either the high or low direction. + * The hilo argument must be either the string '>' or '<'. (This is the function called by gtr and ltr.) + */ + function outside(version: string | SemVer, range: string | Range, hilo: '>' | '<', loose?: boolean): boolean; + + /** + * Returns true if any of the ranges comparators intersect + */ + function intersects(range1: string | Range, range2: string | Range, loose?: boolean): boolean; + + // Coercion + + /** + * Coerces a string to semver if possible + */ + function coerce(version: string | SemVer): SemVer | null; + + class SemVer { + constructor(version: string | SemVer, loose?: boolean); + + raw: string; + loose: boolean; + format(): string; + inspect(): string; + + major: number; + minor: number; + patch: number; + version: string; + build: string[]; + prerelease: string[]; + + compare(other: string | SemVer): 1 | 0 | -1; + compareMain(other: string | SemVer): 1 | 0 | -1; + comparePre(other: string | SemVer): 1 | 0 | -1; + inc(release: I.ReleaseType, identifier?: string): SemVer; + } + + class Comparator { + constructor(comp: string | Comparator, loose?: boolean); + + semver: SemVer; + operator: string; + value: boolean; + parse(comp: string): void; + test(version: string | SemVer): boolean; + intersects(comp: Comparator, loose?: boolean): boolean; + } + + class Range { + constructor(range: string | Range, loose?: boolean); + + range: string; + raw: string; + loose: boolean; + format(): string; + inspect(): string; + + set: Comparator[][]; + parseRange(range: string): Comparator[]; + test(version: string | SemVer): boolean; + intersects(range: Range, loose?: boolean): boolean; + } + } +} diff --git a/types/adone/glosses/shani.d.ts b/types/adone/glosses/shani.d.ts index 0b79633f78..5bc2d0153f 100644 --- a/types/adone/glosses/shani.d.ts +++ b/types/adone/glosses/shani.d.ts @@ -94,6 +94,11 @@ declare namespace adone { * Mark this block as exclusive */ skip: DescribeFunction; + + /** + * Mark this block as todo + */ + todo: DescribeFunction; } interface TestOptions { @@ -146,6 +151,11 @@ declare namespace adone { * Mark this test as exclusive */ skip: TestFunction; + + /** + * Mark this test as todo + */ + todo: TestFunction; } interface HookRuntimeContext { @@ -172,7 +182,7 @@ declare namespace adone { | "end before each hook" | "end after each hook" | "end before test hook" | "end after test hook"; - interface Emitter extends event.EventEmitter { + interface Emitter extends event.Emitter { on(event: "enter block", listener: (event: { block: Block }) => void): this; on(event: "exit block", listener: (event: { block: Block }) => void): this; on(event: "start test", listener: (event: { block: Block, test: Test }) => void): this; @@ -267,6 +277,11 @@ declare namespace adone { */ only(): this; + /** + * Marks this test as todo + */ + todo(): this; + /** * Returns the timeout of the test */ @@ -355,6 +370,11 @@ declare namespace adone { */ only(): this; + /** + * Marks this block as todo + */ + todo(): this; + /** * Returns the timeout of the block */ @@ -1423,7 +1443,7 @@ declare namespace adone { /** * Requires the value to be of the given type */ - typeOf(type: adone.util.I.PossibleTypes): Matcher; + typeOf(type: adone.meta.I.PossibleTypes): Matcher; typeOf(type: string): Matcher; /** diff --git a/types/adone/glosses/std.d.ts b/types/adone/glosses/std.d.ts index ec4bc4c37a..376b814d3e 100644 --- a/types/adone/glosses/std.d.ts +++ b/types/adone/glosses/std.d.ts @@ -1,34 +1,37 @@ -import * as assert from "assert"; -import * as fs from "fs"; -import * as path from "path"; -import * as util from "util"; -import * as events from "events"; -import * as stream from "stream"; -import * as url from "url"; -import * as net from "net"; -import * as http from "http"; -import * as https from "https"; -import * as child_process from "child_process"; -import * as os from "os"; -import * as cluster from "cluster"; -import * as repl from "repl"; -import * as punycode from "punycode"; -import * as readline from "readline"; -import * as string_decoder from "string_decoder"; -import * as querystring from "querystring"; -import * as crypto from "crypto"; -import * as vm from "vm"; -import * as v8 from "v8"; -import * as domain from "domain"; -import * as tty from "tty"; -import * as buffer from "buffer"; -import * as constants from "constants"; -import * as zlib from "zlib"; -import * as tls from "tls"; -import * as console from "console"; -import * as dns from "dns"; -import * as timers from "timers"; -import * as dgram from "dgram"; +import assert = require("assert"); +import fs = require("fs"); +import path = require("path"); +import util = require("util"); +import events = require("events"); +import stream = require("stream"); +import url = require("url"); +import net = require("net"); +import http = require("http"); +import http2 = require("http2"); +import https = require("https"); +import child_process = require("child_process"); +import os = require("os"); +import cluster = require("cluster"); +import repl = require("repl"); +import punycode = require("punycode"); +import readline = require("readline"); +import string_decoder = require("string_decoder"); +import querystring = require("querystring"); +import crypto = require("crypto"); +import vm = require("vm"); +import v8 = require("v8"); +import domain = require("domain"); +import module = require("module"); +import tty = require("tty"); +import buffer = require("buffer"); +import constants = require("constants"); +import zlib = require("zlib"); +import tls = require("tls"); +import console = require("console"); +import dns = require("dns"); +import timers = require("timers"); +import dgram = require("dgram"); +import perf_hooks = require("perf_hooks"); export { assert, @@ -40,6 +43,7 @@ export { url, net, http, + http2, https, child_process, os, @@ -53,6 +57,7 @@ export { vm, v8, domain, + module, tty, buffer, constants, @@ -62,6 +67,7 @@ export { dns, timers, dgram, + perf_hooks }; export as namespace nodestd; diff --git a/types/adone/glosses/streams.d.ts b/types/adone/glosses/streams.d.ts index 012a6aadc3..e4d07065b6 100644 --- a/types/adone/glosses/streams.d.ts +++ b/types/adone/glosses/streams.d.ts @@ -1,223 +1,225 @@ declare namespace adone { namespace stream { - namespace I.CoreStream { - interface ConstructorOptions { - /** - * Whether the initial stream is asynchronous - */ - async?: boolean; + namespace core { + namespace I { + interface ConstructorOptions { + /** + * Whether the initial stream is asynchronous + */ + async?: boolean; - /** - * Whether the initial stream is synchronous - */ - sync?: boolean; + /** + * Whether the initial stream is synchronous + */ + sync?: boolean; - /** - * The initial transform (passthrough is default) - */ - transform?: TransformFunction; + /** + * The initial transform (passthrough is default) + */ + transform?: TransformFunction; - /** - * The initial flush function - */ - flush?: FlushFunction; + /** + * The initial flush function + */ + flush?: FlushFunction; + } + + type Source = S[] | Stream; + + interface TransformContext { + /** + * Pushes the given value into the stream + */ + push(value: T): boolean; + } + + type TransformFunction = (this: TransformContext, value: S) => void; + type FlushFunction = (this: TransformContext) => void; } - type Source = S[] | CoreStream; + /** + * Represents a chain of transform streams + */ + class Stream implements PromiseLike { + constructor(source?: I.Source, options?: I.ConstructorOptions); + + /** + * Writes the given value into the stream + */ + write(value: S): boolean; - interface TransformContext { /** * Pushes the given value into the stream */ push(value: T): boolean; + + /** + * Ends the stream + */ + end(): this; + + /** + * Destroys the stream + */ + destroy(): this; + + /** + * Pauses the stream + */ + pause(): this; + + /** + * Resumes the stream + */ + resume(): this; + + /** + * Whether the stream is paused + */ + isPaused(): boolean; + + /** + * Whether the stream is ended + */ + isEnded(): boolean; + + /** + * Pipes this stream to another + */ + pipe(stream: T, options?: { end?: boolean }): T; + + /** + * Adds a new synchronous transform stream into the chain + */ + throughSync(transform: I.TransformFunction, flush?: I.FlushFunction): Stream; + + /** + * Adds a new asynchronous transform stream into the chain + */ + throughAsync(transform: I.TransformFunction, flush?: I.FlushFunction): Stream; + + /** + * Adds a new transform stream into the chain + */ + through(transform: I.TransformFunction, flush?: I.FlushFunction): Stream; + + /** + * Adds a new map transform into the chain. + * + * Note: synchronous functions create a synchronous transform. + * If your function returns a promise use an asynchronous function if you don't want to pass a promise through the stream + */ + map(callback: (value: T) => R | Promise): Stream; + + /** + * Adds a new conditional map transform into the chain + */ + mapIf(condition: (value: T) => boolean | Promise, callback: (value: T) => R): Stream; + + /** + * Adds a new filter transform into the chain + */ + filter(callback: (value: T) => boolean | Promise): this; + + /** + * Adds a new transform that calls the given callback for each value from the stream. + * + * This method resumes the stream. + */ + forEach(callback: (value: T) => void, options?: { + /** + * Whethe to wait for asynchronous functions (await) + */ + wait?: boolean, + + /** + * Passthrough the read values, by default it eats everything + */ + passthrough?: boolean + }): this; + + /** + * Adds a new transform that calls the given callback when the underlying stream ends. + * + * This method resumes the stream. + */ + done(callback: () => void, options?: { + /** + * Passthrough the read values, by default it eats everything + */ + passthrough?: boolean + }): this; + + /** + * Adds a new transform that gather all the read values into an array and calls the given callback + * when the underlying stream ends. + * + * This method resumes the stream. + */ + toArray(callback: (result: T[]) => void, options?: { + /** + * Passthrough the read values, by default it eats everything + */ + passthrough?: boolean + }): this; + + /** + * Adds a new transform that filters the values by their uniqueness + * + * @param prop callback that calculates value's hash which is used in uniqueness checks + */ + unique(prop?: (value: T) => any): this; + + /** + * Adds a new transform that filters the values using the given given function with ability to restore the filtered values + */ + stash(name: string, filter: (value: T) => boolean): this; + stash(filter: (value: T) => boolean): this; + + /** + * Adds a new transform that restores the previous stashed values + */ + unstash(name?: string): Stream; // ?? + + /** + * Flattens all the read array values + */ + flatten(): Stream; // ?? + + /** + * Merges the given stream into a core stream + */ + static merge(streams: Array | nodestd.stream.Transform | nodestd.stream.Readable | nodestd.stream.Duplex>, options?: { + /** + * Whether to end the stream when all the given streams end + */ + end?: boolean, + + /** + * Options for the initial core stream + */ + sourceOptions?: I.ConstructorOptions + }): Stream; + + /** + * Creates a promise that will be fulfilled with an array of all the emitted values or the first occurred error. + * + * This method resumes the stream. + */ + then(onResolve?: (value: T[]) => T1 | PromiseLike, onReject?: (reason: any) => T2 | PromiseLike): Promise; + + /** + * Creates a promise that will be fulfilled with an array of all the emitted values or the first occurred error. + * + * This method resumes the stream. + */ + catch(onReject?: (reason: any) => T1 | PromiseLike): Promise; } - type TransformFunction = (this: TransformContext, value: S) => void; - type FlushFunction = (this: TransformContext) => void; + /** + * Creates a CoreStream instance + */ + function create(source?: I.Source, options?: I.ConstructorOptions): Stream; } - - /** - * Represents a chain of transform streams - */ - class CoreStream implements PromiseLike { - constructor(source?: I.CoreStream.Source, options?: I.CoreStream.ConstructorOptions); - - /** - * Writes the given value into the stream - */ - write(value: S): boolean; - - /** - * Pushes the given value into the stream - */ - push(value: T): boolean; - - /** - * Ends the stream - */ - end(): this; - - /** - * Destroys the stream - */ - destroy(): this; - - /** - * Pauses the stream - */ - pause(): this; - - /** - * Resumes the stream - */ - resume(): this; - - /** - * Whether the stream is paused - */ - isPaused(): boolean; - - /** - * Whether the stream is ended - */ - isEnded(): boolean; - - /** - * Pipes this stream to another - */ - pipe(stream: T, options?: { end?: boolean }): T; - - /** - * Adds a new synchronous transform stream into the chain - */ - throughSync(transform: I.CoreStream.TransformFunction, flush?: I.CoreStream.FlushFunction): CoreStream; - - /** - * Adds a new asynchronous transform stream into the chain - */ - throughAsync(transform: I.CoreStream.TransformFunction, flush?: I.CoreStream.FlushFunction): CoreStream; - - /** - * Adds a new transform stream into the chain - */ - through(transform: I.CoreStream.TransformFunction, flush?: I.CoreStream.FlushFunction): CoreStream; - - /** - * Adds a new map transform into the chain. - * - * Note: synchronous functions create a synchronous transform. - * If your function returns a promise use an asynchronous function if you don't want to pass a promise through the stream - */ - map(callback: (value: T) => R | Promise): CoreStream; - - /** - * Adds a new conditional map transform into the chain - */ - mapIf(condition: (value: T) => boolean | Promise, callback: (value: T) => R): CoreStream; - - /** - * Adds a new filter transform into the chain - */ - filter(callback: (value: T) => boolean | Promise): this; - - /** - * Adds a new transform that calls the given callback for each value from the stream. - * - * This method resumes the stream. - */ - forEach(callback: (value: T) => void, options?: { - /** - * Whethe to wait for asynchronous functions (await) - */ - wait?: boolean, - - /** - * Passthrough the read values, by default it eats everything - */ - passthrough?: boolean - }): this; - - /** - * Adds a new transform that calls the given callback when the underlying stream ends. - * - * This method resumes the stream. - */ - done(callback: () => void, options?: { - /** - * Passthrough the read values, by default it eats everything - */ - passthrough?: boolean - }): this; - - /** - * Adds a new transform that gather all the read values into an array and calls the given callback - * when the underlying stream ends. - * - * This method resumes the stream. - */ - toArray(callback: (result: T[]) => void, options?: { - /** - * Passthrough the read values, by default it eats everything - */ - passthrough?: boolean - }): this; - - /** - * Adds a new transform that filters the values by their uniqueness - * - * @param prop callback that calculates value's hash which is used in uniqueness checks - */ - unique(prop?: (value: T) => any): this; - - /** - * Adds a new transform that filters the values using the given given function with ability to restore the filtered values - */ - stash(name: string, filter: (value: T) => boolean): this; - stash(filter: (value: T) => boolean): this; - - /** - * Adds a new transform that restores the previous stashed values - */ - unstash(name?: string): CoreStream; // ?? - - /** - * Flattens all the read array values - */ - flatten(): CoreStream; // ?? - - /** - * Merges the given stream into a core stream - */ - static merge(streams: Array | nodestd.stream.Transform | nodestd.stream.Readable | nodestd.stream.Duplex>, options?: { - /** - * Whether to end the stream when all the given streams end - */ - end?: boolean, - - /** - * Options for the initial core stream - */ - sourceOptions?: I.CoreStream.ConstructorOptions - }): CoreStream; - - /** - * Creates a promise that will be fulfilled with an array of all the emitted values or the first occurred error. - * - * This method resumes the stream. - */ - then(onResolve?: (value: T[]) => T1 | PromiseLike, onReject?: (reason: any) => T2 | PromiseLike): Promise; - - /** - * Creates a promise that will be fulfilled with an array of all the emitted values or the first occurred error. - * - * This method resumes the stream. - */ - catch(onReject?: (reason: any) => T1 | PromiseLike): Promise; - } - - /** - * Creates a CoreStream instance - */ - function core(source?: I.CoreStream.Source, options?: I.CoreStream.ConstructorOptions): CoreStream; } } diff --git a/types/adone/glosses/system/env.d.ts b/types/adone/glosses/system/env.d.ts new file mode 100644 index 0000000000..3ad18ab041 --- /dev/null +++ b/types/adone/glosses/system/env.d.ts @@ -0,0 +1,19 @@ +declare namespace adone.system { + namespace env { + function user(): string; + + function prompt(): string; + + function hostname(): string; + + function tmpdir(): string; + + function home(): string; + + function path(): string; + + function editor(): string; + + function shell(): string; + } +} diff --git a/types/adone/glosses/system/index.d.ts b/types/adone/glosses/system/index.d.ts new file mode 100644 index 0000000000..7a3ceced9d --- /dev/null +++ b/types/adone/glosses/system/index.d.ts @@ -0,0 +1,9 @@ +/// +/// +/// + +declare namespace adone { + namespace system { + // + } +} diff --git a/types/adone/glosses/system/process.d.ts b/types/adone/glosses/system/process.d.ts new file mode 100644 index 0000000000..51d0c45ddc --- /dev/null +++ b/types/adone/glosses/system/process.d.ts @@ -0,0 +1,241 @@ +declare namespace adone.system.process { + function errname(code: number): string; + + function errnameFallback(uv: object, code: number): string; + + function stdio(opts: object): any[]; + + namespace I { + type StdIOOption = "pipe" | "ipc" | "ignore" | nodestd.stream.Stream | number | null | undefined; + + interface ExecCommonOptions { + /** + * Current working directory of the child process. + * @default `process.cwd()` + */ + cwd?: string; + + /** + * Environment key-value pairs. + * Extends automatically from `process.env`. + * Set `extendEnv` to `false` if you don"t want this. + * @default `process.env` + */ + env?: NodeJS.ProcessEnv; + + /** + * Set to `false` if you don't want to extend the environment variables when providing the `env` property. + * @default `true` + */ + extendEnv?: boolean; + + /** + * Explicitly set the value of `argv[0]` sent to the child process. + * This will be set to `command` or `file` if not specified. + */ + argv0?: string; + + /** + * The `stdio` option is used to configure the pipes that are established between the parent and child process. + * By default, the child's stdin, stdout, and stderr are redirected to corresponding `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr` streams on the `ChildProcess` object. + * @default `'pipe'` + * + * @see https://nodejs.org/api/child_process.html#child_process_options_stdio + */ + stdio?: "pipe" | "ignore" | "inherit" | StdIOOption[]; + + /** + * Prepare child to run independently of its parent process. + * Specific behavior depends on the platform. + * @see https://nodejs.org/api/child_process.html#child_process_options_detached + */ + detached?: boolean; + + /** + * Sets the user identity of the process. + */ + uid?: number; + + /** + * Sets the group identity of the process. + */ + gid?: number; + + /** + * If `true`, runs `command` inside of a shell. + * Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. + * A different shell can be specified as a string. + * The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows. + * @default `false` + */ + shell?: boolean | string; + + /** + * If `true`, no quoting or escaping of arguments is done on Windows. + * Ignored on other platforms. + * This is set to `true` automatically when `shell` is specified. + * @default `false` + */ + windowsVerbatimArguments?: boolean; + + /** + * Strip EOF (last newline) from the output. + * @default `true` + * @see https://github.com/sindresorhus/strip-eof + */ + stripEof?: boolean; + + /** + * Prefer locally installed binaries when looking for a binary to execute. + * If you `$ npm install foo`, you can then `execa('foo')`. + * @default `true` + */ + preferLocal?: boolean; + + /** + * Preferred path to find locally installed binaries in (use with `preferLocal`). + * @default `process.cwd()` + */ + localDir?: string; + + /** + * Setting this to `false` resolves the promise with the error instead of rejecting it. + * @default `true` + */ + reject?: boolean; + + /** + * Keep track of the spawned process and `kill` it when the parent process exits. + * @default `true` + */ + cleanup?: boolean; + + /** + * Specify the character encoding used to decode the `stdout` and `stderr` output. + * @default `utf8` + */ + encoding?: string; + + /** + * If `timeout` is greater than `0`, the parent will send the signal identified by the `killSignal` property + * (the default is `SIGTERM`) if the child runs longer than `timeout` milliseconds. + * + * @default `0` + */ + timeout?: number; + + /** + * Largest amount of data in bytes allowed on `stdout` or `stderr`. + * @default `10000000` (10MB) + */ + maxBuffer?: number; + + /** + * Signal value to be used when the spawned process will be killed. + * @default `SIGTERM` + */ + killSignal?: string | number; + + /** + * Used to configure the stdin pipe that is established between the parent and child process. + * @default `'pipe'` + * @see https://nodejs.org/api/child_process.html#child_process_options_stdio + */ + stdin?: StdIOOption; + + /** + * Used to configure the stdout pipe that is established between the parent and child process. + * @default `'pipe'` + * @see https://nodejs.org/api/child_process.html#child_process_options_stdio + */ + stdout?: StdIOOption; + + /** + * Used to configure the stderr pipe that is established between the parent and child process. + * @default `'pipe'` + * @see https://nodejs.org/api/child_process.html#child_process_options_stdio + */ + stderr?: StdIOOption; + } + + interface ExecOptions extends ExecCommonOptions { + /** + * Write some input to the `stdin` of your binary. + */ + input?: string | Buffer | nodestd.stream.Stream; + } + + interface ExecSyncOptions extends ExecCommonOptions { + /** + * Write some input to the `stdin` of your binary. + * Streams are not allowed when using the synchronous methods. + */ + input?: string | Buffer; + } + + interface ExecReturns { + /** + * The command that was run. + */ + cmd: string; + + /** + * The exit code of the process that was run. + */ + code: number; + + /** + * Whether the process failed to run. + */ + failed: boolean; + + /** + * Whether the process was killed. + */ + killed: boolean; + + /** + * The signal that was used to terminate the process. + */ + signal: string | null; + + /** + * The output of the process on stderr. + */ + stderr: string; + + /** + * The output of the process on stdout. + */ + stdout: string; + + /** + * Whether the process timed out. + */ + timedOut: boolean; + } + + type ExecError = Error & ExecReturns; + + interface ExecChildPromise { + catch(onrejected?: ((reason: ExecError) => TResult | PromiseLike) | null): Promise; + } + + type ExecChildProcess = nodestd.child_process.ChildProcess & ExecChildPromise & Promise; + } + + function exec(cmd: string, args?: string[], opts?: I.ExecOptions): I.ExecChildProcess; + function exec(cmd: string, opts?: I.ExecOptions): I.ExecChildProcess; + + function execStdout(cmd: string, args?: string[], opts?: I.ExecOptions): Promise; + function execStdout(cmd: string, opts?: I.ExecOptions): Promise; + + function execStderr(cmd: string, args?: string[], opts?: I.ExecOptions): Promise; + function execStderr(cmd: string, opts?: I.ExecOptions): Promise; + + function shell(cmd: string, opts?: I.ExecOptions): I.ExecChildProcess; + + function execSync(cmd: string, args?: string[], opts?: I.ExecSyncOptions): I.ExecReturns; + + function shellSync(cmd: string, opts?: I.ExecSyncOptions): I.ExecReturns; +} diff --git a/types/adone/glosses/system/user.d.ts b/types/adone/glosses/system/user.d.ts new file mode 100644 index 0000000000..508f67e894 --- /dev/null +++ b/types/adone/glosses/system/user.d.ts @@ -0,0 +1,31 @@ +declare namespace adone.system { + /** + * Utils for uid/gid + */ + namespace user { + /** + * Returns uid by the given username + */ + function uid(username: string): { uid: number, gid: number }; + + /** + * Returns gid by the given groupname + */ + function gid(groupname: string): number; + + /** + * Returns gids the given user belongs + */ + function gids(username: string): number[]; + + /** + * Returns username by the given uid + */ + function username(uid: number): string; + + /** + * Returns groupname by the given gid + */ + function groupname(gid: number): string; + } +} diff --git a/types/adone/glosses/templating/dot.d.ts b/types/adone/glosses/templating/dot.d.ts new file mode 100644 index 0000000000..500efe8d35 --- /dev/null +++ b/types/adone/glosses/templating/dot.d.ts @@ -0,0 +1,41 @@ +declare namespace adone.templating { + namespace dot { + namespace I { + type RenderFunction = (...args: any[]) => string; + + interface TemplateSettings { + evaluate: RegExp; + interpolate: RegExp; + encode: RegExp; + use: RegExp; + useParams: RegExp; + define: RegExp; + defineParams: RegExp; + conditional: RegExp; + iterate: RegExp; + varname: string; + strip: boolean; + append: boolean; + selfcontained: boolean; + } + } + const version: string; + + let templateSettings: I.TemplateSettings; + + function template(tmpl: string, c?: I.TemplateSettings, def?: {}): I.RenderFunction; + + function compile(tmpl: string, def?: object): I.RenderFunction; + + namespace I { + interface ProcessOptions { + path?: string; + destination?: string; + global?: string; + templateSettings?: Partial; + } + } + + function process(options?: I.ProcessOptions): { [path: string]: I.RenderFunction }; + } +} diff --git a/types/adone/glosses/templating/index.d.ts b/types/adone/glosses/templating/index.d.ts new file mode 100644 index 0000000000..81f9964335 --- /dev/null +++ b/types/adone/glosses/templating/index.d.ts @@ -0,0 +1,8 @@ +/// +/// + +declare namespace adone { + namespace templating { + // + } +} diff --git a/types/adone/glosses/templating/nunjucks.d.ts b/types/adone/glosses/templating/nunjucks.d.ts new file mode 100644 index 0000000000..d0aed211cc --- /dev/null +++ b/types/adone/glosses/templating/nunjucks.d.ts @@ -0,0 +1,121 @@ +declare namespace adone.templating { + namespace nunjucks { + namespace I { + interface EnvironmentOptions { + dev?: boolean; + autoescape?: boolean; + throOnUndefined?: boolean; + trimBlocks?: boolean; + lstripBlocks?: boolean; + } + + interface FileSystemLoaderOptions { + watch?: boolean; + noCache?: boolean; + } + + type ConfigureOptions = EnvironmentOptions & FileSystemLoaderOptions & { + tags?: { + blockStart?: string, + blockEnd?: string, + variableStart?: string, + variableEnd?: string, + commentStart?: string, + commentEnd?: string + }; + }; + + interface PrecompileOptions { + name?: string; + asFunction?: boolean; + force?: boolean; + env?: Environment; + include?: string[]; + exclude?: string[]; + wrapper?(templates: { name: string, template: string }, opts: PrecompileOptions): string; + } + + interface Extension { + tags: string[]; + parse(parser: any, nodes: any, lexer: any): any; + } + + interface LoaderSource { + src: string; + path: string; + noCache: boolean; + } + + interface Loader { + async?: boolean; + getSource(name: string): LoaderSource; + extend?(extender: Loader): Loader; + } + } + + class Environment { + options: { + autoescape: boolean; + }; + + constructor(loader?: I.Loader | I.Loader[] | null, opts?: I.EnvironmentOptions); + render(name: string, context?: object): string; + render(name: string, context?: object, callback?: (err: any, res: string) => any): void; + + renderString(name: string, context?: object): string; + renderString(name: string, context?: object, callback?: (err: any, res: string) => any): void; + + addFilter(name: string, func: (...args: any[]) => any, async?: boolean): void; + getFilter(name: string): (...args: any[]) => any; + + addExtension(name: string, ext: I.Extension): void; + removeExtension(name: string): void; + getExtension(name: string): I.Extension; + hasExtension(name: string): boolean; + + addGlobal(name: string, value: any): this; + + getTemplate(name: string, eagerCompile?: boolean): Template; + getTemplate(name: string, eagerCompile?: boolean, callback?: (err: any, templ: Template) => Template): void; + + express(app: object): void; + } + + class Template { + constructor(src: string, env?: Environment, eagerCompile?: boolean); + render(context?: object): string; + render(context?: object, callback?: (err: any, res: string) => any): void; + } + + class Loader { + on(name: string, func: (...args: any[]) => any): void; + emit(name: string, ...args: any[]): void; + resolve(from: string, to: string): string; + isRelative(filename: string): boolean; + extend(toExtend: I.Loader): I.Loader; + } + + class FileSystemLoader extends Loader implements I.Loader { + constructor(searchPaths?: string | string[], opts?: I.FileSystemLoaderOptions); + + getSource(name: string): I.LoaderSource; + } + + class PrecompiledLoader extends Loader implements I.Loader { + getSource(name: string): I.LoaderSource; + } + + function renderSync(name: string, context?: object): string; + function render(name: string, context?: object): Promise; + + function renderString(src: string, context?: object): Promise; + function renderStringSync(src: string, context?: object): string; + + function compile(src: string, env?: Environment, path?: string, eagerCompile?: boolean): Template; + + function configure(options?: I.ConfigureOptions): Environment; + function configure(path: string | string[], options?: I.ConfigureOptions): Environment; + + function installJinjaCompat(): void; + } +} diff --git a/types/adone/glosses/text/index.d.ts b/types/adone/glosses/text/index.d.ts new file mode 100644 index 0000000000..57b0fb1867 --- /dev/null +++ b/types/adone/glosses/text/index.d.ts @@ -0,0 +1,76 @@ +/// +/// +/// + +declare namespace adone { + namespace text { + namespace escape { + function regExpPattern(str: string): string; + + function regExpReplacement(str: string): string; + + function format(str: string): string; + + function shellArg(str: string): string; + + function control(str: string): string; + + function htmlSpecialChars(str: string): string; + } + + namespace regexp { + function array2alternatives(array: string[]): string; + } + + function escapeStringRegexp(str: string): string; + + function toCamelCase(str: string): string; + + function camelCaseToDashed(str: string): string; + + const endLineRegExp: RegExp; + + function splitLines(str: string): string[]; + + function regExpIndexOf(str: string, regex: RegExp, index?: number): string; + + function stripAnsi(str: string): string; + + function hasAnsi(str: string): boolean; + + function random(len: number): string; + + function detectNewLine(str: string): "\r\n" | "\n"; + + namespace I { + interface WordWrapOptions { + join?: boolean; + mode?: "soft" | "hard"; + countAnsiEscapeCodes?: boolean; + } + } + + function wordwrap(str: string, stop: number, options: I.WordWrapOptions & { join: false}): string[]; + function wordwrap(str: string, stop: number, options?: I.WordWrapOptions): string; + + function stringDistance(strA: string, strB: string, memo?: number[][]): number; + + function stringDistanceCapped(strA: string, strB: string, cap: number): number; + + function capitalize(str: string): string; + + function capitalizeWords(str: string): string; + + function width(str: string): number; + + function indent(string: string, spaces: number): string; + + function stripEof(str: string): string; + + function stripLastCRLF(str: string): string; + + function stripBOM(str: string): string; + + function toUTF8Array(str: string): number[]; + } +} diff --git a/types/adone/glosses/text/spinners.d.ts b/types/adone/glosses/text/spinners.d.ts new file mode 100644 index 0000000000..962a6aebab --- /dev/null +++ b/types/adone/glosses/text/spinners.d.ts @@ -0,0 +1,468 @@ +declare namespace adone.text { + namespace spinner { + const dots: { + interval: 80, + frames: [ + "⠋", + "⠙", + "⠹", + "⠸", + "⠼", + "⠴", + "⠦", + "⠧", + "⠇", + "⠏" + ] + }; + const dots2: { + interval: 80, + frames: [ + "⣾", + "⣽", + "⣻", + "⢿", + "⡿", + "⣟", + "⣯", + "⣷" + ] + }; + const dots3: { + interval: 80, + frames: [ + "⠋", + "⠙", + "⠚", + "⠞", + "⠖", + "⠦", + "⠴", + "⠲", + "⠳", + "⠓" + ] + }; + const dots4: { + interval: 80, + frames: [ + "⠄", + "⠆", + "⠇", + "⠋", + "⠙", + "⠸", + "⠰", + "⠠", + "⠰", + "⠸", + "⠙", + "⠋", + "⠇", + "⠆" + ] + }; + const dots5: { + interval: 80, + frames: [ + "⠋", + "⠙", + "⠚", + "⠒", + "⠂", + "⠂", + "⠒", + "⠲", + "⠴", + "⠦", + "⠖", + "⠒", + "⠐", + "⠐", + "⠒", + "⠓", + "⠋" + ] + }; + const dots6: { + interval: 80, + frames: [ + "⠁", + "⠉", + "⠙", + "⠚", + "⠒", + "⠂", + "⠂", + "⠒", + "⠲", + "⠴", + "⠤", + "⠄", + "⠄", + "⠤", + "⠴", + "⠲", + "⠒", + "⠂", + "⠂", + "⠒", + "⠚", + "⠙", + "⠉", + "⠁" + ] + }; + const dots7: { + interval: 80, + frames: [ + "⠈", + "⠉", + "⠋", + "⠓", + "⠒", + "⠐", + "⠐", + "⠒", + "⠖", + "⠦", + "⠤", + "⠠", + "⠠", + "⠤", + "⠦", + "⠖", + "⠒", + "⠐", + "⠐", + "⠒", + "⠓", + "⠋", + "⠉", + "⠈" + ] + }; + const dots8: { + interval: 80, + frames: [ + "⠁", + "⠁", + "⠉", + "⠙", + "⠚", + "⠒", + "⠂", + "⠂", + "⠒", + "⠲", + "⠴", + "⠤", + "⠄", + "⠄", + "⠤", + "⠠", + "⠠", + "⠤", + "⠦", + "⠖", + "⠒", + "⠐", + "⠐", + "⠒", + "⠓", + "⠋", + "⠉", + "⠈", + "⠈" + ] + }; + const dots9: { + interval: 80, + frames: [ + "⢹", + "⢺", + "⢼", + "⣸", + "⣇", + "⡧", + "⡗", + "⡏" + ] + }; + const dots10: { + interval: 80, + frames: [ + "⢄", + "⢂", + "⢁", + "⡁", + "⡈", + "⡐", + "⡠" + ] + }; + const dots11: { + interval: 100, + frames: [ + "⠁", + "⠂", + "⠄", + "⡀", + "⢀", + "⠠", + "⠐", + "⠈" + ] + }; + const dots12: { + interval: 80, + frames: [ + "⢀⠀", + "⡀⠀", + "⠄⠀", + "⢂⠀", + "⡂⠀", + "⠅⠀", + "⢃⠀", + "⡃⠀", + "⠍⠀", + "⢋⠀", + "⡋⠀", + "⠍⠁", + "⢋⠁", + "⡋⠁", + "⠍⠉", + "⠋⠉", + "⠋⠉", + "⠉⠙", + "⠉⠙", + "⠉⠩", + "⠈⢙", + "⠈⡙", + "⢈⠩", + "⡀⢙", + "⠄⡙", + "⢂⠩", + "⡂⢘", + "⠅⡘", + "⢃⠨", + "⡃⢐", + "⠍⡐", + "⢋⠠", + "⡋⢀", + "⠍⡁", + "⢋⠁", + "⡋⠁", + "⠍⠉", + "⠋⠉", + "⠋⠉", + "⠉⠙", + "⠉⠙", + "⠉⠩", + "⠈⢙", + "⠈⡙", + "⠈⠩", + "⠀⢙", + "⠀⡙", + "⠀⠩", + "⠀⢘", + "⠀⡘", + "⠀⠨", + "⠀⢐", + "⠀⡐", + "⠀⠠", + "⠀⢀", + "⠀⡀" + ] + }; + const line: { + interval: 130, + frames: [ + "-", + "\\", + "|", + "/" + ] + }; + const pipe: { + interval: 100, + frames: [ + "┤", + "┘", + "┴", + "└", + "├", + "┌", + "┬", + "┐" + ] + }; + const simpleDots: { + interval: 200, + frames: [ + ". ", + ".. ", + "...", + " ..", + " .", + " " + ] + }; + const flip: { + interval: 70, + frames: [ + "_", + "_", + "_", + "-", + "`", + "`", + "'", + "´", + "-", + "_", + "_", + "_" + ] + }; + const growVertical: { + interval: 120, + frames: [ + "▁", + "▃", + "▄", + "▅", + "▆", + "▇", + "▆", + "▅", + "▄", + "▃" + ] + }; + const growHorizontal: { + interval: 120, + frames: [ + "▏", + "▎", + "▍", + "▌", + "▋", + "▊", + "▉", + "▊", + "▋", + "▌", + "▍", + "▎" + ] + }; + const boxBounce: { + interval: 120, + frames: [ + "▖", + "▘", + "▝", + "▗" + ] + }; + const boxBounce2: { + interval: 100, + frames: [ + "▌", + "▀", + "▐", + "▄" + ] + }; + const triangle: { + interval: 50, + frames: [ + "◢", + "◣", + "◤", + "◥" + ] + }; + const squareCorners: { + interval: 180, + frames: [ + "◰", + "◳", + "◲", + "◱" + ] + }; + const circleQuarters: { + interval: 120, + frames: [ + "◴", + "◷", + "◶", + "◵" + ] + }; + const circleHalves: { + interval: 80, + frames: [ + "◐", + "◓", + "◑", + "◒" + ] + }; + const arrow: { + interval: 80, + frames: [ + "⬆️ ", + "↗️ ", + "➡️ ", + "↘️ ", + "⬇️ ", + "↙️ ", + "⬅️ ", + "↖️ " + ] + }; + const arrow3: { + interval: 120, + frames: [ + "▹▹▹▹▹", + "▸▹▹▹▹", + "▹▸▹▹▹", + "▹▹▸▹▹", + "▹▹▹▸▹", + "▹▹▹▹▸" + ] + }; + const bouncingBar: { + interval: 80, + frames: [ + "[ ]", + "[ =]", + "[ ==]", + "[ ===]", + "[====]", + "[=== ]", + "[== ]", + "[= ]" + ] + }; + const clock: { + interval: 100, + frames: [ + "🕐 ", + "🕑 ", + "🕒 ", + "🕓 ", + "🕔 ", + "🕕 ", + "🕖 ", + "🕗 ", + "🕘 ", + "🕙 ", + "🕚 " + ] + }; + } +} diff --git a/types/adone/glosses/text/table.d.ts b/types/adone/glosses/text/table.d.ts new file mode 100644 index 0000000000..2bfaaa07fd --- /dev/null +++ b/types/adone/glosses/text/table.d.ts @@ -0,0 +1,73 @@ +declare namespace adone.text { + namespace table { + namespace I { + interface CharsOptions { + top: string; + "top-mid": string; + "top-left": string; + "top-right": string; + bottom: string; + "bottom-mid": string; + "bottom-left": string; + "bottom-right": string; + left: string; + "left-mid": string; + mid: string; + "mid-mid": string; + right: string; + "right-mid": string; + middle: string; + } + + interface StyleOptions { + "padding-left": number; + "padding-right": number; + head: string[]; + border: string[]; + compact: boolean; + } + + interface CommonOptions { + truncate: string; + colWidths: number[]; + rowHeights: number[]; + colAligns: Array<"left" | "center" | "right">; + rowAligns: Array<"top" | "center" | "bottom">; + head: string[]; + } + + interface Options extends CommonOptions { + style: StyleOptions; + chars: CharsOptions; + } + + interface ConstructorOptions extends Partial { + style?: Partial; + chars?: Partial; + } + } + + class Table extends Array { + constructor(options?: I.ConstructorOptions); + + toString(): string; + + readonly width: number; + + static readonly defaultOptions: I.Options; + } + + namespace I { + interface BorderlessConstructorOptions { + colWidths?: number[]; + head?: string[]; + colAligns?: Array<"left" | "center" | "right">; + style?: Partial; + } + } + + class BorderlessTable extends Table { + constructor(options?: I.BorderlessConstructorOptions); + } + } +} diff --git a/types/adone/glosses/text/unicode.d.ts b/types/adone/glosses/text/unicode.d.ts new file mode 100644 index 0000000000..98b449b9a3 --- /dev/null +++ b/types/adone/glosses/text/unicode.d.ts @@ -0,0 +1,137 @@ +declare namespace adone.text { + namespace unicode { + const symbol: { + tick: "✔", + cross: "✖", + star: "★", + square: "▇", + squareSmall: "◻", + squareSmallFilled: "◼", + play: "▶", + circle: "◯", + circleFilled: "◉", + circleDotted: "◌", + circleDouble: "◎", + circleCircle: "ⓞ", + circleCross: "ⓧ", + circlePipe: "Ⓘ", + circleQuestionMark: "?⃝", + bullet: "●", + dot: "․", + line: "─", + ellipsis: "…", + pointer: "❯", + pointerSmall: "›", + info: "ℹ", + warning: "⚠", + hamburger: "☰", + smiley: "㋡", + mustache: "෴", + heart: "♥", + arrowUp: "↑", + arrowDown: "↓", + arrowLeft: "←", + arrowRight: "→", + radioOn: "◉", + radioOff: "◯", + checkboxOn: "☒", + checkboxOff: "☐", + checkboxCircleOn: "ⓧ", + checkboxCircleOff: "Ⓘ", + questionMarkPrefix: "?" | "?⃝", + oneHalf: "½", + oneThird: "⅓", + oneQuarter: "¼", + oneFifth: "⅕", + oneSixth: "⅙", + oneSeventh: "⅐", + oneEighth: "⅛", + oneNinth: "⅑", + oneTenth: "⅒", + twoThirds: "⅔", + twoFifths: "⅖", + threeQuarters: "¾", + threeFifths: "⅗", + threeEighths: "⅜", + fourFifths: "⅘", + fiveSixths: "⅚", + fiveEighths: "⅝", + sevenEighths: "⅞", + minus: "−" + }; + + const symbolFallback: { + tick: "√", + cross: "×", + star: "*", + square: "█", + squareSmall: "[ ]", + squareSmallFilled: "[█]", + play: "►", + circle: "( )", + circleFilled: "(*)", + circleDotted: "( )", + circleDouble: "( )", + circleCircle: "(○)", + circleCross: "(×)", + circlePipe: "(│)", + circleQuestionMark: "(?)", + bullet: "*", + dot: ".", + line: "─", + ellipsis: "...", + pointer: ">", + pointerSmall: "»", + info: "i", + warning: "‼", + hamburger: "≡", + smiley: "☺", + mustache: "┌─┐", + heart: "♥", + arrowUp: "↑", + arrowDown: "↓", + arrowLeft: "←", + arrowRight: "→", + radioOn: "(*)", + radioOff: "( )", + checkboxOn: "[×]", + checkboxOff: "[ ]", + checkboxCircleOn: "(×)", + checkboxCircleOff: "( )", + questionMarkPrefix: "?", + oneHalf: "1/2", + oneThird: "1/3", + oneQuarter: "1/4", + oneFifth: "1/5", + oneSixth: "1/6", + oneSeventh: "1/7", + oneEighth: "1/8", + oneNinth: "1/9", + oneTenth: "1/10", + twoThirds: "2/3", + twoFifths: "2/5", + threeQuarters: "3/4", + threeFifths: "3/5", + threeEighths: "3/8", + fourFifths: "4/5", + fiveSixths: "5/6", + fiveEighths: "5/8", + sevenEighths: "7/8", + minus: "-" + }; + + function approx(str: string): string; + + function length(str: string): number; + + function toArray(str: string): string[]; + + function surrogatePair(char: string): number; + + function isFullWidthCodePoint(code: number): boolean; + + function isFullWidth(char: string): boolean; + + function toFullWidth(str: string): string; + } +} diff --git a/types/adone/glosses/utils.d.ts b/types/adone/glosses/utils.d.ts index 6a05273ffd..5d2eb5f198 100644 --- a/types/adone/glosses/utils.d.ts +++ b/types/adone/glosses/utils.d.ts @@ -16,10 +16,6 @@ declare namespace adone { function functionName(fn: (...args: any[]) => any): string; - function mapArguments(argmap: (...args: any[]) => any): (...args: any[]) => any; - function mapArguments(argmap: number): (...args: T[]) => T[]; - function mapArguments(...args: any[]): (x: T) => T; - namespace I { interface ParseMsResult { days: number; @@ -33,8 +29,6 @@ declare namespace adone { function pluralizeWord(str: string, plural?: string, count?: number): string; - function functionParams(func: (...args: any[]) => any): string[]; - function randomChoice(arrayLike: ArrayLike, from?: number, to?: number): T; function shuffleArray(array: T[]): T[]; @@ -70,19 +64,8 @@ declare namespace adone { function globParent(str: string): string; - namespace I { - interface ByResult { - (a: S, b: S): R; - compare(a: T, b: T): R; - by(a: S): T; - } - } - function by(by: (a: S) => T, compare?: (a: T, b: T) => R): I.ByResult; - function toFastProperties(object: object): object; - function stripBom(x: string): string; - namespace I { interface SortKeysOptions { deep?: boolean; @@ -103,27 +86,46 @@ declare namespace adone { function invertObject(source: object, options?: I.KeysOptions): object; - namespace I { - interface HumanizeTimeOptions { - msDecimalDigits?: number; - secDecimalDigits?: number; - verbose?: boolean; - compact?: boolean; - } - } - function humanizeTime(ms: number, options?: I.HumanizeTimeOptions): string; - function humanizeSize(num: number, space?: string): string; - function parseSize(str: string | number): number | null; namespace I { interface CloneOptions { + /** + * Clone recursively + * + * `true` by default + */ deep?: boolean; + + /** + * Clone non-plain object, they will be plain objects + * + * `false` by default + */ + nonPlainObjects?: boolean; + + /** + * Clone only enumerable properties + * + * `true` by default + */ + onlyEnumerable?: boolean; } } - function clone(object: object, options?: I.CloneOptions): object; - function toUTF8Array(str: string): number[]; + class Cloner { + /** + * Clones the given object + */ + clone(obj: any, options?: I.CloneOptions): any; + + /** + * Returns a clone function that is binded to this cloner + */ + binding(): (obj: any, options?: I.CloneOptions) => any; + } + + function clone(object: any, options?: I.CloneOptions): any; function asyncIter(array: T[], iter: (elem: T, index: number, cb: () => void) => any, cb: () => void): void; @@ -150,20 +152,31 @@ declare namespace adone { function assignDeep(target: T, ...sources: object[]): T; namespace I { - interface MatchOptions { + interface MatchPathOptions { index?: boolean; start?: number; end?: number; dot?: boolean; } } - function match(criteria: any, options?: I.MatchOptions): (value: any, options?: I.MatchOptions) => number | boolean; - function match(criteria: any, value: any, options?: I.MatchOptions): number | boolean; + function matchPath(criteria: any, options?: I.MatchPathOptions): (value: any, options?: I.MatchPathOptions) => number | boolean; + function matchPath(criteria: any, value: any, options?: I.MatchPathOptions): number | boolean; namespace I { + class Sorter { + edges: string[]; + + add(item: string, deps: string | string[]): void; + + sort(): string[]; + + clear(): void; + } + interface ToposortFunction { - (edges: Array<[T, T]>): T[]; - array(nodes: T[], edges: Array<[T, T]>): T[]; + (edges: Array<[string, string]>): string[]; + array(nodes: string[], edges: Array<[string, string]>): string[]; + Sorter: typeof Sorter; } } const toposort: I.ToposortFunction; @@ -188,16 +201,6 @@ declare namespace adone { } function jsesc(argument: any, options?: I.JSEscOptions): string; - namespace I { - type PossibleTypes = "object" | "class" | "null" | "global" | "Array" | "RegExp" | "Date" - | "Promise" | "Set" | "Map" | "WeakSet" | "DataView" | "Map Iterator" | "Set Iterator" - | "Array Iterator" | "String Iterator" | "Object" | "function" | "boolean" | "number" - | "undefined" | "string" | "symbol"; - } - - function typeOf(obj: any): I.PossibleTypes; - function typeOf(obj: any): string; - namespace memcpy { function utou(target: Buffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number; function atoa(target: ArrayBuffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number; @@ -217,12 +220,12 @@ declare namespace adone { function v1(options?: I.V1Options): string; function v1(options: I.V1Options, buf: any[], offset?: number): number[]; - function v4(options?: any): string; - function v4(options: any, buf: any[], offset?: number): number[]; - function v3(name: string | number[], namespace: string | number[]): string; function v3(name: string | number[], namespace: string | number[], buf: any[], offset?: number): number[]; + function v4(options?: any): string; + function v4(options: any, buf: any[], offset?: number): number[]; + function v5(name: string | number[], namespace: string | number[]): string; function v5(name: string | number[], namespace: string | number[], buf: any[], offset?: number): number[]; } @@ -237,50 +240,231 @@ declare namespace adone { } function delegate(object: object, property: string): I.Delegator; - namespace I { - interface GlobExpOptions { - nocomment?: boolean; - nonegate?: boolean; - nobrace?: boolean; - noglobstar?: boolean; - nocase?: boolean; - dot?: boolean; - noext?: boolean; - matchBase?: boolean; - flipNegate?: boolean; - } - } - - class GlobExp { - constructor(pattern: string, options?: I.GlobExpOptions); - - hasMagic(): boolean; - - static hasMagic(pattern: string, options?: I.GlobExpOptions): boolean; - - expandBraces(): string[]; - - static expandBraces(pattern: string, options?: I.GlobExpOptions): string[]; - - makeRe(): RegExp; - - static makeRe(pattern: string, options?: I.GlobExpOptions): RegExp; - - static test(p: string, pattern: string, options?: I.GlobExpOptions): boolean; - - test(p: string): boolean; - } - namespace iconv { - // TODO: need to normalize source code + namespace I { + namespace encoding { + type Native = "UTF-8" + | "UCS-2" + | "UTF-16LE" + | "ASCII" + | "Binary" + | "Base64" + | "Hex"; + + type Unicode = "UTF-16BE" | "UTF-16"; + + type Windows = "874" + | "1250" + | "1251" + | "1252" + | "1253" + | "1254" + | "1255" + | "1256" + | "1257" + | "1258" + | "CP874" + | "CP1251" + | "CP1252" + | "CP1253" + | "CP1254" + | "CP1255" + | "CP1256" + | "CP1257" + | "CP1258" + | "Win-1251" + | "Win-1252" + | "Win-1253" + | "Win-1254" + | "Win-1255" + | "Win-1256" + | "Win-1257" + | "Win-1258" + | "Windows-1251" + | "Windows-1252" + | "Windows-1253" + | "Windows-1254" + | "Windows-1255" + | "Windows-1256" + | "Windows-1257" + | "Windows-1258"; + + type ISO = "ISO-8829-1" + | "ISO-8859-2" + | "ISO-8859-3" + | "ISO-8859-4" + | "ISO-8859-5" + | "ISO-8859-6" + | "ISO-8859-7" + | "ISO-8859-8" + | "ISO-8859-9" + | "ISO-8859-10" + | "ISO-8859-11" + | "ISO-8859-12" + | "ISO-8859-13" + | "ISO-8859-14" + | "ISO-8859-15" + | "ISO-8859-16"; + + type IBM = "437" + | "737" + | "775" + | "808" + | "850" + | "852" + | "855" + | "856" + | "857" + | "858" + | "860" + | "861" + | "862" + | "863" + | "864" + | "865" + | "866" + | "869" + | "922" + | "1046" + | "1124" + | "1125" + | "1129" + | "1133" + | "1161" + | "1163" + | "CP437" + | "CP737" + | "CP775" + | "CP808" + | "CP850" + | "CP852" + | "CP855" + | "CP856" + | "CP857" + | "CP858" + | "CP860" + | "CP861" + | "CP862" + | "CP863" + | "CP864" + | "CP865" + | "CP866" + | "CP869" + | "CP922" + | "CP1046" + | "CP1124" + | "CP1125" + | "CP1129" + | "CP1133" + | "CP1161" + | "CP1163" + | "IBM437" + | "IBM737" + | "IBM775" + | "IBM808" + | "IBM850" + | "IBM852" + | "IBM855" + | "IBM856" + | "IBM857" + | "IBM858" + | "IBM860" + | "IBM861" + | "IBM862" + | "IBM863" + | "IBM864" + | "IBM865" + | "IBM866" + | "IBM869" + | "IBM922" + | "IBM1046" + | "IBM1124" + | "IBM1125" + | "IBM1129" + | "IBM1133" + | "IBM1161" + | "IBM1163"; + + type Mac = "MacCroatian" + | "MacCyrillic" + | "MacGreek" + | "MacIceland" + | "MacRoman" + | "MacThai" + | "MacTurkish" + | "MacUkraine" + | "MacCentEuro" + | "Macintosh"; + + type KOI8 = "KOI8-R" + | "KOI8-U" + | "KOI8-RU" + | "KOI8-T"; + + type Misc = "ArmSCII8" + | "RK1048" + | "TCVN" + | "GEORGIAN-ACADEMY" + | "GEORGIAN-PS" + | "PT154" + | "VISCII" + | "ISO-646-CN" + | "ISO-646-JP" + | "HP Roman-8" + | "TIS-620"; + + type Singlebyte = Windows + | ISO + | IBM + | Mac + | KOI8 + | Misc; + + type Japanese = "Shift_JIS" + | "Windows-31J" + | "windows-932" + | "EUC-JP"; + + type Chinese = "GB2312" + | "GBK" + | "GB18030" + | "Windows-936" + | "EUC-CN"; + + type Korean = "KS_C_5601" + | "Windows-949" + | "EUC-KR"; + + type TaiwanHongKong = "Big5" + | "Big5-HKSCS" + | "Windows-950"; + + type Multibyte = Japanese + | Chinese + | Korean + | TaiwanHongKong; + } + + type SupportedEncoding = encoding.Native + | encoding.Unicode + | encoding.Singlebyte + | encoding.Multibyte; + } + + const defaultCharUnicode: "�"; + + const defaultCharSingleByte: "?"; + + function encodingExists(encoding: string): boolean; + + function encode(buffer: string, encoding: I.SupportedEncoding, options?: object): Buffer; + + function decode(buffer: Buffer, encoding: I.SupportedEncoding, options?: object): string; } namespace sqlstring { function escapeId(val: string | string[], forbidQualified?: boolean): string; function dateToString(date: any, timeZone?: string): string; - function arrayToList(array: any[]): string; - function bufferToString(buffer: Buffer): string; - function objectToValues(object: object, timeZone?: string): string; function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string; function format(sql: string, values?: any, stringifyObjects?: boolean, timeZone?: string): string; } @@ -316,49 +500,95 @@ declare namespace adone { } const binarySearch: I.BinarySearchFunction; + /** + * buffer tools + */ namespace buffer { - function concat(list: Buffer[], totalLength: number): Buffer; - function mask(buffer: Buffer, mask: Buffer, output: Buffer, offset: number, length: number): void; - function unmask(buffer: Buffer, mask: Buffer): void; + /** + * Converts the given Buffer to ArrayBuffer + */ + function toArrayBuffer(buf: Buffer): ArrayBuffer; + + /** + * Returns a new buffer that represents a^b + * + * If the lengths are not equal, it assumes missing bytes as 0x00 + * + * @param length length of the result buffer. max(a.length, b.length) by default + */ + function xor(a: Buffer, b: Buffer, length?: number): Buffer; } function shebang(str: string): string | null; - class ReInterval { - constructor(callback: (...args: any[]) => void, interval: number, args?: any[]); - - reschedule(interval: number): void; - - clear(): void; - - destroy(): void; - } - - class RateLimiter { - constructor(tokensPerInterval?: number, interval?: number, fireImmediately?: boolean); - - removeTokens(count: number): Promise; - - tryRemoveTokens(count: number): boolean; - - getTokensRemaining(): number; - } - namespace I { - interface ThrottleOptions { - max?: number; - interval?: number; - ordered?: boolean; - waitForReturn?: boolean; + interface ReInterval { + reschedule(interval: number): void; + + clear(): void; + + destroy(): void; } } - function throttle(fn: () => R, options?: I.ThrottleOptions): () => Promise; - function throttle(fn: (a: T1) => R, options?: I.ThrottleOptions): (a: T1) => Promise; - function throttle(fn: (a: T1, b: T2) => R, options?: I.ThrottleOptions): (a: T1, b: T2) => Promise; - function throttle(fn: (a: T1, b: T2, c: T3) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3) => Promise; - function throttle(fn: (a: T1, b: T2, c: T3, d: T4) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4) => Promise; - function throttle(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; - function throttle(fn: (...args: any[]) => R, options?: I.ThrottleOptions): (...args: any[]) => Promise; + + function reinterval(callback: (...args: any[]) => void, interval: number, args?: any[]): I.ReInterval; + + namespace throttle { + namespace I { + interface Options { + concurrency?: number; + interval?: number; + ordered?: boolean; + waitForReturn?: boolean; + onDone?: () => void; + drop?: boolean; + dropLast?: boolean; + } + + interface CreateFunction { + (fn: () => Promise): Promise; + (fn: () => R): Promise; + + (fn: (a: T1) => Promise, a: T1): Promise; + (fn: (a: T1) => R, a: T1): Promise; + + (fn: (a: T1, b: T2) => Promise, a: T1, b: T2): Promise; + (fn: (a: T1, b: T2) => R, a: T1, b: T2): Promise; + + (fn: (a: T1, b: T2, c: T3) => Promise, a: T1, b: T2, c: T3): Promise; + (fn: (a: T1, b: T2, c: T3) => R, a: T1, b: T2, c: T3): Promise; + + (fn: (a: T1, b: T2, c: T3, d: T4) => Promise, a: T1, b: T2, c: T3, d: T4): Promise; + (fn: (a: T1, b: T2, c: T3, d: T4) => R, a: T1, b: T2, c: T3, d: T4): Promise; + + (fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise, a: T1, b: T2, c: T3, d: T4, e: T5): Promise; + (fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, a: T1, b: T2, c: T3, d: T4, e: T5): Promise; + + (fn: (...args: any[]) => Promise, ...args: any[]): Promise; + (fn: (...args: any[]) => R, ...args: any[]): Promise; + } + } + function create(options?: I.Options): I.CreateFunction; + function create(fn: () => R, options?: I.Options): () => Promise; + function create(fn: (a: T1) => R, options?: I.Options): (a: T1) => Promise; + function create(fn: (a: T1, b: T2) => R, options?: I.Options): (a: T1, b: T2) => Promise; + function create(fn: (a: T1, b: T2, c: T3) => R, options?: I.Options): (a: T1, b: T2, c: T3) => Promise; + function create(fn: (a: T1, b: T2, c: T3, d: T4) => R, options?: I.Options): (a: T1, b: T2, c: T3, d: T4) => Promise; + function create(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, options?: I.Options): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; + function create(fn: (...args: any[]) => R, options?: I.Options): (...args: any[]) => Promise; + + class RateLimiter { + constructor(tokensPerInterval?: number, interval?: number, fireImmediately?: boolean); + + removeTokens(count: number): Promise; + + tryRemoveTokens(count: number): boolean; + + getTokensRemaining(): number; + } + + const DROPPED: symbol; + } namespace I.fakeClock { interface Timer { @@ -475,36 +705,6 @@ declare namespace adone { function lowerBoundKey(range: I.Range): T | undefined; } - /** - * Utils for uid/gid - */ - namespace userid { - /** - * Returns uid by the given username - */ - function uid(username: string): { uid: number, gid: number }; - - /** - * Returns gid by the given groupname - */ - function gid(groupname: string): number; - - /** - * Returns username by the given uid - */ - function username(uid: number): string; - - /** - * Returns groupname by the given gid - */ - function groupname(gid: number): string; - - /** - * Returns gids the given user belongs - */ - function gids(username: string): number[]; - } - /** * Represents a log file rotator */ @@ -572,5 +772,598 @@ declare namespace adone { function debounce(fn: (a: T1, b: T2, c: T3, d: T4) => R, timeout: number, options?: I.DebounceOptions): (a: T1, b: T2, c: T3, d: T4) => R; function debounce(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, timeout: number, options?: I.DebounceOptions): (a: T1, b: T2, c: T3, d: T4, e: T5) => R; function debounce(fn: (...args: any[]) => R, timeout: number, options?: I.DebounceOptions): (...args: any[]) => R; + + /** + * Finds difference between the given arrays + */ + function arrayDiff(...arrays: T[][]): T[]; + + namespace I { + type FillRangeTransform = () => void; + + interface FillRangeOptions { + /** + * The increment to use for the range. Can be used with letters or numbers + */ + step?: number; + + /** + * By default, null is returned when an invalid range is passed. + * Enable this option to throw a RangeError on invalid ranges + * + * false by default + */ + strictRanges?: boolean; + + /** + * Cast all returned values to strings. + * + * By default, integers are returned as numbers. + */ + stringify?: boolean; + + /** + * Create a regex-compatible source string, instead of expanding values to an array. + * + * false by default + */ + toRegex?: boolean; + + /** + * Customize each value in the returned array (or string) + */ + transform?: FillRangeTransform; + } + } + + /** + * Expands numbers and letters + */ + function fillRange(from: number, to: number, options: I.FillRangeOptions & { toRegex: true }): string; + function fillRange(from: number, to: number, options: I.FillRangeOptions & { stringify: true }): string[]; + function fillRange(from: number, to: number, options?: I.FillRangeOptions): number[]; + + function fillRange(from: string, to: string, options: I.FillRangeOptions & { toRegex: true }): string; + function fillRange(from: string, to: string, options?: I.FillRangeOptions): string[]; + + function fillRange(from: string | number, to: string | number, options: I.FillRangeOptions & { toRegex: true }): string; + function fillRange(from: string | number, to: string | number, options?: I.FillRangeOptions): Array; + + namespace inflection { + function singularizeWord(str: string, singular?: string): string; + function pluralizeWord(str: string, plural?: string): string; + function underscore(str: string, allUpperCase?: boolean): string; + } + + function machineId(original?: boolean): Promise; + + namespace I { + interface MergeOptions { + plainObjects?: boolean; + allowPrototypes?: boolean; + } + } + + function merge(target: any, source: any, options?: I.MergeOptions): any; + + function omit(obj: any, props: ((v: string) => boolean) | string[] | string): object; + + function parseTime(val: number): number; + function parseTime(val: any): number | null; + + function pick(obj: any, props: Iterable): object; + + // pool: TODO + + namespace querystring { + function escape(str: string): string; + + const formats: { + RFC1738: "RFC1738" + RFC3986: "RFC3986", + default: string, + formatters: { + RFC1738(val: string): string, + RFC3986(val: string): string + } + }; + + namespace I { + interface ParseOptions { + ignoreQueryPrefix?: boolean; + delimiter?: string; + depth?: number; + arrayLimit?: number; + parseArrays?: boolean; + decoder?: (str: string, defaultDecoder: (str: string) => string) => string; + allowDots?: boolean; + plainObjects?: boolean; + allowPrototypes?: boolean; + parameterLimit?: number; + strictNullHandling?: boolean; + } + + interface StringifyOptions { + delimiter?: string; + strictNullHandling?: boolean; + skipNulls?: boolean; + encode?: boolean; + encoder?: (str: string) => any; + filter?: Array | ((prefix: string, value: any) => any); + arrayFormat?: "indices" | "brackets" | "repeat"; + indices?: boolean; + sort?: (a: any, b: any) => number; + serializeDate?: (d: Date) => string; + format?: "RFC1738" | "RFC3986"; + encodeValuesOnly?: boolean; + addQueryPrefix?: boolean; + allowDots?: boolean; + } + } + + function parse(str: string, options?: I.ParseOptions): any; + + function stringify(obj: any, options?: I.StringifyOptions): string; + + function unescape(str: string): string; + } + + namespace I { + interface RegexNotOptions { + contains?: boolean; + } + } + + function regexNot(pattern: string, options?: I.RegexNotOptions): RegExp; + + function repeat(item: T, n: number): T[]; + + // retry: TODO + + function signalNameToCode(signame: string): number; + + function splitBuffer(buf: string | Buffer, splitBuf: string | Buffer, includeDelim?: boolean): Buffer[]; + + namespace I { + type SplitStringSplitFunction = (token: { + val: string; + idx: number; + arr: string[]; + str: string; + }) => void; + + interface SplitStringOptions { + braces?: object | boolean; + keepEscaping?: boolean; + keepQuotes?: boolean; + keepDoubleQuotes?: boolean; + keepSingleQuotes?: boolean; + separator?: string; + split?: SplitStringSplitFunction; + } + } + + function splitString(str: string): string[]; + function splitString(str: string, options: I.SplitStringOptions): string[]; + function splitString(str: string, splitter: I.SplitStringSplitFunction): string[]; + function splitString(str: string, options: I.SplitStringOptions, splitter: I.SplitStringSplitFunction): string[]; + + // terraformer: TODO + + namespace I { + interface ToRegexOptions { + contains?: boolean; + negate?: boolean; + nocase?: boolean; + flags?: string; + cache?: boolean; + } + } + + function toRegex(patterns: string | string[], options?: I.ToRegexOptions): RegExp; + + namespace I { + interface ToRegexRangeOptions { + capture?: boolean; + shorthand?: boolean; + relaxZeros?: boolean; + } + } + + function toRegexRange(min: string | number, max: string | number, options?: I.ToRegexRangeOptions): RegExp; + + namespace xorDistance { + function compare(a: Buffer, b: Buffer): boolean; + + function create(a: Buffer, b: Buffer): Buffer; + + function gt(a: Buffer, b: Buffer): boolean; + + function lt(a: Buffer, b: Buffer): boolean; + + function eq(a: Buffer, b: Buffer): boolean; + } + + namespace I { + interface BracesOptions { + /** + * Generate an "expanded" brace pattern (this option is unncessary with the `.expand` method, which does the same thing). + * + * @default undefined + */ + expand?: boolean; + + /** + * Enabled by default. + * + * @default true + */ + optimize?: boolean; + + /** + * Duplicates are removed by default. To keep duplicates, pass `{nodupes: false}` on the options + * + * @default true + */ + nodupes?: boolean; + + /** + * When `braces.expand()` is used, or `options.expand` is true, brace patterns will automatically be [optimized](#optionsoptimize) + * when the difference between the range minimum and range maximum exceeds the `rangeLimit`. + * This is to prevent huge ranges from freezing your application. + * + * You can set this to any number, or change `options.rangeLimit` to `Inifinity` to disable this altogether. + * + * @default 250 + */ + rangeLimit?: number; + + /** + * Customize range expansion. + * + * @default undefined + */ + transform?: (str: string) => string; + + /** + * In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times. + * + * Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists) + * + * The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) + * are defined in the given pattern, and not to try to expand them as lists. + * + * @default undefined + */ + quantifiers?: boolean; + + /** + * Strip backslashes that were used for escaping from the result. + * + * @default undefined + */ + unescape?: boolean; + } + interface BracesFunction { + (pattern: string, options?: BracesOptions): string[]; + expand(pattern: string, options?: BracesOptions): string[]; + MAX_LENGTH: number; + clearCache(): void; + resizeCache(newSize: number): void; + getCache(): object; // TODO + makeRe(pattern: string, options?: BracesOptions): RegExp; + } + } + + const braces: I.BracesFunction; + + namespace I { + interface MatchOptions { + /** + * Allow glob patterns without slashes to match a file path based on its basename. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `matchBase`. + * + * @default false + */ + basename?: boolean; + + /** + * Enabled by default, this option enforces bash-like behavior with stars immediately following a bracket expression. + * Bash bracket expressions are similar to regex character classes, but unlike regex, a star following a bracket expression **does not repeat the bracketed characters**. + * Instead, the star is treated the same as an other star. + * + * @default true + */ + bash?: boolean; + + /** + * Disable regex and function memoization. + * + * @default undefined + */ + cache?: boolean; + + /** + * Match dotfiles. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `dot`. + * + * @default false + */ + dot?: boolean; + + /** + * Similar to the `--failglob` behavior in Bash, throws an error when no matches are found. + * + * @default undefined + */ + failglob?: boolean; + + /** + * String or array of glob patterns to match files to ignore. + * + * @default undefined + */ + ignore?: string | string[]; + + /** + * Alias for [options.basename](#options-basename). + */ + matchBase?: boolean; + + /** + * Disable expansion of brace patterns. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nobrace`. + * + * @default undefined + */ + nobrace?: boolean; + + /** + * Use a case-insensitive regex for matching files. Same behavior as [minimatch](https://github.com/isaacs/minimatch). + * + * @default undefined + */ + nocase?: boolean; + + /** + * Remove duplicate elements from the result array. + * + * @default undefined + */ + nodupes?: boolean; + + /** + * Disable extglob support, so that extglobs are regarded as literal characters. + * + * @default undefined + */ + noext?: boolean; + + /** + * Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. + * + * @default undefined + */ + nonegate?: boolean; + + /** + * Disable matching with globstars (`**`). + * + * @default undefined + */ + noglobstar?: boolean; + + /** + * Alias for [options.nullglob](#options-nullglob). + */ + nonull?: boolean; + + /** + * If `true`, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. + * Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nonull`. + * + * @default undefined + */ + nullglob?: boolean; + + /** + * Pass your own instance of [snapdragon](https://github.com/jonschlinkert/snapdragon), to customize parsers or compilers. + * + * @default undefined + */ + snapdragon?: object; + + /** + * Generate a source map by enabling the `sourcemap` option with the `.parse`, `.compile`, or `.create` methods. + * + * _(Note that sourcemaps are currently not enabled for brace patterns)_ + */ + sourcemap?: boolean; + + /** + * Remove backslashes from returned matches. + * + * @default undefined + */ + unescape?: boolean; + + /** + * Convert path separators on returned files to posix/unix-style forward slashes. + * + * @default true + */ + unixify?: boolean; + } + + interface MatchFunction { + /** + * The main function takes a list of strings and one or more glob patterns to use for matching. + * + * @param list A list of strings to match + * @param patterns One or more glob patterns to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns an array of matches + */ + (list: string[], patterns: string | string[], options?: MatchOptions): string[]; + + /** + * Similar to the main function, but `pattern` must be a string. + * + * @param list Array of strings to match + * @param pattern Glob pattern to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns an array of matches + */ + match(list: string[], pattern: string, options?: MatchOptions): string[]; + + /** + * Returns true if the specified `string` matches the given glob `pattern`. + * + * @param string String to match + * @param pattern Glob pattern to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns true if the string matches the glob pattern. + */ + isMatch(string: string, pattern: string, options?: MatchOptions): boolean; + + /** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * @param list The string or array of strings to test. Returns as soon as the first match is found. + * @param patterns One or more glob patterns to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns true if any patterns match `str` + */ + some(list: string | string[], patterns: string | string[], options?: MatchOptions): boolean; + + /** + * Returns true if every string in the given `list` matches any of the given glob `patterns`. + * + * @param list The string or array of strings to test. + * @param patterns One or more glob patterns to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns true if any patterns match `str` + */ + every(list: string | string[], patterns: string | string[], options?: MatchOptions): boolean; + + /** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * @param str The string to test. + * @param patterns One or more glob patterns to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns true if any patterns match `str` + */ + any(str: string | string[], patterns: string | string[], options?: MatchOptions): boolean; + + /** + * Returns true if **all** of the given `patterns` match the specified string. + * + * @param str The string to test. + * @param patterns One or more glob patterns to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns true if any patterns match `str` + */ + all(str: string | string[], patterns: string | string[], options?: MatchOptions): boolean; + + /** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * @param list Array of strings to match. + * @param patterns One or more glob pattern to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns an array of strings that **do not match** the given patterns. + */ + not(list: string[], patterns: string | string[], options?: MatchOptions): string[]; + + /** + * Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * @param str The string to match. + * @param patterns Glob pattern to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns true if the patter matches any part of `str`. + */ + contains(str: string, patterns: string | string[], options?: MatchOptions): boolean; + + /** + * Filter the keys of the given object with the given `glob` pattern and `options`. Does not attempt to match nested keys. + * If you need this feature, use [glob-object](https://github.com/jonschlinkert/glob-object) instead. + * + * @param object The object with keys to filter. + * @param patterns One or more glob patterns to use for matching. + * @param options See available options for changing how matches are performed + * @returns Returns an object with only keys that match the given patterns. + */ + matchKeys(object: T, patterns: string | string[], options?: MatchOptions): Partial; + + /** + * Returns a memoized matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns true if the string is a match. + * + * @param pattern Glob pattern + * @param options See available options for changing how matches are performed. + * @returns Returns a matcher function. + */ + matcher(pattern: string | string[], options?: MatchOptions): (str: string) => boolean; + + /** + * Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. + * + * @param pattern Glob pattern to use for matching. + * @param string String to match + * @param options See available options for changing how matches are performed + * @returns Returns an array of captures if the string matches the glob pattern, otherwise `null`. + */ + capture(pattern: string, string: string, options?: MatchOptions): string[] | null; + + /** + * Create a regular expression from the given glob `pattern`. + * + * @param pattern A glob pattern to convert to regex. + * @param options See available options for changing how matches are performed. + * @returns Returns a regex created from the given pattern. + */ + makeRe(pattern: string, options?: MatchOptions): RegExp; + + /** + * Expand the given brace `pattern`. + * + * @param pattern String with brace pattern to expand. + * @param options Any options to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. + */ + braces(pattern: string, options?: MatchOptions): string[]; + + /** + * Parses the given glob `pattern` and returns an array of abstract syntax trees (ASTs), with the compiled `output` and optional source `map` on each AST. + * + * @param pattern Glob pattern to parse and compile. + * @param options Any options to change how parsing and compiling is performed. + * @returns Returns an object with the parsed AST, compiled string and optional source map. + */ + create(pattern: string, options?: MatchOptions): object; + + /** + * Parse the given `str` with the given `options`. + * + * @returns Returns an AST + */ + parse(str: string, options?: MatchOptions): object; + + /** + * Compile the given `ast` or string with the given `options`. + * + * @returns Returns an object that has an `output` property with the compiled string. + */ + compile(ast: object | string, options?: MatchOptions): object; + + MAX_LENGTH: number; + + clearCache(): void; + + resizeCache(newSize: number): void; + + getCache(): object; // TODO + } + } + + const match: I.MatchFunction; } } diff --git a/types/adone/glosses/vault.d.ts b/types/adone/glosses/vault.d.ts new file mode 100644 index 0000000000..2fc39c0c3b --- /dev/null +++ b/types/adone/glosses/vault.d.ts @@ -0,0 +1,204 @@ +declare namespace adone { + namespace vault { + namespace I { + interface VaultConstructorOptions { + // TODO: leveldb options + location: string; + ValuableClass?: object; + } + + interface VaultClearOptions { + hosts?: boolean; + tags?: boolean; + } + + interface VaultToJSONOptions { + valuable?: ValuableToJSONOptions; + includeStats?: boolean; + } + + interface ValuableToJSONOptions { + includeId?: boolean; + includeEntryId?: boolean; + entriesAsArray?: boolean; + tags?: "normal" | "onlyName" | "onlyId" | "none"; + } + + interface VaultJSONStats { + location: string; + created: number; + updated: number; + } + } + + class Vault { + constructor(options: I.VaultConstructorOptions); + + open(): Promise; + + close(): Promise; + + location(): string; + + create(name: string, tags?: string[]): Promise; + + get(name: string): Promise; + + release(name: string): void; + + delete(name: string): Promise; + + clear(options?: I.VaultClearOptions): Promise; + + has(name: string): boolean; + + keys(): string[]; + + values(): Promise; + + entries(): Promise<{ [key: string]: any }>; + + toJSON(options: I.VaultToJSONOptions & { valuable: object, includeStats: true }): Promise<{ + valuables: object[], + stats: I.VaultJSONStats + }>; + toJSON(options: I.VaultToJSONOptions & { valuable: object }): Promise<{ + valuables: object[] + }>; + toJSON(options: I.VaultToJSONOptions & { includeStats: true }): Promise<{ + stats: I.VaultJSONStats + }>; + toJSON(): {}; + + addTag(tag: string, vid?: number): Promise; + + deleteTag(tag: string): Promise; + + tags(ids?: number[], opts?: { privateProps?: boolean }): object[]; + + tagNames(ids?: number[]): string[]; + + getNotes(): string; + + setNotes(notes: string): Promise; + } + + namespace I { + interface ValueableEntriesOptions { + entriesAsArray?: boolean; + includeEntryId?: boolean; + } + + interface ValuableEntry { + name: string; + value: any; + type: string; + } + + interface ValuableClearOptions { + includeNotes?: boolean; + includeTags?: boolean; + } + + interface ValuableJSON { + name: string; + notes: string; + entries: I.ValuableEntry[]; + } + } + + class Valuable { + constructor(vaule: Vault, id: number, metaData: object, tags: object[]); + + name(): string; + + internalId(): number; + + getNotes(): string; + + setNotes(notes: string): Promise; + + set(name: string, value: any, type?: string): Promise; + + setMulti(entries: object): Promise; + + get(name: string): Promise; + + type(name: string): any; + + has(name: string): boolean; + + keys(): string[]; + + entries(opts: I.ValueableEntriesOptions & { entriesAsArray: true }): Promise; + entries(opts: I.ValueableEntriesOptions & { entriesAsArray: true, includeEntryId: true }): Promise>; + entries(opts?: I.ValueableEntriesOptions): Promise; + + delete(name: string): Promise; + + clear(opts?: I.ValuableClearOptions): Promise; + + toJSON(opts?: I.ValuableToJSONOptions): object; // TODO + + fromJSON(json: object): Promise; + + addTag(tag: string): Promise; + + hasTag(tag: string): boolean; + + deleteTag(tag: string): Promise; + + deleteAllTags(): Promise; + + tags(): object[]; + } + + function open(options?: I.VaultConstructorOptions): Promise; + + namespace I { + interface SlicedValuable { + name(): string; + + internalId(): number; + + getNotes(): string; + + setNotes(notes: string): Promise; + + set(name: string, value: any, type?: string): Promise; + + setMulti(entries: object): Promise; + + get(name: string): Promise; + + type(name: string): any; + + has(name: string): boolean; + + keys(): string[]; + + entries(opts: I.ValueableEntriesOptions & { entriesAsArray: true }): Promise; + entries(opts: I.ValueableEntriesOptions & { entriesAsArray: true, includeEntryId: true }): Promise>; + entries(opts?: I.ValueableEntriesOptions): Promise; + + delete(name: string): Promise; + + toJSON(opts?: I.ValuableToJSONOptions): object; + + fromJSON(json: object): Promise; + + addTag(tag: string): Promise; + + hasTag(tag: string): boolean; + + deleteTag(tag: string): Promise; + + deleteAllTags(): Promise; + + tags(): object[]; + } + } + + function slice(valuable: Valuable, prefix: string | string[], separator?: string): I.SlicedValuable; + } +} diff --git a/types/adone/index.d.ts b/types/adone/index.d.ts index 74883c2185..a74641c4df 100644 --- a/types/adone/index.d.ts +++ b/types/adone/index.d.ts @@ -8,22 +8,33 @@ /// /// /// -/// +/// /// +/// /// /// /// -/// +/// +/// /// /// /// /// +/// +/// +/// /// -/// +/// +/// /// +/// /// /// +/// +/// +/// /// +/// declare const _adone: typeof adone; diff --git a/types/adone/test/glosses/application.ts b/types/adone/test/glosses/application.ts new file mode 100644 index 0000000000..38c5b0c8ff --- /dev/null +++ b/types/adone/test/glosses/application.ts @@ -0,0 +1,1663 @@ +namespace applicationTests { + const { + CliApplication, + DApplication, + DSubsystem, + DCliCommand, + DMainCliCommand, + Subsystem, + runCli, + Application + } = adone.application; + + namespace DApplicationTests { + { + @DApplication() + class App extends CliApplication {} + } + { + @DApplication({}) + class App extends CliApplication {} + } + { + @DApplication({ + name: "hello" + }) + class App extends CliApplication {} + } + { + @DApplication({ + description: "hello" + }) + class App extends CliApplication {} + } + { + @DApplication({ + subsystems: [ + { + name: "hello", + subsystem: "a.js" + } + ] + }) + class App extends CliApplication {} + } + { + @DApplication({ + subsystems: [ + { + name: "hello", + subsystem: "a.js", + transpile: true + } + ] + }) + class App extends CliApplication {} + } + { + @DApplication({ + commandsGroups: [{ + name: "a", + description: "b" + }] + }) + class App extends CliApplication {} + } + } + + namespace DSubsystemTests { + { + @DSubsystem() + class App extends Subsystem {} + } + { + @DSubsystem({}) + class App extends Subsystem {} + } + { + @DSubsystem({ + name: "hello" + }) + class App extends Subsystem {} + } + { + @DSubsystem({ + description: "hello" + }) + class App extends Subsystem {} + } + { + @DSubsystem({ + subsystems: [ + { + name: "hello", + subsystem: "a.js" + } + ] + }) + class App extends Subsystem {} + } + { + @DSubsystem({ + subsystems: [ + { + name: "hello", + subsystem: "a.js", + transpile: true + } + ] + }) + class App extends Subsystem {} + } + { + @DSubsystem({ + commandsGroups: [{ + name: "a", + description: "b" + }] + }) + class App extends Subsystem {} + } + } + + namespace DMainCliCommandTests { + { + class App extends CliApplication { + @DMainCliCommand() + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({}) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({}) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + blindMode: true + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + description: "a" + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + match: (arg) => arg.startsWith("hello") + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + optionsGroups: [{ + description: "a", + name: "a" + }] + }) + main() {} + } + } + + namespace argumentsTests { + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: ["hello"] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: ["hello"] + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + action: "append" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + action: "count" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + action: "set" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + action: "store_const" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + action: "store_false" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + action: "store_true" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + action: "store" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + appendChoicesHelpMessage: true + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + appendDefaultMessage: false + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + default: null + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + description: "hello" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + enabled: false + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + help: "asd" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + holder: "a" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + holder: ["a"] + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + nargs: 1 + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + nargs: "*" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + nargs: "+" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + nargs: "?" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + required: false + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + type: String + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + type: (x: string, i: number) => { + return true; + } + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + type: [(x: string, i: number) => { + return true; + }] + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + type: [/^abc$/] + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + arguments: [{ + name: "hello", + verify: (args, opts) => { + return true; + } + }] + }) + main() {} + } + } + } + + namespace optionsTests { + { + class App extends CliApplication { + @DMainCliCommand({ + options: ["--hello"] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: ["hello"] + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + action: "append" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + action: "count" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + action: "set" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + action: "store_const" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + action: "store_false" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + action: "store_true" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + action: "store" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + appendChoicesHelpMessage: true + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + appendDefaultMessage: false + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + default: null + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + description: "hello" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + enabled: false + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + help: "asd" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + holder: "a" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + holder: ["a"] + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + nargs: 1 + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + nargs: "*" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + nargs: "+" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + nargs: "?" + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + required: false + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + type: String + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + type: (x: string, i: number) => { + return true; + } + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + type: [(x: string, i: number) => { + return true; + }] + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + type: [/^abc$/] + }] + }) + main() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + verify: (args, opts) => { + return true; + } + }] + }) + main() {} + } + } + } + } + + namespace DCliCommandTests { + { + class App extends CliApplication { + @DCliCommand() + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({}) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({}) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + blindMode: true + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + description: "a" + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + match: (arg) => arg.startsWith("hello") + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + optionsGroups: [{ + description: "a", + name: "a" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + name: "cmdd" + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + group: "asdasd" + }) + cmd() {} + } + } + + namespace argumentsTests { + { + class App extends CliApplication { + @DCliCommand({ + arguments: ["hello"] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: ["hello"] + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + action: "append" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + action: "count" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + action: "set" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + action: "store_const" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + action: "store_false" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + action: "store_true" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + action: "store" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + appendChoicesHelpMessage: true + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + appendDefaultMessage: false + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + default: null + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + description: "hello" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + enabled: false + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + help: "asd" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + holder: "a" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + holder: ["a"] + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + nargs: 1 + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + nargs: "*" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + nargs: "+" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + nargs: "?" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + required: false + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + type: String + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + type: (x: string, i: number) => { + return true; + } + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + type: [(x: string, i: number) => { + return true; + }] + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + type: [/^abc$/] + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + arguments: [{ + name: "hello", + verify: (args, opts) => { + return true; + } + }] + }) + cmd() {} + } + } + } + + namespace optionsTests { + { + class App extends CliApplication { + @DCliCommand({ + options: ["--hello"] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: ["hello"] + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + action: "append" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + action: "count" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + action: "set" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + action: "store_const" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + action: "store_false" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + action: "store_true" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + action: "store" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + appendChoicesHelpMessage: true + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + appendDefaultMessage: false + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + default: null + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + description: "hello" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + enabled: false + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + help: "asd" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + holder: "a" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + holder: ["a"] + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + nargs: 1 + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + nargs: "*" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + nargs: "+" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + nargs: "?" + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + required: false + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + type: String + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + type: (x: string, i: number) => { + return true; + } + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + type: [(x: string, i: number) => { + return true; + }] + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DCliCommand({ + options: [{ + name: "--hello", + type: [/^abc$/] + }] + }) + cmd() {} + } + } + { + class App extends CliApplication { + @DMainCliCommand({ + options: [{ + name: "--hello", + verify: (args, opts) => { + return true; + } + }] + }) + cmd() {} + } + } + } + } + + namespace subsystemTests { + new Subsystem().name; + new Subsystem().root; + new Subsystem().setRoot(new Subsystem()); + new Subsystem().parent; + new Subsystem().state + 2; + new Subsystem().isOwned === true; + new Subsystem().setState(1); + new Subsystem().waitForState(2).then(() => {}); + new Subsystem().waitForState(2, 100).then(() => {}); + new Subsystem().configure(); + new Subsystem().initialize(); + new Subsystem().uninitialize(); + new Subsystem().configureSubsystems().then(() => {}); + new Subsystem().uninitializeSubsystems().then(() => {}); + new Subsystem().reinitializeSubsystems().then(() => {}); + new Subsystem().configureSubsystem("a").then(() => {}); + new Subsystem().loadSubsystem("a").then(() => {}); + new Subsystem().loadSubsystem(new Subsystem()).then(() => {}); + new Subsystem().loadSubsystem(new Subsystem(), {}).then(() => {}); + new Subsystem().loadSubsystem(new Subsystem(), { description: "a" }).then(() => {}); + new Subsystem().loadSubsystem(new Subsystem(), { group: "a" }).then(() => {}); + new Subsystem().loadSubsystem(new Subsystem(), { name: "a" }).then(() => {}); + new Subsystem().loadSubsystem(new Subsystem(), { transpile: false }).then(() => {}); + new Subsystem().unloadSubsystem("a").then(() => {}); + new Subsystem().initializeSubsystem("a").then(() => {}); + new Subsystem().uninitializeSubsystem("a").then(() => {}); + new Subsystem().getSubsystem("a").waitForState(2).then(() => {}); + new Subsystem().hasSubsystem("a") === true; + new Subsystem().hasSubsystem("a") === true; + new Subsystem().hasSubsystems() === true; + new Subsystem().addSubsystem({ subsystem: "ppp" }); + new Subsystem().addSubsystem({ subsystem: "ppp", bind: true }); + new Subsystem().addSubsystem({ subsystem: "ppp", bind: "a" }); + new Subsystem().addSubsystem({ subsystem: "ppp", configureArgs: [1] }); + new Subsystem().addSubsystem({ subsystem: "ppp", description: "a" }); + new Subsystem().addSubsystem({ subsystem: "ppp", group: "a" }); + new Subsystem().addSubsystem({ subsystem: "ppp", name: "a" }); + new Subsystem().addSubsystem({ subsystem: "ppp", transpile: false }); + new Subsystem().addSubsystem({ subsystem: "ppp", useFilename: true }); + { + const sysInfo = new Subsystem().addSubsystem({ subsystem: "ppp" }); + sysInfo.configureArgs[0]; + sysInfo.description.charCodeAt(10); + sysInfo.group.charCodeAt(10); + sysInfo.instance.waitForState(2, 30).then(() => {}); + sysInfo.name.charCodeAt(100); + sysInfo.path.charCodeAt(100); + } + { + const sysInfo = new Subsystem().addSubsystem({ subsystem: new Subsystem() }); + sysInfo.configureArgs[0]; + sysInfo.description.charCodeAt(10); + sysInfo.group.charCodeAt(10); + sysInfo.instance.waitForState(2, 30).then(() => {}); + sysInfo.name.charCodeAt(100); + sysInfo.path === null; + } + new Subsystem().addSubsystemsFrom("asd", {}); + new Subsystem().addSubsystemsFrom("asd", { filter: ["a"] }); + new Subsystem().addSubsystemsFrom("asd", { filter: (file) => file.charCodeAt(100) === 100 }); + new Subsystem().addSubsystemsFrom("asd", { filter: async (file) => file.charCodeAt(100) === 100 }); + new Subsystem().addSubsystemsFrom("asd", { bind: "a" }); + new Subsystem().addSubsystemsFrom("asd", { bind: true }); + new Subsystem().addSubsystemsFrom("asd", { configureArgs: [1] }); + new Subsystem().addSubsystemsFrom("asd", { description: "a" }); + new Subsystem().addSubsystemsFrom("asd", { group: "a" }); + new Subsystem().addSubsystemsFrom("asd", { name: "a" }); + new Subsystem().addSubsystemsFrom("asd", { transpile: true }); + new Subsystem().addSubsystemsFrom("asd", { useFilename: true }); + + new Subsystem().instantiateSubsystem("asd").waitForState(2, 200).then(() => {}); + new Subsystem().instantiateSubsystem(new Subsystem()).waitForState(2, 200).then(() => {}); + new Subsystem().instantiateSubsystem(new Subsystem(), { transpile: false }).waitForState(2, 200).then(() => {}); + new Subsystem().deleteSubsystem("name"); + new Subsystem().deleteSubsystem("name", true); + new Subsystem().getSubsystemInfo("name").configureArgs[0]; + new Subsystem().getSubsystems()[0].configureArgs[0]; + } + + namespace applicationTests { + new Application().isMain === true; + new Application().main(); + new Application().enableReport(); + new Application().enableReport({}); + new Application().enableReport({ directory: "a" }); + new Application().enableReport({ events: "a" }); + new Application().enableReport({ filename: "a" }); + new Application().enableReport({ signal: "a" }); + new Application().run().then(() => {}); + new Application().exit().then(() => {}); + new Application().exit(1).then(() => {}); + new Application().exitOnSignal("SIGINT", "SIGUSR1"); + new Application().removeProcesshandlers(); + new Application()._uncaughtException; + new Application()._unhandledRejection; + new Application()._rejectionHandled; + new Application()._signalExit("asd"); + } + + namespace cliApplicationTests { + new CliApplication().run({ ignoreArgs: true }).then(() => {}); + new CliApplication().getVersion().then(() => {}); + new CliApplication().exposeCliInterface(); + new CliApplication().mainCommand; + new CliApplication().defineMainCommand({ + arguments: [{ + name: "a", + default: 100500, + nargs: 100, + required: false + }], + options: [{ + name: "--a", + default: 1000, + nargs: 101231 + }], + optionsGroups: [{ + name: "a", + description: "a" + }] + }); + new CliApplication().defineCommand({ + name: "a", + arguments: [{ + name: "a", + default: 100500, + nargs: 100, + required: false + }], + options: [{ + name: "--a", + default: 1000, + nargs: 101231 + }], + optionsGroups: [{ + name: "a", + description: "a" + }] + }); + new CliApplication().defineCommandFromSubsystem({ + configureArgs: [1], + description: "a", + lazily: true, + subsystem: "a", + group: "a", + name: "a", + transpile: false + }); + new CliApplication().defineOption({ + name: "--a", + action: "store" + }); + new CliApplication().defineOptionsGroup({ + name: "a", + description: "b" + }); + new CliApplication().defineCommandsGroup({ + name: "a", + description: "b" + }); + new CliApplication().option("a"); + new CliApplication().option("a", { value: true }); + } +} diff --git a/types/adone/test/glosses/assertion.ts b/types/adone/test/glosses/assertion.ts index 4d07c78182..292cfa190c 100644 --- a/types/adone/test/glosses/assertion.ts +++ b/types/adone/test/glosses/assertion.ts @@ -3,9 +3,9 @@ namespace assertionTests { namespace assertionInterface { namespace exception { - const a: adone.x.Exception = new assertion.AssertionError(); - const b: adone.x.Exception = new assertion.AssertionError("hello"); - const c: adone.x.Exception = new assertion.AssertionError("hello", { actual: 2, expected: 3 }, () => {}); + const a: adone.error.Exception = new assertion.AssertionError(); + const b: adone.error.Exception = new assertion.AssertionError("hello"); + const c: adone.error.Exception = new assertion.AssertionError("hello", { actual: 2, expected: 3 }, () => {}); } namespace config { @@ -38,11 +38,11 @@ namespace assertionTests { assert.fail(1, 2, "hello"); assert.fail(1, 2, "hello", "<"); - assert.isOk(1); - assert.isOk(1, "hello"); + assert.ok(1); + assert.ok(1, "hello"); - assert.isNotOk(1); - assert.isNotOk(1, "hello"); + assert.notOk(1); + assert.notOk(1, "hello"); assert.equal(1, 2); assert.equal(1, 2, "hello"); @@ -68,38 +68,38 @@ namespace assertionTests { assert.notDeepEqual(1, 2); assert.notDeepEqual(1, 2, "hello"); - assert.isAbove(1, 2); - assert.isAbove(1, 2, "hello"); + assert.above(1, 2); + assert.above(1, 2, "hello"); - assert.isAtLeast(1, 2); - assert.isAtLeast(1, 2, "hello"); + assert.atLeast(1, 2); + assert.atLeast(1, 2, "hello"); - assert.isBelow(1, 2); - assert.isBelow(1, 2, "hello"); + assert.below(1, 2); + assert.below(1, 2, "hello"); - assert.isAtMost(1, 2); - assert.isAtMost(1, 2, "hello"); + assert.atMost(1, 2); + assert.atMost(1, 2, "hello"); - assert.isTrue(1); - assert.isTrue(1, "hello"); + assert.true(1); + assert.true(1, "hello"); - assert.isNotTrue(1); - assert.isNotTrue(1, "hello"); + assert.notTrue(1); + assert.notTrue(1, "hello"); - assert.isFalse(1); - assert.isFalse(1, "hello"); + assert.false(1); + assert.false(1, "hello"); - assert.isNotFalse(1); - assert.isNotFalse(1, "hello"); + assert.notFalse(1); + assert.notFalse(1, "hello"); - assert.isNull(1); - assert.isNull(1, "hello"); + assert.null(1); + assert.null(1, "hello"); - assert.isNaN(1); - assert.isNaN(1, "hello"); + assert.NaN(1); + assert.NaN(1, "hello"); - assert.isNotNaN(1); - assert.isNotNaN(1, "hello"); + assert.NotNaN(1); + assert.NotNaN(1, "hello"); assert.exists(1); assert.exists(1, "hello"); @@ -107,49 +107,49 @@ namespace assertionTests { assert.notExists(1); assert.notExists(1, "hello"); - assert.isUndefined(1); - assert.isUndefined(1, "hello"); + assert.undefined(1); + assert.undefined(1, "hello"); - assert.isDefined(1); - assert.isDefined(1, "hello"); + assert.defined(1); + assert.defined(1, "hello"); - assert.isFunction(1); - assert.isFunction(1, "hello"); + assert.function(1); + assert.function(1, "hello"); - assert.isNotFunction(1); - assert.isNotFunction(1, "hello"); + assert.notFunction(1); + assert.notFunction(1, "hello"); - assert.isObject(1); - assert.isObject(1, "hello"); + assert.object(1); + assert.object(1, "hello"); - assert.isNotObject(1); - assert.isNotObject(1, "hello"); + assert.notObject(1); + assert.notObject(1, "hello"); - assert.isArray(1); - assert.isArray(1, "hello"); + assert.array(1); + assert.array(1, "hello"); - assert.isNotArray(1); - assert.isNotArray(1, "hello"); + assert.notArray(1); + assert.notArray(1, "hello"); - assert.isString(1, "hello"); + assert.string(1, "hello"); - assert.isNotString(1); - assert.isNotString(1, "hello"); + assert.notString(1); + assert.notString(1, "hello"); - assert.isNumber(1); - assert.isNumber(1, "hello"); + assert.number(1); + assert.number(1, "hello"); - assert.isNotNumber(1); - assert.isNotNumber(1, "hello"); + assert.notNumber(1); + assert.notNumber(1, "hello"); - assert.isFinite(1); - assert.isFinite(1, "hello"); + assert.finite(1); + assert.finite(1, "hello"); - assert.isBoolean(1); - assert.isBoolean(1, "hello"); + assert.boolean(1); + assert.boolean(1, "hello"); - assert.isNotBoolean(1); - assert.isNotBoolean(1, "hello"); + assert.notBoolean(1); + assert.notBoolean(1, "hello"); assert.typeOf(1, "string"); assert.typeOf(1, "number", "hello"); @@ -457,26 +457,26 @@ namespace assertionTests { assert.ifError(1); - assert.isExtensible({}); - assert.isExtensible({}, "hello"); + assert.extensible({}); + assert.extensible({}, "hello"); - assert.isNotExtensible({}); - assert.isNotExtensible({}, "hello"); + assert.notExtensible({}); + assert.notExtensible({}, "hello"); - assert.isSealed({}); - assert.isSealed({}, "hello"); + assert.sealed({}); + assert.sealed({}, "hello"); - assert.isNotSealed({}); - assert.isNotSealed({}, "hello"); + assert.notSealed({}); + assert.notSealed({}, "hello"); - assert.isFrozen({}); - assert.isFrozen({}, "hello"); + assert.frozen({}); + assert.frozen({}, "hello"); - assert.isNotFrozen({}); - assert.isNotFrozen({}, "hello"); + assert.notFrozen({}); + assert.notFrozen({}, "hello"); - assert.isEmpty({}); - assert.isEmpty({}, "hello"); + assert.empty({}); + assert.empty({}, "hello"); } const { expect } = assertion; @@ -499,16 +499,16 @@ namespace assertionTests { expect(1).to.contain(2, "hello").and; expect(1).but.contains(2).and; expect(1).but.contains(2, "hello").and; - expect(1).to.ok.not.ok; - expect(1).to.be.true.but.false; - expect(1).to.be.false.but.true; - expect(1).to.be.null.and.null; - expect(1).to.be.undefined.and.true; - expect(1).to.be.NaN.and.null; - expect(1).to.exist.and.be.null; - expect(1).to.be.empty.and.true; - expect(1).to.be.arguments.and.a("number"); - expect(1).to.be.Arguments.and.false; + expect(1).to.ok().and.a("string"); + expect(1).to.be.true().but.false(); + expect(1).to.be.false().but.true(); + expect(1).to.be.null().and.null(); + expect(1).to.be.undefined().and.true(); + expect(1).to.be.NaN().and.null(); + expect(1).to.exist().and.be.null(); + expect(1).to.be.empty().and.true(); + expect(1).to.be.arguments().and.a("number"); + expect(1).to.be.Arguments().and.false(); expect(1).to.be.equal(2).and; expect(1).to.be.equal(2, "hello").and; expect(1).but.equals(2).and; @@ -624,19 +624,19 @@ namespace assertionTests { expect(() => {}).but.decreases({}, "a", "hello").and; expect(() => {}).to.decreases({}).by(2).and; expect(() => {}).to.decreases({}).by(2, "hello").and; - expect({}).to.be.extensible.and; - expect({}).to.be.sealed.and; - expect({}).to.be.frozen.and; - expect({}).to.be.finite.and; + expect({}).to.be.extensible().and; + expect({}).to.be.sealed().and; + expect({}).to.be.frozen().and; + expect({}).to.be.finite().and; namespace mockTests { const s1 = adone.shani.util.spy(); const s2 = adone.shani.util.spy(); - expect(s1).to.have.been.called; - expect(s1).to.have.been.calledOnce; - expect(s1).to.have.been.calledTwice; - expect(s1).to.have.been.calledThrice; + expect(s1).to.have.been.called(); + expect(s1).to.have.been.calledOnce(); + expect(s1).to.have.been.calledTwice(); + expect(s1).to.have.been.calledThrice(); expect(s1).to.have.callCount(100); expect(s1).to.have.been.calledBefore(s2); expect(s1).to.have.been.calledAfter(s2); diff --git a/types/adone/test/glosses/collections.ts b/types/adone/test/glosses/collections.ts deleted file mode 100644 index ec227d4440..0000000000 --- a/types/adone/test/glosses/collections.ts +++ /dev/null @@ -1,1003 +0,0 @@ -namespace collectionTests { - const { collection } = adone; - - namespace linkedListTests { - const { LinkedList } = collection; - - namespace creation { - new LinkedList(); - new LinkedList(10); - } - - namespace properties { - { const a: boolean = new LinkedList().full; } - { const a: boolean = new LinkedList().empty; } - { const a: number = new LinkedList().maxLength; } - { const a: number = new LinkedList().length; } - { const a: boolean = new LinkedList().autoresize; } - } - - namespace resize { - { const a: boolean = new LinkedList().resize(100).full; } - } - - namespace push { - const a = new LinkedList().push(10); - a.next; - a.prev; - const b: number = a.value; - } - - namespace pop { - const a: number | undefined = new LinkedList().pop(); - } - - namespace shift { - const a: number | undefined = new LinkedList().shift(); - } - - namespace unshift { - const a = new LinkedList().unshift("hello"); - a.next; - a.prev; - const b: string = a.value; - } - - namespace pushNode { - const a = new LinkedList(); - const node = a.push("1230"); - a.pushNode(node); - } - - namespace unshiftNode { - const a = new LinkedList(); - const node = a.push(10); - a.unshiftNode(node); - } - - namespace removeNode { - const a = new LinkedList(); - const node = a.unshift("10"); - a.removeNode(node); - } - - namespace clear { - new LinkedList().clear(); - new LinkedList().clear(true); - } - - namespace toArray { - const a = new LinkedList(); - const b: number[] = a.toArray(); - } - - namespace front { - const a = new LinkedList(); - const b: number = a.front; - } - - namespace back { - const a = new LinkedList(); - const b: number = a.back; - } - - namespace iterating { - const a = new LinkedList(); - for (const b of a) { - const i: string = b; - } - const c = new LinkedList(); - for (const b of c) { - const i: number = b; - } - } - - namespace nextNode { - const a = new LinkedList(); - const n1 = a.push("h"); - const n2 = a.nextNode(n1); - n1.next; - n1.prev; - const t: string = n1.value; - } - - namespace map { - const a = new LinkedList(); - const f = (a: number, idx: number) => `${a}${idx}`; - const b = a.map(f); - const c: string = b.front; - } - - namespace forEach { - const a = new LinkedList(); - - a.forEach((a: number, b: number) => { - const c = a + b; - }); - } - - namespace static { - const a: number = LinkedList.DEFAULT_LENGTH; - } - } - - namespace ByteArrayTests { - const { ByteArray } = collection; - - new ByteArray(); - new ByteArray(10); - new ByteArray(10, true); - - const buffer = new ByteArray(); - - namespace readBitSet { - const a: boolean[] = buffer.readBitSet(); - const b: boolean[] = buffer.readBitSet(10); - } - - namespace read { - const a: adone.collection.ByteArray = buffer.read(1); - const b: adone.collection.ByteArray = buffer.read(1, 10); - } - - namespace readInt8 { - const a: number = buffer.readInt8(); - const b: number = buffer.readInt8(10); - } - - namespace readUInt8 { - const a: number = buffer.readUInt8(); - const b: number = buffer.readUInt8(10); - } - - namespace readInt16LE { - const a: number = buffer.readInt16LE(); - const b: number = buffer.readInt16LE(10); - } - - namespace readUInt16LE { - const a: number = buffer.readUInt16LE(); - const b: number = buffer.readUInt16LE(10); - } - - namespace readInt16BE { - const a: number = buffer.readInt16BE(); - const b: number = buffer.readInt16BE(10); - } - - namespace readUInt16BE { - const a: number = buffer.readUInt16BE(); - const b: number = buffer.readUInt16BE(10); - } - - namespace readInt32LE { - const a: number = buffer.readInt32LE(); - const b: number = buffer.readInt32LE(10); - } - - namespace readUInt32LE { - const a: number = buffer.readUInt32LE(); - const b: number = buffer.readUInt32LE(10); - } - - namespace readInt32BE { - const a: number = buffer.readInt32BE(); - const b: number = buffer.readInt32BE(10); - } - - namespace readUInt32BE { - const a: number = buffer.readUInt32BE(); - const b: number = buffer.readUInt32BE(10); - } - - namespace readInt64LE { - const a: adone.math.Long = buffer.readInt64LE(); - const b: adone.math.Long = buffer.readInt64LE(10); - } - - namespace readUInt64LE { - const a: adone.math.Long = buffer.readUInt64LE(); - const b: adone.math.Long = buffer.readUInt64LE(10); - } - - namespace readInt64BE { - const a: adone.math.Long = buffer.readInt64BE(); - const b: adone.math.Long = buffer.readInt64BE(10); - } - - namespace readUInt64BE { - const a: adone.math.Long = buffer.readUInt64BE(); - const b: adone.math.Long = buffer.readUInt64BE(10); - } - - namespace readFloatLE { - const a: number = buffer.readFloatLE(); - const b: number = buffer.readFloatLE(10); - } - - namespace readFloatBE { - const a: number = buffer.readFloatBE(); - const b: number = buffer.readFloatBE(10); - } - - namespace readDoubleLE { - const a: number = buffer.readDoubleLE(); - const b: number = buffer.readDoubleLE(10); - } - - namespace readDoubleBE { - const a: number = buffer.readDoubleBE(); - const b: number = buffer.readDoubleBE(10); - } - - namespace write { - const a: adone.collection.ByteArray = buffer.write("1"); - const b: adone.collection.ByteArray = buffer.write(new ByteArray()); - const c: adone.collection.ByteArray = buffer.write(Buffer.alloc(10)); - const d: adone.collection.ByteArray = buffer.write(new Uint8Array([1, 2, 3])); - const e: adone.collection.ByteArray = buffer.write(new ArrayBuffer(10)); - const f: adone.collection.ByteArray = buffer.write("1", 10); - const g: adone.collection.ByteArray = buffer.write("1", 10, 10); - const h: adone.collection.ByteArray = buffer.write("1", 10, 10, "utf8"); - } - - namespace writeBitSet { - const a: adone.collection.ByteArray = buffer.writeBitSet([1, 2, 3]); - const b: number = buffer.writeBitSet([1, 2, 3], 10); - } - - namespace writeInt8 { - const a: adone.collection.ByteArray = buffer.writeInt8(10); - const b: adone.collection.ByteArray = buffer.writeInt8(10, 10); - } - - namespace writeUInt8 { - const a: adone.collection.ByteArray = buffer.writeUInt8(10); - const b: adone.collection.ByteArray = buffer.writeUInt8(10, 10); - } - - namespace writeInt16LE { - const a: adone.collection.ByteArray = buffer.writeInt16LE(10); - const b: adone.collection.ByteArray = buffer.writeInt16LE(10, 10); - } - - namespace writeInt16BE { - const a: adone.collection.ByteArray = buffer.writeInt16BE(10); - const b: adone.collection.ByteArray = buffer.writeInt16BE(10, 10); - } - - namespace writeUInt16LE { - const a: adone.collection.ByteArray = buffer.writeUInt16LE(10); - const b: adone.collection.ByteArray = buffer.writeUInt16LE(10, 10); - } - - namespace writeUInt16BE { - const a: adone.collection.ByteArray = buffer.writeUInt16BE(10); - const b: adone.collection.ByteArray = buffer.writeUInt16BE(10, 10); - } - - namespace writeInt32LE { - const a: adone.collection.ByteArray = buffer.writeInt32LE(10); - const b: adone.collection.ByteArray = buffer.writeInt32LE(10, 10); - } - - namespace writeInt32BE { - const a: adone.collection.ByteArray = buffer.writeInt32BE(10); - const b: adone.collection.ByteArray = buffer.writeInt32BE(10, 10); - } - - namespace writeUInt32LE { - const a: adone.collection.ByteArray = buffer.writeUInt32LE(10); - const b: adone.collection.ByteArray = buffer.writeUInt32LE(10, 10); - } - - namespace writeUInt32BE { - const a: adone.collection.ByteArray = buffer.writeUInt32BE(10); - const b: adone.collection.ByteArray = buffer.writeUInt32BE(10, 10); - } - - namespace writeInt64LE { - const a: adone.collection.ByteArray = buffer.writeInt64LE(10); - const b: adone.collection.ByteArray = buffer.writeInt64LE(10, 10); - } - - namespace writeInt64BE { - const a: adone.collection.ByteArray = buffer.writeInt64BE(10); - const b: adone.collection.ByteArray = buffer.writeInt64BE(10, 10); - } - - namespace writeUInt64LE { - const a: adone.collection.ByteArray = buffer.writeUInt64LE(10); - const b: adone.collection.ByteArray = buffer.writeUInt64LE(10, 10); - } - - namespace writeUInt64BE { - const a: adone.collection.ByteArray = buffer.writeUInt64BE(10); - const b: adone.collection.ByteArray = buffer.writeUInt64BE(10, 10); - } - - namespace writeFloatLE { - const a: adone.collection.ByteArray = buffer.writeFloatLE(10); - const b: adone.collection.ByteArray = buffer.writeFloatLE(10, 10); - } - - namespace writeFloatBE { - const a: adone.collection.ByteArray = buffer.writeFloatBE(10); - const b: adone.collection.ByteArray = buffer.writeFloatBE(10, 10); - } - - namespace writeDoubleLE { - const a: adone.collection.ByteArray = buffer.writeDoubleLE(10); - const b: adone.collection.ByteArray = buffer.writeDoubleLE(10, 10); - } - - namespace writeDoubleBE { - const a: adone.collection.ByteArray = buffer.writeDoubleBE(10); - const b: adone.collection.ByteArray = buffer.writeDoubleBE(10, 10); - } - - namespace writeVarInt32 { - const a: adone.collection.ByteArray = buffer.writeVarint32(10); - const b: number = buffer.writeVarint32(10, 10); - } - - namespace writeVarInt32ZigZag { - const a: adone.collection.ByteArray = buffer.writeVarint32ZigZag(10); - const b: number = buffer.writeVarint32ZigZag(10, 10); - } - - namespace readVarint32 { - const a: number = buffer.readVarint32(); - const b: { value: number, length: number } = buffer.readVarint32(10); - } - - namespace readVarint32ZigZag { - const a: number = buffer.readVarint32ZigZag(); - const b: { value: number, length: number } = buffer.readVarint32ZigZag(10); - } - - namespace writeVarint64 { - const a: adone.collection.ByteArray = buffer.writeVarint64(10); - const b: number = buffer.writeVarint64(10, 10); - } - - namespace writeVarint64ZigZag { - const a: adone.collection.ByteArray = buffer.writeVarint64ZigZag(10); - const b: number = buffer.writeVarint64ZigZag(10, 10); - } - - namespace readVarint64 { - const a: adone.math.Long = buffer.readVarint64(); - const b: { value: adone.math.Long, length: number } = buffer.readVarint64(10); - } - - namespace readVarint64ZigZag { - const a: adone.math.Long = buffer.readVarint64ZigZag(); - const b: { value: adone.math.Long, length: number } = buffer.readVarint64ZigZag(10); - } - - namespace writeCString { - const a: adone.collection.ByteArray = buffer.writeCString("asd"); - const b: number = buffer.writeCString("123", 10); - } - - namespace readCString { - const a: string = buffer.readCString(); - const b: { string: string, length: number } = buffer.readCString(10); - } - - namespace writeString { - const a: adone.collection.ByteArray = buffer.writeString("abc"); - const b: number = buffer.writeString("abc", 10); - } - - namespace readString { - const a: string = buffer.readString(10); - const b: string = buffer.readString(10, "b"); - const c: string = buffer.readString(10, "c"); - const d: { string: string, length: number } = buffer.readString(10, "c", 10); - } - - namespace writeVString { - const a: adone.collection.ByteArray = buffer.writeVString("abc"); - const b: number = buffer.writeVString("abc", 10); - } - - namespace readVString { - const a: string = buffer.readVString(); - const b: { string: string, length: number } = buffer.readVString(10); - } - - namespace appendTo { - const a: adone.collection.ByteArray = buffer.appendTo(new ByteArray()); - const b: adone.collection.ByteArray = buffer.appendTo(new ByteArray(), 10); - } - - namespace assert { - const a: adone.collection.ByteArray = buffer.assert(); - const b: adone.collection.ByteArray = buffer.assert(true); - } - - namespace capacity { - const a: number = buffer.capacity(); - } - - namespace clear { - const a: adone.collection.ByteArray = buffer.clear(); - } - - namespace copy { - const a: adone.collection.ByteArray = buffer.clone(); - const c: adone.collection.ByteArray = buffer.clone(true); - } - - namespace compact { - const a: adone.collection.ByteArray = buffer.compact(); - const b: adone.collection.ByteArray = buffer.compact(1); - const c: adone.collection.ByteArray = buffer.compact(1, 10); - } - - namespace copyTo { - const a: adone.collection.ByteArray = buffer.copyTo(new ByteArray()); - const b: adone.collection.ByteArray = buffer.copyTo(new ByteArray(), 0); - const c: adone.collection.ByteArray = buffer.copyTo(new ByteArray(), 0, 0); - const d: adone.collection.ByteArray = buffer.copyTo(new ByteArray(), 0, 0, 10); - } - - namespace ensureCapacity { - const a: adone.collection.ByteArray = buffer.ensureCapacity(10); - } - - namespace fill { - const a: adone.collection.ByteArray = buffer.fill("0"); - const b: adone.collection.ByteArray = buffer.fill(0); - const c: adone.collection.ByteArray = buffer.fill(0, 0); - const d: adone.collection.ByteArray = buffer.fill(0, 0, 10); - } - - namespace flip { - const a: adone.collection.ByteArray = buffer.flip(); - } - - namespace mark { - const a: adone.collection.ByteArray = buffer.mark(); - const b: adone.collection.ByteArray = buffer.mark(10); - } - - namespace prepend { - const a: adone.collection.ByteArray = buffer.prepend(""); - const b: adone.collection.ByteArray = buffer.prepend(new ByteArray()); - const c: adone.collection.ByteArray = buffer.prepend(Buffer.alloc(10)); - const d: adone.collection.ByteArray = buffer.prepend(new Uint8Array([1, 2, 3])); - const e: adone.collection.ByteArray = buffer.prepend(new ArrayBuffer(10)); - const f: adone.collection.ByteArray = buffer.prepend("", "utf8"); - const g: adone.collection.ByteArray = buffer.prepend("", "utf8", 10); - const h: adone.collection.ByteArray = buffer.prepend("", 10); - } - - namespace prependTo { - const a: adone.collection.ByteArray = buffer.prependTo(new ByteArray()); - const b: adone.collection.ByteArray = buffer.prependTo(new ByteArray(), 10); - } - - namespace remaining { - const a: number = buffer.remaining(); - } - - namespace reset { - const a: adone.collection.ByteArray = buffer.reset(); - } - - namespace resize { - const a: adone.collection.ByteArray = buffer.resize(10); - } - - namespace reverse { - const a: adone.collection.ByteArray = buffer.reverse(); - const b: adone.collection.ByteArray = buffer.reverse(1); - const c: adone.collection.ByteArray = buffer.reverse(1, 10); - } - - namespace skip { - const a: adone.collection.ByteArray = buffer.skip(10); - } - - namespace slice { - const a: adone.collection.ByteArray = buffer.slice(); - const b: adone.collection.ByteArray = buffer.slice(1); - const c: adone.collection.ByteArray = buffer.slice(1, 10); - } - - namespace toBuffer { - const a: Buffer = buffer.toBuffer(); - const b: Buffer = buffer.toBuffer(true); - const c: Buffer = buffer.toBuffer(true, 0); - const d: Buffer = buffer.toBuffer(true, 0, 10); - } - - namespace toArrayBuffer { - const a: ArrayBuffer = buffer.toArrayBuffer(); - } - - namespace toString { - const a: string = buffer.toString(); - const b: string = buffer.toString("utf8"); - const c: string = buffer.toString("utf8", 0); - const d: string = buffer.toString("utf8", 0, 10); - } - - namespace toBase64 { - const a: string = buffer.toBase64(); - const b: string = buffer.toBase64(0); - const c: string = buffer.toBase64(0, 10); - } - - namespace toBinary { - const a: string = buffer.toBinary(); - const b: string = buffer.toBinary(0); - const c: string = buffer.toBinary(0, 10); - } - - namespace toDebug { - const a: string = buffer.toDebug(); - const b: string = buffer.toDebug(true); - } - - namespace toUTF8 { - const a: string = buffer.toUTF8(); - const b: string = buffer.toUTF8(0); - const c: string = buffer.toUTF8(0, 10); - } - - namespace static { - namespace accessor { - const a: typeof Buffer = ByteArray.accessor(); - } - - namespace allocate { - const a: adone.collection.ByteArray = ByteArray.allocate(); - const b: adone.collection.ByteArray = ByteArray.allocate(10); - const c: adone.collection.ByteArray = ByteArray.allocate(10, true); - } - - namespace concat { - const a: adone.collection.ByteArray = ByteArray.concat([ - new ByteArray(), - Buffer.alloc(10), - new Uint8Array([1, 2, 3]), - new ArrayBuffer(10) - ]); - const b: adone.collection.ByteArray = ByteArray.concat([ - new ByteArray(), - Buffer.alloc(10), - new Uint8Array([1, 2, 3]), - new ArrayBuffer(10) - ], "utf8"); - const c: adone.collection.ByteArray = ByteArray.concat([ - new ByteArray(), - Buffer.alloc(10), - new Uint8Array([1, 2, 3]), - new ArrayBuffer(10) - ], "utf8", true); - } - - namespace type { - const a: typeof Buffer = ByteArray.type(); - } - - namespace wrap { - const a: adone.collection.ByteArray = ByteArray.wrap(""); - const b: adone.collection.ByteArray = ByteArray.wrap(new ByteArray()); - const c: adone.collection.ByteArray = ByteArray.wrap(Buffer.alloc(10)); - const d: adone.collection.ByteArray = ByteArray.wrap(new Uint8Array([1, 2, 3])); - const e: adone.collection.ByteArray = ByteArray.wrap(new ArrayBuffer(10)); - const f: adone.collection.ByteArray = ByteArray.wrap("", "utf8"); - const g: adone.collection.ByteArray = ByteArray.wrap("", "utf8", true); - } - - namespace calculateVarint32 { - const a: number = ByteArray.calculateVarint32(10); - } - - namespace zigZagEncode32 { - const a: number = ByteArray.zigZagEncode32(10); - } - - namespace zigZagDecode32 { - const a: number = ByteArray.zigZagDecode32(10); - } - - namespace calculateVarint64 { - const a: number = ByteArray.calculateVarint64(10); - const b: number = ByteArray.calculateVarint64("10"); - } - - namespace zigZagEncode64 { - const a: adone.math.Long = ByteArray.zigZagEncode64(10); - const b: adone.math.Long = ByteArray.zigZagEncode64("10"); - const c: adone.math.Long = ByteArray.zigZagEncode64(adone.math.Long.fromValue(10)); - } - - namespace zigZagDecode64 { - const a: adone.math.Long = ByteArray.zigZagDecode64(10); - const b: adone.math.Long = ByteArray.zigZagDecode64("10"); - const c: adone.math.Long = ByteArray.zigZagDecode64(adone.math.Long.fromValue(10)); - } - - namespace calculateUTF8Chars { - const a: number = ByteArray.calculateUTF8Chars("123"); - } - - namespace calculateString { - const a: number = ByteArray.calculateString("123"); - } - - namespace fromBase64 { - const a: adone.collection.ByteArray = ByteArray.fromBase64("123"); - } - - namespace btoa { - const a: string = ByteArray.btoa("123"); - } - - namespace atob { - const a: string = ByteArray.atob("123"); - } - - namespace fromBinary { - const a: adone.collection.ByteArray = ByteArray.fromBinary("123"); - } - - namespace fromDebug { - const a: adone.collection.ByteArray = ByteArray.fromDebug("12"); - const b: adone.collection.ByteArray = ByteArray.fromDebug("12", true); - } - - namespace fromHex { - const a: adone.collection.ByteArray = ByteArray.fromHex("192"); - const b: adone.collection.ByteArray = ByteArray.fromHex("192", true); - } - - namespace fromUTF8 { - const a: adone.collection.ByteArray = ByteArray.fromUTF8("123"); - const b: adone.collection.ByteArray = ByteArray.fromUTF8("123", true); - } - - namespace constants { - const a: number = ByteArray.DEFAULT_CAPACITY; - const b: boolean = ByteArray.DEFAULT_NOASSERT; - const c: number = ByteArray.MAX_VARINT32_BYTES; - const d: number = ByteArray.MAX_VARINT64_BYTES; - const e: string = ByteArray.METRICS_CHARS; - const f: string = ByteArray.METRICS_BYTES; - } - } - } - - namespace queueTests { - const { Queue } = collection; - type Queue = adone.collection.Queue; - - new Queue(); - { const a: Queue = new Queue().push(123).push(123); } - { const a: number | undefined = new Queue().push(123).pop(); } - { const a: string | undefined = new Queue().push(123).pop(); } - { const a: boolean = new Queue().full; } - { const a: number = new Queue().length; } - { const a: boolean = new Queue().empty; } - } - - namespace asyncQueueTests { - const { AsyncQueue } = collection; - type AsyncQueue = adone.collection.AsyncQueue; - - { const a: AsyncQueue = new AsyncQueue().push(123); } - { const a: Promise = new AsyncQueue().push(123).pop(); } - } - - namespace priorityQueueTests { - const { PriorityQueue } = collection; - type PriorityQueue = adone.collection.PriorityQueue; - - { const a: boolean = new PriorityQueue().empty; } - { const a: number = new PriorityQueue().length; } - new PriorityQueue(); - new PriorityQueue({}); - new PriorityQueue({ - compare(a: number, b: number) { - return a - b; - } - }); - new PriorityQueue({ - priority(a: string, b: string) { - return a.length - b.length; - } - }); - { const a: PriorityQueue = new PriorityQueue().clone(); } - { const a: PriorityQueue = new PriorityQueue().push("123"); } - { const a: string | undefined = new PriorityQueue().pop(); } - { const a: PriorityQueue = new PriorityQueue().delete("123"); } - { const a: PriorityQueue = new PriorityQueue().delete("123"); } - { const a: string = new PriorityQueue().replace("123"); } - { const a: string = new PriorityQueue().pushpop("123"); } - { const a: string[] = new PriorityQueue().toArray(); } - { const a: PriorityQueue = PriorityQueue.from(["1"]); } - { const a: PriorityQueue = PriorityQueue.from(["1"], {}); } - { const a: PriorityQueue = PriorityQueue.from(["1"], { compare: (a: string, b: string) => a.length - b.length }); } - { const a: PriorityQueue = PriorityQueue.from(["1"], { priority: (a: string, b: string) => a.length - b.length }); } - } - - namespace fastlruTests { - const { FastLRU } = collection; - - new FastLRU(); - new FastLRU(100); - new FastLRU(100, { dispose: (key: string, value: number) => null }); - { const a: number = new FastLRU().size; } - { const a: number | undefined = new FastLRU().get("key"); } - new FastLRU().set("key", 123); - { const a: boolean = new FastLRU().delete("key"); } - { const a: boolean = new FastLRU().has("key"); } - { const a: string[] = [...new FastLRU().keys()]; } - { const a: number[] = [...new FastLRU().values()]; } - { const a: number[] = [...new FastLRU().values()]; } - { const a: Array<[string, number]> = [...new FastLRU().entries()]; } - new FastLRU().clear(); - } - - namespace stackTests { - const { Stack } = collection; - type Stack = adone.collection.Stack; - - { const a: boolean = new Stack().empty; } - { const a: number = new Stack().top; } - { const a: Stack = new Stack().push(123); } - { const a: number | undefined = new Stack().pop(); } - { const a: number[] = [...new Stack()]; } - { const a: Stack = Stack.from([1, 2, 3]); } - } - - namespace binarySearchTreeTests { - const { BinarySearchTree } = collection; - type BinarySearchTree = adone.collection.BinarySearchTree; - - new BinarySearchTree(); - new BinarySearchTree({}); - new BinarySearchTree({ checkValueEquality: (a: number, b: number) => a === b }); - new BinarySearchTree({ compareKeys: (a: string, b: string) => a.length - b.length }); - new BinarySearchTree({ parent: new BinarySearchTree() }); - new BinarySearchTree({ unique: true }); - new BinarySearchTree({ value: 123 }); - { const a: BinarySearchTree = new BinarySearchTree().getMaxKeyDescendant(); } - { const a: string = new BinarySearchTree().getMaxKey(); } - { const a: BinarySearchTree = new BinarySearchTree().getMinKeyDescendant(); } - { const a: string = new BinarySearchTree().getMinKey(); } - new BinarySearchTree().checkAllNodesFullfillCondition((key: string, value: number) => null); - new BinarySearchTree().checkIsBST(); - { const a: number = new BinarySearchTree().getNumberOfKeys(); } - new BinarySearchTree().insert("asd", 123); - { const a: number[] = new BinarySearchTree().search("asd"); } - { const a: number[] = new BinarySearchTree().betweenBounds({ $gt: "" }); } - { const a: number[] = new BinarySearchTree().betweenBounds({ $lt: "" }); } - { const a: number[] = new BinarySearchTree().betweenBounds({ $lte: "" }); } - { const a: number[] = new BinarySearchTree().betweenBounds({ $gte: "" }); } - new BinarySearchTree().delete("key"); - new BinarySearchTree().delete("key", 123); - new BinarySearchTree().executeOnEveryNode((tree: BinarySearchTree) => null); - new BinarySearchTree().prettyPrint(); - new BinarySearchTree().prettyPrint(true); - new BinarySearchTree().prettyPrint(true, " "); - } - - namespace avlTreeTests { - const { AVLTree } = collection; - type AVLTree = adone.collection.AVLTree; - - new AVLTree(); - new AVLTree({ checkValueEquality: (a: number, b: number) => a === b }); - new AVLTree({ compareKeys: (a: string, b: string) => a.length - b.length }); - new AVLTree({ parent: new AVLTree() }); - new AVLTree({ unique: false }); - new AVLTree({ value: 123 }); - new AVLTree().checkIsAVLT(); - new AVLTree().insert("123", 123); - new AVLTree().delete("123"); - new AVLTree().delete("123", 123); - { const a: number = new AVLTree().getNumberOFKeys(); } - { const a: number[] = new AVLTree().search("key"); } - { const a: number[] = new AVLTree().betweenBounds({}); } - { const a: number[] = new AVLTree().betweenBounds({ $gt: "ads" }); } - { const a: number[] = new AVLTree().betweenBounds({ $lt: "ads" }); } - { const a: number[] = new AVLTree().betweenBounds({ $gte: "ads" }); } - { const a: number[] = new AVLTree().betweenBounds({ $lte: "ads" }); } - new AVLTree().executeOnEveryNode((tree: AVLTree) => null); - } - - namespace redBlackTreeTests { - const { RedBlackTree } = collection; - type RedBlackTree = adone.collection.RedBlackTree; - type RedBlackTreeIterator = adone.collection.I.RedBlackTree.Iterator; - type RedBlackTreeNode = adone.collection.I.RedBlackTree.Node; - - new RedBlackTree(); - new RedBlackTree((a: string, b: string) => a.length - b.length); - new RedBlackTree(undefined, new RedBlackTree()); - { const a: string[] = new RedBlackTree().keys; } - { const a: number[] = new RedBlackTree().values; } - { const a: number = new RedBlackTree().length; } - { - const a: RedBlackTreeIterator = new RedBlackTree().begin; - { const b: boolean = a.valid; } - { const b: RedBlackTreeNode | null = a.node; } - { const b: string | undefined = a.key; } - { const b: number | undefined = a.value; } - { const b: number = a.index; } - { const b: boolean = a.hasNext; } - { const b: boolean = a.hasPrev; } - { const b: RedBlackTree = a.tree; } - { const b: RedBlackTreeIterator = a.clone(); } - { const b: RedBlackTree = a.remove(); } - a.next(); - { const b: RedBlackTree = a.update(333); } - a.prev(); - } - { const a: RedBlackTreeIterator = new RedBlackTree().end; } - { const a: RedBlackTree = new RedBlackTree().insert("123", 456); } - { const a: number = new RedBlackTree().forEach((key: string, value: number) => value); } - { const a: number = new RedBlackTree().forEach((key: string, value: number) => value, "1"); } - { const a: number = new RedBlackTree().forEach((key: string, value: number) => value, "1", "2"); } - { const a: RedBlackTreeIterator = new RedBlackTree().at(1); } - { const a: RedBlackTreeIterator = new RedBlackTree().ge("1"); } - { const a: RedBlackTreeIterator = new RedBlackTree().gt("1"); } - { const a: RedBlackTreeIterator = new RedBlackTree().lt("1"); } - { const a: RedBlackTreeIterator = new RedBlackTree().le("1"); } - { const a: RedBlackTreeIterator | null = new RedBlackTree().find("1"); } - { const a: RedBlackTree = new RedBlackTree().remove("1"); } - { const a: RedBlackTree = new RedBlackTree().remove("1"); } - { const a: number | undefined = new RedBlackTree().get("1"); } - } - - namespace arraySetTests { - const { ArraySet } = collection; - type ArraySet = adone.collection.ArraySet; - - new ArraySet(); - { const a: number = new ArraySet().length; } - { const a: ArraySet = new ArraySet().add("hello"); } - { const a: ArraySet = new ArraySet().add("hello", true); } - { const a: boolean = new ArraySet().has("string"); } - { const a: number = new ArraySet().indexOf("hello"); } - { const a: string[] = new ArraySet().toArray(); } - { const a: ArraySet = ArraySet.from([1]); } - { const a: ArraySet = ArraySet.from([1], true); } - } - - namespace bufferListTests { - const { BufferList } = collection; - type BufferList = adone.collection.BufferList; - - new BufferList(); - new BufferList(Buffer.from("123")); - new BufferList("123"); - new BufferList(123); - new BufferList([Buffer.from("123"), "123", 123]); - new BufferList((err: any, data: Buffer) => null); - new BufferList().append(Buffer.from("123")); - new BufferList().append("123"); - new BufferList().append(123); - new BufferList().append([Buffer.from("123"), "123", 123]); - new BufferList().end(Buffer.from("123")); - new BufferList().end(); - { const a: number = new BufferList().get(123); } - { const a: Buffer = new BufferList().slice(); } - { const a: Buffer = new BufferList().slice(1); } - { const a: Buffer = new BufferList().slice(1, 2); } - { const a: Buffer = new BufferList().copy(Buffer.alloc(100)); } - { const a: Buffer = new BufferList().copy(Buffer.alloc(100), 0); } - { const a: Buffer = new BufferList().copy(Buffer.alloc(100), 0, 1); } - { const a: Buffer = new BufferList().copy(Buffer.alloc(100), 0, 1, 2); } - { const a: BufferList = new BufferList().shallowSlice(); } - { const a: BufferList = new BufferList().shallowSlice(1); } - { const a: BufferList = new BufferList().shallowSlice(1, 2); } - { const a: string = new BufferList().toString(); } - { const a: string = new BufferList().toString("utf8"); } - { const a: string = new BufferList().toString("utf8", 1); } - { const a: string = new BufferList().toString("utf8", 1, 2); } - { const a: BufferList = new BufferList().consume(10); } - { const a: BufferList = new BufferList().duplicate(); } - new BufferList().destroy(); - new BufferList().then((x: Buffer) => null); - new BufferList().catch((err: any) => null); - } - - namespace defaultMapTests { - const { DefaultMap } = collection; - type DefaultMap = adone.collection.DefaultMap; - - new DefaultMap(); - { const a: DefaultMap = new DefaultMap(undefined, [["1", 2]]); } - { const a: DefaultMap = new DefaultMap((key: string) => 123); } - { const a: DefaultMap = new DefaultMap({ a: 123 }); } - } - - namespace lruTests { - const { LRU } = collection; - type LRU = adone.collection.LRU; - - new LRU(); - new LRU(100); - new LRU({}); - new LRU({ max: 100 }); - new LRU({ dispose: (key: string, value: number) => null }); - new LRU({ maxAge: 100 }); - new LRU({ noDisposeOnSet: false }); - new LRU({ stale: true }); - { const a: number = new LRU().max; } - { new LRU().max = 100; } - { const a: boolean = new LRU().allowStale; } - { new LRU().allowStale = false; } - { const a: number = new LRU().maxAge; } - { new LRU().maxAge = 100; } - { const a: (v: number, k: string) => number = new LRU().lengthCalculator; } - { new LRU().lengthCalculator = () => 123; } - { const a: number = new LRU().length; } - { const a: number = new LRU().itemCount; } - new LRU().rforEach((value: number, key: string) => null); - new LRU().rforEach(function (value: number, key: string) { - const b: number = this.a; - }, { a: 1 }); - new LRU().forEach((value: number, key: string) => null); - new LRU().forEach(function (value: number, key: string) { - const b: number = this.a; - }, { a: 1 }); - { const a: string[] = new LRU().keys(); } - { const a: number[] = new LRU().values(); } - new LRU().reset(); - { - const a: Array> = new LRU().dump(); - const [b] = a; - { const c: number = b.e; } - { const c: string = b.key; } - { const c: number = b.value; } - } - { - const a: adone.collection.LinkedList> = new LRU().dumpLru(); - const b = a.shift(); - if (b !== undefined) { - { const a: string = b.key; } - { const a: number = b.value; } - { const a: number = b.now; } - { const a: number = b.maxAge; } - } - } - { const a: string = new LRU().inspect(); } - { const a: string = new LRU().inspect({}); } - { const a: boolean = new LRU().set("asd", 13); } - { const a: boolean = new LRU().set("asd", 13, 100500); } - { const a: boolean = new LRU().has("asd"); } - { const a: number | undefined = new LRU().get("asd"); } - { const a: number | undefined = new LRU().peek("asd"); } - { const a: adone.collection.I.LRU.Entry = new LRU().pop(); } - new LRU().del("asd"); - new LRU().load(new LRU().dump()); - new LRU().prune(); - } - - namespace timedoutMapTests { - const { TimedoutMap } = collection; - type TimedoutMap = adone.collection.TimedoutMap; - - new TimedoutMap(); - new TimedoutMap(1000); - new TimedoutMap(1000, (key: string) => null); - { - const a: TimedoutMap = new TimedoutMap().forEach((value: number, key: string) => null); - } - { - const a: TimedoutMap = new TimedoutMap().forEach(function (value: number, key: string) { - const a: number = this.a; - }, { a: 1 }); - } - { const a: boolean = new TimedoutMap().delete("123"); } - } -} diff --git a/types/adone/test/glosses/collections/array_set.ts b/types/adone/test/glosses/collections/array_set.ts new file mode 100644 index 0000000000..49fd8582ce --- /dev/null +++ b/types/adone/test/glosses/collections/array_set.ts @@ -0,0 +1,19 @@ +namespace adoneTests.collection.ArraySet { + const { + collection: { + ArraySet + } + } = adone; + + type ArraySet = adone.collection.ArraySet; + + new ArraySet(); + { const a: number = new ArraySet().length; } + { const a: ArraySet = new ArraySet().add("hello"); } + { const a: ArraySet = new ArraySet().add("hello", true); } + { const a: boolean = new ArraySet().has("string"); } + { const a: number = new ArraySet().indexOf("hello"); } + { const a: string[] = new ArraySet().toArray(); } + { const a: ArraySet = ArraySet.from([1]); } + { const a: ArraySet = ArraySet.from([1], true); } +} diff --git a/types/adone/test/glosses/collections/async_queue.ts b/types/adone/test/glosses/collections/async_queue.ts new file mode 100644 index 0000000000..43374e6d3a --- /dev/null +++ b/types/adone/test/glosses/collections/async_queue.ts @@ -0,0 +1,12 @@ +namespace adoneTests.collection.AsyncQueue { + const { + collection: { + AsyncQueue + } + } = adone; + + type AsyncQueue = adone.collection.AsyncQueue; + + { const a: AsyncQueue = new AsyncQueue().push(123); } + { const a: Promise = new AsyncQueue().push(123).pop(); } +} diff --git a/types/adone/test/glosses/collections/avl_tree.ts b/types/adone/test/glosses/collections/avl_tree.ts new file mode 100644 index 0000000000..9c032deb2d --- /dev/null +++ b/types/adone/test/glosses/collections/avl_tree.ts @@ -0,0 +1,28 @@ +namespace adoneTests.collection.AVLTree { + const { + collection: { + AVLTree + } + } = adone; + + type AVLTree = adone.collection.AVLTree; + + new AVLTree(); + new AVLTree({ checkValueEquality: (a: number, b: number) => a === b }); + new AVLTree({ compareKeys: (a: string, b: string) => a.length - b.length }); + new AVLTree({ parent: new AVLTree() }); + new AVLTree({ unique: false }); + new AVLTree({ value: 123 }); + new AVLTree().checkIsAVLT(); + new AVLTree().insert("123", 123); + new AVLTree().delete("123"); + new AVLTree().delete("123", 123); + { const a: number = new AVLTree().getNumberOFKeys(); } + { const a: number[] = new AVLTree().search("key"); } + { const a: number[] = new AVLTree().betweenBounds({}); } + { const a: number[] = new AVLTree().betweenBounds({ $gt: "ads" }); } + { const a: number[] = new AVLTree().betweenBounds({ $lt: "ads" }); } + { const a: number[] = new AVLTree().betweenBounds({ $gte: "ads" }); } + { const a: number[] = new AVLTree().betweenBounds({ $lte: "ads" }); } + new AVLTree().executeOnEveryNode((tree: AVLTree) => null); +} diff --git a/types/adone/test/glosses/collections/binary_search_tree.ts b/types/adone/test/glosses/collections/binary_search_tree.ts new file mode 100644 index 0000000000..56f9a28e72 --- /dev/null +++ b/types/adone/test/glosses/collections/binary_search_tree.ts @@ -0,0 +1,36 @@ +namespace adoneTests.collection.BinarySearchTree { + const { + collection: { + BinarySearchTree + } + } = adone; + + type BinarySearchTree = adone.collection.BinarySearchTree; + + new BinarySearchTree(); + new BinarySearchTree({}); + new BinarySearchTree({ checkValueEquality: (a: number, b: number) => a === b }); + new BinarySearchTree({ compareKeys: (a: string, b: string) => a.length - b.length }); + new BinarySearchTree({ parent: new BinarySearchTree() }); + new BinarySearchTree({ unique: true }); + new BinarySearchTree({ value: 123 }); + { const a: BinarySearchTree = new BinarySearchTree().getMaxKeyDescendant(); } + { const a: string = new BinarySearchTree().getMaxKey(); } + { const a: BinarySearchTree = new BinarySearchTree().getMinKeyDescendant(); } + { const a: string = new BinarySearchTree().getMinKey(); } + new BinarySearchTree().checkAllNodesFullfillCondition((key: string, value: number) => null); + new BinarySearchTree().checkIsBST(); + { const a: number = new BinarySearchTree().getNumberOfKeys(); } + new BinarySearchTree().insert("asd", 123); + { const a: number[] = new BinarySearchTree().search("asd"); } + { const a: number[] = new BinarySearchTree().betweenBounds({ $gt: "" }); } + { const a: number[] = new BinarySearchTree().betweenBounds({ $lt: "" }); } + { const a: number[] = new BinarySearchTree().betweenBounds({ $lte: "" }); } + { const a: number[] = new BinarySearchTree().betweenBounds({ $gte: "" }); } + new BinarySearchTree().delete("key"); + new BinarySearchTree().delete("key", 123); + new BinarySearchTree().executeOnEveryNode((tree: BinarySearchTree) => null); + new BinarySearchTree().prettyPrint(); + new BinarySearchTree().prettyPrint(true); + new BinarySearchTree().prettyPrint(true, " "); +} diff --git a/types/adone/test/glosses/collections/buffer_list.ts b/types/adone/test/glosses/collections/buffer_list.ts new file mode 100644 index 0000000000..265d54033f --- /dev/null +++ b/types/adone/test/glosses/collections/buffer_list.ts @@ -0,0 +1,42 @@ +namespace adoneTests.collection.BufferList { + const { + collection: { + BufferList + } + } = adone; + + type BufferList = adone.collection.BufferList; + + new BufferList(); + new BufferList(Buffer.from("123")); + new BufferList("123"); + new BufferList(123); + new BufferList([Buffer.from("123"), "123", 123]); + new BufferList((err: any, data: Buffer) => null); + new BufferList().append(Buffer.from("123")); + new BufferList().append("123"); + new BufferList().append(123); + new BufferList().append([Buffer.from("123"), "123", 123]); + new BufferList().end(Buffer.from("123")); + new BufferList().end(); + { const a: number = new BufferList().get(123); } + { const a: Buffer = new BufferList().slice(); } + { const a: Buffer = new BufferList().slice(1); } + { const a: Buffer = new BufferList().slice(1, 2); } + { const a: Buffer = new BufferList().copy(Buffer.alloc(100)); } + { const a: Buffer = new BufferList().copy(Buffer.alloc(100), 0); } + { const a: Buffer = new BufferList().copy(Buffer.alloc(100), 0, 1); } + { const a: Buffer = new BufferList().copy(Buffer.alloc(100), 0, 1, 2); } + { const a: BufferList = new BufferList().shallowSlice(); } + { const a: BufferList = new BufferList().shallowSlice(1); } + { const a: BufferList = new BufferList().shallowSlice(1, 2); } + { const a: string = new BufferList().toString(); } + { const a: string = new BufferList().toString("utf8"); } + { const a: string = new BufferList().toString("utf8", 1); } + { const a: string = new BufferList().toString("utf8", 1, 2); } + { const a: BufferList = new BufferList().consume(10); } + { const a: BufferList = new BufferList().duplicate(); } + new BufferList().destroy(); + new BufferList().then((x: Buffer) => null); + new BufferList().catch((err: any) => null); +} diff --git a/types/adone/test/glosses/collections/byte_array.ts b/types/adone/test/glosses/collections/byte_array.ts new file mode 100644 index 0000000000..7254008322 --- /dev/null +++ b/types/adone/test/glosses/collections/byte_array.ts @@ -0,0 +1,561 @@ +namespace adoneTests.collection.ByteArray { + const { + collection: { + ByteArray + } + } = adone; + + new ByteArray(); + new ByteArray(10); + new ByteArray(10, true); + + const buffer = new ByteArray(); + + buffer.woffset === 2; + buffer.roffset === 3; + buffer.noAssert === true; + buffer.buffer.writeUInt8(0, 0); + + namespace readBitSet { + const a: boolean[] = buffer.readBitSet(); + const b: boolean[] = buffer.readBitSet(10); + } + + namespace read { + const a: adone.collection.ByteArray = buffer.read(1); + const b: adone.collection.ByteArray = buffer.read(1, 10); + } + + namespace readInt8 { + const a: number = buffer.readInt8(); + const b: number = buffer.readInt8(10); + } + + namespace readUInt8 { + const a: number = buffer.readUInt8(); + const b: number = buffer.readUInt8(10); + } + + namespace readInt16LE { + const a: number = buffer.readInt16LE(); + const b: number = buffer.readInt16LE(10); + } + + namespace readUInt16LE { + const a: number = buffer.readUInt16LE(); + const b: number = buffer.readUInt16LE(10); + } + + namespace readInt16BE { + const a: number = buffer.readInt16BE(); + const b: number = buffer.readInt16BE(10); + } + + namespace readUInt16BE { + const a: number = buffer.readUInt16BE(); + const b: number = buffer.readUInt16BE(10); + } + + namespace readInt32LE { + const a: number = buffer.readInt32LE(); + const b: number = buffer.readInt32LE(10); + } + + namespace readUInt32LE { + const a: number = buffer.readUInt32LE(); + const b: number = buffer.readUInt32LE(10); + } + + namespace readInt32BE { + const a: number = buffer.readInt32BE(); + const b: number = buffer.readInt32BE(10); + } + + namespace readUInt32BE { + const a: number = buffer.readUInt32BE(); + const b: number = buffer.readUInt32BE(10); + } + + namespace readInt64LE { + const a: adone.math.Long = buffer.readInt64LE(); + const b: adone.math.Long = buffer.readInt64LE(10); + } + + namespace readUInt64LE { + const a: adone.math.Long = buffer.readUInt64LE(); + const b: adone.math.Long = buffer.readUInt64LE(10); + } + + namespace readInt64BE { + const a: adone.math.Long = buffer.readInt64BE(); + const b: adone.math.Long = buffer.readInt64BE(10); + } + + namespace readUInt64BE { + const a: adone.math.Long = buffer.readUInt64BE(); + const b: adone.math.Long = buffer.readUInt64BE(10); + } + + namespace readFloatLE { + const a: number = buffer.readFloatLE(); + const b: number = buffer.readFloatLE(10); + } + + namespace readFloatBE { + const a: number = buffer.readFloatBE(); + const b: number = buffer.readFloatBE(10); + } + + namespace readDoubleLE { + const a: number = buffer.readDoubleLE(); + const b: number = buffer.readDoubleLE(10); + } + + namespace readDoubleBE { + const a: number = buffer.readDoubleBE(); + const b: number = buffer.readDoubleBE(10); + } + + namespace write { + const a: adone.collection.ByteArray = buffer.write("1"); + const b: adone.collection.ByteArray = buffer.write(new ByteArray()); + const c: adone.collection.ByteArray = buffer.write(Buffer.alloc(10)); + const d: adone.collection.ByteArray = buffer.write(new Uint8Array([1, 2, 3])); + const e: adone.collection.ByteArray = buffer.write(new ArrayBuffer(10)); + const f: adone.collection.ByteArray = buffer.write("1", 10); + const g: adone.collection.ByteArray = buffer.write("1", 10, 10); + const h: adone.collection.ByteArray = buffer.write("1", 10, 10, "utf8"); + } + + namespace writeBitSet { + const a: adone.collection.ByteArray = buffer.writeBitSet([1, 2, 3]); + const b: number = buffer.writeBitSet([1, 2, 3], 10); + } + + namespace writeInt8 { + const a: adone.collection.ByteArray = buffer.writeInt8(10); + const b: adone.collection.ByteArray = buffer.writeInt8(10, 10); + } + + namespace writeUInt8 { + const a: adone.collection.ByteArray = buffer.writeUInt8(10); + const b: adone.collection.ByteArray = buffer.writeUInt8(10, 10); + } + + namespace writeInt16LE { + const a: adone.collection.ByteArray = buffer.writeInt16LE(10); + const b: adone.collection.ByteArray = buffer.writeInt16LE(10, 10); + } + + namespace writeInt16BE { + const a: adone.collection.ByteArray = buffer.writeInt16BE(10); + const b: adone.collection.ByteArray = buffer.writeInt16BE(10, 10); + } + + namespace writeUInt16LE { + const a: adone.collection.ByteArray = buffer.writeUInt16LE(10); + const b: adone.collection.ByteArray = buffer.writeUInt16LE(10, 10); + } + + namespace writeUInt16BE { + const a: adone.collection.ByteArray = buffer.writeUInt16BE(10); + const b: adone.collection.ByteArray = buffer.writeUInt16BE(10, 10); + } + + namespace writeInt32LE { + const a: adone.collection.ByteArray = buffer.writeInt32LE(10); + const b: adone.collection.ByteArray = buffer.writeInt32LE(10, 10); + } + + namespace writeInt32BE { + const a: adone.collection.ByteArray = buffer.writeInt32BE(10); + const b: adone.collection.ByteArray = buffer.writeInt32BE(10, 10); + } + + namespace writeUInt32LE { + const a: adone.collection.ByteArray = buffer.writeUInt32LE(10); + const b: adone.collection.ByteArray = buffer.writeUInt32LE(10, 10); + } + + namespace writeUInt32BE { + const a: adone.collection.ByteArray = buffer.writeUInt32BE(10); + const b: adone.collection.ByteArray = buffer.writeUInt32BE(10, 10); + } + + namespace writeInt64LE { + const a: adone.collection.ByteArray = buffer.writeInt64LE(10); + const b: adone.collection.ByteArray = buffer.writeInt64LE(10, 10); + } + + namespace writeInt64BE { + const a: adone.collection.ByteArray = buffer.writeInt64BE(10); + const b: adone.collection.ByteArray = buffer.writeInt64BE(10, 10); + } + + namespace writeUInt64LE { + const a: adone.collection.ByteArray = buffer.writeUInt64LE(10); + const b: adone.collection.ByteArray = buffer.writeUInt64LE(10, 10); + } + + namespace writeUInt64BE { + const a: adone.collection.ByteArray = buffer.writeUInt64BE(10); + const b: adone.collection.ByteArray = buffer.writeUInt64BE(10, 10); + } + + namespace writeFloatLE { + const a: adone.collection.ByteArray = buffer.writeFloatLE(10); + const b: adone.collection.ByteArray = buffer.writeFloatLE(10, 10); + } + + namespace writeFloatBE { + const a: adone.collection.ByteArray = buffer.writeFloatBE(10); + const b: adone.collection.ByteArray = buffer.writeFloatBE(10, 10); + } + + namespace writeDoubleLE { + const a: adone.collection.ByteArray = buffer.writeDoubleLE(10); + const b: adone.collection.ByteArray = buffer.writeDoubleLE(10, 10); + } + + namespace writeDoubleBE { + const a: adone.collection.ByteArray = buffer.writeDoubleBE(10); + const b: adone.collection.ByteArray = buffer.writeDoubleBE(10, 10); + } + + namespace writeVarInt32 { + const a: adone.collection.ByteArray = buffer.writeVarint32(10); + const b: number = buffer.writeVarint32(10, 10); + } + + namespace writeVarInt32ZigZag { + const a: adone.collection.ByteArray = buffer.writeVarint32ZigZag(10); + const b: number = buffer.writeVarint32ZigZag(10, 10); + } + + namespace readVarint32 { + const a: number = buffer.readVarint32(); + const b: { value: number, length: number } = buffer.readVarint32(10); + } + + namespace readVarint32ZigZag { + const a: number = buffer.readVarint32ZigZag(); + const b: { value: number, length: number } = buffer.readVarint32ZigZag(10); + } + + namespace writeVarint64 { + const a: adone.collection.ByteArray = buffer.writeVarint64(10); + const b: number = buffer.writeVarint64(10, 10); + } + + namespace writeVarint64ZigZag { + const a: adone.collection.ByteArray = buffer.writeVarint64ZigZag(10); + const b: number = buffer.writeVarint64ZigZag(10, 10); + } + + namespace readVarint64 { + const a: adone.math.Long = buffer.readVarint64(); + const b: { value: adone.math.Long, length: number } = buffer.readVarint64(10); + } + + namespace readVarint64ZigZag { + const a: adone.math.Long = buffer.readVarint64ZigZag(); + const b: { value: adone.math.Long, length: number } = buffer.readVarint64ZigZag(10); + } + + namespace writeCString { + const a: adone.collection.ByteArray = buffer.writeCString("asd"); + const b: number = buffer.writeCString("123", 10); + } + + namespace readCString { + const a: string = buffer.readCString(); + const b: { string: string, length: number } = buffer.readCString(10); + } + + namespace writeString { + const a: adone.collection.ByteArray = buffer.writeString("abc"); + const b: number = buffer.writeString("abc", 10); + } + + namespace readString { + const a: string = buffer.readString(10); + const b: string = buffer.readString(10, "b"); + const c: string = buffer.readString(10, "c"); + const d: { string: string, length: number } = buffer.readString(10, "c", 10); + } + + namespace writeVString { + const a: adone.collection.ByteArray = buffer.writeVString("abc"); + const b: number = buffer.writeVString("abc", 10); + } + + namespace readVString { + const a: string = buffer.readVString(); + const b: { string: string, length: number } = buffer.readVString(10); + } + + namespace appendTo { + const a: adone.collection.ByteArray = buffer.appendTo(new ByteArray()); + const b: adone.collection.ByteArray = buffer.appendTo(new ByteArray(), 10); + } + + namespace assert { + const a: adone.collection.ByteArray = buffer.assert(); + const b: adone.collection.ByteArray = buffer.assert(true); + } + + namespace capacity { + const a: number = buffer.capacity(); + } + + namespace clear { + const a: adone.collection.ByteArray = buffer.clear(); + } + + namespace copy { + const a: adone.collection.ByteArray = buffer.clone(); + const c: adone.collection.ByteArray = buffer.clone(true); + } + + namespace compact { + const a: adone.collection.ByteArray = buffer.compact(); + const b: adone.collection.ByteArray = buffer.compact(1); + const c: adone.collection.ByteArray = buffer.compact(1, 10); + } + + namespace copyTo { + const a: adone.collection.ByteArray = buffer.copyTo(new ByteArray()); + const b: adone.collection.ByteArray = buffer.copyTo(new ByteArray(), 0); + const c: adone.collection.ByteArray = buffer.copyTo(new ByteArray(), 0, 0); + const d: adone.collection.ByteArray = buffer.copyTo(new ByteArray(), 0, 0, 10); + } + + namespace ensureCapacity { + const a: adone.collection.ByteArray = buffer.ensureCapacity(10); + } + + namespace fill { + const a: adone.collection.ByteArray = buffer.fill("0"); + const b: adone.collection.ByteArray = buffer.fill(0); + const c: adone.collection.ByteArray = buffer.fill(0, 0); + const d: adone.collection.ByteArray = buffer.fill(0, 0, 10); + } + + namespace flip { + const a: adone.collection.ByteArray = buffer.flip(); + } + + namespace mark { + const a: adone.collection.ByteArray = buffer.mark(); + const b: adone.collection.ByteArray = buffer.mark(10); + } + + namespace prepend { + const a: adone.collection.ByteArray = buffer.prepend(""); + const b: adone.collection.ByteArray = buffer.prepend(new ByteArray()); + const c: adone.collection.ByteArray = buffer.prepend(Buffer.alloc(10)); + const d: adone.collection.ByteArray = buffer.prepend(new Uint8Array([1, 2, 3])); + const e: adone.collection.ByteArray = buffer.prepend(new ArrayBuffer(10)); + const f: adone.collection.ByteArray = buffer.prepend("", "utf8"); + const g: adone.collection.ByteArray = buffer.prepend("", "utf8", 10); + const h: adone.collection.ByteArray = buffer.prepend("", 10); + } + + namespace prependTo { + const a: adone.collection.ByteArray = buffer.prependTo(new ByteArray()); + const b: adone.collection.ByteArray = buffer.prependTo(new ByteArray(), 10); + } + + namespace remaining { + const a: number = buffer.remaining(); + } + + namespace reset { + const a: adone.collection.ByteArray = buffer.reset(); + } + + namespace resize { + const a: adone.collection.ByteArray = buffer.resize(10); + } + + namespace reverse { + const a: adone.collection.ByteArray = buffer.reverse(); + const b: adone.collection.ByteArray = buffer.reverse(1); + const c: adone.collection.ByteArray = buffer.reverse(1, 10); + } + + namespace skip { + const a: adone.collection.ByteArray = buffer.skip(10); + } + + namespace slice { + const a: adone.collection.ByteArray = buffer.slice(); + const b: adone.collection.ByteArray = buffer.slice(1); + const c: adone.collection.ByteArray = buffer.slice(1, 10); + } + + namespace toBuffer { + const a: Buffer = buffer.toBuffer(); + const b: Buffer = buffer.toBuffer(true); + const c: Buffer = buffer.toBuffer(true, 0); + const d: Buffer = buffer.toBuffer(true, 0, 10); + } + + namespace toArrayBuffer { + const a: ArrayBuffer = buffer.toArrayBuffer(); + } + + namespace toString { + const a: string = buffer.toString(); + const b: string = buffer.toString("utf8"); + const c: string = buffer.toString("utf8", 0); + const d: string = buffer.toString("utf8", 0, 10); + } + + namespace toBase64 { + const a: string = buffer.toBase64(); + const b: string = buffer.toBase64(0); + const c: string = buffer.toBase64(0, 10); + } + + namespace toBinary { + const a: string = buffer.toBinary(); + const b: string = buffer.toBinary(0); + const c: string = buffer.toBinary(0, 10); + } + + namespace toDebug { + const a: string = buffer.toDebug(); + const b: string = buffer.toDebug(true); + } + + namespace toUTF8 { + const a: string = buffer.toUTF8(); + const b: string = buffer.toUTF8(0); + const c: string = buffer.toUTF8(0, 10); + } + + namespace static { + namespace accessor { + const a: typeof Buffer = ByteArray.accessor(); + } + + namespace allocate { + const a: adone.collection.ByteArray = ByteArray.allocate(); + const b: adone.collection.ByteArray = ByteArray.allocate(10); + const c: adone.collection.ByteArray = ByteArray.allocate(10, true); + } + + namespace concat { + const a: adone.collection.ByteArray = ByteArray.concat([ + new ByteArray(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ]); + const b: adone.collection.ByteArray = ByteArray.concat([ + new ByteArray(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ], "utf8"); + const c: adone.collection.ByteArray = ByteArray.concat([ + new ByteArray(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ], "utf8", true); + } + + namespace type { + const a: typeof Buffer = ByteArray.type(); + } + + namespace wrap { + const a: adone.collection.ByteArray = ByteArray.wrap(""); + const b: adone.collection.ByteArray = ByteArray.wrap(new ByteArray()); + const c: adone.collection.ByteArray = ByteArray.wrap(Buffer.alloc(10)); + const d: adone.collection.ByteArray = ByteArray.wrap(new Uint8Array([1, 2, 3])); + const e: adone.collection.ByteArray = ByteArray.wrap(new ArrayBuffer(10)); + const f: adone.collection.ByteArray = ByteArray.wrap("", "utf8"); + const g: adone.collection.ByteArray = ByteArray.wrap("", "utf8", true); + } + + namespace calculateVarint32 { + const a: number = ByteArray.calculateVarint32(10); + } + + namespace zigZagEncode32 { + const a: number = ByteArray.zigZagEncode32(10); + } + + namespace zigZagDecode32 { + const a: number = ByteArray.zigZagDecode32(10); + } + + namespace calculateVarint64 { + const a: number = ByteArray.calculateVarint64(10); + const b: number = ByteArray.calculateVarint64("10"); + } + + namespace zigZagEncode64 { + const a: adone.math.Long = ByteArray.zigZagEncode64(10); + const b: adone.math.Long = ByteArray.zigZagEncode64("10"); + const c: adone.math.Long = ByteArray.zigZagEncode64(adone.math.Long.fromValue(10)); + } + + namespace zigZagDecode64 { + const a: adone.math.Long = ByteArray.zigZagDecode64(10); + const b: adone.math.Long = ByteArray.zigZagDecode64("10"); + const c: adone.math.Long = ByteArray.zigZagDecode64(adone.math.Long.fromValue(10)); + } + + namespace calculateUTF8Chars { + const a: number = ByteArray.calculateUTF8Chars("123"); + } + + namespace calculateString { + const a: number = ByteArray.calculateString("123"); + } + + namespace fromBase64 { + const a: adone.collection.ByteArray = ByteArray.fromBase64("123"); + } + + namespace btoa { + const a: string = ByteArray.btoa("123"); + } + + namespace atob { + const a: string = ByteArray.atob("123"); + } + + namespace fromBinary { + const a: adone.collection.ByteArray = ByteArray.fromBinary("123"); + } + + namespace fromDebug { + const a: adone.collection.ByteArray = ByteArray.fromDebug("12"); + const b: adone.collection.ByteArray = ByteArray.fromDebug("12", true); + } + + namespace fromHex { + const a: adone.collection.ByteArray = ByteArray.fromHex("192"); + const b: adone.collection.ByteArray = ByteArray.fromHex("192", true); + } + + namespace fromUTF8 { + const a: adone.collection.ByteArray = ByteArray.fromUTF8("123"); + const b: adone.collection.ByteArray = ByteArray.fromUTF8("123", true); + } + + namespace constants { + const a: number = ByteArray.DEFAULT_CAPACITY; + const b: boolean = ByteArray.DEFAULT_NOASSERT; + const c: number = ByteArray.MAX_VARINT32_BYTES; + const d: number = ByteArray.MAX_VARINT64_BYTES; + const e: string = ByteArray.METRICS_CHARS; + const f: string = ByteArray.METRICS_BYTES; + } + } +} diff --git a/types/adone/test/glosses/collections/default_map.ts b/types/adone/test/glosses/collections/default_map.ts new file mode 100644 index 0000000000..1273b91982 --- /dev/null +++ b/types/adone/test/glosses/collections/default_map.ts @@ -0,0 +1,14 @@ +namespace adoneTests.collection.DefaultMap { + const { + collection: { + DefaultMap + } + } = adone; + + type DefaultMap = adone.collection.DefaultMap; + + new DefaultMap(); + { const a: DefaultMap = new DefaultMap(undefined, [["1", 2]]); } + { const a: DefaultMap = new DefaultMap((key: string) => 123); } + { const a: DefaultMap = new DefaultMap({ a: 123 }); } +} diff --git a/types/adone/test/glosses/collections/fast_lru.ts b/types/adone/test/glosses/collections/fast_lru.ts new file mode 100644 index 0000000000..0e61f51dc5 --- /dev/null +++ b/types/adone/test/glosses/collections/fast_lru.ts @@ -0,0 +1,21 @@ +namespace adoneTests.collection.FastLRU { + const { + collection: { + FastLRU + } + } = adone; + + new FastLRU(); + new FastLRU(100); + new FastLRU(100, { dispose: (key: string, value: number) => null }); + { const a: number = new FastLRU().size; } + { const a: number | undefined = new FastLRU().get("key"); } + new FastLRU().set("key", 123); + { const a: boolean = new FastLRU().delete("key"); } + { const a: boolean = new FastLRU().has("key"); } + { const a: string[] = [...new FastLRU().keys()]; } + { const a: number[] = [...new FastLRU().values()]; } + { const a: number[] = [...new FastLRU().values()]; } + { const a: Array<[string, number]> = [...new FastLRU().entries()]; } + new FastLRU().clear(); +} diff --git a/types/adone/test/glosses/collections/linked_list.ts b/types/adone/test/glosses/collections/linked_list.ts new file mode 100644 index 0000000000..f64a32c1aa --- /dev/null +++ b/types/adone/test/glosses/collections/linked_list.ts @@ -0,0 +1,123 @@ +namespace adoneTests.collection.LinkedList { + const { + collection: { + LinkedList + } + } = adone; + + namespace creation { + new LinkedList(); + new LinkedList(10); + } + + namespace properties { + { const a: boolean = new LinkedList().full; } + { const a: boolean = new LinkedList().empty; } + { const a: number = new LinkedList().maxLength; } + { const a: number = new LinkedList().length; } + { const a: boolean = new LinkedList().autoresize; } + } + + namespace resize { + { const a: boolean = new LinkedList().resize(100).full; } + } + + namespace push { + const a = new LinkedList().push(10); + a.next; + a.prev; + const b: number = a.value; + } + + namespace pop { + const a: number | undefined = new LinkedList().pop(); + } + + namespace shift { + const a: number | undefined = new LinkedList().shift(); + } + + namespace unshift { + const a = new LinkedList().unshift("hello"); + a.next; + a.prev; + const b: string = a.value; + } + + namespace pushNode { + const a = new LinkedList(); + const node = a.push("1230"); + a.pushNode(node); + } + + namespace unshiftNode { + const a = new LinkedList(); + const node = a.push(10); + a.unshiftNode(node); + } + + namespace removeNode { + const a = new LinkedList(); + const node = a.unshift("10"); + a.removeNode(node); + } + + namespace clear { + new LinkedList().clear(); + new LinkedList().clear(true); + } + + namespace toArray { + const a = new LinkedList(); + const b: number[] = a.toArray(); + } + + namespace front { + const a = new LinkedList(); + const b: number = a.front; + } + + namespace back { + const a = new LinkedList(); + const b: number = a.back; + } + + namespace iterating { + const a = new LinkedList(); + for (const b of a) { + const i: string = b; + } + const c = new LinkedList(); + for (const b of c) { + const i: number = b; + } + } + + namespace nextNode { + const a = new LinkedList(); + const n1 = a.push("h"); + const n2 = a.nextNode(n1); + n1.next; + n1.prev; + const t: string = n1.value; + } + + namespace map { + const a = new LinkedList(); + const f = (a: number, idx: number) => `${a}${idx}`; + const b = a.map(f); + const c: string = b.front; + } + + namespace forEach { + const a = new LinkedList(); + + a.forEach((a: number, b: number) => { + const c = a + b; + }); + } + + namespace static { + const a: number = LinkedList.DEFAULT_LENGTH; + } +} diff --git a/types/adone/test/glosses/collections/lru.ts b/types/adone/test/glosses/collections/lru.ts new file mode 100644 index 0000000000..934e5a1fbf --- /dev/null +++ b/types/adone/test/glosses/collections/lru.ts @@ -0,0 +1,67 @@ +namespace adoneTests.collection.LRU { + const { + collection: { + LRU + } + } = adone; + + type LRU = adone.collection.LRU; + + new LRU(); + new LRU(100); + new LRU({}); + new LRU({ max: 100 }); + new LRU({ dispose: (key: string, value: number) => null }); + new LRU({ maxAge: 100 }); + new LRU({ noDisposeOnSet: false }); + new LRU({ stale: true }); + { const a: number = new LRU().max; } + { new LRU().max = 100; } + { const a: boolean = new LRU().allowStale; } + { new LRU().allowStale = false; } + { const a: number = new LRU().maxAge; } + { new LRU().maxAge = 100; } + { const a: (v: number, k: string) => number = new LRU().lengthCalculator; } + { new LRU().lengthCalculator = () => 123; } + { const a: number = new LRU().length; } + { const a: number = new LRU().itemCount; } + new LRU().rforEach((value: number, key: string) => null); + new LRU().rforEach(function (value: number, key: string) { + const b: number = this.a; + }, { a: 1 }); + new LRU().forEach((value: number, key: string) => null); + new LRU().forEach(function (value: number, key: string) { + const b: number = this.a; + }, { a: 1 }); + { const a: string[] = new LRU().keys(); } + { const a: number[] = new LRU().values(); } + new LRU().reset(); + { + const a: Array> = new LRU().dump(); + const [b] = a; + { const c: number = b.e; } + { const c: string = b.key; } + { const c: number = b.value; } + } + { + const a: adone.collection.LinkedList> = new LRU().dumpLru(); + const b = a.shift(); + if (b !== undefined) { + { const a: string = b.key; } + { const a: number = b.value; } + { const a: number = b.now; } + { const a: number = b.maxAge; } + } + } + { const a: string = new LRU().inspect(); } + { const a: string = new LRU().inspect({}); } + { const a: boolean = new LRU().set("asd", 13); } + { const a: boolean = new LRU().set("asd", 13, 100500); } + { const a: boolean = new LRU().has("asd"); } + { const a: number | undefined = new LRU().get("asd"); } + { const a: number | undefined = new LRU().peek("asd"); } + { const a: adone.collection.I.LRU.Entry = new LRU().pop(); } + new LRU().del("asd"); + new LRU().load(new LRU().dump()); + new LRU().prune(); +} diff --git a/types/adone/test/glosses/collections/map_cache.ts b/types/adone/test/glosses/collections/map_cache.ts new file mode 100644 index 0000000000..bcd0ffb887 --- /dev/null +++ b/types/adone/test/glosses/collections/map_cache.ts @@ -0,0 +1,21 @@ +namespace adoneTests.collection.MapCache { + const { + collection: { + MapCache + } + } = adone; + + new MapCache(); + + new MapCache().has("hello"); + new MapCache().get("hello"); + new MapCache().set("hello", "world"); + new MapCache().delete("hello"); + new MapCache().clear(); + + { + const a = new MapCache(); + a.set("a", "b"); + a.get("a").charCodeAt(20); + } +} diff --git a/types/adone/test/glosses/collections/ns_cache.ts b/types/adone/test/glosses/collections/ns_cache.ts new file mode 100644 index 0000000000..a8e8c14397 --- /dev/null +++ b/types/adone/test/glosses/collections/ns_cache.ts @@ -0,0 +1,21 @@ +namespace adoneTests.collection.NSCache { + const { + collection: { + NSCache + } + } = adone; + + new NSCache(10, ["a", "b", "c"]); + new NSCache(10, ["a", "b", "c"]).resize(100); + new NSCache(10, ["a", "b", "c"]).set("a", "b", "c"); + new NSCache(10, ["a", "b", "c"]).get("a", "b"); + new NSCache(10, ["a", "b", "c"]).has("a", "b"); + new NSCache(10, ["a", "b", "c"]).delete("a", "b"); + new NSCache(10, ["a", "b", "c"]).clear(); + + { + const a = new NSCache(10, ["a", "b", "c"]); + a.set("a", "b", "c"); + a.get("a", "b").charCodeAt(100); + } +} diff --git a/types/adone/test/glosses/collections/priority_queue.ts b/types/adone/test/glosses/collections/priority_queue.ts new file mode 100644 index 0000000000..950e7394e7 --- /dev/null +++ b/types/adone/test/glosses/collections/priority_queue.ts @@ -0,0 +1,36 @@ +namespace adoneTests.collection.PriorityQueue { + const { + collection: { + PriorityQueue + } + } = adone; + + type PriorityQueue = adone.collection.PriorityQueue; + + { const a: boolean = new PriorityQueue().empty; } + { const a: number = new PriorityQueue().length; } + new PriorityQueue(); + new PriorityQueue({}); + new PriorityQueue({ + compare(a: number, b: number) { + return a - b; + } + }); + new PriorityQueue({ + priority(a: string, b: string) { + return a.length - b.length; + } + }); + { const a: PriorityQueue = new PriorityQueue().clone(); } + { const a: PriorityQueue = new PriorityQueue().push("123"); } + { const a: string | undefined = new PriorityQueue().pop(); } + { const a: PriorityQueue = new PriorityQueue().delete("123"); } + { const a: PriorityQueue = new PriorityQueue().delete("123"); } + { const a: string = new PriorityQueue().replace("123"); } + { const a: string = new PriorityQueue().pushpop("123"); } + { const a: string[] = new PriorityQueue().toArray(); } + { const a: PriorityQueue = PriorityQueue.from(["1"]); } + { const a: PriorityQueue = PriorityQueue.from(["1"], {}); } + { const a: PriorityQueue = PriorityQueue.from(["1"], { compare: (a: string, b: string) => a.length - b.length }); } + { const a: PriorityQueue = PriorityQueue.from(["1"], { priority: (a: string, b: string) => a.length - b.length }); } +} diff --git a/types/adone/test/glosses/collections/queue.ts b/types/adone/test/glosses/collections/queue.ts new file mode 100644 index 0000000000..2aefee9716 --- /dev/null +++ b/types/adone/test/glosses/collections/queue.ts @@ -0,0 +1,28 @@ +namespace adoneTests.collection.Queue { + const { + collection: { + Queue + } + } = adone; + + type Queue = adone.collection.Queue; + + new Queue(); + { const a: Queue = new Queue().push(123).push(123); } + { const a: number | undefined = new Queue().push(123).pop(); } + { const a: string | undefined = new Queue().push(123).pop(); } + { const a: boolean = new Queue().full; } + { const a: number = new Queue().length; } + { const a: boolean = new Queue().empty; } + + { + const q = Queue.from([1, 2, 3]); + const a: number | undefined = q.pop(); + } + { + const q = Queue.from((function*() { + yield 42; + })()); + const a: number | undefined = q.pop(); + } +} diff --git a/types/adone/test/glosses/collections/rb_tree.ts b/types/adone/test/glosses/collections/rb_tree.ts new file mode 100644 index 0000000000..1b624284f6 --- /dev/null +++ b/types/adone/test/glosses/collections/rb_tree.ts @@ -0,0 +1,48 @@ +namespace adoneTests.collection.RedBlackTree { + const { + collection: { + RedBlackTree + } + } = adone; + + type RedBlackTree = adone.collection.RedBlackTree; + type RedBlackTreeIterator = adone.collection.I.RedBlackTree.Iterator; + type RedBlackTreeNode = adone.collection.I.RedBlackTree.Node; + + new RedBlackTree(); + new RedBlackTree((a: string, b: string) => a.length - b.length); + new RedBlackTree(undefined, new RedBlackTree()); + { const a: string[] = new RedBlackTree().keys; } + { const a: number[] = new RedBlackTree().values; } + { const a: number = new RedBlackTree().length; } + { + const a: RedBlackTreeIterator = new RedBlackTree().begin; + { const b: boolean = a.valid; } + { const b: RedBlackTreeNode | null = a.node; } + { const b: string | undefined = a.key; } + { const b: number | undefined = a.value; } + { const b: number = a.index; } + { const b: boolean = a.hasNext; } + { const b: boolean = a.hasPrev; } + { const b: RedBlackTree = a.tree; } + { const b: RedBlackTreeIterator = a.clone(); } + { const b: RedBlackTree = a.remove(); } + a.next(); + { const b: RedBlackTree = a.update(333); } + a.prev(); + } + { const a: RedBlackTreeIterator = new RedBlackTree().end; } + { const a: RedBlackTree = new RedBlackTree().insert("123", 456); } + { const a: number = new RedBlackTree().forEach((key: string, value: number) => value); } + { const a: number = new RedBlackTree().forEach((key: string, value: number) => value, "1"); } + { const a: number = new RedBlackTree().forEach((key: string, value: number) => value, "1", "2"); } + { const a: RedBlackTreeIterator = new RedBlackTree().at(1); } + { const a: RedBlackTreeIterator = new RedBlackTree().ge("1"); } + { const a: RedBlackTreeIterator = new RedBlackTree().gt("1"); } + { const a: RedBlackTreeIterator = new RedBlackTree().lt("1"); } + { const a: RedBlackTreeIterator = new RedBlackTree().le("1"); } + { const a: RedBlackTreeIterator | null = new RedBlackTree().find("1"); } + { const a: RedBlackTree = new RedBlackTree().remove("1"); } + { const a: RedBlackTree = new RedBlackTree().remove("1"); } + { const a: number | undefined = new RedBlackTree().get("1"); } +} diff --git a/types/adone/test/glosses/collections/refcounted_cache.ts b/types/adone/test/glosses/collections/refcounted_cache.ts new file mode 100644 index 0000000000..6262d57d60 --- /dev/null +++ b/types/adone/test/glosses/collections/refcounted_cache.ts @@ -0,0 +1,17 @@ +namespace adoneTests.collection.RefcountedCache { + const { + collection: { + RefcountedCache + } + } = adone; + + new RefcountedCache(); + new RefcountedCache().ref("a"); + new RefcountedCache().unref("a"); + new RefcountedCache().references("a") === 5; + + { + const a = new RefcountedCache(); + a.get("b").charCodeAt(100); + } +} diff --git a/types/adone/test/glosses/collections/set.ts b/types/adone/test/glosses/collections/set.ts new file mode 100644 index 0000000000..2e2314956e --- /dev/null +++ b/types/adone/test/glosses/collections/set.ts @@ -0,0 +1,26 @@ +namespace adoneTests.collection.Set { + const { + collection: { + Set + } + } = adone; + + new Set().add("a"); + new Set().has("a"); + new Set().delete("a"); + new Set().get("a"); + new Set().has("a") === true; + new Set().only(); + new Set().size === 5; + + { + const a = new Set(); + + a.add(1); + a.has(2); + a.delete(2); + a.get(2); // ??? + a.only() === 5; + a.size === 5; + } +} diff --git a/types/adone/test/glosses/collections/stack.ts b/types/adone/test/glosses/collections/stack.ts new file mode 100644 index 0000000000..df13f82f8e --- /dev/null +++ b/types/adone/test/glosses/collections/stack.ts @@ -0,0 +1,16 @@ +namespace adoneTests.collection.Stack { + const { + collection: { + Stack + } + } = adone; + + type Stack = adone.collection.Stack; + + { const a: boolean = new Stack().empty; } + { const a: number = new Stack().top; } + { const a: Stack = new Stack().push(123); } + { const a: number | undefined = new Stack().pop(); } + { const a: number[] = [...new Stack()]; } + { const a: Stack = Stack.from([1, 2, 3]); } +} diff --git a/types/adone/test/glosses/collections/timedout_map.ts b/types/adone/test/glosses/collections/timedout_map.ts new file mode 100644 index 0000000000..ffca754e2a --- /dev/null +++ b/types/adone/test/glosses/collections/timedout_map.ts @@ -0,0 +1,22 @@ +namespace adoneTests.collection.TimedoutMap { + const { + collection: { + TimedoutMap + } + } = adone; + + type TimedoutMap = adone.collection.TimedoutMap; + + new TimedoutMap(); + new TimedoutMap(1000); + new TimedoutMap(1000, (key: string) => null); + { + const a: TimedoutMap = new TimedoutMap().forEach((value: number, key: string) => null); + } + { + const a: TimedoutMap = new TimedoutMap().forEach(function (value: number, key: string) { + const a: number = this.a; + }, { a: 1 }); + } + { const a: boolean = new TimedoutMap().delete("123"); } +} diff --git a/types/adone/test/glosses/crypto/asn1.ts b/types/adone/test/glosses/crypto/asn1.ts new file mode 100644 index 0000000000..447c71c34e --- /dev/null +++ b/types/adone/test/glosses/crypto/asn1.ts @@ -0,0 +1,3183 @@ +namespace adoneTests.crypto.asn1 { + const { + crypto: { + asn1 + } + } = adone; + + let arrBuf: ArrayBuffer; + let num: number; + let bool: boolean; + let str: string; + let date: Date; + + namespace BaseBlock { + const { + BaseBlock + } = asn1; + + new BaseBlock({ + blockLength: 10 + }); + new BaseBlock({ + error: "a" + }); + new BaseBlock({ + name: "a" + }); + new BaseBlock({ + optional: true + }); + new BaseBlock({ + primitiveSchema: {} + }); + new BaseBlock({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new BaseBlock({ + warnings: ["a"] + }); + + const b = new BaseBlock(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + } + + str = b.warnings[0]; + } + + namespace Primitive { + const { + Primitive + } = asn1; + + new Primitive({ + blockLength: 10 + }); + new Primitive({ + error: "a" + }); + new Primitive({ + name: "a" + }); + new Primitive({ + optional: true + }); + new Primitive({ + primitiveSchema: {} + }); + new Primitive({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new Primitive({ + warnings: ["a"] + }); + + const b = new Primitive(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + } + + str = b.warnings[0]; + } + + namespace Constructed { + const { + Constructed + } = asn1; + + new Constructed({ + blockLength: 10 + }); + new Constructed({ + error: "a" + }); + new Constructed({ + name: "a" + }); + new Constructed({ + optional: true + }); + new Constructed({ + primitiveSchema: {} + }); + new Constructed({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new Constructed({ + warnings: ["a"] + }); + + const b = new Constructed(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + bool = b.valueBlock.isIndefiniteForm; + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + } + + str = b.warnings[0]; + } + + namespace EndOfContent { + const { + EndOfContent + } = asn1; + + new EndOfContent({ + blockLength: 10 + }); + new EndOfContent({ + error: "a" + }); + new EndOfContent({ + name: "a" + }); + new EndOfContent({ + optional: true + }); + new EndOfContent({ + primitiveSchema: {} + }); + new EndOfContent({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new EndOfContent({ + warnings: ["a"] + }); + + const b = new EndOfContent(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + } + + str = b.warnings[0]; + } + + namespace Boolean { + const { + Boolean: _Boolean + } = asn1; + + new _Boolean({ + blockLength: 10 + }); + new _Boolean({ + error: "a" + }); + new _Boolean({ + name: "a" + }); + new _Boolean({ + optional: true + }); + new _Boolean({ + primitiveSchema: {} + }); + new _Boolean({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new _Boolean({ + warnings: ["a"] + }); + + const b = new _Boolean(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + } + + str = b.warnings[0]; + } + + namespace Sequence { + const { + Sequence + } = asn1; + + new Sequence({ + blockLength: 10 + }); + new Sequence({ + error: "a" + }); + new Sequence({ + name: "a" + }); + new Sequence({ + optional: true + }); + new Sequence({ + primitiveSchema: {} + }); + new Sequence({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new Sequence({ + warnings: ["a"] + }); + + const b = new Sequence(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + bool = b.valueBlock.isIndefiniteForm; + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + } + + str = b.warnings[0]; + } + + namespace Set { + const { + Set + } = asn1; + + new Set({ + blockLength: 10 + }); + new Set({ + error: "a" + }); + new Set({ + name: "a" + }); + new Set({ + optional: true + }); + new Set({ + primitiveSchema: {} + }); + new Set({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new Set({ + warnings: ["a"] + }); + + const b = new Set(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + bool = b.valueBlock.isIndefiniteForm; + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + } + + str = b.warnings[0]; + } + + namespace Null { + const { + Null: Null + } = asn1; + + new Null({ + blockLength: 10 + }); + new Null({ + error: "a" + }); + new Null({ + name: "a" + }); + new Null({ + optional: true + }); + new Null({ + primitiveSchema: {} + }); + new Null({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new Null({ + warnings: ["a"] + }); + + const b = new Null(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + } + + str = b.warnings[0]; + } + + namespace OctetString { + const { + OctetString + } = asn1; + + new OctetString({ + blockLength: 10 + }); + new OctetString({ + error: "a" + }); + new OctetString({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new OctetString({ + warnings: ["a"] + }); + + const b = new OctetString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + bool = b.valueBlock.isConstructed; + bool = b.valueBlock.isHexOnly; + bool = b.valueBlock.isIndefiniteForm; + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + const [v] = b.valueBlock.value; + num = v.blockLength; + str = v.error; + v.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = v.toBER(); + { + const j = v.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = v.valueBeforeDecode; + str = v.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace BitString { + const { + BitString + } = asn1; + + new BitString({ + blockLength: 10 + }); + new BitString({ + error: "a" + }); + new BitString({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new BitString({ + warnings: ["a"] + }); + + const b = new BitString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + bool = b.valueBlock.isConstructed; + bool = b.valueBlock.isHexOnly; + bool = b.valueBlock.isIndefiniteForm; + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + const [v] = b.valueBlock.value; + num = v.blockLength; + str = v.error; + v.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = v.toBER(); + { + const j = v.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = v.valueBeforeDecode; + str = v.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace Integer { + const { + Integer + } = asn1; + + new Integer({ + value: 10 + }); + + const b = new Integer(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + num = b.valueBlock.valueDec; + } + + str = b.warnings[0]; + } + + namespace Enumerated { + const { + Enumerated + } = asn1; + + new Enumerated({ + value: 10 + }); + + const b = new Enumerated(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + num = b.valueBlock.valueDec; + } + + str = b.warnings[0]; + } + + namespace ObjectIdentifier { + const { + ObjectIdentifier + } = asn1; + + new ObjectIdentifier({ + blockLength: 10 + }); + new ObjectIdentifier({ + error: "a" + }); + new ObjectIdentifier({ + value: "ha" + }); + new ObjectIdentifier({ + valueBeforeDecode: new ArrayBuffer(10) + }); + new ObjectIdentifier({ + warnings: ["a"] + }); + + const b = new ObjectIdentifier(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + str = b.valueBlock.toString(); + arrBuf = b.valueBlock.valueBeforeDecode; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace Utf8String { + const { + Utf8String + } = asn1; + + new Utf8String({ + value: "ha" + }); + + const b = new Utf8String({ + value: "a" + }); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + str = b.valueBlock.toString(); + arrBuf = b.valueBlock.valueBeforeDecode; + str = b.valueBlock.warnings[0]; + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.valueHex; + } + + str = b.warnings[0]; + } + + namespace BmpString { + const { + BmpString + } = asn1; + + new BmpString({ + value: "ha" + }); + + const b = new BmpString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + str = b.valueBlock.toString(); + arrBuf = b.valueBlock.valueBeforeDecode; + str = b.valueBlock.warnings[0]; + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.value; + } + + str = b.warnings[0]; + } + + namespace UniversalString { + const { + UniversalString + } = asn1; + + new UniversalString({ + value: "ha" + }); + + const b = new UniversalString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + str = b.valueBlock.toString(); + arrBuf = b.valueBlock.valueBeforeDecode; + str = b.valueBlock.warnings[0]; + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.value; + } + + str = b.warnings[0]; + } + + namespace NumericString { + const { + NumericString + } = asn1; + + new NumericString({ + value: "123" + }); + + const b = new NumericString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace PrintableString { + const { + PrintableString + } = asn1; + + new PrintableString({ + value: "123" + }); + + const b = new PrintableString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace TeletexString { + const { + TeletexString + } = asn1; + + new TeletexString({ + value: "123" + }); + + const b = new TeletexString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace VideotexString { + const { + VideotexString + } = asn1; + + new VideotexString({ + value: "123" + }); + + const b = new VideotexString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace IA5String { + const { + IA5String + } = asn1; + + new IA5String({ + value: "123" + }); + + const b = new IA5String(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace GraphicString { + const { + GraphicString + } = asn1; + + new GraphicString({ + value: "123" + }); + + const b = new GraphicString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace VisibleString { + const { + VisibleString + } = asn1; + + new VisibleString({ + value: "123" + }); + + const b = new VisibleString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace GeneralString { + const { + GeneralString + } = asn1; + + new GeneralString({ + value: "123" + }); + + const b = new GeneralString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace CharacterString { + const { + CharacterString + } = asn1; + + new CharacterString({ + value: "123" + }); + + const b = new CharacterString(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace UTCTime { + const { + UTCTime + } = asn1; + + new UTCTime({ + value: "123" + }); + + new UTCTime({ + blockLength: 10 + }); + + new UTCTime({ + error: "a" + }); + + new UTCTime({ + isHexOnly: true + }); + + new UTCTime({ + valueBeforeDecode: new ArrayBuffer(10) + }); + + new UTCTime({ + valueDate: new Date() + }); + + new UTCTime({ + valueHex: new ArrayBuffer(10) + }); + + new UTCTime({ + warnings: ["a"] + }); + + const b = new UTCTime(); + + num = b.year; + num = b.month; + num = b.day; + num = b.hour; + num = b.minute; + num = b.second; + + arrBuf = b.toBuffer(); + + b.fromDate(new Date()); + + date = b.toDate(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace GeneralizedTime { + const { + GeneralizedTime + } = asn1; + + new GeneralizedTime({ + value: "123" + }); + + new GeneralizedTime({ + blockLength: 10 + }); + + new GeneralizedTime({ + error: "a" + }); + + new GeneralizedTime({ + isHexOnly: true + }); + + new GeneralizedTime({ + valueBeforeDecode: new ArrayBuffer(10) + }); + + new GeneralizedTime({ + valueDate: new Date() + }); + + new GeneralizedTime({ + valueHex: new ArrayBuffer(10) + }); + + new GeneralizedTime({ + warnings: ["a"] + }); + + const b = new GeneralizedTime(); + + num = b.year; + num = b.month; + num = b.day; + num = b.hour; + num = b.minute; + num = b.second; + num = b.millisecond; + + arrBuf = b.toBuffer(); + + b.fromDate(new Date()); + + date = b.toDate(); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + bool = b.valueBlock.isHexOnly; + str = b.valueBlock.value; + arrBuf = b.valueBlock.valueBeforeDecode; + arrBuf = b.valueBlock.valueHex; + str = b.valueBlock.warnings[0]; + } + + str = b.warnings[0]; + } + + namespace DATE { + const { + DATE + } = asn1; + + new DATE({ + value: "ha" + }); + + const b = new DATE({ + value: "a" + }); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + str = b.valueBlock.toString(); + arrBuf = b.valueBlock.valueBeforeDecode; + str = b.valueBlock.warnings[0]; + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.valueHex; + } + + str = b.warnings[0]; + } + + namespace TimeOfDay { + const { + TimeOfDay + } = asn1; + + new TimeOfDay({ + value: "ha" + }); + + const b = new TimeOfDay({ + value: "a" + }); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + str = b.valueBlock.toString(); + arrBuf = b.valueBlock.valueBeforeDecode; + str = b.valueBlock.warnings[0]; + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.valueHex; + } + + str = b.warnings[0]; + } + + namespace DateTime { + const { + DateTime + } = asn1; + + new DateTime({ + value: "ha" + }); + + const b = new DateTime({ + value: "a" + }); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + str = b.valueBlock.toString(); + arrBuf = b.valueBlock.valueBeforeDecode; + str = b.valueBlock.warnings[0]; + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.valueHex; + } + + str = b.warnings[0]; + } + + namespace Duration { + const { + Duration + } = asn1; + + new Duration({ + value: "ha" + }); + + const b = new Duration({ + value: "a" + }); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + str = b.valueBlock.toString(); + arrBuf = b.valueBlock.valueBeforeDecode; + str = b.valueBlock.warnings[0]; + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.valueHex; + } + + str = b.warnings[0]; + } + + namespace TIME { + const { + TIME + } = asn1; + + new TIME({ + value: "ha" + }); + + const b = new TIME({ + value: "a" + }); + + namespace idblock { + num = b.idBlock.blockLength; + str = b.idBlock.error; + bool = b.idBlock.isConstructed; + bool = b.idBlock.isHexOnly; + num = b.idBlock.tagClass; + num = b.idBlock.tagNumber; + arrBuf = b.idBlock.toBER(); + { + const j = b.idBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.idBlock.valueBeforeDecode; + arrBuf = b.idBlock.valueHex; + str = b.idBlock.warnings[0]; + } + + namespace lenblock { + num = b.lenBlock.blockLength; + str = b.lenBlock.error; + b.lenBlock.fromBER(new ArrayBuffer(10), 1, 1); + bool = b.lenBlock.isIndefiniteForm; + num = b.lenBlock.length; + bool = b.lenBlock.longFormUsed; + arrBuf = b.lenBlock.toBER(); + { + const j = b.lenBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.lenBlock.valueBeforeDecode; + str = b.lenBlock.warnings[0]; + } + + arrBuf = b.toBER(); + arrBuf = b.toBER(true); + + { + const j = b.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = b.valueBeforeDecode; + + namespace valueBlock { + num = b.valueBlock.blockLength; + str = b.valueBlock.error; + b.valueBlock.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = b.valueBlock.toBER(); + { + const j = b.valueBlock.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + str = b.valueBlock.toString(); + arrBuf = b.valueBlock.valueBeforeDecode; + str = b.valueBlock.warnings[0]; + bool = b.valueBlock.isHexOnly; + arrBuf = b.valueBlock.valueHex; + } + + str = b.warnings[0]; + } + + namespace Choice { + const { + Choice + } = asn1; + + new Choice({ + optional: true + }); + + const c = new Choice({ + value: [new asn1.Integer({ value: 10 })] + }); + + c.value[0].toBER(); + bool = c.optional; + } + + namespace Any { + const { + Any + } = asn1; + + const a = new Any({ + name: "A", + optional: true + }); + + str = a.name; + bool = a.optional; + } + + namespace Repeated { + const { + Repeated + } = asn1; + + new Repeated(); + new Repeated({ + local: true + }); + new Repeated({ + name: "a" + }); + new Repeated({ + optional: true + }); + const r = new Repeated({ + value: new asn1.Any() + }); + + str = r.name; + bool = r.optional; + str = r.value.name; + bool = r.value.optional; + bool = r.local; + } + + namespace RawData { + const { + RawData + } = asn1; + + const r = new RawData({ + data: new ArrayBuffer(10) + }); + arrBuf = r.data; + num = r.fromBER(new ArrayBuffer(10), 0, 0); + arrBuf = r.toBER(); + } + + namespace fromBER { + const r = asn1.fromBER(new ArrayBuffer(10)); + num = r.offset; + const { result } = r; + num = result.blockLength; + str = result.error; + { + const j = result.toJSON(); + num = j.blockLength; + str = j.blockName; + str = j.error; + arrBuf = j.valueBeforeDecode; + str = j.warnings[0]; + } + arrBuf = result.valueBeforeDecode; + str = result.warnings[0]; + } + + namespace compareSchema { + const res = asn1.compareSchema({}, {}, {}); + bool = res.verified; + res.result; + } + + namespace verifySchema { + const res = asn1.verifySchema(new ArrayBuffer(10), {}); + bool = res.verified; + res.result; + } +} diff --git a/types/adone/test/glosses/crypto/ed25519.ts b/types/adone/test/glosses/crypto/ed25519.ts new file mode 100644 index 0000000000..8c0326abf9 --- /dev/null +++ b/types/adone/test/glosses/crypto/ed25519.ts @@ -0,0 +1,28 @@ +namespace adoneTests.crypto.ed25519 { + const { + crypto: { + ed25519 + } + } = adone; + + let buf: Buffer; + let num: number; + let bool: boolean; + + num = ed25519.privateKeyLength; + num = ed25519.publicKeyLength; + + const pair = ed25519.generateKeyPair(Buffer.from("123")); + buf = pair.publicKey; + buf = pair.privateKey; + + buf = ed25519.sign(Buffer.from("hello"), Buffer.from("seed")); + buf = ed25519.sign(Buffer.from("hello"), { + publicKey: Buffer.from("hello"), + privateKey: Buffer.from("hello") + }); + + buf = ed25519.sign(Buffer.from("hello"), ed25519.generateKeyPair(Buffer.from("hello"))); + + bool = ed25519.verify(Buffer.from("hello"), Buffer.from("world"), Buffer.from("key")); +} diff --git a/types/adone/test/glosses/crypto/secp256k1.ts b/types/adone/test/glosses/crypto/secp256k1.ts new file mode 100644 index 0000000000..5f80b61537 --- /dev/null +++ b/types/adone/test/glosses/crypto/secp256k1.ts @@ -0,0 +1,97 @@ +namespace adoneTests.crypto.secp256k1 { + const { + crypto: { + secp256k1 + } + } = adone; + + let bool: boolean; + let buf: Buffer; + let num: number; + + const privateKey = Buffer.from("hello"); + const tweak = Buffer.from("world"); + const publicKey = Buffer.from("olleh"); + const signature = Buffer.from("dlrow"); + + bool = secp256k1.privateKeyVerify(privateKey); + + buf = secp256k1.privateKeyExport(privateKey); + buf = secp256k1.privateKeyExport(privateKey, true); + + buf = secp256k1.privateKeyImport(privateKey); + + buf = secp256k1.privateKeyNegate(privateKey); + + buf = secp256k1.privateKeyTweakAdd(privateKey, tweak); + + buf = secp256k1.privateKeyTweakMul(privateKey, tweak); + + buf = secp256k1.publicKeyConvert(publicKey); + buf = secp256k1.publicKeyConvert(publicKey, true); + + bool = secp256k1.publicKeyVerify(publicKey); + + buf = secp256k1.publicKeyTweakAdd(publicKey, tweak); + buf = secp256k1.publicKeyTweakAdd(publicKey, tweak, true); + + buf = secp256k1.publicKeyTweakMul(publicKey, tweak); + buf = secp256k1.publicKeyTweakMul(publicKey, tweak, true); + + buf = secp256k1.publicKeyCombine([publicKey, publicKey]); + buf = secp256k1.publicKeyCombine([publicKey, publicKey], true); + + buf = secp256k1.signatureNormalize(signature); + + buf = secp256k1.signatureExport(signature); + + buf = secp256k1.signatureImport(signature); + + buf = secp256k1.signatureImportLax(signature); + + const message = Buffer.from("msg"); + + { + const res = secp256k1.sign(message, privateKey); + buf = res.signature; + num = res.recovery; + } + { + const res = secp256k1.sign(message, privateKey, {}); + buf = res.signature; + num = res.recovery; + } + { + const res = secp256k1.sign(message, privateKey, { + data: null + }); + buf = res.signature; + num = res.recovery; + } + { + const res = secp256k1.sign(message, privateKey, { + data: Buffer.from("123") + }); + buf = res.signature; + num = res.recovery; + } + { + const res = secp256k1.sign(message, privateKey, { + noncefn(msg: Buffer, privateKey: Buffer, algo: Buffer, data: Buffer, attempt: number) { + return Buffer.from("hehe"); + } + }); + buf = res.signature; + num = res.recovery; + } + + bool = secp256k1.verify(message, signature, publicKey); + + buf = secp256k1.recover(message, signature, 1); + buf = secp256k1.recover(message, signature, 1, true); + + buf = secp256k1.ecdh(publicKey, privateKey); + + buf = secp256k1.ecdhUnsafe(publicKey, privateKey); + buf = secp256k1.ecdhUnsafe(publicKey, privateKey, true); +} diff --git a/types/adone/test/glosses/data.ts b/types/adone/test/glosses/data.ts index e8ccedddcc..00403a56da 100644 --- a/types/adone/test/glosses/data.ts +++ b/types/adone/test/glosses/data.ts @@ -11,6 +11,7 @@ namespace dataTests { { const a: Buffer = json.encode(1, { replacer: ["a", "b", "c"] }); } { const a: Buffer = json.encode(1, { replacer: (k: string, v: any) => null }); } { const a: Buffer = json.encode(1, { space: " " }); } + { const a: Buffer = json.encode(1, { newline: true }); } json.decode("123"); json.decode(Buffer.from("123")); @@ -52,6 +53,8 @@ namespace dataTests { mpak.decode(new Uint8Array(10)); mpak.decode(new ArrayBuffer(10)); + mpak.tryDecode(new adone.collection.ByteArray()); + new mpak.Encoder([]); new mpak.Encoder([{ type: 10, @@ -73,6 +76,9 @@ namespace dataTests { new mpak.Decoder([]).decode(new ArrayBuffer(10)); new mpak.Decoder([]).tryDecode(adone.collection.ByteArray.wrap("hello")); + new mpak.Serializer(); + new mpak.Serializer(100); + mpak.registerCommonTypesFor(new mpak.Serializer()); { const a: adone.data.mpak.Encoder = new mpak.Serializer().encoder; } { const a: adone.data.mpak.Decoder = new mpak.Serializer().decoder; } { const a: adone.data.mpak.Serializer = new mpak.Serializer().registerEncoder(10, (x) => true, (x) => new adone.collection.ByteArray(10)); } @@ -125,6 +131,7 @@ namespace dataTests { { const a: string = base64.decode("string", {}); } { const a: string = base64.decode("string", { buffer: false }); } { const a: Buffer = base64.decode("string", { buffer: true }); } + { const a: string = base64.decode("string", { encoding: "utf8" }); } { const a: string = base64.encodeVLQ(123); } { const a: number = base64.decodeVLQ("H"); } @@ -563,4 +570,277 @@ namespace dataTests { bson.decode(bson.encode({ a: 1 }), { promoteLongs: false }).a; bson.decode(bson.encode({ a: 1 }), { promoteValues: true }).a; } + + namespace protobuf { + const { + protobuf + } = data; + + protobuf.create("hello"); + protobuf.create(Buffer.from("hello")); + protobuf.create({}); + protobuf.create({}, {}); + + namespace schema { + const { + schema + } = protobuf; + + const s = schema.parse("hello"); + s.syntax; + s.package; + if (!adone.is.null(s.package)) { + const c: string = s.package; + } + s.imports[0].charCodeAt(100); + + namespace enums { + const [a] = s.enums; + a.name.charCodeAt(100); + a.values; + a.options; + } + + namespace message { + const [msg] = s.messages; + msg.name; + { + const [a] = msg.enums; + a.name; + a.options; + a.values; + } + { + const [a] = msg.extends; + a.name; + a.message; + } + { + const [a] = msg.messages; + a.name; + a.enums; + a.extends; + a.messages; + a.fields; + a.extensions; + } + { + const [a] = msg.fields; + if (!adone.is.null(a.name)) { + a.name.charCodeAt(100); + } + if (!adone.is.null(a.type)) { + a.type.charCodeAt(100); + } + a.tag === 3; + if (!adone.is.null(a.map)) { + a.map.from.charCodeAt(100); + a.map.to.charCodeAt(100); + } + if (!adone.is.null(a.oneof)) { + a.oneof.charCodeAt(100); + } + a.required === false; + a.repeated === true; + a.options; + } + if (!adone.is.null(msg.extensions)) { + msg.extensions.from === 2; + msg.extensions.to === 3; + } + } + + s.options; + + s.extends[0].message; + s.extends[0].name; + + if (!adone.is.nil(s.services)) { + const [svc] = s.services; + + svc.name.charCodeAt(100); + svc.options; + + const [m] = svc.methods; + + m.name.charCodeAt(100); + if (!adone.is.null(m.input_type)) { + m.input_type.charCodeAt(100); + } + if (!adone.is.null(m.output_type)) { + m.output_type.charCodeAt(100); + } + m.client_streaming === true; + m.server_streaming === true; + m.options; + } + } + } + + namespace base32 { + const { + base32 + } = data; + + base32.charmap("asd"); + base32.charmap("asd", {}); + + base32.rfc4648.alphabet.charCodeAt(0); + base32.rfc4648.charmap["X"] === 2; + + base32.crockford.alphabet.charCodeAt(0); + base32.crockford.charmap["X"] === 2; + + base32.base32hex.alphabet.charCodeAt(0); + base32.base32hex.charmap["X"] === 2; + + namespace decoder { + const { + Decoder + } = base32; + new Decoder(); + new Decoder({ + type: "base32hex" + }); + new Decoder({ + type: "crockford" + }); + new Decoder({ + type: "rfc4648" + }); + new Decoder({ + type: "rfc4648", + charmap: {} + }); + const d = new Decoder(); + d.write("asd").write("aa"); + { const a: Buffer = d.finalize(); } + { const a: Buffer = d.finalize("c"); } + } + + namespace encoder { + const { + Encoder + } = base32; + + new Encoder(); + new Encoder({ + type: "base32hex" + }); + new Encoder({ + type: "crockford" + }); + new Encoder({ + type: "rfc4648" + }); + new Encoder({ + type: "rfc4648", + alphabet: "a" + }); + + const e = new Encoder(); + e.write(Buffer.from("b")).write(Buffer.from("a")); + { const a: string = e.finalize(); } + { const a: string = e.finalize(Buffer.from("c")); } + } + + base32.encode(Buffer.from("hello")).charCodeAt(100); + base32.encode(Buffer.from("hello"), { + type: "rfc4648" + }).charCodeAt(100); + base32.encode(Buffer.from("hello"), { + type: "crockford" + }).charCodeAt(100); + base32.encode(Buffer.from("hello"), { + type: "base32hex" + }).charCodeAt(100); + base32.encode(Buffer.from("hello"), { + type: "base32hex", + alphabet: "asd" + }).charCodeAt(100); + + base32.decode("asd").writeUInt8(100, 0); + base32.decode("asd", { + type: "base32hex" + }).writeUInt8(100, 0); + base32.decode("asd", { + type: "crockford" + }).writeUInt8(100, 0); + base32.decode("asd", { + type: "rfc4648" + }).writeUInt8(100, 0); + base32.decode("asd", { + type: "rfc4648", + charmap: {} + }).writeUInt8(100, 0); + } + + namespace basex { + const { + basex + } = data; + + const d = basex("abc"); + const a: Buffer = d.decode("str"); + const b: string = d.encode(Buffer.from("hello")); + const c: Buffer = d.decodeUnsafe("hello"); + } + + namespace base58 { + const { + base58 + } = data; + + const a: Buffer = base58.decode("str"); + const b: string = base58.encode(Buffer.from("hello")); + const c: Buffer = base58.decodeUnsafe("hello"); + } + + namespace base64url { + const { + base64url + } = data; + + base64url.unescape("a").charCodeAt(100); + base64url.escape("a").charCodeAt(100); + + base64url.encode("a").charCodeAt(100); + base64url.encode(Buffer.from("a")).charCodeAt(100); + base64url.encode(Buffer.from("a"), {}).charCodeAt(100); + base64url.encode(Buffer.from("a"), { + encoding: "utf8" + }).charCodeAt(100); + + base64url.decode("a").charCodeAt(100); + base64url.decode("a", { buffer: true }).writeUInt8(0, 0); + base64url.decode("a", { encoding: "utf8" }).charCodeAt(100); + } + + namespace varint { + const { + varint + } = data; + + varint.encode(12)[0]; + varint.encode(12, [])[0]; + varint.encode(12, [], 1)[0]; + + varint.decode(Buffer.from("hello")) === 5; + varint.decode(Buffer.from("hello"), 2) === 5; + varint.encodingLength(100500) === 5; + } + + namespace varintSigned { + const { + varintSigned + } = data; + + varintSigned.encode(12)[0]; + varintSigned.encode(12, [])[0]; + varintSigned.encode(12, [], 1)[0]; + + varintSigned.decode(Buffer.from("hello")) === 5; + varintSigned.decode(Buffer.from("hello"), 2) === 5; + varintSigned.encodingLength(100500) === 5; + } } diff --git a/types/adone/test/glosses/errors.ts b/types/adone/test/glosses/errors.ts new file mode 100644 index 0000000000..d84a267b07 --- /dev/null +++ b/types/adone/test/glosses/errors.ts @@ -0,0 +1,36 @@ +namespace ErrorsTests { + { const a: Error = new adone.error.Exception(); } + { const a: Error = new adone.error.Exception("message"); } + { const a: Error = new adone.error.Exception(new Error()); } + { const a: Error = new adone.error.Exception(new Error(), true); } + { const a: adone.error.Exception = new adone.error.Runtime(); } + { const a: adone.error.Exception = new adone.error.IncompleteBufferError(); } + { const a: adone.error.Exception = new adone.error.NotImplemented(); } + { const a: adone.error.Exception = new adone.error.IllegalState(); } + { const a: adone.error.Exception = new adone.error.NotValid(); } + { const a: adone.error.Exception = new adone.error.Unknown(); } + { const a: adone.error.Exception = new adone.error.NotExists(); } + { const a: adone.error.Exception = new adone.error.Exists(); } + { const a: adone.error.Exception = new adone.error.Empty(); } + { const a: adone.error.Exception = new adone.error.InvalidAccess(); } + { const a: adone.error.Exception = new adone.error.NotSupported(); } + { const a: adone.error.Exception = new adone.error.InvalidArgument(); } + { const a: adone.error.Exception = new adone.error.InvalidNumberOfArguments(); } + { const a: adone.error.Exception = new adone.error.NotFound(); } + { const a: adone.error.Exception = new adone.error.Timeout(); } + { const a: adone.error.Exception = new adone.error.Incorrect(); } + { const a: adone.error.Exception = new adone.error.NotAllowed(); } + { const a: adone.error.Exception = new adone.error.LimitExceeded(); } + { const a: adone.error.Exception = new adone.error.Encoding(); } + { const a: adone.error.Exception = new adone.error.Network(); } + { const a: adone.error.Exception = new adone.error.Bind(); } + { const a: adone.error.Exception = new adone.error.Connect(); } + { const a: adone.error.Exception = new adone.error.Database(); } + { const a: adone.error.Exception = new adone.error.DatabaseInitialization(); } + { const a: adone.error.Exception = new adone.error.DatabaseOpen(); } + { const a: adone.error.Exception = new adone.error.DatabaseRead(); } + { const a: adone.error.Exception = new adone.error.DatabaseWrite(); } + { const a: adone.error.Exception = new adone.error.NetronIllegalState(); } + { const a: adone.error.Exception = new adone.error.NetronPeerDisconnected(); } + { const a: adone.error.Exception = new adone.error.NetronTimeout(); } +} diff --git a/types/adone/test/glosses/events.ts b/types/adone/test/glosses/events.ts index 7f31089b52..448867951e 100644 --- a/types/adone/test/glosses/events.ts +++ b/types/adone/test/glosses/events.ts @@ -1,76 +1,86 @@ namespace eventsTests { namespace EventEmitter { namespace static { - const a: number = adone.event.EventEmitter.listenerCount(new adone.event.EventEmitter(), "event"); - const b: number = adone.event.EventEmitter.defaultMaxListeners; + const a: number = adone.event.Emitter.listenerCount(new adone.event.Emitter(), "event"); + const b: number = adone.event.Emitter.defaultMaxListeners; } namespace addListener { - const a: adone.event.EventEmitter = new adone.event.EventEmitter().addListener("event", () => { }); - const b: adone.event.EventEmitter = new adone.event.EventEmitter().addListener(Symbol("event"), () => { }); + const a: adone.event.Emitter = new adone.event.Emitter().addListener("event", () => { }); + const b: adone.event.Emitter = new adone.event.Emitter().addListener(Symbol("event"), () => { }); } namespace on { - const a: adone.event.EventEmitter = new adone.event.EventEmitter().on("event", () => { }); - const b: adone.event.EventEmitter = new adone.event.EventEmitter().on(Symbol("event"), () => { }); + const a: adone.event.Emitter = new adone.event.Emitter().on("event", () => { }); + const b: adone.event.Emitter = new adone.event.Emitter().on(Symbol("event"), () => { }); } namespace once { - const a: adone.event.EventEmitter = new adone.event.EventEmitter().once("event", () => { }); - const b: adone.event.EventEmitter = new adone.event.EventEmitter().once(Symbol("event"), () => { }); + const a: adone.event.Emitter = new adone.event.Emitter().once("event", () => { }); + const b: adone.event.Emitter = new adone.event.Emitter().once(Symbol("event"), () => { }); } namespace prependListener { - const a: adone.event.EventEmitter = new adone.event.EventEmitter().prependListener("event", () => { }); - const b: adone.event.EventEmitter = new adone.event.EventEmitter().prependListener(Symbol("event"), () => { }); + const a: adone.event.Emitter = new adone.event.Emitter().prependListener("event", () => { }); + const b: adone.event.Emitter = new adone.event.Emitter().prependListener(Symbol("event"), () => { }); } namespace prependOnceListener { - const a: adone.event.EventEmitter = new adone.event.EventEmitter().prependOnceListener("event", () => { }); - const b: adone.event.EventEmitter = new adone.event.EventEmitter().prependOnceListener(Symbol("event"), () => { }); + const a: adone.event.Emitter = new adone.event.Emitter().prependOnceListener("event", () => { }); + const b: adone.event.Emitter = new adone.event.Emitter().prependOnceListener(Symbol("event"), () => { }); } namespace removeListener { - const a: adone.event.EventEmitter = new adone.event.EventEmitter().removeListener("event", () => { }); - const b: adone.event.EventEmitter = new adone.event.EventEmitter().removeListener(Symbol("event"), () => { }); + const a: adone.event.Emitter = new adone.event.Emitter().removeListener("event", () => { }); + const b: adone.event.Emitter = new adone.event.Emitter().removeListener(Symbol("event"), () => { }); } namespace removeAllListeners { - const a: adone.event.EventEmitter = new adone.event.EventEmitter().removeAllListeners("event"); - const b: adone.event.EventEmitter = new adone.event.EventEmitter().removeAllListeners(Symbol("event")); + const a: adone.event.Emitter = new adone.event.Emitter().removeAllListeners("event"); + const b: adone.event.Emitter = new adone.event.Emitter().removeAllListeners(Symbol("event")); } namespace setMaxListeners { - const a: adone.event.EventEmitter = new adone.event.EventEmitter().setMaxListeners(10); + const a: adone.event.Emitter = new adone.event.Emitter().setMaxListeners(10); } namespace getMaxListeners { - const a: number = new adone.event.EventEmitter().getMaxListeners(); + const a: number = new adone.event.Emitter().getMaxListeners(); } namespace listeners { - const a: Array<(...args: any[]) => any> = new adone.event.EventEmitter().listeners("event"); - const b: Array<(...args: any[]) => any> = new adone.event.EventEmitter().listeners(Symbol("event")); + const a: Array<(...args: any[]) => any> = new adone.event.Emitter().listeners("event"); + const b: Array<(...args: any[]) => any> = new adone.event.Emitter().listeners(Symbol("event")); } namespace emit { - const a: boolean = new adone.event.EventEmitter().emit("event", 1, 2, 3); - const b: boolean = new adone.event.EventEmitter().emit(Symbol("event"), 1, 2, 3); + const a: boolean = new adone.event.Emitter().emit("event", 1, 2, 3); + const b: boolean = new adone.event.Emitter().emit(Symbol("event"), 1, 2, 3); } namespace eventNames { - const a: Array = new adone.event.EventEmitter().eventNames(); - const b: Array = new adone.event.EventEmitter().eventNames(); + const a: Array = new adone.event.Emitter().eventNames(); + const b: Array = new adone.event.Emitter().eventNames(); } namespace listenerCount { - const a: number = new adone.event.EventEmitter().listenerCount("event"); - const b: number = new adone.event.EventEmitter().listenerCount(Symbol("event")); + const a: number = new adone.event.Emitter().listenerCount("event"); + const b: number = new adone.event.Emitter().listenerCount(Symbol("event")); + } + + namespace propagateEvents { + const e = new adone.event.Emitter().propagateEvents(new adone.event.Emitter(), ["a"]); + e.end(); + } + + namespace staticPropagateEvents { + const e = adone.event.Emitter.propagateEvents(new adone.event.Emitter(), new adone.event.Emitter(), ["a"]); + e.end(); } } namespace AsyncEmitter { - const a: adone.event.EventEmitter = new adone.event.AsyncEmitter(); + const a: adone.event.Emitter = new adone.event.AsyncEmitter(); new adone.event.AsyncEmitter(10); namespace setConcurrency { diff --git a/types/adone/test/glosses/exceptions.ts b/types/adone/test/glosses/exceptions.ts deleted file mode 100644 index e13dc3fff7..0000000000 --- a/types/adone/test/glosses/exceptions.ts +++ /dev/null @@ -1,36 +0,0 @@ -namespace ExcetpionsTests { - { const a: Error = new adone.x.Exception(); } - { const a: Error = new adone.x.Exception("message"); } - { const a: Error = new adone.x.Exception(new Error()); } - { const a: Error = new adone.x.Exception(new Error(), true); } - { const a: adone.x.Exception = new adone.x.Runtime(); } - { const a: adone.x.Exception = new adone.x.IncompleteBufferError(); } - { const a: adone.x.Exception = new adone.x.NotImplemented(); } - { const a: adone.x.Exception = new adone.x.IllegalState(); } - { const a: adone.x.Exception = new adone.x.NotValid(); } - { const a: adone.x.Exception = new adone.x.Unknown(); } - { const a: adone.x.Exception = new adone.x.NotExists(); } - { const a: adone.x.Exception = new adone.x.Exists(); } - { const a: adone.x.Exception = new adone.x.Empty(); } - { const a: adone.x.Exception = new adone.x.InvalidAccess(); } - { const a: adone.x.Exception = new adone.x.NotSupported(); } - { const a: adone.x.Exception = new adone.x.InvalidArgument(); } - { const a: adone.x.Exception = new adone.x.InvalidNumberOfArguments(); } - { const a: adone.x.Exception = new adone.x.NotFound(); } - { const a: adone.x.Exception = new adone.x.Timeout(); } - { const a: adone.x.Exception = new adone.x.Incorrect(); } - { const a: adone.x.Exception = new adone.x.NotAllowed(); } - { const a: adone.x.Exception = new adone.x.LimitExceeded(); } - { const a: adone.x.Exception = new adone.x.Encoding(); } - { const a: adone.x.Exception = new adone.x.Network(); } - { const a: adone.x.Exception = new adone.x.Bind(); } - { const a: adone.x.Exception = new adone.x.Connect(); } - { const a: adone.x.Exception = new adone.x.Database(); } - { const a: adone.x.Exception = new adone.x.DatabaseInitialization(); } - { const a: adone.x.Exception = new adone.x.DatabaseOpen(); } - { const a: adone.x.Exception = new adone.x.DatabaseRead(); } - { const a: adone.x.Exception = new adone.x.DatabaseWrite(); } - { const a: adone.x.Exception = new adone.x.NetronIllegalState(); } - { const a: adone.x.Exception = new adone.x.NetronPeerDisconnected(); } - { const a: adone.x.Exception = new adone.x.NetronTimeout(); } -} diff --git a/types/adone/test/glosses/fake.ts b/types/adone/test/glosses/fake.ts new file mode 100644 index 0000000000..016d7ba7b0 --- /dev/null +++ b/types/adone/test/glosses/fake.ts @@ -0,0 +1,206 @@ +namespace adoneTests.fake { + const { + fake + } = adone; + + { const a: string = fake.address.zipCode(); } + { const a: string = fake.address.zipCode('###'); } + { const a: string = fake.address.city(); } + { const a: string = fake.address.city(0); } + { const a: string = fake.address.cityPrefix(); } + { const a: string = fake.address.citySuffix(); } + { const a: string = fake.address.streetName(); } + { const a: string = fake.address.streetAddress(); } + { const a: string = fake.address.streetAddress(false); } + { const a: string = fake.address.streetSuffix(); } + { const a: string = fake.address.streetPrefix(); } + { const a: string = fake.address.secondaryAddress(); } + { const a: string = fake.address.county(); } + { const a: string = fake.address.country(); } + { const a: string = fake.address.countryCode(); } + { const a: string = fake.address.state(); } + { const a: string = fake.address.state(false); } + { const a: string = fake.address.stateAbbr(); } + { const a: string = fake.address.latitude(); } + { const a: string = fake.address.longitude(); } + + { const a: string = fake.commerce.color(); } + { const a: string = fake.commerce.department(); } + { const a: string = fake.commerce.productName(); } + { const a: string = fake.commerce.price(); } + { const a: string = fake.commerce.price(0, 0, 0, '#'); } + { const a: string = fake.commerce.productAdjective(); } + { const a: string = fake.commerce.productMaterial(); } + { const a: string = fake.commerce.product(); } + + { const a: string[] = fake.company.suffixes(); } + { const a: string = fake.company.companyName(); } + { const a: string = fake.company.companyName(0); } + { const a: string = fake.company.companySuffix(); } + { const a: string = fake.company.catchPhrase(); } + { const a: string = fake.company.bs(); } + { const a: string = fake.company.catchPhraseAdjective(); } + { const a: string = fake.company.catchPhraseDescriptor(); } + { const a: string = fake.company.catchPhraseNoun(); } + { const a: string = fake.company.bsAdjective(); } + { const a: string = fake.company.bsBuzz(); } + { const a: string = fake.company.bsNoun(); } + + { const a: string = fake.database.column(); } + { const a: string = fake.database.type(); } + { const a: string = fake.database.collation(); } + { const a: string = fake.database.engine(); } + + { const a: Date = fake.date.past(); } + { const a: Date = fake.date.future(); } + { const a: Date = fake.date.between('foo', 'bar'); } + { const a: Date = fake.date.between(new Date(), new Date()); } + { const a: Date = fake.date.recent(); } + { const a: Date = fake.date.recent(100); } + { const a: Date = fake.date.soon(); } + { const a: Date = fake.date.soon(30); } + { const a: string = fake.date.month(); } + { const a: string = fake.date.month({ + abbr: true, + context: true + }); } + { const a: string = fake.date.weekday(); } + { const a: string = fake.date.weekday({ + abbr: true, + context: true + }); } + + { const a: string = fake.finance.account(); } + { const a: string = fake.finance.account(0); } + { const a: string = fake.finance.accountName(); } + { const a: string = fake.finance.mask(); } + { const a: string = fake.finance.mask(0, false, false); } + { const a: string = fake.finance.amount(); } + { const a: string = fake.finance.amount(0, 0, 0, '#'); } + { const a: string = fake.finance.transactionType(); } + { const a: string = fake.finance.currencyCode(); } + { const a: string = fake.finance.currencyName(); } + { const a: string = fake.finance.currencySymbol(); } + { const a: string = fake.finance.bitcoinAddress(); } + { const a: string = fake.finance.ethereumAddress(); } + { const a: string = fake.finance.iban(); } + { const a: string = fake.finance.iban(true); } + { const a: string = fake.finance.bic(); } + + { const a: string = fake.hacker.abbreviation(); } + { const a: string = fake.hacker.adjective(); } + { const a: string = fake.hacker.noun(); } + { const a: string = fake.hacker.verb(); } + { const a: string = fake.hacker.ingverb(); } + { const a: string = fake.hacker.phrase(); } + + { const a: string = fake.helpers.randomize(); } + { const a: number = fake.helpers.randomize([1, 2, 3, 4]); } + { const a: string = fake.helpers.randomize(['foo', 'bar', 'quux']); } + { const a: string = fake.helpers.slugify('foo bar quux'); } + { const a: string = fake.helpers.replaceSymbolWithNumber('foo# bar#'); } + { const a: string = fake.helpers.replaceSymbols('foo# bar? quux#'); } + { const a: string[] = fake.helpers.shuffle(['foo', 'bar', 'quux']); } + { const a: string = fake.helpers.mustache('{{foo}}{{bar}}', {foo: 'x', bar: 'y'}); } + + const card = fake.helpers.createCard(); + { const a: string = card.name; } + { const a: string = card.address.streetA; } + const contextualCard = fake.helpers.contextualCard(); + { const a: string = contextualCard.name; } + { const a: string = contextualCard.address.suite; } + const userCard = fake.helpers.userCard(); + { const a: string = userCard.name; } + { const a: string = userCard.address.suite; } + + { const a: string = fake.internet.avatar(); } + { const a: string = fake.internet.email(); } + { const a: string = fake.internet.email('foo', 'bar', 'quux'); } + { const a: string = fake.internet.exampleEmail(); } + { const a: string = fake.internet.exampleEmail('foo', 'bar'); } + { const a: string = fake.internet.protocol(); } + { const a: string = fake.internet.url(); } + { const a: string = fake.internet.domainName(); } + { const a: string = fake.internet.domainSuffix(); } + { const a: string = fake.internet.domainWord(); } + { const a: string = fake.internet.ip(); } + { const a: string = fake.internet.userAgent(); } + { const a: string = fake.internet.color(); } + { const a: string = fake.internet.color(0, 0, 0); } + { const a: string = fake.internet.mac(); } + { const a: string = fake.internet.password(); } + { const a: string = fake.internet.password(0, false, '#', 'foo'); } + + { const a: string = fake.lorem.word(); } + { const a: string = fake.lorem.words(); } + { const a: string = fake.lorem.words(0); } + { const a: string = fake.lorem.sentence(); } + { const a: string = fake.lorem.sentence(0, 0); } + { const a: string = fake.lorem.slug(); } + { const a: string = fake.lorem.slug(0); } + { const a: string = fake.lorem.sentences(); } + { const a: string = fake.lorem.sentences(0); } + { const a: string = fake.lorem.paragraph(); } + { const a: string = fake.lorem.paragraph(0); } + { const a: string = fake.lorem.paragraphs(); } + { const a: string = fake.lorem.paragraphs(0, ''); } + { const a: string = fake.lorem.text(); } + { const a: string = fake.lorem.text(0); } + { const a: string = fake.lorem.lines(); } + { const a: string = fake.lorem.lines(0); } + + { const a: string = fake.name.firstName(); } + { const a: string = fake.name.firstName(0); } + { const a: string = fake.name.lastName(); } + { const a: string = fake.name.lastName(0); } + { const a: string = fake.name.findName(); } + { const a: string = fake.name.findName('', '', 0); } + { const a: string = fake.name.jobTitle(); } + { const a: string = fake.name.prefix(); } + { const a: string = fake.name.suffix(); } + { const a: string = fake.name.title(); } + { const a: string = fake.name.jobDescriptor(); } + { const a: string = fake.name.jobArea(); } + { const a: string = fake.name.jobType(); } + + { const a: string = fake.phone.phoneNumber(); } + { const a: string = fake.phone.phoneNumber('#'); } + { const a: string = fake.phone.phoneNumberFormat(); } + { const a: string = fake.phone.phoneNumberFormat(0); } + { const a: string = fake.phone.phoneFormats(); } + + { const a: number = fake.random.number(); } + { const a: number = fake.random.number(0); } + { const a: number = fake.random.number({ + min: 0, + max: 0, + precision: 0 + }); } + { const a: string = fake.random.arrayElement(); } + { const a: string = fake.random.arrayElement(['foo', 'bar', 'quux']); } + { const a: string = fake.random.objectElement(); } + { const a: string = fake.random.objectElement({foo: 'bar', field: 'foo'}); } + { const a: string = fake.random.uuid(); } + { const a: boolean = fake.random.boolean(); } + { const a: string = fake.random.word(); } + { const a: string = fake.random.word("noun"); } + { const a: string = fake.random.words(); } + { const a: string = fake.random.words(0); } + { const a: string = fake.random.image(); } + { const a: string = fake.random.locale(); } + { const a: string = fake.random.alphaNumeric(); } + { const a: string = fake.random.alphaNumeric(0); } + { const a: string = fake.random.hexaDecimal(); } + { const a: string = fake.random.hexaDecimal(3); } + + { const a: string = fake.system.fileName("foo", "bar"); } + { const a: string = fake.system.commonFileName("foo", "bar"); } + { const a: string = fake.system.mimeType(); } + { const a: string = fake.system.commonFileType(); } + { const a: string = fake.system.commonFileExt(); } + { const a: string = fake.system.fileType(); } + { const a: string = fake.system.fileExt("foo"); } + { const a: string = fake.system.directoryPath(); } + { const a: string = fake.system.filePath(); } + { const a: string = fake.system.semver(); } +} diff --git a/types/adone/test/glosses/fs.ts b/types/adone/test/glosses/fs.ts index 8b7e765c9f..e7c5333624 100644 --- a/types/adone/test/glosses/fs.ts +++ b/types/adone/test/glosses/fs.ts @@ -11,6 +11,15 @@ namespace fsTests { fs.readlink("file", null).then((x: Buffer) => x); fs.readlink("file", "hex").then((x: string) => x); fs.readlink("file").then((x: string) => x); + fs.readlinkSync("file"); + fs.readlinkSync(Buffer.from("file")); + fs.readlinkSync(new URL("file://file")); + { const a: string = fs.readlinkSync("file", {}); } + { const a: string = fs.readlinkSync("file", { encoding: "utf8" }); } + { const a: Buffer = fs.readlinkSync("file", { encoding: null }); } + { const a: Buffer = fs.readlinkSync("file", null); } + { const a: string = fs.readlinkSync("file", "hex"); } + { const a: string = fs.readlinkSync("file"); } } namespace unlinkTests { @@ -22,6 +31,24 @@ namespace fsTests { fs.unlinkSync(new URL("file://file")); } + namespace utimesTests { + fs.utimes("hello", 100, 100).then(() => {}); + fs.utimes(Buffer.from("hello"), 100, 100).then(() => {}); + fs.utimes(new URL("hello"), 100, 100).then(() => {}); + fs.utimes("hello", "100", "100").then(() => {}); + fs.utimes("hello", new Date(100), new Date(100)).then(() => {}); + + fs.utimesSync("hello", 100, 100); + fs.utimesSync(Buffer.from("hello"), 100, 100); + fs.utimesSync(new URL("hello"), 100, 100); + fs.utimesSync("hello", "100", "100"); + fs.utimesSync("hello", new Date(100), new Date(100)); + + fs.utimesMillis("hello", 100, 100); + fs.utimesMillis(Buffer.from("hello"), 100, 100); + fs.utimesMillis(new URL("hello"), 100, 100); + } + namespace chmodTests { fs.chmod("file", 0o333).then(() => {}); fs.chmod(Buffer.from("file"), 0o333).then(() => {}); @@ -60,6 +87,87 @@ namespace fsTests { const e: Buffer[] = fs.readdirSync("file", { encoding: null }); } + namespace readdirpTests { + fs.readdirp("hello").forEach((entry) => { + { const a: string = entry.fullParentDir; } + { const a: string = entry.fullPath; } + { const a: string = entry.name; } + { const a: string = entry.parentDir; } + { const a: string = entry.path; } + { const a: adone.fs.I.Stats = entry.stat; } + }); + + fs.readdirp(Buffer.from("hello")); + fs.readdirp(new URL("hello")); + fs.readdirp("hello", {}); + fs.readdirp("hello", { depth: 100 }); + fs.readdirp("hello", { directories: true }); + fs.readdirp("hello", { directoryFilter: () => true }); + fs.readdirp("hello", { + directoryFilter: (entry) => { + { const a: string = entry.fullParentDir; } + { const a: string = entry.fullPath; } + { const a: string = entry.name; } + { const a: string = entry.parentDir; } + { const a: string = entry.path; } + { const a: adone.fs.I.Stats = entry.stat; } + return true; + } + }); + fs.readdirp("hello", { + directoryFilter: [(entry) => { + { const a: string = entry.fullParentDir; } + { const a: string = entry.fullPath; } + { const a: string = entry.name; } + { const a: string = entry.parentDir; } + { const a: string = entry.path; } + { const a: adone.fs.I.Stats = entry.stat; } + return true; + }] + }); + fs.readdirp("hello", { + directoryFilter: ["*"] + }); + fs.readdirp("hello", { + directoryFilter: "*" + }); + fs.readdirp("hello", { fileFilter: () => true }); + fs.readdirp("hello", { + fileFilter: (entry) => { + { const a: string = entry.fullParentDir; } + { const a: string = entry.fullPath; } + { const a: string = entry.name; } + { const a: string = entry.parentDir; } + { const a: string = entry.path; } + { const a: adone.fs.I.Stats = entry.stat; } + return true; + } + }); + fs.readdirp("hello", { + fileFilter: [(entry) => { + { const a: string = entry.fullParentDir; } + { const a: string = entry.fullPath; } + { const a: string = entry.name; } + { const a: string = entry.parentDir; } + { const a: string = entry.path; } + { const a: adone.fs.I.Stats = entry.stat; } + return true; + }] + }); + fs.readdirp("hello", { + fileFilter: ["*"] + }); + fs.readdirp("hello", { + fileFilter: "*" + }); + fs.readdirp("hello", { + files: false + }); + fs.readdirp("hello", { + lstat: true + }); + } + namespace lstatTests { fs.lstat("file").then((x: nodestd.fs.Stats) => {}); fs.lstat(Buffer.from("file")).then((x: nodestd.fs.Stats) => {}); @@ -119,6 +227,15 @@ namespace fsTests { fs.appendFile("file", "hello", { encoding: "utf8" }).then(() => {}); fs.appendFile("file", "hello", { mode: 0o755 }).then(() => {}); fs.appendFile("file", "hello", { flag: "w" }).then(() => {}); + + fs.appendFileSync("file", "hello"); + fs.appendFileSync(Buffer.from("file"), "hello"); + fs.appendFileSync(10, "hello"); + fs.appendFileSync("file", Buffer.from("hello")); + fs.appendFileSync("file", "hello", {}); + fs.appendFileSync("file", "hello", { encoding: "utf8" }); + fs.appendFileSync("file", "hello", { mode: 0o755 }); + fs.appendFileSync("file", "hello", { flag: "w" }); } namespace accessTests { @@ -153,6 +270,12 @@ namespace fsTests { fs.rm("file", { cwd: __dirname }).then((x) => {}); } + namespace rmEmptyTests { + fs.rmEmpty("file").then(() => {}); + fs.rmEmpty("file", { cwd: "a" }).then(() => {}); + fs.rmEmpty("file", { filter: (filename) => filename.charCodeAt(0) === 100 }).then(() => {}); + } + namespace ModeTests { const stat = fs.statSync("file"); const mode = new fs.Mode(stat); @@ -513,37 +636,36 @@ namespace fsTests { } namespace fdTests { - const { fd } = fs; - fd.open("hello", "r+").then((x: number) => {}); - fd.open(Buffer.from("hello"), "r+").then((x: number) => {}); - fd.open(new URL("file://hello"), "r+").then((x: number) => {}); - { const a: number = fd.openSync("hello", "r+"); } - { const a: number = fd.openSync(Buffer.from("hello"), "r+"); } - { const a: number = fd.openSync(new URL("file://hello"), "r+"); } - fd.close(10).then(() => {}); - fd.closeSync(10); - fd.utimes(10, 100500, 100500).then(() => {}); - fd.utimesSync(10, 100500, 100500); - fd.stat(10).then((x: adone.fs.I.Stats) => {}); - { const a: adone.fs.I.Stats = fd.statSync(10); } - fd.truncate(10).then(() => {}); - fd.truncate(10, 10).then(() => {}); - fd.truncateSync(10); - fd.truncateSync(10, 10); - fd.read(10, Buffer.alloc(10), 0, 10, 10).then((x: number) => {}); - { const a: number = fd.readSync(10, Buffer.alloc(10), 0, 10, 10); } - fd.write(10, Buffer.alloc(10), 0, 10, 10).then((x: number) => {}); - { const a: number = fd.writeSync(10, Buffer.alloc(10), 0, 10, 10); } - fd.write(10, "hello", 10, "utf8").then((x: number) => {}); - { const a: number = fd.writeSync(10, "hello", 10, "utf8"); } - fd.sync(10).then(() => {}); - fd.syncSync(10); - fd.chown(10, 0, 0).then(() => {}); - fd.chownSync(10, 0, 0); - fd.chmod(10, 0o755).then(() => {}); - fd.chmodSync(10, 0o755); - fd.seek(10, 100, 0).then((x: number) => {}); - fd.lock(10, "sh").then(() => {}); + fs.open("hello", "r+").then((x: number) => {}); + fs.open(Buffer.from("hello"), "r+").then((x: number) => {}); + fs.open(new URL("file://hello"), "r+").then((x: number) => {}); + { const a: number = fs.openSync("hello", "r+"); } + { const a: number = fs.openSync(Buffer.from("hello"), "r+"); } + { const a: number = fs.openSync(new URL("file://hello"), "r+"); } + fs.close(10).then(() => {}); + fs.closeSync(10); + fs.futimes(10, 100500, 100500).then(() => {}); + fs.futimesSync(10, 100500, 100500); + fs.fstat(10).then((x: adone.fs.I.Stats) => {}); + { const a: adone.fs.I.Stats = fs.fstatSync(10); } + fs.ftruncate(10).then(() => {}); + fs.ftruncate(10, 10).then(() => {}); + fs.ftruncateSync(10); + fs.ftruncateSync(10, 10); + fs.read(10, Buffer.alloc(10), 0, 10, 10).then((x: number) => {}); + { const a: number = fs.readSync(10, Buffer.alloc(10), 0, 10, 10); } + fs.write(10, Buffer.alloc(10), 0, 10, 10).then((x: number) => {}); + { const a: number = fs.writeSync(10, Buffer.alloc(10), 0, 10, 10); } + fs.write(10, "hello", 10, "utf8").then((x: number) => {}); + { const a: number = fs.writeSync(10, "hello", 10, "utf8"); } + fs.fsync(10).then(() => {}); + fs.fsyncSync(10); + fs.fchown(10, 0, 0).then(() => {}); + fs.fchownSync(10, 0, 0); + fs.fchmod(10, 0o755).then(() => {}); + fs.fchmodSync(10, 0o755); + fs.seek(10, 100, 0).then((x: number) => {}); + fs.flock(10, "sh").then(() => {}); } namespace constantsTests { @@ -668,13 +790,44 @@ namespace fsTests { namespace mkdirTests { fs.mkdir("/path/to/some/dir").then(() => {}); fs.mkdir("/path/to/some/dir", 0o755).then(() => {}); + + fs.mkdirSync("/path/to/some/dir").then(() => {}); + fs.mkdirSync("/path/to/some/dir", 0o755).then(() => {}); + } + + namespace mkdirTests { + fs.mkdirp("/path/to/some/dir").then(() => {}); + fs.mkdirp("/path/to/some/dir", 0o755).then(() => {}); + + fs.mkdirpSync("/path/to/some/dir").then(() => {}); + fs.mkdirpSync("/path/to/some/dir", 0o755).then(() => {}); } namespace copyTests { fs.copy("a", "b").then(() => {}); - fs.copy("a", "b", {}).then(() => {}); - fs.copy("a", "b", { cwd: "/tmp" }).then(() => {}); - fs.copy("a", "b", { ignoreExisting: true }).then(() => {}); + fs.copy("a", "b", {}); + fs.copy("a", "b", { clobber: true }).then(() => {}); + fs.copy("a", "b", { overwrite: true }).then(() => {}); + fs.copy("a", "b", { filter: /asd/ }).then(() => {}); + fs.copy("a", "b", { filter: () => true }).then(() => {}); + fs.copy("a", "b", { filter: (a) => a.charCodeAt(0) === 100 }).then(() => {}); + fs.copy("a", "b", { + transform(r, w, file) { + file.atime.getDay(); + file.mtime.getDay(); + file.mode.toExponential(); + file.name.charCodeAt(0); + file.stats.atimeMs.toExponential(); + r.pipe(w); + } + }).then(() => {}); + } + + namespace copyTests { + fs.copyTo("a", "b").then(() => {}); + fs.copyTo("a", "b", {}); + fs.copyTo("a", "b", { cwd: "/tmp" }).then(() => {}); + fs.copyTo("a", "b", { ignoreExisting: true }).then(() => {}); } namespace renameTests { @@ -689,6 +842,7 @@ namespace fsTests { fs.tail("file", 10, {}).then((x: Buffer[]) => {}); fs.tail("file", 10, { separator: "\n" }).then((x: Buffer[]) => {}); fs.tail("file", 10, { chunkLength: 4096 }).then((x: Buffer[]) => {}); + fs.tail("file", 10, { pos: 10 }).then((x: Buffer[]) => {}); } namespace statVFSTests { diff --git a/types/adone/test/glosses/is.ts b/types/adone/test/glosses/is.ts index 2734824822..045818f0ec 100644 --- a/types/adone/test/glosses/is.ts +++ b/types/adone/test/glosses/is.ts @@ -1,115 +1,493 @@ namespace isTests { - { const a: boolean = adone.is.null({}); } - { const a: boolean = adone.is.undefined({}); } - { const a: boolean = adone.is.exist({}); } - { const a: boolean = adone.is.nil({}); } - { const a: boolean = adone.is.number({}); } - { const a: boolean = adone.is.numeral({}); } - { const a: boolean = adone.is.infinite({}); } - { const a: boolean = adone.is.odd({}); } - { const a: boolean = adone.is.even({}); } - { const a: boolean = adone.is.float({}); } - { const a: boolean = adone.is.negativeZero({}); } - { const a: boolean = adone.is.string({}); } - { const a: boolean = adone.is.emptyString({}); } - { const a: boolean = adone.is.substring("abc", "abcdef"); } - { const a: boolean = adone.is.substring("abc", "abcdef", 0); } - { const a: boolean = adone.is.prefix("abc", "abcdef"); } - { const a: boolean = adone.is.suffix("def", "abbdef"); } - { const a: boolean = adone.is.boolean({}); } - { const a: boolean = adone.is.json({}); } - { const a: boolean = adone.is.object({}); } - { const a: boolean = adone.is.plainObject({}); } - { const a: boolean = adone.is.class({}); } - { const a: boolean = adone.is.emptyObject({}); } - { const a: boolean = adone.is.propertyOwned({}, "a"); } - { const a: boolean = adone.is.propertyDefined({}, "a"); } - { const a: boolean = adone.is.conforms({}, {}); } - { const a: boolean = adone.is.conforms({}, {}, true); } - { const a: boolean = adone.is.arrayLikeObject({}); } - { const a: boolean = adone.is.inArray(1, [1, 2, 3]); } - { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0); } - { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0, (a, b) => a === b); } - { const a: boolean = adone.is.sameType({}, {}); } - { const a: boolean = adone.is.primitive({}); } - { const a: boolean = adone.is.equalArrays([], []); } - { const a: boolean = adone.is.deepEqual({}, {}); } - { const a: boolean = adone.is.shallowEqual({}, {}); } - { const a: boolean = adone.is.stream({}); } - { const a: boolean = adone.is.writableStream({}); } - { const a: boolean = adone.is.readableStream({}); } - { const a: boolean = adone.is.duplexStream({}); } - { const a: boolean = adone.is.transformStream({}); } - { const a: boolean = adone.is.utf8(Buffer.alloc(10)); } - { const a: boolean = adone.is.win32PathAbsolute("abc"); } - { const a: boolean = adone.is.posixPathAbsolute("abc"); } - { const a: boolean = adone.is.pathAbsolute("abc"); } - { const a: boolean = adone.is.glob("abc"); } - { const a: boolean = adone.is.dotfile("abc"); } - { const a: boolean = adone.is.function(() => { }); } - { const a: boolean = adone.is.asyncFunction(async () => { }); } - { const a: boolean = adone.is.promise({}); } - { const a: boolean = adone.is.validDate("07.08.2017"); } - { const a: boolean = adone.is.buffer({}); } - { const a: boolean = adone.is.callback({}); } - { const a: boolean = adone.is.generator({}); } - { const a: boolean = adone.is.nan({}); } - { const a: boolean = adone.is.finite({}); } - { const a: boolean = adone.is.integer({}); } - { const a: boolean = adone.is.safeInteger({}); } - { const a: boolean = adone.is.array({}); } - { const a: boolean = adone.is.uint8Array({}); } - { const a: boolean = adone.is.configuration({}); } - { const a: boolean = adone.is.long({}); } - { const a: boolean = adone.is.bigNumber({}); } - { const a: boolean = adone.is.byteArray({}); } - { const a: boolean = adone.is.datetime({}); } - { const a: boolean = adone.is.transform({}); } - { const a: boolean = adone.is.subsystem({}); } - { const a: boolean = adone.is.application({}); } - { const a: boolean = adone.is.logger({}); } - { const a: boolean = adone.is.coreStream({}); } - { const a: boolean = adone.is.fastStream({}); } - { const a: boolean = adone.is.fastLocalStream({}); } - { const a: boolean = adone.is.fastLocalMapStream({}); } - { const a: boolean = adone.is.genesisNetron({}); } - { const a: boolean = adone.is.genesisPeer({}); } - { const a: boolean = adone.is.netronAdapter({}); } - { const a: boolean = adone.is.netron({}); } - { const a: boolean = adone.is.netronPeer({}); } - { const a: boolean = adone.is.netronDefinition({}); } - { const a: boolean = adone.is.netronDefinitions({}); } - { const a: boolean = adone.is.netronReference({}); } - { const a: boolean = adone.is.netronInterface({}); } - { const a: boolean = adone.is.netronContext({}); } - { const a: boolean = adone.is.netronIMethod({}, "hello"); } - { const a: boolean = adone.is.netronIProperty({}, "hello"); } - { const a: boolean = adone.is.netronStub({}); } - { const a: boolean = adone.is.netronRemoteStub({}); } - { const a: boolean = adone.is.netronStream({}); } - { const a: boolean = adone.is.iterable({}); } - { const a: boolean = adone.is.windows; } - { const a: boolean = adone.is.linux; } - { const a: boolean = adone.is.freebsd; } - { const a: boolean = adone.is.darwin; } - { const a: boolean = adone.is.sunos; } - { const a: boolean = adone.is.uppercase("abc"); } - { const a: boolean = adone.is.lowercase("abc"); } - { const a: boolean = adone.is.digits("012"); } - { const a: boolean = adone.is.identifier("someMethod"); } - { const a: boolean = adone.is.binaryExtension("mp3"); } - { const a: boolean = adone.is.binaryPath("a.mp3"); } - { const a: boolean = adone.is.ip4("192.168.1.1"); } - { const a: boolean = adone.is.ip6("::192.168.1.1"); } - { const a: boolean = adone.is.arrayBuffer({}); } - { const a: boolean = adone.is.arrayBufferView({}); } - { const a: boolean = adone.is.date({}); } - { const a: boolean = adone.is.error({}); } - { const a: boolean = adone.is.map({}); } - { const a: boolean = adone.is.regexp({}); } - { const a: boolean = adone.is.set({}); } - { const a: boolean = adone.is.symbol({}); } - { const a: boolean = adone.is.validUTF8(Buffer.from("hello")); } - { const a: boolean = adone.is.vaultValuable({}); } - { const a: boolean = adone.is.task({}); } + const { + is + } = adone; + { + const a: boolean = is.null({}); + const b: any = 2; + if (is.null(b)) { + const c: null = b; + } + } + { + const a: boolean = is.undefined({}); + const b: any = 2; + if (is.undefined(b)) { + const c: undefined = b; + } + } + { const a: boolean = is.exist({}); } + { + const a: boolean = is.nil({}); + const b: any = 2; + if (is.nil(b)) { + const c: null | undefined = b; + } + } + { + const a: boolean = is.number({}); + const b: any = 2; + if (is.number(b)) { + b.toExponential(); + } + } + { + const a: boolean = is.numeral({}); + const b: any = 2; + if (is.numeral(b)) { + const c: string | number = b; + } + } + { + const a: boolean = is.infinite({}); + const b: any = 2; + if (is.infinite(b)) { + b.toPrecision(); + } + } + { + const a: boolean = is.odd({}); + const b: any = 2; + if (is.odd(b)) { + b.toFixed(2); + } + } + { + const a: boolean = is.even({}); + const b: any = 2; + if (is.even(b)) { + b.toFixed(2); + } + } + { + const a: boolean = is.float({}); + const b: any = 2; + if (is.float(b)) { + b.toFixed(); + } + } + { + const a: boolean = is.negativeZero({}); + const b: any = 2; + if (is.negativeZero(b)) { + b.toFixed(); + } + } + { + const a: boolean = is.string({}); + const b: any = 2; + if (is.string(b)) { + b.charCodeAt(0); + } + } + { + const a: boolean = is.emptyString({}); + const b: any = 2; + if (is.emptyString(b)) { + b.charCodeAt(0); + } + } + { const a: boolean = is.substring("abc", "abcdef"); } + { const a: boolean = is.substring("abc", "abcdef", 0); } + { const a: boolean = is.prefix("abc", "abcdef"); } + { const a: boolean = is.suffix("def", "abbdef"); } + { + const a: boolean = is.boolean({}); + const b: any = 2; + if (is.boolean(b)) { + b === true; + } + } + { const a: boolean = is.json({}); } + { + const a: boolean = is.object({}); + const b: any = 2; + if (is.object(b)) { + const c: object = b; + } + } + { + const a: boolean = is.plainObject({}); + const b: any = 2; + if (is.plainObject(b)) { + const c: object = b; + } + } + { const a: boolean = is.class({}); } + { const a: boolean = is.emptyObject({}); } + { const a: boolean = is.propertyOwned({}, "a"); } + { const a: boolean = is.propertyDefined({}, "a"); } + { const a: boolean = is.conforms({}, {}); } + { const a: boolean = is.conforms({}, {}, true); } + { + const a: boolean = is.arrayLikeObject({}); + const b: any = {}; + if (is.arrayLikeObject(b)) { + const c: number = b.length; + b[0]; + } + } + { const a: boolean = is.inArray(1, [1, 2, 3]); } + { const a: boolean = is.inArray(1, [1, 2, 3], 0); } + { const a: boolean = is.inArray(1, [1, 2, 3], 0, (a, b) => a === b); } + { const a: boolean = is.sameType({}, {}); } + { const a: boolean = is.primitive({}); } + { const a: boolean = is.equalArrays([], []); } + { const a: boolean = is.deepEqual({}, {}); } + { const a: boolean = is.shallowEqual({}, {}); } + { const a: boolean = is.stream({}); } + { const a: boolean = is.writableStream({}); } + { const a: boolean = is.readableStream({}); } + { const a: boolean = is.duplexStream({}); } + { const a: boolean = is.transformStream({}); } + { const a: boolean = is.utf8(Buffer.alloc(10)); } + { const a: boolean = is.win32PathAbsolute("abc"); } + { const a: boolean = is.posixPathAbsolute("abc"); } + { const a: boolean = is.pathAbsolute("abc"); } + { + const a: boolean = is.glob("abc"); + const b: any = 2; + if (is.glob(b)) { + b.charCodeAt(0); + } + } + { const a: boolean = is.dotfile("abc"); } + { + const a: boolean = is.function(() => { }); + const b: any = 2; + if (is.function(b)) { + b(); + } + } + { + const a: boolean = is.asyncFunction(async () => { }); + const b: any = 2; + if (is.asyncFunction(b)) { + b().then(() => {}); + } + } + { + const a: boolean = is.promise({}); + const b: any = 2; + if (is.promise(b)) { + b.then(() => {}); + } + const c = Promise.resolve(2); + if (is.promise(c)) { + c.then((x) => x.toFixed(2)); + } + } + { const a: boolean = is.validDate("07.08.2017"); } + { + const a: boolean = is.buffer({}); + const b: any = 2; + if (is.buffer(b)) { + b.writeDoubleBE(10, 10); + } + } + { const a: boolean = is.callback({}); } + { + const a: boolean = is.generator({}); + const b: any = 2; + if (is.generator(b)) { + b().next(); + } + } + { const a: boolean = is.nan({}); } + { + const a: boolean = is.finite({}); + const b: any = 2; + if (is.finite(b)) { + b.toFixed(); + } + } + { + const a: boolean = is.integer({}); + const b: any = 2; + if (is.integer(b)) { + b.toFixed(); + } + } + { + const a: boolean = is.safeInteger({}); + const b: any = 2; + if (is.safeInteger(b)) { + b.toFixed(); + } + } + { + const a: boolean = is.array({}); + const b: any = 2; + if (is.array(b)) { + b.length + b[0]; + } + const c = [1, 2, 3]; + if (is.array(c)) { + c[0].toFixed(0); + } + } + { + const a: boolean = is.uint8Array({}); + const b: any = 2; + if (is.uint8Array(b)) { + b.copyWithin(1, 2); + } + } + { const a: boolean = is.configuration({}); } + { + const a: boolean = is.long({}); + const b: any = 2; + if (is.long(b)) { + b.getHighBitsUnsigned(); + } + } + { + const a: boolean = is.bigNumber({}); + const b: any = 2; + if (is.bigNumber(b)) { + b.add(b).isBitSet(10); + } + } + { + const a: boolean = is.byteArray({}); + const b: any = 2; + if (is.byteArray(b)) { + b.toBuffer(); + } + } + { + const a: boolean = is.datetime({}); + const b: any = 2; + if (is.datetime(b)) { + b.add(2, "hours"); + } + } + { const a: boolean = is.transform({}); } + { + const a: boolean = is.subsystem({}); + const b: any = 2; + if (is.subsystem(b)) { + b.configureSubsystems().then(() => {}); + } + } + { + const a: boolean = is.application({}); + const b: any = 2; + if (is.application(b)) { + b.exitOnSignal("SIGINT"); + } + } + { const a: boolean = is.logger({}); } + { + const a: boolean = is.coreStream({}); + const b: any = 2; + if (is.coreStream(b)) { + b.map((x) => 2).forEach((t: number) => { + // + }); + } + } + { + const a: boolean = is.fastStream({}); + const b: any = 2; + if (is.fastStream(b)) { + b.compress("deflate"); + } + } + { + const a: boolean = is.fastLocalStream({}); + const b: any = 2; + if (is.fastLocalStream(b)) { + b.compress("gz"); + } + } + { + const a: boolean = is.fastLocalMapStream({}); + const b: any = 2; + if (is.fastLocalMapStream(b)) { + b.decompress("gz"); + } + } + { const a: boolean = is.genesisNetron({}); } + { const a: boolean = is.genesisPeer({}); } + { const a: boolean = is.netronAdapter({}); } + { const a: boolean = is.netron({}); } + { const a: boolean = is.netronPeer({}); } + { const a: boolean = is.netronDefinition({}); } + { const a: boolean = is.netronDefinitions({}); } + { const a: boolean = is.netronReference({}); } + { const a: boolean = is.netronInterface({}); } + { const a: boolean = is.netronContext({}); } + { const a: boolean = is.netronIMethod({}, "hello"); } + { const a: boolean = is.netronIProperty({}, "hello"); } + { const a: boolean = is.netronStub({}); } + { const a: boolean = is.netronRemoteStub({}); } + { const a: boolean = is.netronStream({}); } + { + const a: boolean = is.iterable({}); + const b: any = 2; + if (is.iterable(b)) { + const it = b[Symbol.iterator](); + it.next(); + } + } + { const a: boolean = is.windows; } + { const a: boolean = is.linux; } + { const a: boolean = is.freebsd; } + { const a: boolean = is.darwin; } + { const a: boolean = is.sunos; } + { const a: boolean = is.uppercase("abc"); } + { const a: boolean = is.lowercase("abc"); } + { const a: boolean = is.digits("012"); } + { const a: boolean = is.identifier("someMethod"); } + { const a: boolean = is.binaryExtension("mp3"); } + { const a: boolean = is.binaryPath("a.mp3"); } + { const a: boolean = is.ip4("192.168.1.1"); } + { const a: boolean = is.ip6("::192.168.1.1"); } + { + const a: boolean = is.arrayBuffer({}); + const b: any = 2; + if (is.arrayBuffer(b)) { + b.slice(10); + } + } + { + const a: boolean = is.arrayBufferView({}); + const b: any = 2; + if (is.arrayBufferView(b)) { + b.byteLength + b.byteOffset; + } + } + { + const a: boolean = is.date({}); + const b: any = 2; + if (is.date(b)) { + b.getMonth() + b.getDate(); + } + } + { const a: boolean = is.error({}); } + { + const a: boolean = is.map({}); + const b: any = 2; + if (is.map(b)) { + b.has("asd"); + b.set(1, 2); + b.set("1", 2); + } + } + { + const a: boolean = is.regexp({}); + const b: any = 2; + if (is.regexp(b)) { + b.test("hello"); + } + } + { + const a: boolean = is.set({}); + const b: any = 2; + if (is.set(b)) { + b.add("h"); + b.has(1); + } + } + { const a: boolean = is.symbol({}); } + { const a: boolean = is.vaultValuable({}); } + { const a: boolean = is.task({}); } + { + const a: boolean = is.fqdn(1); + const b: any = 2; + if (is.fqdn(b)) { + b.charCodeAt(0); + } + if (is.fqdn(b, {})) { + b.charCodeAt(0); + } + is.fqdn(1, { + allowTrailingDot: false + }); + is.fqdn(1, { + allowUnderscores: false + }); + is.fqdn(1, { + requireTld: true + }); + } + { + const a: boolean = is.email(1); + const b: any = 2; + if (is.email(b)) { + b.charCodeAt(0); + } + if (is.email(b, {})) { + b.charCodeAt(0); + } + is.email(1, { + allowDisplayName: false + }); + is.email(1, { + allowUtf8LocalPart: false + }); + is.email(1, { + requireDisplayName: false + }); + is.email(1, { + requireTld: false + }); + } + { + const a: boolean = is.uuid(2); + const b: any = 2; + if (is.uuid(b)) { + b.charCodeAt(0); + } + } + { + const a: boolean = is.uuid(2, "all"); + const b: any = 2; + if (is.uuid(b, "all")) { + b.charCodeAt(0); + } + } + { + const a: boolean = is.uuid(2, "all"); + const b: any = 2; + if (is.uuid(b, "all")) { + b.charCodeAt(0); + } + } + { + const a: boolean = is.uuid(2, 1); + const b: any = 2; + if (is.uuid(b, 1)) { + b.charCodeAt(0); + } + } + { + const a: boolean = is.uuid(2, 2); + const b: any = 2; + if (is.uuid(b, 2)) { + b.charCodeAt(0); + } + } + { + const a: boolean = is.uuid(2, 3); + const b: any = 2; + if (is.uuid(b, 2)) { + b.charCodeAt(0); + } + } + { + const a: boolean = is.uuid(2, 4); + const b: any = 2; + if (is.uuid(b, 2)) { + b.charCodeAt(0); + } + } + { + const a: boolean = is.uuid(2, 5); + const b: any = 2; + if (is.uuid(b, 2)) { + b.charCodeAt(0); + } + } } diff --git a/types/adone/test/glosses/meta.ts b/types/adone/test/glosses/meta.ts new file mode 100644 index 0000000000..fbcde09b1a --- /dev/null +++ b/types/adone/test/glosses/meta.ts @@ -0,0 +1,7 @@ +namespace metaTests { + const { meta } = adone; + + namespace typeOf { + const a: string = meta.typeOf(1); + } +} diff --git a/types/adone/test/glosses/net/http/client.ts b/types/adone/test/glosses/net/http/client.ts new file mode 100644 index 0000000000..0992c1576c --- /dev/null +++ b/types/adone/test/glosses/net/http/client.ts @@ -0,0 +1,499 @@ +namespace adoneTests.net.http.client { + const { + net: { + http: { + client + } + } + } = adone; + + let bool: boolean; + let num: number; + let str: string; + let buf: Buffer; + let stream: nodestd.stream.Readable; + + namespace Client { + const { + Client + } = client; + + new Client(); + new Client({}); + new Client({ + auth: { + username: "a" + } + }); + new Client({ + auth: { + password: "a" + } + }); + new Client({ + cancelToken: new client.CancelToken(() => {}) + }); + new Client({ + data: Buffer.from("hello") + }); + new Client({ + data: "hello" + }); + new Client({ + data: adone.fs.createReadStream(__filename) + }); + new Client({ + data: new ArrayBuffer(10) + }); + new Client({ + formData: { + a: "string" + } + }); + new Client({ + formData: { + a: ["string"] + } + }); + new Client({ + formData: { + a: [adone.fs.createReadStream(__filename)] + } + }); + new Client({ + formData: { + a: { + value: "string", + options: {} + } + } + }); + new Client({ + formData: { + a: { + value: "string", + options: { + contentType: "a" + } + } + } + }); + new Client({ + formData: { + a: { + value: "string", + options: { + filename: "a" + } + } + } + }); + new Client({ + formData: { + a: { + value: "string", + options: { + header: "a" + } + } + } + }); + new Client({ + formData: { + a: { + value: "string", + options: { + header: { + a: "a" + } + } + } + } + }); + new Client({ + formData: { + a: { + value: "string", + options: { + knownLength: 100500 + } + } + } + }); + new Client({ + formData: { + a: [{ + value: "string", + options: { + knownLength: 100500 + } + }] + } + }); + new Client({ + headers: { + "User-Agent": "true" + } + }); + new Client({ + httpAgent: {} + }); + new Client({ + httpsAgent: {} + }); + new Client({ + maxContentLength: 100500 + }); + new Client({ + maxRedirects: 100500 + }); + new Client({ + method: "GET" + }); + new Client({ + onUploadProgress(event) { + bool = event.lengthComputable; + num = event.loaded; + num = event.total; + } + }); + new Client({ + params: { + a: 1 + } + }); + new Client({ + paramsSerializer(params: object) { + return "asd"; + } + }); + new Client({ + proxy: "socks5://localhost" + }); + new Client({ + proxy: { + protocol: "socks5", + host: "127.0.0.1", + port: 9000, + auth: { + username: "hello", + password: "world" + } + } + }); + + new Client({ + rejectUnauthorized: true + }); + new Client({ + responseEncoding: "CP1251" + }); + new Client({ + responseType: "stream" + }); + new Client({ + timeout: 100 + }); + new Client({ + transformRequest: [(data, headers, config) => { + return data; + }] + }); + new Client({ + transformResponse: [(data, headers, config) => { + return data; + }] + }); + new Client({ + transport: adone.std.http + }); + new Client({ + validateStatus(status) { + return status > 100; + } + }); + new Client({ + xsrfCookieName: "a" + }); + new Client({ + xsrfHeaderName: "a" + }); + + const req = new Client(); + + namespace request { + req.request({ + method: "GET" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + const len = resp.headers["content-length"]; + if (!adone.is.undefined(len)) { + str = len; + } + const data = resp.data; + if (!adone.is.object(data)) { + str = data; + } + }); + req.request({ + method: "GET", + responseType: "string" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + str = resp.data; + }); + req.request({ + method: "GET", + responseType: "buffer" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + buf = resp.data; + }); + req.request({ + method: "GET", + responseType: "stream" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + stream = resp.data; + }); + } + + namespace get { + req.get("url").then((resp) => { + num = resp.status; + str = resp.statusText; + const data = resp.data; + if (!adone.is.object(data)) { + str = data; + } + }); + req.get("url", { + responseType: "string" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + str = resp.data; + }); + req.get("url", { + responseType: "buffer" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + buf = resp.data; + }); + req.get("url", { + responseType: "stream" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + stream = resp.data; + }); + } + + namespace post { + req.post("url", {}).then((resp) => { + num = resp.status; + str = resp.statusText; + const data = resp.data; + if (!adone.is.object(data)) { + str = data; + } + }); + req.post("url", {}, { + responseType: "string" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + str = resp.data; + }); + req.post("url", {}, { + responseType: "buffer" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + buf = resp.data; + }); + req.post("url", {}, { + responseType: "stream" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + stream = resp.data; + }); + } + + namespace put { + req.put("url", {}).then((resp) => { + num = resp.status; + str = resp.statusText; + const data = resp.data; + if (!adone.is.object(data)) { + str = data; + } + }); + req.put("url", {}, { + responseType: "string" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + str = resp.data; + }); + req.put("url", {}, { + responseType: "buffer" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + buf = resp.data; + }); + req.put("url", {}, { + responseType: "stream" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + stream = resp.data; + }); + } + + namespace patch { + req.patch("url", {}).then((resp) => { + num = resp.status; + str = resp.statusText; + const data = resp.data; + if (!adone.is.object(data)) { + str = data; + } + }); + req.patch("url", {}, { + responseType: "string" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + str = resp.data; + }); + req.patch("url", {}, { + responseType: "buffer" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + buf = resp.data; + }); + req.patch("url", {}, { + responseType: "stream" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + stream = resp.data; + }); + } + + namespace _delete { + req.delete("url").then((resp) => { + num = resp.status; + str = resp.statusText; + const data = resp.data; + if (!adone.is.object(data)) { + str = data; + } + }); + req.delete("url", { + responseType: "string" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + str = resp.data; + }); + req.delete("url", { + responseType: "buffer" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + buf = resp.data; + }); + req.delete("url", { + responseType: "stream" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + stream = resp.data; + }); + } + + namespace options { + req.options("url").then((resp) => { + num = resp.status; + str = resp.statusText; + const data = resp.data; + if (!adone.is.object(data)) { + str = data; + } + }); + req.options("url", { + responseType: "string" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + str = resp.data; + }); + req.options("url", { + responseType: "buffer" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + buf = resp.data; + }); + req.options("url", { + responseType: "stream" + }).then((resp) => { + num = resp.status; + str = resp.statusText; + stream = resp.data; + }); + } + } + + namespace request { + client.request.get("htllo").then((x) => { + num = x.status; + }); + } + + namespace create { + client.create(); + client.create({}); + const req = client.create({ + headers: { + "User-Agent": "Hello" + } + }); + req.get("hello world").then((x) => { + num = x.status; + }); + } + + namespace cancel { + const { + Cancel, + CancelToken, + isCancel + } = client; + + new CancelToken((s: string) => 123).promise.then((x) => { + str = x.message; + }); + new CancelToken((s: string) => 123).reason; + CancelToken.source().token.promise; + CancelToken.source().cancel("hello"); + + new Cancel("hello").message; + + const a: any = 2; + + if (isCancel(a)) { + str = a.message; + } + } +} diff --git a/types/adone/test/glosses/pretty/json.ts b/types/adone/test/glosses/pretty/json.ts new file mode 100644 index 0000000000..730447baba --- /dev/null +++ b/types/adone/test/glosses/pretty/json.ts @@ -0,0 +1,19 @@ +namespace adoneTests.pretty.json { + const { + json + } = adone.pretty; + + let str: string; + + str = json({}); + str = json({}, {}); + str = json({}, {}, 1); + str = json({}, { dashColor: "green" }); + str = json({}, { defaultIndentation: 10 }); + str = json({}, { emptyArrayMsg: "asdas" }); + str = json({}, { keysColor: "green" }); + str = json({}, { noAlign: true }); + str = json({}, { noColor: true }); + str = json({}, { numberColor: "green" }); + str = json({}, { stringColor: "green" }); +} diff --git a/types/adone/test/glosses/pretty/size.ts b/types/adone/test/glosses/pretty/size.ts new file mode 100644 index 0000000000..1ed5e904fe --- /dev/null +++ b/types/adone/test/glosses/pretty/size.ts @@ -0,0 +1,12 @@ +namespace adoneTests.pretty.size { + const { + pretty: { + size + } + } = adone; + + let str: string; + + str = size(12345); + str = size(12345, ""); +} diff --git a/types/adone/test/glosses/pretty/table.ts b/types/adone/test/glosses/pretty/table.ts new file mode 100644 index 0000000000..0ed4099bbc --- /dev/null +++ b/types/adone/test/glosses/pretty/table.ts @@ -0,0 +1,177 @@ +namespace adoneTests.pretty.table { + const { + table + } = adone.pretty; + + let str: string; + + str = table([], { + model: [] + }); + str = table([], { + borderless: true, + model: [] + }); + str = table([], { + countAnsiEscapeCodes: true, + model: [] + }); + str = table([], { + noHeader: true, + model: [] + }); + str = table([], { + style: { + "padding-left": 1 + }, + model: [] + }); + str = table([], { + style: { + "padding-right": 1 + }, + model: [] + }); + str = table([], { + style: { + broder: ["a"] + }, + model: [] + }); + str = table([], { + style: { + compact: true + }, + model: [] + }); + str = table([], { + style: { + head: ["a"] + }, + model: [] + }); + str = table([], { + width: 100, + model: [] + }); + str = table([], { + width: "100%", + model: [] + }); + str = table([], { + model: [{ + id: "ads", + align: "center" + }] + }); + str = table([], { + model: [{ + id: "ads", + format: "%s" + }] + }); + str = table([], { + model: [{ + id: "ads", + format(val: any, item: object) { + return "2"; + } + }] + }); + str = table([], { + model: [{ + id: "ads", + handle(item: object) { + return "a"; + } + }] + }); + str = table([], { + model: [{ + id: "ads", + header: "he" + }] + }); + str = table([], { + model: [{ + id: "ads", + maxWidth: "100%" + }] + }); + str = table([], { + model: [{ + id: "ads", + maxWidth: 100 + }] + }); + str = table([], { + model: [{ + id: "ads", + style: "asd" + }] + }); + str = table([], { + model: [{ + id: "ads", + style(val: any, str: string) { + return "1"; + } + }] + }); + str = table([], { + model: [{ + id: "ads", + width: 100 + }] + }); + str = table([], { + model: [{ + id: "ads", + width: "100%" + }] + }); + str = table([], { + model: [{ + id: "ads", + wordwrap: "soft" + }] + }); + str = table([], { + model: [{ + id: "ads", + wordwrap: "hard" + }] + }); + str = table([], { + model: [{ + id: "ads", + wordwrap: { + countAnsiEscapeCodes: true + } + }] + }); + str = table([], { + model: [{ + id: "ads", + wordwrap: { + join: true + } + }] + }); + str = table([], { + model: [{ + id: "ads", + wordwrap: { + mode: "soft" + } + }] + }); + str = table([], { + model: [{ + id: "ads", + wordwrap: { + mode: "hard" + } + }] + }); +} diff --git a/types/adone/test/glosses/pretty/time.ts b/types/adone/test/glosses/pretty/time.ts new file mode 100644 index 0000000000..79d1e6325f --- /dev/null +++ b/types/adone/test/glosses/pretty/time.ts @@ -0,0 +1,14 @@ +namespace adoneTests.pretty.time { + const { + time + } = adone.pretty; + + let str: string; + + str = time(12345); + str = time(12345, {}); + str = time(12345, { compact: true }); + str = time(12345, { msDecimalDigits: 2 }); + str = time(12345, { secDecimalDigits: 2 }); + str = time(12345, { verbose: true }); +} diff --git a/types/adone/test/glosses/promise.ts b/types/adone/test/glosses/promise.ts index a8866d95a1..9df672cae8 100644 --- a/types/adone/test/glosses/promise.ts +++ b/types/adone/test/glosses/promise.ts @@ -106,4 +106,34 @@ namespace promiseTests { namespace _finally { promise.finally(Promise.resolve(2), () => 2).then((x: number) => {}); } + + namespace props { + promise.props({ a: Promise.resolve(2) }).then((x) => x.a); + } + + namespace retry { + promise.retry((info) => { + { const a: number = info.current; } + }); + + promise.retry(() => {}, {}); + promise.retry(() => {}, { backOffBase: 1000 }); + promise.retry(() => {}, { backOffExponent: 2 }); + promise.retry(() => {}, { match: "a" }); + promise.retry(() => {}, { match: ["a"] }); + promise.retry(() => {}, { match: [/abc/] }); + promise.retry(() => {}, { match: /abc/ }); + promise.retry(() => {}, { match: [new Error()] }); + promise.retry(() => {}, { match: new Error() }); + promise.retry(() => {}, { max: 100 }); + promise.retry(() => {}, { name: "asd" }); + promise.retry(() => {}, { + report(msg: string, opts) { + opts.backOffBase < 100; + } + }); + promise.retry(() => {}, { + timeout: 100 + }); + } } diff --git a/types/adone/test/glosses/regex.ts b/types/adone/test/glosses/regex.ts new file mode 100644 index 0000000000..7aab1e0d8d --- /dev/null +++ b/types/adone/test/glosses/regex.ts @@ -0,0 +1,17 @@ +namespace adoneTests.regex { + const { + regex + } = adone; + + regex.ansi().test("a"); + regex.filename().test("a"); + regex.idn().test("a"); + regex.ip4().test("a"); + regex.ip6().test("a"); + regex.protocol().test("a"); + regex.punycode().test("a"); + regex.shebang().test("a"); + regex.uri().test("a"); + regex.uuid4().test("a"); + regex.uuid5().test("a"); +} diff --git a/types/adone/test/glosses/semver.ts b/types/adone/test/glosses/semver.ts new file mode 100644 index 0000000000..e6ac7a50b0 --- /dev/null +++ b/types/adone/test/glosses/semver.ts @@ -0,0 +1,131 @@ +namespace adoneTests.semver { + const { + semver + } = adone; + + type ReleaseType = adone.semver.I.ReleaseType; + type Operator = adone.semver.I.Operator; + type SemVer = adone.semver.SemVer; + type Comparator = adone.semver.Comparator; + + let bool: boolean; + let num: number; + let str = ''; + let strn: string | null = ''; + let diff: ReleaseType | null; + const op: Operator = ''; + declare const arr: any[]; + declare const exp: RegExp; + let strArr: string[] | null; + declare const numArr: string[]; + let comparatorResult: -1 | 0 | 1; + let versionsArr: Array; + + const v1 = ''; + const v2 = ''; + const version = ''; + const versions: string[] = []; + const loose = true; + let sem: SemVer | null; + + sem = semver.parse(str); + strn = semver.valid(str); + strn = semver.clean(str); + + strn = semver.valid(str, loose); + strn = semver.clean(str, loose); + strn = semver.inc(str, "major", loose); + strn = semver.inc(str, "premajor", loose); + strn = semver.inc(str, "minor", loose); + strn = semver.inc(str, "preminor", loose); + strn = semver.inc(str, "patch", loose); + strn = semver.inc(str, "prepatch", loose); + strn = semver.inc(str, "prerelease", loose); + strn = semver.inc(str, "prerelease", loose, "alpha"); + num = semver.major(str, loose); + num = semver.minor(str, loose); + num = semver.patch(str, loose); + strArr = semver.prerelease(str, loose); + + // Comparison + bool = semver.gt(v1, v2, loose); + bool = semver.gte(v1, v2, loose); + bool = semver.lt(v1, v2, loose); + bool = semver.lte(v1, v2, loose); + bool = semver.eq(v1, v2, loose); + bool = semver.neq(v1, v2, loose); + bool = semver.cmp(v1, op, v2, loose); + comparatorResult = semver.compare(v1, v2, loose); + comparatorResult = semver.rcompare(v1, v2, loose); + comparatorResult = semver.compareIdentifiers(str, str); + comparatorResult = semver.rcompareIdentifiers(str, str); + versionsArr = semver.sort(['', new semver.SemVer('')]); + versionsArr = semver.rsort(['', new semver.SemVer('')]); + diff = semver.diff(v1, v2, loose); + + // Ranges + str = semver.validRange(str, loose); + bool = semver.satisfies(version, str, loose); + str = semver.maxSatisfying(versions, str, loose); + str = semver.minSatisfying(versions, str, loose); + bool = semver.gtr(version, str, loose); + bool = semver.ltr(version, str, loose); + bool = semver.outside(version, str, '<', loose); + bool = semver.intersects(str, str, loose); + + // Coercion + sem = semver.coerce(str); + + let ver = new semver.SemVer(str, bool); + str = ver.raw; + bool = ver.loose; + str = ver.format(); + str = ver.inspect(); + str = ver.toString(); + + num = ver.major; + num = ver.minor; + num = ver.patch; + str = ver.version; + strArr = ver.build; + strArr = ver.prerelease; + + comparatorResult = ver.compare(ver); + comparatorResult = ver.compareMain(ver); + comparatorResult = ver.comparePre(ver); + ver = ver.inc("major"); + ver = ver.inc("premajor"); + ver = ver.inc("minor"); + ver = ver.inc("preminor"); + ver = ver.inc("patch"); + ver = ver.inc("prepatch"); + ver = ver.inc("prerelease"); + ver = ver.inc("prerelease", "alpha"); + + const comp = new semver.Comparator(str, bool); + str = comp.toString(); + + ver = comp.semver; + str = comp.operator; + bool = comp.value; + comp.parse(str); + bool = comp.test(ver); + bool = comp.intersects(new semver.Comparator(str)); + bool = comp.intersects(new semver.Comparator(str), bool); + + const range = new semver.Range(str, bool); + str = range.raw; + bool = range.loose; + str = range.format(); + str = range.inspect(); + str = range.toString(); + bool = range.test(ver); + bool = range.intersects(new semver.Range('')); + bool = range.intersects(new semver.Range(''), bool); + + let sets: Comparator[][]; + sets = range.set; + + let lims: Comparator[]; + lims = range.parseRange(str); +} diff --git a/types/adone/test/glosses/std.ts b/types/adone/test/glosses/std.ts index 9bcb6687d4..a84d9cc901 100644 --- a/types/adone/test/glosses/std.ts +++ b/types/adone/test/glosses/std.ts @@ -39,6 +39,12 @@ namespace stdTests { std.http.get("http://localhost").end(); } + namespace http2 { + std.http2.connect("somewhere").on("stream", (stream) => { + stream.pipe(process.stdout); + }); + } + namespace https { std.https.get("https://adone.io").end(); } @@ -91,6 +97,10 @@ namespace stdTests { std.domain.create().members; } + namespace module { + new std.module.Module("1").exports; + } + namespace tty { const a: boolean = std.tty.isatty(1); } @@ -126,4 +136,8 @@ namespace stdTests { namespace dgram { std.dgram.createSocket("udp4").bind(31337); } + + namespace perf_hooks { + std.perf_hooks.performance.measure("1", "2", "3"); + } } diff --git a/types/adone/test/glosses/streams.ts b/types/adone/test/glosses/streams.ts index bd090dc467..caa278955a 100644 --- a/types/adone/test/glosses/streams.ts +++ b/types/adone/test/glosses/streams.ts @@ -2,82 +2,82 @@ namespace streamsTests { const { stream } = adone; namespace CoreStreamTests { - const { CoreStream } = stream; + const { core: { Stream } } = stream; - new CoreStream(); - new CoreStream(undefined); - new CoreStream(undefined, {}); - new CoreStream(undefined, { async: true }); - new CoreStream(undefined, { sync: true }); - new CoreStream(undefined, { + new Stream(); + new Stream(undefined); + new Stream(undefined, {}); + new Stream(undefined, { async: true }); + new Stream(undefined, { sync: true }); + new Stream(undefined, { transform(x) { this.push(x); } }); - new CoreStream(undefined, { + new Stream(undefined, { flush() { this.push(1); } }); - new CoreStream([]); - new CoreStream(new CoreStream([])); + new Stream([]); + new Stream(new Stream([])); - { const a: boolean = new CoreStream().write(1); } - { const a: boolean = new CoreStream().push(1); } - { const a: adone.stream.CoreStream = new CoreStream().end(); } - { const a: adone.stream.CoreStream = new CoreStream().destroy(); } - { const a: adone.stream.CoreStream = new CoreStream().pause(); } - { const a: adone.stream.CoreStream = new CoreStream().resume(); } - { const a: boolean = new CoreStream().isPaused(); } - { const a: boolean = new CoreStream().isEnded(); } - { const a: nodestd.stream.Transform = new CoreStream().pipe(new adone.std.stream.Transform()); } - { const a: adone.stream.CoreStream = new CoreStream().throughSync(function () { this.push(1); }); } - { const a: adone.stream.CoreStream = new CoreStream().throughSync(function () { this.push(1); }, function () { this.push(1); }); } - { const a: adone.stream.CoreStream = new CoreStream().throughAsync(function () { this.push(1); }); } - { const a: adone.stream.CoreStream = new CoreStream().throughAsync(function () { this.push(1); }, function () { this.push(1); }); } - { const a: adone.stream.CoreStream = new CoreStream().through(function () { this.push(1); }, function () { this.push(1); }); } - { const a: adone.stream.CoreStream = new CoreStream([1, 2, 3]).map((x) => `${x}`); } - { const a: adone.stream.CoreStream = new CoreStream().mapIf((x) => x === "1", () => 1); } - { const a: adone.stream.CoreStream = new CoreStream().mapIf(async (x) => x === "1", () => 1); } - { const a: adone.stream.CoreStream = new CoreStream().filter((x) => x === 1); } - { const a: adone.stream.CoreStream = new CoreStream().filter(async (x) => x === 1); } - { const a: adone.stream.CoreStream = new CoreStream().forEach(async (x) => x === 1); } - { const a: adone.stream.CoreStream = new CoreStream().forEach(async (x) => x === 1, {}); } - { const a: adone.stream.CoreStream = new CoreStream().forEach(async (x) => x === 1, { passthrough: true }); } - { const a: adone.stream.CoreStream = new CoreStream().forEach(async (x) => x === 1, { wait: true }); } - { const a: adone.stream.CoreStream = new CoreStream().done(() => {}); } - { const a: adone.stream.CoreStream = new CoreStream().done(() => {}, {}); } - { const a: adone.stream.CoreStream = new CoreStream().done(() => {}, { passthrough: true }); } - { const a: adone.stream.CoreStream = new CoreStream().toArray((x: any[]) => {}); } - { const a: adone.stream.CoreStream = new CoreStream().toArray((x: any[]) => {}, {}); } - { const a: adone.stream.CoreStream = new CoreStream().toArray((x: any[]) => {}, { passthrough: true }); } - { const a: adone.stream.CoreStream = new CoreStream().unique(); } - { const a: adone.stream.CoreStream = new CoreStream().unique((x) => x + 1); } - { const a: adone.stream.CoreStream = new CoreStream().stash((x) => x === 1); } - { const a: adone.stream.CoreStream = new CoreStream().stash("hello", (x) => x === 1); } - { const a: adone.stream.CoreStream = new CoreStream().unstash("hello"); } - { const a: adone.stream.CoreStream = new CoreStream().unstash(); } - { const a: adone.stream.CoreStream = new CoreStream().flatten(); } - { const a: Promise = new CoreStream().then(); } - { const a: Promise = new CoreStream().then(() => "1"); } - { const a: Promise = new CoreStream().then(() => 1, () => 2); } - { const a: Promise = new CoreStream().catch(); } - { const a: Promise = new CoreStream().catch(() => 1); } - { const a: adone.stream.CoreStream = CoreStream.merge([new CoreStream()]); } - { const a: adone.stream.CoreStream = CoreStream.merge([new adone.std.stream.Readable()]); } - { const a: adone.stream.CoreStream = CoreStream.merge([new adone.std.stream.Transform()]); } - { const a: adone.stream.CoreStream = CoreStream.merge([new adone.std.stream.Transform()]); } - { const a: adone.stream.CoreStream = CoreStream.merge([new adone.std.stream.Duplex()]); } - { const a: adone.stream.CoreStream = CoreStream.merge([], {}); } - { const a: adone.stream.CoreStream = CoreStream.merge([], { end: true }); } - { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: {} }); } - { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: { async: true } }); } - { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: { sync: false } }); } - { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: { transform(x) { this.push(x); } } }); } - { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: { flush() { this.push(1); } } }); } + { const a: boolean = new Stream().write(1); } + { const a: boolean = new Stream().push(1); } + { const a: adone.stream.core.Stream = new Stream().end(); } + { const a: adone.stream.core.Stream = new Stream().destroy(); } + { const a: adone.stream.core.Stream = new Stream().pause(); } + { const a: adone.stream.core.Stream = new Stream().resume(); } + { const a: boolean = new Stream().isPaused(); } + { const a: boolean = new Stream().isEnded(); } + { const a: nodestd.stream.Transform = new Stream().pipe(new adone.std.stream.Transform()); } + { const a: adone.stream.core.Stream = new Stream().throughSync(function () { this.push(1); }); } + { const a: adone.stream.core.Stream = new Stream().throughSync(function () { this.push(1); }, function () { this.push(1); }); } + { const a: adone.stream.core.Stream = new Stream().throughAsync(function () { this.push(1); }); } + { const a: adone.stream.core.Stream = new Stream().throughAsync(function () { this.push(1); }, function () { this.push(1); }); } + { const a: adone.stream.core.Stream = new Stream().through(function () { this.push(1); }, function () { this.push(1); }); } + { const a: adone.stream.core.Stream = new Stream([1, 2, 3]).map((x) => `${x}`); } + { const a: adone.stream.core.Stream = new Stream().mapIf((x) => x === "1", () => 1); } + { const a: adone.stream.core.Stream = new Stream().mapIf(async (x) => x === "1", () => 1); } + { const a: adone.stream.core.Stream = new Stream().filter((x) => x === 1); } + { const a: adone.stream.core.Stream = new Stream().filter(async (x) => x === 1); } + { const a: adone.stream.core.Stream = new Stream().forEach(async (x) => x === 1); } + { const a: adone.stream.core.Stream = new Stream().forEach(async (x) => x === 1, {}); } + { const a: adone.stream.core.Stream = new Stream().forEach(async (x) => x === 1, { passthrough: true }); } + { const a: adone.stream.core.Stream = new Stream().forEach(async (x) => x === 1, { wait: true }); } + { const a: adone.stream.core.Stream = new Stream().done(() => {}); } + { const a: adone.stream.core.Stream = new Stream().done(() => {}, {}); } + { const a: adone.stream.core.Stream = new Stream().done(() => {}, { passthrough: true }); } + { const a: adone.stream.core.Stream = new Stream().toArray((x: any[]) => {}); } + { const a: adone.stream.core.Stream = new Stream().toArray((x: any[]) => {}, {}); } + { const a: adone.stream.core.Stream = new Stream().toArray((x: any[]) => {}, { passthrough: true }); } + { const a: adone.stream.core.Stream = new Stream().unique(); } + { const a: adone.stream.core.Stream = new Stream().unique((x) => x + 1); } + { const a: adone.stream.core.Stream = new Stream().stash((x) => x === 1); } + { const a: adone.stream.core.Stream = new Stream().stash("hello", (x) => x === 1); } + { const a: adone.stream.core.Stream = new Stream().unstash("hello"); } + { const a: adone.stream.core.Stream = new Stream().unstash(); } + { const a: adone.stream.core.Stream = new Stream().flatten(); } + { const a: Promise = new Stream().then(); } + { const a: Promise = new Stream().then(() => "1"); } + { const a: Promise = new Stream().then(() => 1, () => 2); } + { const a: Promise = new Stream().catch(); } + { const a: Promise = new Stream().catch(() => 1); } + { const a: adone.stream.core.Stream = Stream.merge([new Stream()]); } + { const a: adone.stream.core.Stream = Stream.merge([new adone.std.stream.Readable()]); } + { const a: adone.stream.core.Stream = Stream.merge([new adone.std.stream.Transform()]); } + { const a: adone.stream.core.Stream = Stream.merge([new adone.std.stream.Transform()]); } + { const a: adone.stream.core.Stream = Stream.merge([new adone.std.stream.Duplex()]); } + { const a: adone.stream.core.Stream = Stream.merge([], {}); } + { const a: adone.stream.core.Stream = Stream.merge([], { end: true }); } + { const a: adone.stream.core.Stream = Stream.merge([], { sourceOptions: {} }); } + { const a: adone.stream.core.Stream = Stream.merge([], { sourceOptions: { async: true } }); } + { const a: adone.stream.core.Stream = Stream.merge([], { sourceOptions: { sync: false } }); } + { const a: adone.stream.core.Stream = Stream.merge([], { sourceOptions: { transform(x) { this.push(x); } } }); } + { const a: adone.stream.core.Stream = Stream.merge([], { sourceOptions: { flush() { this.push(1); } } }); } (async () => { - const res = await new CoreStream([1, 2, 3, 4, 5]) + const res = await new Stream([1, 2, 3, 4, 5]) .map((x: number) => `${x}`) .mapIf((x: string) => x[0] === "1", (x) => x.slice(1)) .map((x) => [x, x, x]) @@ -91,13 +91,13 @@ namespace streamsTests { } namespace coreTests { - { const a: adone.stream.CoreStream = stream.core(); } - { const a: adone.stream.CoreStream = stream.core([1, 2, 3]); } - { const a: adone.stream.CoreStream = stream.core(stream.core([])); } - { const a: adone.stream.CoreStream = stream.core(undefined, {}); } - { const a: adone.stream.CoreStream = stream.core(undefined, { async: true }); } - { const a: adone.stream.CoreStream = stream.core(undefined, { sync: false }); } - { const a: adone.stream.CoreStream = stream.core(undefined, { transform(x) { this.push(Number(x)); } }); } - { const a: adone.stream.CoreStream = stream.core(undefined, { flush() { this.push(1); } }); } + { const a: adone.stream.core.Stream = stream.core.create(); } + { const a: adone.stream.core.Stream = stream.core.create([1, 2, 3]); } + { const a: adone.stream.core.Stream = stream.core.create(stream.core.create([])); } + { const a: adone.stream.core.Stream = stream.core.create(undefined, {}); } + { const a: adone.stream.core.Stream = stream.core.create(undefined, { async: true }); } + { const a: adone.stream.core.Stream = stream.core.create(undefined, { sync: false }); } + { const a: adone.stream.core.Stream = stream.core.create(undefined, { transform(x) { this.push(Number(x)); } }); } + { const a: adone.stream.core.Stream = stream.core.create(undefined, { flush() { this.push(1); } }); } } } diff --git a/types/adone/test/glosses/system/env.ts b/types/adone/test/glosses/system/env.ts new file mode 100644 index 0000000000..6f77ede2fa --- /dev/null +++ b/types/adone/test/glosses/system/env.ts @@ -0,0 +1,25 @@ +namespace adoneTests.system.env { + const { + system: { + env + } + } = adone; + + let str: string; + + str = env.user(); + + str = env.prompt(); + + str = env.hostname(); + + str = env.tmpdir(); + + str = env.home(); + + str = env.path(); + + str = env.editor(); + + str = env.shell(); +} diff --git a/types/adone/test/glosses/system/process.ts b/types/adone/test/glosses/system/process.ts new file mode 100644 index 0000000000..9ffd3c33a5 --- /dev/null +++ b/types/adone/test/glosses/system/process.ts @@ -0,0 +1,1200 @@ +namespace adoneTests.system.process { + const { + system: { + process + } + } = adone; + + let str: string; + let num: number; + let bool: boolean; + let anyArr: any[]; + + str = process.errname(1); + + str = process.errnameFallback({}, 1); + + anyArr = process.stdio({}); + + namespace exec { + process.exec("node"); + process.exec("node", ["1.js"]); + process.exec("node", ["1.js"], {}); + process.exec("node", ["1.js"], { + cwd: "hello" + }); + process.exec("node", ["1.js"], { + env: { + a: "a" + } + }); + process.exec("node", ["1.js"], { + extendEnv: true + }); + process.exec("node", ["1.js"], { + argv0: "a" + }); + { + process.exec("node", ["1.js"], { + stdio: "pipe" + }); + process.exec("node", ["1.js"], { + stdio: "ignore" + }); + process.exec("node", ["1.js"], { + stdio: "inherit" + }); + process.exec("node", ["1.js"], { + stdio: ["pipe"] + }); + process.exec("node", ["1.js"], { + stdio: ["ipc"] + }); + process.exec("node", ["1.js"], { + stdio: ["ignore"] + }); + process.exec("node", ["1.js"], { + stdio: [new adone.std.stream.Stream()] + }); + process.exec("node", ["1.js"], { + stdio: [0] + }); + process.exec("node", ["1.js"], { + stdio: [null] + }); + process.exec("node", ["1.js"], { + stdio: [undefined] + }); + } + process.exec("node", ["1.js"], { + detached: true + }); + process.exec("node", ["1.js"], { + uid: 1000 + }); + process.exec("node", ["1.js"], { + gid: 1000 + }); + process.exec("node", ["1.js"], { + shell: true + }); + process.exec("node", ["1.js"], { + windowsVerbatimArguments: true + }); + process.exec("node", ["1.js"], { + stripEof: true + }); + process.exec("node", ["1.js"], { + preferLocal: true + }); + process.exec("node", ["1.js"], { + localDir: "a" + }); + process.exec("node", ["1.js"], { + reject: false + }); + process.exec("node", ["1.js"], { + cleanup: true + }); + process.exec("node", ["1.js"], { + encoding: "utf8" + }); + process.exec("node", ["1.js"], { + timeout: 100 + }); + process.exec("node", ["1.js"], { + maxBuffer: 1010101 + }); + process.exec("node", ["1.js"], { + killSignal: "SIGINT" + }); + { + process.exec("node", ["1.js"], { + stdin: "pipe" + }); + process.exec("node", ["1.js"], { + stdin: "ignore" + }); + process.exec("node", ["1.js"], { + stdin: "ipc" + }); + process.exec("node", ["1.js"], { + stdin: "ignore" + }); + process.exec("node", ["1.js"], { + stdin: new adone.std.stream.Stream() + }); + process.exec("node", ["1.js"], { + stdin: 0 + }); + process.exec("node", ["1.js"], { + stdin: null + }); + process.exec("node", ["1.js"], { + stdin: undefined + }); + } + { + process.exec("node", ["1.js"], { + stdout: "pipe" + }); + process.exec("node", ["1.js"], { + stdout: "ignore" + }); + process.exec("node", ["1.js"], { + stdout: "ipc" + }); + process.exec("node", ["1.js"], { + stdout: "ignore" + }); + process.exec("node", ["1.js"], { + stdout: new adone.std.stream.Stream() + }); + process.exec("node", ["1.js"], { + stdout: 0 + }); + process.exec("node", ["1.js"], { + stdout: null + }); + process.exec("node", ["1.js"], { + stdout: undefined + }); + } + { + process.exec("node", ["1.js"], { + stderr: "pipe" + }); + process.exec("node", ["1.js"], { + stderr: "ignore" + }); + process.exec("node", ["1.js"], { + stderr: "ipc" + }); + process.exec("node", ["1.js"], { + stderr: "ignore" + }); + process.exec("node", ["1.js"], { + stderr: new adone.std.stream.Stream() + }); + process.exec("node", ["1.js"], { + stderr: 0 + }); + process.exec("node", ["1.js"], { + stderr: null + }); + process.exec("node", ["1.js"], { + stderr: undefined + }); + } + { + process.exec("node", ["1.js"], { + input: "a" + }); + process.exec("node", ["1.js"], { + input: Buffer.from("a") + }); + process.exec("node", ["1.js"], { + input: adone.fs.createReadStream(__filename) + }); + } + { + const ret = process.exec("node", ["1.js"]); + ret.then((x) => { + str = x.cmd; + num = x.code; + bool = x.killed; + if (!adone.is.null(x.signal)) { + str = x.signal; + } + str = x.stderr; + str = x.stdout; + bool = x.timedOut; + }); + ret.catch((x) => { + str = x.cmd; + num = x.code; + bool = x.killed; + if (!adone.is.null(x.signal)) { + str = x.signal; + } + str = x.stderr; + str = x.stdout; + bool = x.timedOut; + }); + + ret.on("message", () => {}); + ret.stdout.pipe(adone.fs.createWriteStream(__filename)); + } + } + + namespace execStdout { + process.execStdout("node"); + process.execStdout("node", ["1.js"]); + process.execStdout("node", ["1.js"], {}); + process.execStdout("node", ["1.js"], { + cwd: "hello" + }); + process.execStdout("node", ["1.js"], { + env: { + a: "a" + } + }); + process.execStdout("node", ["1.js"], { + extendEnv: true + }); + process.execStdout("node", ["1.js"], { + argv0: "a" + }); + { + process.execStdout("node", ["1.js"], { + stdio: "pipe" + }); + process.execStdout("node", ["1.js"], { + stdio: "ignore" + }); + process.execStdout("node", ["1.js"], { + stdio: "inherit" + }); + process.execStdout("node", ["1.js"], { + stdio: ["pipe"] + }); + process.execStdout("node", ["1.js"], { + stdio: ["ipc"] + }); + process.execStdout("node", ["1.js"], { + stdio: ["ignore"] + }); + process.execStdout("node", ["1.js"], { + stdio: [new adone.std.stream.Stream()] + }); + process.execStdout("node", ["1.js"], { + stdio: [0] + }); + process.execStdout("node", ["1.js"], { + stdio: [null] + }); + process.execStdout("node", ["1.js"], { + stdio: [undefined] + }); + } + process.execStdout("node", ["1.js"], { + detached: true + }); + process.execStdout("node", ["1.js"], { + uid: 1000 + }); + process.execStdout("node", ["1.js"], { + gid: 1000 + }); + process.execStdout("node", ["1.js"], { + shell: true + }); + process.execStdout("node", ["1.js"], { + windowsVerbatimArguments: true + }); + process.execStdout("node", ["1.js"], { + stripEof: true + }); + process.execStdout("node", ["1.js"], { + preferLocal: true + }); + process.execStdout("node", ["1.js"], { + localDir: "a" + }); + process.execStdout("node", ["1.js"], { + reject: false + }); + process.execStdout("node", ["1.js"], { + cleanup: true + }); + process.execStdout("node", ["1.js"], { + encoding: "utf8" + }); + process.execStdout("node", ["1.js"], { + timeout: 100 + }); + process.execStdout("node", ["1.js"], { + maxBuffer: 1010101 + }); + process.execStdout("node", ["1.js"], { + killSignal: "SIGINT" + }); + { + process.execStdout("node", ["1.js"], { + stdin: "pipe" + }); + process.execStdout("node", ["1.js"], { + stdin: "ignore" + }); + process.execStdout("node", ["1.js"], { + stdin: "ipc" + }); + process.execStdout("node", ["1.js"], { + stdin: "ignore" + }); + process.execStdout("node", ["1.js"], { + stdin: new adone.std.stream.Stream() + }); + process.execStdout("node", ["1.js"], { + stdin: 0 + }); + process.execStdout("node", ["1.js"], { + stdin: null + }); + process.execStdout("node", ["1.js"], { + stdin: undefined + }); + } + { + process.execStdout("node", ["1.js"], { + stdout: "pipe" + }); + process.execStdout("node", ["1.js"], { + stdout: "ignore" + }); + process.execStdout("node", ["1.js"], { + stdout: "ipc" + }); + process.execStdout("node", ["1.js"], { + stdout: "ignore" + }); + process.execStdout("node", ["1.js"], { + stdout: new adone.std.stream.Stream() + }); + process.execStdout("node", ["1.js"], { + stdout: 0 + }); + process.execStdout("node", ["1.js"], { + stdout: null + }); + process.execStdout("node", ["1.js"], { + stdout: undefined + }); + } + { + process.execStdout("node", ["1.js"], { + stderr: "pipe" + }); + process.execStdout("node", ["1.js"], { + stderr: "ignore" + }); + process.execStdout("node", ["1.js"], { + stderr: "ipc" + }); + process.execStdout("node", ["1.js"], { + stderr: "ignore" + }); + process.execStdout("node", ["1.js"], { + stderr: new adone.std.stream.Stream() + }); + process.execStdout("node", ["1.js"], { + stderr: 0 + }); + process.execStdout("node", ["1.js"], { + stderr: null + }); + process.execStdout("node", ["1.js"], { + stderr: undefined + }); + } + { + process.execStdout("node", ["1.js"], { + input: "a" + }); + process.execStdout("node", ["1.js"], { + input: Buffer.from("a") + }); + process.execStdout("node", ["1.js"], { + input: adone.fs.createReadStream(__filename) + }); + } + { + const ret = process.execStdout("node", ["1.js"]); + ret.then((x) => { + str = x; + }); + } + } + + namespace execStderr { + process.execStderr("node"); + process.execStderr("node", ["1.js"]); + process.execStderr("node", ["1.js"], {}); + process.execStderr("node", ["1.js"], { + cwd: "hello" + }); + process.execStderr("node", ["1.js"], { + env: { + a: "a" + } + }); + process.execStderr("node", ["1.js"], { + extendEnv: true + }); + process.execStderr("node", ["1.js"], { + argv0: "a" + }); + { + process.execStderr("node", ["1.js"], { + stdio: "pipe" + }); + process.execStderr("node", ["1.js"], { + stdio: "ignore" + }); + process.execStderr("node", ["1.js"], { + stdio: "inherit" + }); + process.execStderr("node", ["1.js"], { + stdio: ["pipe"] + }); + process.execStderr("node", ["1.js"], { + stdio: ["ipc"] + }); + process.execStderr("node", ["1.js"], { + stdio: ["ignore"] + }); + process.execStderr("node", ["1.js"], { + stdio: [new adone.std.stream.Stream()] + }); + process.execStderr("node", ["1.js"], { + stdio: [0] + }); + process.execStderr("node", ["1.js"], { + stdio: [null] + }); + process.execStderr("node", ["1.js"], { + stdio: [undefined] + }); + } + process.execStderr("node", ["1.js"], { + detached: true + }); + process.execStderr("node", ["1.js"], { + uid: 1000 + }); + process.execStderr("node", ["1.js"], { + gid: 1000 + }); + process.execStderr("node", ["1.js"], { + shell: true + }); + process.execStderr("node", ["1.js"], { + windowsVerbatimArguments: true + }); + process.execStderr("node", ["1.js"], { + stripEof: true + }); + process.execStderr("node", ["1.js"], { + preferLocal: true + }); + process.execStderr("node", ["1.js"], { + localDir: "a" + }); + process.execStderr("node", ["1.js"], { + reject: false + }); + process.execStderr("node", ["1.js"], { + cleanup: true + }); + process.execStderr("node", ["1.js"], { + encoding: "utf8" + }); + process.execStderr("node", ["1.js"], { + timeout: 100 + }); + process.execStderr("node", ["1.js"], { + maxBuffer: 1010101 + }); + process.execStderr("node", ["1.js"], { + killSignal: "SIGINT" + }); + { + process.execStderr("node", ["1.js"], { + stdin: "pipe" + }); + process.execStderr("node", ["1.js"], { + stdin: "ignore" + }); + process.execStderr("node", ["1.js"], { + stdin: "ipc" + }); + process.execStderr("node", ["1.js"], { + stdin: "ignore" + }); + process.execStderr("node", ["1.js"], { + stdin: new adone.std.stream.Stream() + }); + process.execStderr("node", ["1.js"], { + stdin: 0 + }); + process.execStderr("node", ["1.js"], { + stdin: null + }); + process.execStderr("node", ["1.js"], { + stdin: undefined + }); + } + { + process.execStderr("node", ["1.js"], { + stdout: "pipe" + }); + process.execStderr("node", ["1.js"], { + stdout: "ignore" + }); + process.execStderr("node", ["1.js"], { + stdout: "ipc" + }); + process.execStderr("node", ["1.js"], { + stdout: "ignore" + }); + process.execStderr("node", ["1.js"], { + stdout: new adone.std.stream.Stream() + }); + process.execStderr("node", ["1.js"], { + stdout: 0 + }); + process.execStderr("node", ["1.js"], { + stdout: null + }); + process.execStderr("node", ["1.js"], { + stdout: undefined + }); + } + { + process.execStderr("node", ["1.js"], { + stderr: "pipe" + }); + process.execStderr("node", ["1.js"], { + stderr: "ignore" + }); + process.execStderr("node", ["1.js"], { + stderr: "ipc" + }); + process.execStderr("node", ["1.js"], { + stderr: "ignore" + }); + process.execStderr("node", ["1.js"], { + stderr: new adone.std.stream.Stream() + }); + process.execStderr("node", ["1.js"], { + stderr: 0 + }); + process.execStderr("node", ["1.js"], { + stderr: null + }); + process.execStderr("node", ["1.js"], { + stderr: undefined + }); + } + { + process.execStderr("node", ["1.js"], { + input: "a" + }); + process.execStderr("node", ["1.js"], { + input: Buffer.from("a") + }); + process.execStderr("node", ["1.js"], { + input: adone.fs.createReadStream(__filename) + }); + } + { + const ret = process.execStderr("node", ["1.js"]); + ret.then((x) => { + str = x; + }); + } + } + + namespace shell { + process.shell("node 1.js"); + process.shell("node 1.js", {}); + process.shell("node 1.js", { + cwd: "hello" + }); + process.shell("node 1.js", { + env: { + a: "a" + } + }); + process.shell("node 1.js", { + extendEnv: true + }); + process.shell("node 1.js", { + argv0: "a" + }); + { + process.shell("node 1.js", { + stdio: "pipe" + }); + process.shell("node 1.js", { + stdio: "ignore" + }); + process.shell("node 1.js", { + stdio: "inherit" + }); + process.shell("node 1.js", { + stdio: ["pipe"] + }); + process.shell("node 1.js", { + stdio: ["ipc"] + }); + process.shell("node 1.js", { + stdio: ["ignore"] + }); + process.shell("node 1.js", { + stdio: [new adone.std.stream.Stream()] + }); + process.shell("node 1.js", { + stdio: [0] + }); + process.shell("node 1.js", { + stdio: [null] + }); + process.shell("node 1.js", { + stdio: [undefined] + }); + } + process.shell("node 1.js", { + detached: true + }); + process.shell("node 1.js", { + uid: 1000 + }); + process.shell("node 1.js", { + gid: 1000 + }); + process.shell("node 1.js", { + shell: true + }); + process.shell("node 1.js", { + windowsVerbatimArguments: true + }); + process.shell("node 1.js", { + stripEof: true + }); + process.shell("node 1.js", { + preferLocal: true + }); + process.shell("node 1.js", { + localDir: "a" + }); + process.shell("node 1.js", { + reject: false + }); + process.shell("node 1.js", { + cleanup: true + }); + process.shell("node 1.js", { + encoding: "utf8" + }); + process.shell("node 1.js", { + timeout: 100 + }); + process.shell("node 1.js", { + maxBuffer: 1010101 + }); + process.shell("node 1.js", { + killSignal: "SIGINT" + }); + { + process.shell("node 1.js", { + stdin: "pipe" + }); + process.shell("node 1.js", { + stdin: "ignore" + }); + process.shell("node 1.js", { + stdin: "ipc" + }); + process.shell("node 1.js", { + stdin: "ignore" + }); + process.shell("node 1.js", { + stdin: new adone.std.stream.Stream() + }); + process.shell("node 1.js", { + stdin: 0 + }); + process.shell("node 1.js", { + stdin: null + }); + process.shell("node 1.js", { + stdin: undefined + }); + } + { + process.shell("node 1.js", { + stdout: "pipe" + }); + process.shell("node 1.js", { + stdout: "ignore" + }); + process.shell("node 1.js", { + stdout: "ipc" + }); + process.shell("node 1.js", { + stdout: "ignore" + }); + process.shell("node 1.js", { + stdout: new adone.std.stream.Stream() + }); + process.shell("node 1.js", { + stdout: 0 + }); + process.shell("node 1.js", { + stdout: null + }); + process.shell("node 1.js", { + stdout: undefined + }); + } + { + process.shell("node 1.js", { + stderr: "pipe" + }); + process.shell("node 1.js", { + stderr: "ignore" + }); + process.shell("node 1.js", { + stderr: "ipc" + }); + process.shell("node 1.js", { + stderr: "ignore" + }); + process.shell("node 1.js", { + stderr: new adone.std.stream.Stream() + }); + process.shell("node 1.js", { + stderr: 0 + }); + process.shell("node 1.js", { + stderr: null + }); + process.shell("node 1.js", { + stderr: undefined + }); + } + { + process.shell("node 1.js", { + input: "a" + }); + process.shell("node 1.js", { + input: Buffer.from("a") + }); + process.shell("node 1.js", { + input: adone.fs.createReadStream(__filename) + }); + } + { + const ret = process.shell("node 1.js"); + ret.then((x) => { + str = x.cmd; + num = x.code; + bool = x.killed; + if (!adone.is.null(x.signal)) { + str = x.signal; + } + str = x.stderr; + str = x.stdout; + bool = x.timedOut; + }); + ret.catch((x) => { + str = x.cmd; + num = x.code; + bool = x.killed; + if (!adone.is.null(x.signal)) { + str = x.signal; + } + str = x.stderr; + str = x.stdout; + bool = x.timedOut; + }); + + ret.on("message", () => {}); + ret.stdout.pipe(adone.fs.createWriteStream(__filename)); + } + } + + namespace execSync { + process.execSync("node"); + process.execSync("node", ["1.js"]); + process.execSync("node", ["1.js"], {}); + process.execSync("node", ["1.js"], { + cwd: "hello" + }); + process.execSync("node", ["1.js"], { + env: { + a: "a" + } + }); + process.execSync("node", ["1.js"], { + extendEnv: true + }); + process.execSync("node", ["1.js"], { + argv0: "a" + }); + { + process.execSync("node", ["1.js"], { + stdio: "pipe" + }); + process.execSync("node", ["1.js"], { + stdio: "ignore" + }); + process.execSync("node", ["1.js"], { + stdio: "inherit" + }); + process.execSync("node", ["1.js"], { + stdio: ["pipe"] + }); + process.execSync("node", ["1.js"], { + stdio: ["ipc"] + }); + process.execSync("node", ["1.js"], { + stdio: ["ignore"] + }); + process.execSync("node", ["1.js"], { + stdio: [new adone.std.stream.Stream()] + }); + process.execSync("node", ["1.js"], { + stdio: [0] + }); + process.execSync("node", ["1.js"], { + stdio: [null] + }); + process.execSync("node", ["1.js"], { + stdio: [undefined] + }); + } + process.execSync("node", ["1.js"], { + detached: true + }); + process.execSync("node", ["1.js"], { + uid: 1000 + }); + process.execSync("node", ["1.js"], { + gid: 1000 + }); + process.execSync("node", ["1.js"], { + shell: true + }); + process.execSync("node", ["1.js"], { + windowsVerbatimArguments: true + }); + process.execSync("node", ["1.js"], { + stripEof: true + }); + process.execSync("node", ["1.js"], { + preferLocal: true + }); + process.execSync("node", ["1.js"], { + localDir: "a" + }); + process.execSync("node", ["1.js"], { + reject: false + }); + process.execSync("node", ["1.js"], { + cleanup: true + }); + process.execSync("node", ["1.js"], { + encoding: "utf8" + }); + process.execSync("node", ["1.js"], { + timeout: 100 + }); + process.execSync("node", ["1.js"], { + maxBuffer: 1010101 + }); + process.execSync("node", ["1.js"], { + killSignal: "SIGINT" + }); + { + process.execSync("node", ["1.js"], { + stdin: "pipe" + }); + process.execSync("node", ["1.js"], { + stdin: "ignore" + }); + process.execSync("node", ["1.js"], { + stdin: "ipc" + }); + process.execSync("node", ["1.js"], { + stdin: "ignore" + }); + process.execSync("node", ["1.js"], { + stdin: new adone.std.stream.Stream() + }); + process.execSync("node", ["1.js"], { + stdin: 0 + }); + process.execSync("node", ["1.js"], { + stdin: null + }); + process.execSync("node", ["1.js"], { + stdin: undefined + }); + } + { + process.execSync("node", ["1.js"], { + stdout: "pipe" + }); + process.execSync("node", ["1.js"], { + stdout: "ignore" + }); + process.execSync("node", ["1.js"], { + stdout: "ipc" + }); + process.execSync("node", ["1.js"], { + stdout: "ignore" + }); + process.execSync("node", ["1.js"], { + stdout: new adone.std.stream.Stream() + }); + process.execSync("node", ["1.js"], { + stdout: 0 + }); + process.execSync("node", ["1.js"], { + stdout: null + }); + process.execSync("node", ["1.js"], { + stdout: undefined + }); + } + { + process.execSync("node", ["1.js"], { + stderr: "pipe" + }); + process.execSync("node", ["1.js"], { + stderr: "ignore" + }); + process.execSync("node", ["1.js"], { + stderr: "ipc" + }); + process.execSync("node", ["1.js"], { + stderr: "ignore" + }); + process.execSync("node", ["1.js"], { + stderr: new adone.std.stream.Stream() + }); + process.execSync("node", ["1.js"], { + stderr: 0 + }); + process.execSync("node", ["1.js"], { + stderr: null + }); + process.execSync("node", ["1.js"], { + stderr: undefined + }); + } + { + process.execSync("node", ["1.js"], { + input: "a" + }); + process.execSync("node", ["1.js"], { + input: Buffer.from("a") + }); + } + { + const x = process.execSync("node", ["1.js"]); + str = x.cmd; + num = x.code; + bool = x.killed; + if (!adone.is.null(x.signal)) { + str = x.signal; + } + str = x.stderr; + str = x.stdout; + bool = x.timedOut; + } + } + + namespace shell { + process.shellSync("node 1.js"); + process.shellSync("node 1.js", {}); + process.shellSync("node 1.js", { + cwd: "hello" + }); + process.shellSync("node 1.js", { + env: { + a: "a" + } + }); + process.shellSync("node 1.js", { + extendEnv: true + }); + process.shellSync("node 1.js", { + argv0: "a" + }); + { + process.shellSync("node 1.js", { + stdio: "pipe" + }); + process.shellSync("node 1.js", { + stdio: "ignore" + }); + process.shellSync("node 1.js", { + stdio: "inherit" + }); + process.shellSync("node 1.js", { + stdio: ["pipe"] + }); + process.shellSync("node 1.js", { + stdio: ["ipc"] + }); + process.shellSync("node 1.js", { + stdio: ["ignore"] + }); + process.shellSync("node 1.js", { + stdio: [new adone.std.stream.Stream()] + }); + process.shellSync("node 1.js", { + stdio: [0] + }); + process.shellSync("node 1.js", { + stdio: [null] + }); + process.shellSync("node 1.js", { + stdio: [undefined] + }); + } + process.shellSync("node 1.js", { + detached: true + }); + process.shellSync("node 1.js", { + uid: 1000 + }); + process.shellSync("node 1.js", { + gid: 1000 + }); + process.shellSync("node 1.js", { + shell: true + }); + process.shellSync("node 1.js", { + windowsVerbatimArguments: true + }); + process.shellSync("node 1.js", { + stripEof: true + }); + process.shellSync("node 1.js", { + preferLocal: true + }); + process.shellSync("node 1.js", { + localDir: "a" + }); + process.shellSync("node 1.js", { + reject: false + }); + process.shellSync("node 1.js", { + cleanup: true + }); + process.shellSync("node 1.js", { + encoding: "utf8" + }); + process.shellSync("node 1.js", { + timeout: 100 + }); + process.shellSync("node 1.js", { + maxBuffer: 1010101 + }); + process.shellSync("node 1.js", { + killSignal: "SIGINT" + }); + { + process.shellSync("node 1.js", { + stdin: "pipe" + }); + process.shellSync("node 1.js", { + stdin: "ignore" + }); + process.shellSync("node 1.js", { + stdin: "ipc" + }); + process.shellSync("node 1.js", { + stdin: "ignore" + }); + process.shellSync("node 1.js", { + stdin: new adone.std.stream.Stream() + }); + process.shellSync("node 1.js", { + stdin: 0 + }); + process.shellSync("node 1.js", { + stdin: null + }); + process.shellSync("node 1.js", { + stdin: undefined + }); + } + { + process.shellSync("node 1.js", { + stdout: "pipe" + }); + process.shellSync("node 1.js", { + stdout: "ignore" + }); + process.shellSync("node 1.js", { + stdout: "ipc" + }); + process.shellSync("node 1.js", { + stdout: "ignore" + }); + process.shellSync("node 1.js", { + stdout: new adone.std.stream.Stream() + }); + process.shellSync("node 1.js", { + stdout: 0 + }); + process.shellSync("node 1.js", { + stdout: null + }); + process.shellSync("node 1.js", { + stdout: undefined + }); + } + { + process.shellSync("node 1.js", { + stderr: "pipe" + }); + process.shellSync("node 1.js", { + stderr: "ignore" + }); + process.shellSync("node 1.js", { + stderr: "ipc" + }); + process.shellSync("node 1.js", { + stderr: "ignore" + }); + process.shellSync("node 1.js", { + stderr: new adone.std.stream.Stream() + }); + process.shellSync("node 1.js", { + stderr: 0 + }); + process.shellSync("node 1.js", { + stderr: null + }); + process.shellSync("node 1.js", { + stderr: undefined + }); + } + { + process.shellSync("node 1.js", { + input: "a" + }); + process.shellSync("node 1.js", { + input: Buffer.from("a") + }); + } + { + const x = process.shellSync("node 1.js"); + str = x.cmd; + num = x.code; + bool = x.killed; + if (!adone.is.null(x.signal)) { + str = x.signal; + } + str = x.stderr; + str = x.stdout; + bool = x.timedOut; + } + } +} diff --git a/types/adone/test/glosses/system/user.ts b/types/adone/test/glosses/system/user.ts new file mode 100644 index 0000000000..3e1b643d7d --- /dev/null +++ b/types/adone/test/glosses/system/user.ts @@ -0,0 +1,22 @@ +namespace adoneTests.system.process.user { + const { + system: { + user + } + } = adone; + + let str: string; + let num: number; + + const a = user.uid("hello"); + num = a.uid; + num = a.gid; + + num = user.gid("hello"); + + num = user.gids("hello")[0]; + + str = user.username(1000); + + str = user.groupname(1000); +} diff --git a/types/adone/test/glosses/templating/dot.ts b/types/adone/test/glosses/templating/dot.ts new file mode 100644 index 0000000000..69cd15d500 --- /dev/null +++ b/types/adone/test/glosses/templating/dot.ts @@ -0,0 +1,70 @@ +namespace adoneTests.templating.dot { + const { + templating: { + dot + } + } = adone; + + let str: string; + let bool; + let regexp: RegExp; + + str = dot.version; + + bool = dot.templateSettings.append; + regexp = dot.templateSettings.conditional; + regexp = dot.templateSettings.define; + regexp = dot.templateSettings.defineParams; + regexp = dot.templateSettings.encode; + regexp = dot.templateSettings.evaluate; + regexp = dot.templateSettings.interpolate; + regexp = dot.templateSettings.iterate; + bool = dot.templateSettings.selfcontained; + bool = dot.templateSettings.strip; + regexp = dot.templateSettings.use; + regexp = dot.templateSettings.useParams; + str = dot.templateSettings.varname; + + const r = dot.template("asd", { + append: true, + define: /a/, + encode: /a/, + evaluate: /a/, + conditional: /a/, + defineParams: /a/, + interpolate: /a/, + iterate: /a/, + selfcontained: true, + strip: false, + use: /a/, + useParams: /a/, + varname: "a" + }); + str = r("a"); + + str = dot.compile("asd")(); + str = dot.compile("asd", {})(); + + const a = dot.process(); + str = a["hello"](); + + dot.process({ + destination: "a" + }); + dot.process({ + global: "a" + }); + dot.process({ + path: "a" + }); + dot.process({ + templateSettings: { + append: true + } + }); + dot.process({ + templateSettings: { + useParams: /a/ + } + }); +} diff --git a/types/adone/test/glosses/templating/nunjucks.ts b/types/adone/test/glosses/templating/nunjucks.ts new file mode 100644 index 0000000000..85bd2e49e5 --- /dev/null +++ b/types/adone/test/glosses/templating/nunjucks.ts @@ -0,0 +1,139 @@ +namespace adoneTests.templating.nunjucks { + const { + templating: { + nunjucks + } + } = adone; + + let str: string; + let bool: boolean; + let pstr: Promise; + + namespace Environment { + const { + Environment + } = nunjucks; + + new Environment(); + new Environment(new nunjucks.FileSystemLoader()); + new Environment(new nunjucks.FileSystemLoader(), { autoescape: true }); + new Environment(new nunjucks.FileSystemLoader(), { dev: true }); + new Environment(new nunjucks.FileSystemLoader(), { lstripBlocks: true }); + new Environment(new nunjucks.FileSystemLoader(), { throOnUndefined: true }); + new Environment(new nunjucks.FileSystemLoader(), { trimBlocks: true }); + + const e = new Environment(); + str = e.render("a"); + e.render("a", {}, (e, r: string) => {}); + str = e.renderString("a"); + str = e.renderString("a", {}); + e.renderString("a", {}, (e, r: string) => {}); + + e.addFilter("name", () => 2); + e.addFilter("name", () => 2, true); + e.getFilter("name")(); + + e.addExtension("name", { parse() { return "a"; }, tags: ["a"] }); + e.removeExtension("name"); + e.getExtension("name").parse({}, {}, {}); + str = e.getExtension("name").tags[0]; + bool = e.hasExtension("name"); + e.addGlobal("a", "b"); + str = e.getTemplate("name", true).render(); + str = e.getTemplate("name").render(); + } + + namespace Template { + const { + Template + } = nunjucks; + + new Template("asd"); + new Template("asd", new nunjucks.Environment()); + new Template("asd", new nunjucks.Environment(), true); + str = new Template("asd").render(); + new Template("asd").render({}, (e: any, res: string) => {}); + } + + namespace Loader { + const { + Loader + } = nunjucks; + + new Loader(); + new Loader().on("asd", () => {}); + new Loader().emit("asd", 1, 2, 3); + str = new Loader().resolve("asd", "asd"); + bool = new Loader().isRelative("asd"); + new Loader().extend({ + async: true, + getSource(name: string) { + return { src: "a", path: "b", noCache: true }; + }, + extend(extender) { + extender.async; + extender.extend; + extender.getSource("a"); + return extender; + } + }); + } + + namespace FileSystemLoader { + const { + FileSystemLoader + } = nunjucks; + + new FileSystemLoader(); + new FileSystemLoader(["a"]); + new FileSystemLoader(["a"], { noCache: true }); + new FileSystemLoader(["a"], { watch: true }); + bool = new FileSystemLoader(["a"], { watch: true }).getSource("name").noCache; + str = new FileSystemLoader(["a"], { watch: true }).getSource("name").path; + str = new FileSystemLoader(["a"], { watch: true }).getSource("name").src; + } + + namespace PrecompiledLoader { + const { + PrecompiledLoader + } = nunjucks; + + new PrecompiledLoader(); + bool = new PrecompiledLoader().getSource("name").noCache; + str = new PrecompiledLoader().getSource("name").path; + str = new PrecompiledLoader().getSource("name").src; + } + + pstr = nunjucks.render("he"); + pstr = nunjucks.render("he", {}); + + str = nunjucks.renderSync("he"); + str = nunjucks.renderSync("he", {}); + + pstr = nunjucks.renderString("he"); + pstr = nunjucks.renderString("he", {}); + + str = nunjucks.renderStringSync("he"); + str = nunjucks.renderStringSync("he", {}); + + let t = nunjucks.compile("he"); + t = nunjucks.compile("he", new nunjucks.Environment()); + t = nunjucks.compile("he", new nunjucks.Environment(), "asd"); + t = nunjucks.compile("he", new nunjucks.Environment(), "asd", true); + str = t.render(); + + let e = nunjucks.configure(); + e = nunjucks.configure({}); + e = nunjucks.configure({ autoescape: true }); + e = nunjucks.configure({ dev: true }); + e = nunjucks.configure({ lstripBlocks: true }); + e = nunjucks.configure({ noCache: true }); + e = nunjucks.configure({ tags: { blockEnd: "{" } }); + e = nunjucks.configure({ throOnUndefined: true }); + e = nunjucks.configure({ trimBlocks: true }); + e = nunjucks.configure({ watch: true }); + e = nunjucks.configure("a", { watch: true }); + e.addFilter("name", () => true); + + nunjucks.installJinjaCompat(); +} diff --git a/types/adone/test/glosses/text/index.ts b/types/adone/test/glosses/text/index.ts new file mode 100644 index 0000000000..7f5fc88692 --- /dev/null +++ b/types/adone/test/glosses/text/index.ts @@ -0,0 +1,58 @@ +namespace adoneTests.text { + const { + text + } = adone; + + let str: string; + let regExp: RegExp; + let bool: boolean; + let num: number; + + namespace escape { + const { + escape + } = text; + + str = escape.regExpPattern("asd"); + str = escape.regExpReplacement("asd"); + str = escape.format("asd"); + str = escape.shellArg("asd"); + str = escape.control("sad"); + str = escape.htmlSpecialChars("asd"); + } + + namespace regexp { + const { + regexp + } = text; + + str = regexp.array2alternatives(["a"]); + } + + str = text.escapeStringRegexp("asd"); + str = text.toCamelCase("asd"); + str = text.camelCaseToDashed("asd"); + regExp = text.endLineRegExp; + str = text.splitLines("a")[0]; + str = text.regExpIndexOf("a", /ads/); + str = text.regExpIndexOf("a", /ads/, 1); + str = text.stripAnsi("ad"); + bool = text.hasAnsi("asd"); + str = text.random(100); + str = text.detectNewLine("asd"); + str = text.wordwrap("ads", 10)[0]; + str = text.wordwrap("ads", 10, { join: true }); + str = text.wordwrap("ads", 10, { countAnsiEscapeCodes: true }); + str = text.wordwrap("ads", 10, { mode: "hard" }); + num = text.stringDistance("as", "ds"); + num = text.stringDistance("as", "ds", [[1]]); + num = text.stringDistanceCapped("a", "b", 10); + str = text.capitalize("asd"); + str = text.capitalizeWords("asd"); + num = text.width("asd"); + str = text.indent("asd", 10); + str = text.stripEof("asd"); + str = text.stripLastCRLF("asd"); + str = text.stripBOM("ads"); + num = text.toUTF8Array("asd")[0]; +} diff --git a/types/adone/test/glosses/text/spinners.ts b/types/adone/test/glosses/text/spinners.ts new file mode 100644 index 0000000000..abd3627151 --- /dev/null +++ b/types/adone/test/glosses/text/spinners.ts @@ -0,0 +1,41 @@ +namespace adoneTests.text.spinners { + const { + text: { + spinner + } + } = adone; + + let sp: { + interval: number; + frames: string[] + }; + + sp = spinner.dots; + sp = spinner.dots2; + sp = spinner.dots3; + sp = spinner.dots4; + sp = spinner.dots5; + sp = spinner.dots6; + sp = spinner.dots7; + sp = spinner.dots8; + sp = spinner.dots9; + sp = spinner.dots10; + sp = spinner.dots11; + sp = spinner.dots12; + sp = spinner.line; + sp = spinner.pipe; + sp = spinner.simpleDots; + sp = spinner.flip; + sp = spinner.growVertical; + sp = spinner.growHorizontal; + sp = spinner.boxBounce; + sp = spinner.boxBounce2; + sp = spinner.triangle; + sp = spinner.squareCorners; + sp = spinner.circleQuarters; + sp = spinner.circleHalves; + sp = spinner.arrow; + sp = spinner.arrow3; + sp = spinner.bouncingBar; + sp = spinner.clock; +} diff --git a/types/adone/test/glosses/text/table.ts b/types/adone/test/glosses/text/table.ts new file mode 100644 index 0000000000..7670f6b1de --- /dev/null +++ b/types/adone/test/glosses/text/table.ts @@ -0,0 +1,65 @@ +namespace adoneTests.text.table { + const { + text: { + table + } + } = adone; + + let num: number; + let str: string; + + namespace Table { + const { + Table + } = table; + + new Table(); + new Table({ chars: {} }); + new Table({ chars: { "bottom-left": "a" } }); + new Table({ chars: { "bottom-mid": "a" } }); + new Table({ chars: { "bottom-right": "a" } }); + new Table({ chars: { "left-mid": "a" } }); + new Table({ chars: { "mid-mid": "a" } }); + new Table({ chars: { "right-mid": "a" } }); + new Table({ chars: { "top-left": "a" } }); + new Table({ chars: { "top-mid": "a" } }); + new Table({ chars: { "top-right": "a" } }); + new Table({ chars: { bottom: "a" } }); + new Table({ chars: { left: "a" } }); + new Table({ chars: { mid: "a" } }); + new Table({ chars: { middle: "a" } }); + new Table({ chars: { right: "a" } }); + new Table({ chars: { top: "a" } }); + new Table({ colAligns: ["left"] }); + new Table({ rowAligns: ["top"] }); + new Table({ head: ["a"] }); + new Table({ rowHeights: [10] }); + new Table({ style: { "padding-left": 1 } }); + new Table({ style: { "padding-right": 1 } }); + new Table({ style: { border: ["a"] } }); + new Table({ style: { compact: true } }); + new Table({ style: { head: ["a"] } }); + new Table({ truncate: "a" }); + new Table({ colWidths: [10] }); + + num = new Table().width; + str = new Table().toString(); + + const def = Table.defaultOptions; + str = def.chars["bottom-mid"]; + num = def.style["padding-right"]; + } + + namespace BorderlessTable { + const { + BorderlessTable + } = table; + + new BorderlessTable(); + new BorderlessTable({}); + new BorderlessTable({ colAligns: ["center"] }); + new BorderlessTable({ colWidths: [10] }); + new BorderlessTable({ head: ["a"] }); + new BorderlessTable({ style: { "padding-right": 1 } }); + } +} diff --git a/types/adone/test/glosses/text/unicode.ts b/types/adone/test/glosses/text/unicode.ts new file mode 100644 index 0000000000..9b331afa60 --- /dev/null +++ b/types/adone/test/glosses/text/unicode.ts @@ -0,0 +1,135 @@ +namespace adoneTests.text.unicode { + const { + text: { + unicode + } + } = adone; + + let str: string; + let num: number; + let bool: boolean; + + str = unicode.symbol.tick; + str = unicode.symbol.cross; + str = unicode.symbol.star; + str = unicode.symbol.square; + str = unicode.symbol.squareSmall; + str = unicode.symbol.squareSmallFilled; + str = unicode.symbol.play; + str = unicode.symbol.circle; + str = unicode.symbol.circleFilled; + str = unicode.symbol.circleDotted; + str = unicode.symbol.circleDouble; + str = unicode.symbol.circleCircle; + str = unicode.symbol.circleCross; + str = unicode.symbol.circlePipe; + str = unicode.symbol.circleQuestionMark; + str = unicode.symbol.bullet; + str = unicode.symbol.dot; + str = unicode.symbol.line; + str = unicode.symbol.ellipsis; + str = unicode.symbol.pointer; + str = unicode.symbol.pointerSmall; + str = unicode.symbol.info; + str = unicode.symbol.warning; + str = unicode.symbol.hamburger; + str = unicode.symbol.smiley; + str = unicode.symbol.mustache; + str = unicode.symbol.heart; + str = unicode.symbol.arrowUp; + str = unicode.symbol.arrowDown; + str = unicode.symbol.arrowLeft; + str = unicode.symbol.arrowRight; + str = unicode.symbol.radioOn; + str = unicode.symbol.radioOff; + str = unicode.symbol.checkboxOn; + str = unicode.symbol.checkboxOff; + str = unicode.symbol.checkboxCircleOn; + str = unicode.symbol.checkboxCircleOff; + str = unicode.symbol.questionMarkPrefix; + str = unicode.symbol.oneHalf; + str = unicode.symbol.oneThird; + str = unicode.symbol.oneQuarter; + str = unicode.symbol.oneFifth; + str = unicode.symbol.oneSixth; + str = unicode.symbol.oneSeventh; + str = unicode.symbol.oneEighth; + str = unicode.symbol.oneNinth; + str = unicode.symbol.oneTenth; + str = unicode.symbol.twoThirds; + str = unicode.symbol.twoFifths; + str = unicode.symbol.threeQuarters; + str = unicode.symbol.threeFifths; + str = unicode.symbol.threeEighths; + str = unicode.symbol.fourFifths; + str = unicode.symbol.fiveSixths; + str = unicode.symbol.fiveEighths; + str = unicode.symbol.sevenEighths; + str = unicode.symbol.minus; + + str = unicode.symbolFallback.tick; + str = unicode.symbolFallback.cross; + str = unicode.symbolFallback.star; + str = unicode.symbolFallback.square; + str = unicode.symbolFallback.squareSmall; + str = unicode.symbolFallback.squareSmallFilled; + str = unicode.symbolFallback.play; + str = unicode.symbolFallback.circle; + str = unicode.symbolFallback.circleFilled; + str = unicode.symbolFallback.circleDotted; + str = unicode.symbolFallback.circleDouble; + str = unicode.symbolFallback.circleCircle; + str = unicode.symbolFallback.circleCross; + str = unicode.symbolFallback.circlePipe; + str = unicode.symbolFallback.circleQuestionMark; + str = unicode.symbolFallback.bullet; + str = unicode.symbolFallback.dot; + str = unicode.symbolFallback.line; + str = unicode.symbolFallback.ellipsis; + str = unicode.symbolFallback.pointer; + str = unicode.symbolFallback.pointerSmall; + str = unicode.symbolFallback.info; + str = unicode.symbolFallback.warning; + str = unicode.symbolFallback.hamburger; + str = unicode.symbolFallback.smiley; + str = unicode.symbolFallback.mustache; + str = unicode.symbolFallback.heart; + str = unicode.symbolFallback.arrowUp; + str = unicode.symbolFallback.arrowDown; + str = unicode.symbolFallback.arrowLeft; + str = unicode.symbolFallback.arrowRight; + str = unicode.symbolFallback.radioOn; + str = unicode.symbolFallback.radioOff; + str = unicode.symbolFallback.checkboxOn; + str = unicode.symbolFallback.checkboxOff; + str = unicode.symbolFallback.checkboxCircleOn; + str = unicode.symbolFallback.checkboxCircleOff; + str = unicode.symbolFallback.questionMarkPrefix; + str = unicode.symbolFallback.oneHalf; + str = unicode.symbolFallback.oneThird; + str = unicode.symbolFallback.oneQuarter; + str = unicode.symbolFallback.oneFifth; + str = unicode.symbolFallback.oneSixth; + str = unicode.symbolFallback.oneSeventh; + str = unicode.symbolFallback.oneEighth; + str = unicode.symbolFallback.oneNinth; + str = unicode.symbolFallback.oneTenth; + str = unicode.symbolFallback.twoThirds; + str = unicode.symbolFallback.twoFifths; + str = unicode.symbolFallback.threeQuarters; + str = unicode.symbolFallback.threeFifths; + str = unicode.symbolFallback.threeEighths; + str = unicode.symbolFallback.fourFifths; + str = unicode.symbolFallback.fiveSixths; + str = unicode.symbolFallback.fiveEighths; + str = unicode.symbolFallback.sevenEighths; + str = unicode.symbolFallback.minus; + + str = unicode.approx("asd"); + num = unicode.length("ad"); + str = unicode.toArray("asd")[0]; + num = unicode.surrogatePair("a"); + bool = unicode.isFullWidthCodePoint(100); + bool = unicode.isFullWidth("a"); + str = unicode.toFullWidth("asd"); +} diff --git a/types/adone/test/glosses/utils.ts b/types/adone/test/glosses/utils.ts index 33698bfb29..a01d010608 100644 --- a/types/adone/test/glosses/utils.ts +++ b/types/adone/test/glosses/utils.ts @@ -34,13 +34,6 @@ namespace utilTests { const b: string = util.functionName((a, b, c) => { }); } - namespace mapArguments { - const a: (...args: any[]) => any = util.mapArguments(() => { }); - const b: (...args: T[]) => T[] = util.mapArguments(1); - const c: (...args: any[]) => any = util.mapArguments([1]); - const d: (x: T) => T = util.mapArguments(); - } - namespace parseMs { const result: { days: number; @@ -56,10 +49,6 @@ namespace utilTests { const c: string = util.pluralizeWord("day", "days", 1); } - namespace functionParams { - const a: string[] = util.functionParams((a: any, b: any, c: any) => { }); - } - namespace randomChoice { const a: number = util.randomChoice([1, 2, 3]); const b: string = util.randomChoice(["1", "2", "3"]); @@ -174,19 +163,10 @@ namespace utilTests { const a: string = util.globParent("a/b/c/**"); } - namespace by { - const a: (a: number, b: number) => any = util.by((x: number): number => x); - const b: (a: number, b: number) => number = util.by((x: number): string => `${x}`, (a: string, b: string) => a.length - b.length); - } - namespace toFastProperties { const a: object = util.toFastProperties({}); } - namespace stripBom { - const a: string = util.stripBom("123"); - } - namespace sortKeys { const a: object = util.sortKeys({}); const b: object = util.sortKeys({}, {}); @@ -215,35 +195,32 @@ namespace utilTests { const e: object = util.invertObject({}, { onlyEnumerable: true }); } - namespace humanizeTime { - const a: string = util.humanizeTime(12345); - const b: string = util.humanizeTime(12345, {}); - const c: string = util.humanizeTime(12345, { compact: true }); - const d: string = util.humanizeTime(12345, { msDecimalDigits: 2 }); - const e: string = util.humanizeTime(12345, { secDecimalDigits: 2 }); - const f: string = util.humanizeTime(12345, { verbose: true }); - } - - namespace humanizeSize { - const a: string = util.humanizeSize(12345); - const b: string = util.humanizeSize(12345, ""); - } - namespace parseSize { const a: number | null = util.parseSize(123); const b: number | null = util.parseSize("123Kb"); } + namespace Cloner { + const a = new util.Cloner(); + a.clone({}); + a.clone({}, {}); + a.clone({}, { deep: true }); + a.clone({}, { nonPlainObjects: false }); + a.clone({}, { onlyEnumerable: true }); + const c = a.binding(); + c({}); + c({}, {}); + c({}, { deep: true }); + c({}, { onlyEnumerable: false }); + c({}, { nonPlainObjects: true }); + } + namespace clone { const a: object = util.clone({}); const b: object = util.clone({}, {}); const c: object = util.clone({}, { deep: true }); } - namespace toUTF8Array { - const a: number[] = util.toUTF8Array("hello"); - } - namespace asyncIter { util.asyncIter([1, 2, 3], () => { }, () => { }); } @@ -298,28 +275,34 @@ namespace utilTests { const a: object = util.assignDeep({ a: 1 }, { a: 2 }); } - namespace match { - const a: number | boolean = util.match(["a", "b", "c"], "a"); - const b: (a: any, b: any) => number | boolean = util.match("a", { index: true }); - const c: number | boolean = util.match(["a", "b", "c"], "a", { dot: true }); - const d: (a: any, b: any) => number | boolean = util.match("a", { end: 2 }); - const e: (a: any, b: any) => number | boolean = util.match("a", { start: 2 }); - const f: (a: any, b: any) => number | boolean = util.match("a"); + namespace matchPath { + const a: number | boolean = util.matchPath(["a", "b", "c"], "a"); + const b: (a: any, b: any) => number | boolean = util.matchPath("a", { index: true }); + const c: number | boolean = util.matchPath(["a", "b", "c"], "a", { dot: true }); + const d: (a: any, b: any) => number | boolean = util.matchPath("a", { end: 2 }); + const e: (a: any, b: any) => number | boolean = util.matchPath("a", { start: 2 }); + const f: (a: any, b: any) => number | boolean = util.matchPath("a"); } namespace toposort { - const a: number[] = util.toposort([ - [0, 1], - [2, 3], - [4, 5], - [6, 7] + const a: string[] = util.toposort([ + ["0", "1"], + ["2", "3"], + ["4", "5"], + ["6", "7"] ]); - const b: number[] = util.toposort.array([0, 1, 2], [ - [0, 1], - [2, 3], - [4, 5], - [6, 7] + const b: string[] = util.toposort.array(["0", "1", "2"], [ + ["0", "1"], + ["2", "3"], + ["4", "5"], + ["6", "7"] ]); + const sorter = new util.toposort.Sorter(); + sorter.add("a", "b"); + sorter.add("a", ["c"]); + const c: string[] = sorter.sort(); + sorter.clear(); + sorter.edges[0][0].charCodeAt(100); } namespace jsesc { @@ -340,10 +323,6 @@ namespace utilTests { const o: string = util.jsesc({ a: 1 }, { __inline2__: true }); } - namespace typeOf { - const a: string = util.typeOf(1); - } - namespace memcpy { const a: number = util.memcpy.utou(Buffer.alloc(10), 0, Buffer.alloc(10), 0, 10); const b: number = util.memcpy.atoa(new ArrayBuffer(10), 0, new ArrayBuffer(10), 0, 10); @@ -394,73 +373,6 @@ namespace utilTests { a.getter("a").access("b").method("c").setter("d"); } - namespace GlobExp { - { - const glob = new util.GlobExp("*.js"); - const a: boolean = glob.hasMagic(); - const b: string[] = glob.expandBraces(); - const c: RegExp = glob.makeRe(); - const d: boolean = glob.test("a.js"); - } - { - const a: boolean = util.GlobExp.hasMagic("*.js"); - const b: string[] = util.GlobExp.expandBraces("*.js"); - const c: RegExp = util.GlobExp.makeRe("*.js"); - const d: boolean = util.GlobExp.test("*.js", "a.js"); - } - new util.GlobExp(""); - new util.GlobExp("", {}); - new util.GlobExp("", { dot: true }); - new util.GlobExp("", { flipNegate: true }); - new util.GlobExp("", { matchBase: true }); - new util.GlobExp("", { nobrace: true }); - new util.GlobExp("", { nocase: true }); - new util.GlobExp("", { nocomment: true }); - new util.GlobExp("", { noext: true }); - new util.GlobExp("", { noglobstar: true }); - new util.GlobExp("", { nonegate: true }); - util.GlobExp.hasMagic("", {}); - util.GlobExp.hasMagic("", { dot: true }); - util.GlobExp.hasMagic("", { flipNegate: true }); - util.GlobExp.hasMagic("", { matchBase: true }); - util.GlobExp.hasMagic("", { nobrace: true }); - util.GlobExp.hasMagic("", { nocase: true }); - util.GlobExp.hasMagic("", { nocomment: true }); - util.GlobExp.hasMagic("", { noext: true }); - util.GlobExp.hasMagic("", { noglobstar: true }); - util.GlobExp.hasMagic("", { nonegate: true }); - util.GlobExp.expandBraces("", {}); - util.GlobExp.expandBraces("", { dot: true }); - util.GlobExp.expandBraces("", { flipNegate: true }); - util.GlobExp.expandBraces("", { matchBase: true }); - util.GlobExp.expandBraces("", { nobrace: true }); - util.GlobExp.expandBraces("", { nocase: true }); - util.GlobExp.expandBraces("", { nocomment: true }); - util.GlobExp.expandBraces("", { noext: true }); - util.GlobExp.expandBraces("", { noglobstar: true }); - util.GlobExp.expandBraces("", { nonegate: true }); - util.GlobExp.makeRe("", {}); - util.GlobExp.makeRe("", { dot: true }); - util.GlobExp.makeRe("", { flipNegate: true }); - util.GlobExp.makeRe("", { matchBase: true }); - util.GlobExp.makeRe("", { nobrace: true }); - util.GlobExp.makeRe("", { nocase: true }); - util.GlobExp.makeRe("", { nocomment: true }); - util.GlobExp.makeRe("", { noext: true }); - util.GlobExp.makeRe("", { noglobstar: true }); - util.GlobExp.makeRe("", { nonegate: true }); - util.GlobExp.test("a", "b", {}); - util.GlobExp.test("a", "b", { dot: true }); - util.GlobExp.test("a", "b", { flipNegate: true }); - util.GlobExp.test("a", "b", { matchBase: true }); - util.GlobExp.test("a", "b", { nobrace: true }); - util.GlobExp.test("a", "b", { nocase: true }); - util.GlobExp.test("a", "b", { nocomment: true }); - util.GlobExp.test("a", "b", { noext: true }); - util.GlobExp.test("a", "b", { noglobstar: true }); - util.GlobExp.test("a", "b", { nonegate: true }); - } - namespace iconv { // TODO } @@ -477,19 +389,6 @@ namespace utilTests { const b: string = util.sqlstring.dateToString(123, "local"); } - namespace arrayToList { - const a: string = util.sqlstring.arrayToList(["1", "a"]); - } - - namespace bufferToString { - const a: string = util.sqlstring.bufferToString(Buffer.alloc(10)); - } - - namespace objectToValues { - const a: string = util.sqlstring.objectToValues({ a: 1 }); - const b: string = util.sqlstring.objectToValues({ a: 1 }, "local"); - } - namespace escape { const a: string = util.sqlstring.escape(1); const b: string = util.sqlstring.escape(1, true); @@ -532,44 +431,82 @@ namespace utilTests { } namespace buffer { - const a: Buffer = util.buffer.concat([Buffer.alloc(10), Buffer.alloc(20)], 30); - util.buffer.mask(Buffer.alloc(10), Buffer.alloc(10), Buffer.alloc(10), 0, 10); - util.buffer.unmask(Buffer.alloc(10), Buffer.alloc(10)); + namespace toArrayBuffer { + const a = util.buffer.toArrayBuffer(Buffer.from("hello")); + a.slice(10); + } + + namespace xor { + const a = util.buffer.xor(Buffer.from("hello"), Buffer.from("world")); + a.writeUInt32LE(20, 1); + } } namespace shebang { const a: string | null = util.shebang("#!/bin/sh"); } - namespace ReInterval { - new util.ReInterval(() => { }, 1000); - new util.ReInterval(() => { }, 1000, [1]); - const a = new util.ReInterval(() => { }, 1000); + namespace reinterval { + util.reinterval(() => { }, 1000); + util.reinterval(() => { }, 1000, [1]); + const a = util.reinterval(() => { }, 1000); a.reschedule(400); a.clear(); a.destroy(); } - namespace RateLimiter { - new util.RateLimiter(); - new util.RateLimiter(1); - new util.RateLimiter(1, 1000); - new util.RateLimiter(1, 1000, true); - const a = new util.RateLimiter(); - a.removeTokens(1).then((x: number) => { }); - const b: boolean = a.tryRemoveTokens(10); - const c: number = a.getTokensRemaining(); - } - namespace throttle { - const a: () => Promise = util.throttle(() => 42); - const b: (a: number) => Promise = util.throttle((a: number) => `${a}`); - const c: (a: number, b: string) => Promise = util.throttle((a: number, b: string) => String(a) + b); - const d = util.throttle(() => { }, {}); - const e = util.throttle(() => { }, { interval: 1000 }); - const f = util.throttle(() => { }, { max: 10 }); - const g = util.throttle(() => { }, { ordered: true }); - const h = util.throttle(() => { }, { waitForReturn: true }); + namespace RateLimiter { + new util.throttle.RateLimiter(); + new util.throttle.RateLimiter(1); + new util.throttle.RateLimiter(1, 1000); + new util.throttle.RateLimiter(1, 1000, true); + const a = new util.throttle.RateLimiter(); + a.removeTokens(1).then((x: number) => { }); + const b: boolean = a.tryRemoveTokens(10); + const c: number = a.getTokensRemaining(); + } + + const a: () => Promise = util.throttle.create(() => 42); + const b: (a: number) => Promise = util.throttle.create((a: number) => `${a}`); + const c: (a: number, b: string) => Promise = util.throttle.create((a: number, b: string) => String(a) + b); + const d = util.throttle.create(() => { }, {}); + const e = util.throttle.create(() => { }, { interval: 1000 }); + const f = util.throttle.create(() => { }, { concurrency: 10 }); + const g = util.throttle.create(() => { }, { ordered: true }); + const h = util.throttle.create(() => { }, { waitForReturn: true }); + const i = util.throttle.create(() => { }, { onDone() {} }); + const j = util.throttle.create(() => { }, { drop: true }); + const k = util.throttle.create(() => { }, { dropLast: true }); + + const l: symbol = util.throttle.DROPPED; + + { + const t = util.throttle.create(); + t(() => 2).then((x: number) => {}); + t(() => Promise.resolve(2)).then((x: number) => {}); + + t(() => "2").then((x: string) => {}); + t(() => Promise.resolve("2")).then((x: string) => {}); + + t((a) => a, 2).then((x: number) => {}); + t((a) => Promise.resolve(a), 2).then((x: number) => {}); + + t((a, b) => String(a) + b, 2, "3").then((x: string) => {}); + t(async (a, b) => String(a) + b, 2, "3").then((x: string) => x); + + t((a, b, c) => String(a) + b + c, 2, "3", "4").then((x: string) => {}); + t(async (a, b, c) => String(a) + b + c, 2, "3", "4").then((x: string) => x); + + t((a, b, c, d) => String(a) + b + c + String(d), 2, "3", "4", 5).then((x: string) => {}); + t(async (a, b, c, d) => String(a) + b + c + String(d), 2, "3", "4", 5).then((x: string) => x); + + t((a, b, c, d, e) => String(a) + b + c + String(d) + e.join(","), 2, "3", "4", 5, [1, 2, 3]).then((x: string) => {}); + t(async (a, b, c, d, e) => String(a) + b + c + String(d) + e.join(","), 2, "3", "4", 5, [1, 2, 3]).then((x: string) => x); + + t((a, b, c, d, e, f) => String(a) + b + c + String(d) + e.join(",") + f, 2, "3", "4", 5, [1, 2, 3], 6).then((x: any) => {}); + t(async (a, b, c, d, e, f) => String(a) + b + c + String(d) + e.join(",") + f, 2, "3", "4", 5, [1, 2, 3], 6).then((x: any) => x); + } } namespace fakeClock { @@ -741,17 +678,6 @@ namespace utilTests { } } - namespace userid { - const { userid } = util; - - { const a: number = userid.uid("someone").gid; } - { const a: number = userid.uid("someone").uid; } - { const a: number = userid.gid("someone"); } - { const a: string = userid.username(1000); } - { const a: string = userid.groupname(1000); } - { const gids: number[] = userid.gids("someone"); } - } - namespace LogRotator { const { LogRotator } = util; new LogRotator("file.log"); @@ -766,4 +692,697 @@ namespace utilTests { new LogRotator("file.log").start(); new LogRotator("file.log").stop(); } + + namespace arrayDiff { + const { arrayDiff } = util; + + arrayDiff([1, 2, 3], [4, 5, 6])[0].toFixed(); + arrayDiff(["1"])[0].charCodeAt(100); + } + + namespace fillRange { + const { fillRange } = util; + + { const a: number[] = fillRange(1, 2); } + { const a: string[] = fillRange(1, 2, { stringify: true }); } + { const a: string = fillRange(1, 2, { toRegex: true }); } + { const a: string[] = fillRange("1", "2"); } + { const a: string = fillRange("1", "2", { toRegex: true }); } + } + + namespace inflection { + const { inflection } = util; + + { const a: string = inflection.singularizeWord("hello"); } + { const a: string = inflection.singularizeWord("hello", "aaaa"); } + { const a: string = inflection.pluralizeWord("hello"); } + { const a: string = inflection.pluralizeWord("hello", "aaaa"); } + { const a: string = inflection.underscore("hello"); } + } + + namespace machineId { + const { machineId } = util; + + (async () => { + const a: string = await machineId(); + }); + } + + namespace merge { + const { merge } = util; + + merge({}, {}); + merge({}, {}, { allowPrototypes: true }); + merge({}, {}, { plainObjects: false }); + } + + namespace omit { + const { omit } = util; + + omit({}, ["a"]); + omit({}, "a"); + omit({}, (x) => x === "a"); + } + + namespace parseTime { + const { parseTime } = util; + + { const a: number = parseTime(123); } + { const a: number | null = parseTime("12"); } + } + + namespace pick { + const { pick } = util; + + pick({}, ["a", "b", "c"]); + pick({}, new Set(["a", "b", "c"])); + } + + namespace querystring { + const { querystring: qs } = util; + + { const a: string = qs.escape("asd"); } + { const a: string = qs.formats.default; } + { const a: string = qs.formats.RFC1738; } + { const a: string = qs.formats.RFC3986; } + { const a: string = qs.formats.formatters.RFC1738("ha"); } + { const a: string = qs.formats.formatters.RFC3986("ha"); } + { const a: object = qs.parse("asdasd"); } + { const a: object = qs.parse("asdasd", {}); } + { const a: object = qs.parse("asdasd", { allowDots: false }); } + { const a: object = qs.parse("asdasd", { allowPrototypes: false }); } + { const a: object = qs.parse("asdasd", { arrayLimit: 100 }); } + { const a: object = qs.parse("asdasd", { decoder: (s) => s }); } + { const a: object = qs.parse("asdasd", { decoder: (s, d) => d(s) }); } + { const a: object = qs.parse("asdasd", { delimiter: "a" }); } + { const a: object = qs.parse("asdasd", { depth: 100 }); } + { const a: object = qs.parse("asdasd", { ignoreQueryPrefix: false }); } + { const a: object = qs.parse("asdasd", { parameterLimit: 100 }); } + { const a: object = qs.parse("asdasd", { parseArrays: false }); } + { const a: object = qs.parse("asdasd", { plainObjects: true }); } + { const a: object = qs.parse("asdasd", { strictNullHandling: false }); } + { const a: string = qs.stringify({}); } + { const a: string = qs.stringify({}, {}); } + { const a: string = qs.stringify({}, { addQueryPrefix: false }); } + { const a: string = qs.stringify({}, { allowDots: false }); } + { const a: string = qs.stringify({}, { arrayFormat: "indices" }); } + { const a: string = qs.stringify({}, { arrayFormat: "brackets" }); } + { const a: string = qs.stringify({}, { arrayFormat: "repeat" }); } + { const a: string = qs.stringify({}, { delimiter: "1" }); } + { const a: string = qs.stringify({}, { encode: true }); } + { const a: string = qs.stringify({}, { encoder: (s) => s }); } + { const a: string = qs.stringify({}, { encodeValuesOnly: false }); } + { const a: string = qs.stringify({}, { filter: [1, 2, 3] }); } + { const a: string = qs.stringify({}, { filter: ["1", "2", "3"] }); } + { const a: string = qs.stringify({}, { filter: (prefix: string, value: any) => value === 1 }); } + { const a: string = qs.stringify({}, { indices: false }); } + { const a: string = qs.stringify({}, { serializeDate(d) { return String(d.getTime()); } }); } + { const a: string = qs.stringify({}, { skipNulls: false }); } + { const a: string = qs.stringify({}, { sort(a, b) { return a - b; } }); } + { const a: string = qs.stringify({}, { strictNullHandling: false }); } + } + + namespace regexNot { + const { regexNot } = util; + + { const a: RegExp = regexNot("a"); } + { const a: RegExp = regexNot("a", {}); } + { const a: RegExp = regexNot("a", { contains: false }); } + } + + namespace repeat { + const { repeat } = util; + { const a: number[] = repeat(1, 10); } + { const a: string[] = repeat("a", 10); } + { const a: number[][] = repeat([2], 10); } + } + + namespace signalNameToCode { + const { signalNameToCode } = util; + signalNameToCode("SIGINT").toFixed(2); + } + + namespace splitBuffer { + const { splitBuffer } = util; + + { const a: Buffer[] = splitBuffer(Buffer.from("asd"), Buffer.from("|")); } + { const a: Buffer[] = splitBuffer(Buffer.from("asd"), Buffer.from("|"), true); } + { const a: Buffer[] = splitBuffer("asd", Buffer.from("|"), true); } + { const a: Buffer[] = splitBuffer("asd", "|"); } + } + + namespace splitString { + const { splitString } = util; + + splitString("a"); + splitString("a", {}); + splitString("a", { braces: false }); + splitString("a", { keepDoubleQuotes: false }); + splitString("a", { keepEscaping: false }); + splitString("a", { keepQuotes: false }); + splitString("a", { keepSingleQuotes: false }); + splitString("a", { separator: "|" }); + splitString("a", { + split(token) { + { const a: string[] = token.arr; } + { const a: number = token.idx; } + { const a: string = token.str; } + { const a: string = token.val; } + } + }); + splitString("a", (token) => { + { const a: string[] = token.arr; } + { const a: number = token.idx; } + { const a: string = token.str; } + { const a: string = token.val; } + }); + splitString("a", {}, (token) => { + { const a: string[] = token.arr; } + { const a: number = token.idx; } + { const a: string = token.str; } + { const a: string = token.val; } + }); + } + + namespace toRegex { + const { toRegex } = util; + + { const a: RegExp = toRegex("a"); } + { const a: RegExp = toRegex(["a"]); } + { const a: RegExp = toRegex(["a"], {}); } + { const a: RegExp = toRegex(["a"], { cache: false }); } + { const a: RegExp = toRegex(["a"], { contains: false }); } + { const a: RegExp = toRegex(["a"], { flags: "i" }); } + { const a: RegExp = toRegex(["a"], { negate: false }); } + { const a: RegExp = toRegex(["a"], { nocase: false }); } + } + + namespace toRegexRange { + const { toRegexRange } = util; + + { const a: RegExp = toRegexRange(1, 10); } + { const a: RegExp = toRegexRange("1", "10"); } + { const a: RegExp = toRegexRange(1, 10, {}); } + { const a: RegExp = toRegexRange(1, 10, { capture: false }); } + { const a: RegExp = toRegexRange(1, 10, { relaxZeros: true }); } + { const a: RegExp = toRegexRange(1, 10, { shorthand: false }); } + } + + namespace xorDistance { + const { compare, create, eq, gt, lt } = util.xorDistance; + + { const a: boolean = compare(Buffer.from("1"), Buffer.from("2")); } + { const a: Buffer = create(Buffer.from("1"), Buffer.from("2")); } + { const a: boolean = gt(Buffer.from("1"), Buffer.from("2")); } + { const a: boolean = lt(Buffer.from("1"), Buffer.from("2")); } + { const a: boolean = eq(Buffer.from("1"), Buffer.from("2")); } + } + + namespace braces { + const { braces } = util; + + { const a: string[] = braces("a"); } + { const a: string[] = braces("a", {}); } + { const a: string[] = braces("a", { expand: false }); } + { const a: string[] = braces("a", { nodupes: false }); } + { const a: string[] = braces("a", { optimize: true }); } + { const a: string[] = braces("a", { quantifiers: false }); } + { const a: string[] = braces("a", { rangeLimit: 100 }); } + { const a: string[] = braces("a", { transform: (s: string) => s }); } + { const a: string[] = braces("a", { unescape: false }); } + + { const a: string[] = braces.expand("a"); } + { const a: string[] = braces.expand("a", {}); } + { const a: string[] = braces.expand("a", { expand: false }); } + { const a: string[] = braces.expand("a", { nodupes: false }); } + { const a: string[] = braces.expand("a", { optimize: true }); } + { const a: string[] = braces.expand("a", { quantifiers: false }); } + { const a: string[] = braces.expand("a", { rangeLimit: 100 }); } + { const a: string[] = braces.expand("a", { transform: (s: string) => s }); } + { const a: string[] = braces.expand("a", { unescape: false }); } + + { const a: RegExp = braces.makeRe("a"); } + { const a: RegExp = braces.makeRe("a", {}); } + { const a: RegExp = braces.makeRe("a", { expand: false }); } + { const a: RegExp = braces.makeRe("a", { nodupes: false }); } + { const a: RegExp = braces.makeRe("a", { optimize: true }); } + { const a: RegExp = braces.makeRe("a", { quantifiers: false }); } + { const a: RegExp = braces.makeRe("a", { rangeLimit: 100 }); } + { const a: RegExp = braces.makeRe("a", { transform: (s: string) => s }); } + { const a: RegExp = braces.makeRe("a", { unescape: false }); } + + { const a: number = braces.MAX_LENGTH; } + { const a: object = braces.getCache(); } + braces.clearCache(); + braces.resizeCache(100500); + } + + namespace match { + const { match } = util; + + { const a: string[] = match(["a"], "a"); } + { const a: string[] = match(["a"], ["a"]); } + { const a: string[] = match(["a"], ["a"], {}); } + { const a: string[] = match(["a"], ["a"], { basename: false }); } + { const a: string[] = match(["a"], ["a"], { bash: false }); } + { const a: string[] = match(["a"], ["a"], { cache: false }); } + { const a: string[] = match(["a"], ["a"], { dot: true }); } + { const a: string[] = match(["a"], ["a"], { failglob: false }); } + { const a: string[] = match(["a"], ["a"], { ignore: "a" }); } + { const a: string[] = match(["a"], ["a"], { ignore: ["a"] }); } + { const a: string[] = match(["a"], ["a"], { matchBase: false }); } + { const a: string[] = match(["a"], ["a"], { nobrace: true }); } + { const a: string[] = match(["a"], ["a"], { nocase: false }); } + { const a: string[] = match(["a"], ["a"], { nodupes: true }); } + { const a: string[] = match(["a"], ["a"], { noext: false }); } + { const a: string[] = match(["a"], ["a"], { noglobstar: true }); } + { const a: string[] = match(["a"], ["a"], { nonegate: false }); } + { const a: string[] = match(["a"], ["a"], { nonull: false }); } + { const a: string[] = match(["a"], ["a"], { nullglob: false }); } + { const a: string[] = match(["a"], ["a"], { snapdragon: {} }); } + { const a: string[] = match(["a"], ["a"], { sourcemap: false }); } + { const a: string[] = match(["a"], ["a"], { unescape: false }); } + { const a: string[] = match(["a"], ["a"], { unixify: false }); } + + { const a: string[] = match.match(["a"], "a"); } + { const a: string[] = match.match(["a"], "a", {}); } + { const a: string[] = match.match(["a"], "a", { basename: false }); } + { const a: string[] = match.match(["a"], "a", { bash: false }); } + { const a: string[] = match.match(["a"], "a", { cache: false }); } + { const a: string[] = match.match(["a"], "a", { dot: true }); } + { const a: string[] = match.match(["a"], "a", { failglob: false }); } + { const a: string[] = match.match(["a"], "a", { ignore: "a" }); } + { const a: string[] = match.match(["a"], "a", { ignore: ["a"] }); } + { const a: string[] = match.match(["a"], "a", { matchBase: false }); } + { const a: string[] = match.match(["a"], "a", { nobrace: true }); } + { const a: string[] = match.match(["a"], "a", { nocase: false }); } + { const a: string[] = match.match(["a"], "a", { nodupes: true }); } + { const a: string[] = match.match(["a"], "a", { noext: false }); } + { const a: string[] = match.match(["a"], "a", { noglobstar: true }); } + { const a: string[] = match.match(["a"], "a", { nonegate: false }); } + { const a: string[] = match.match(["a"], "a", { nonull: false }); } + { const a: string[] = match.match(["a"], "a", { nullglob: false }); } + { const a: string[] = match.match(["a"], "a", { snapdragon: {} }); } + { const a: string[] = match.match(["a"], "a", { sourcemap: false }); } + { const a: string[] = match.match(["a"], "a", { unescape: false }); } + { const a: string[] = match.match(["a"], "a", { unixify: false }); } + + { const a: boolean = match.isMatch("a", "a"); } + { const a: boolean = match.isMatch("a", "a", {}); } + { const a: boolean = match.isMatch("a", "a", { basename: false }); } + { const a: boolean = match.isMatch("a", "a", { bash: false }); } + { const a: boolean = match.isMatch("a", "a", { cache: false }); } + { const a: boolean = match.isMatch("a", "a", { dot: true }); } + { const a: boolean = match.isMatch("a", "a", { failglob: false }); } + { const a: boolean = match.isMatch("a", "a", { ignore: "a" }); } + { const a: boolean = match.isMatch("a", "a", { ignore: ["a"] }); } + { const a: boolean = match.isMatch("a", "a", { matchBase: false }); } + { const a: boolean = match.isMatch("a", "a", { nobrace: true }); } + { const a: boolean = match.isMatch("a", "a", { nocase: false }); } + { const a: boolean = match.isMatch("a", "a", { nodupes: true }); } + { const a: boolean = match.isMatch("a", "a", { noext: false }); } + { const a: boolean = match.isMatch("a", "a", { noglobstar: true }); } + { const a: boolean = match.isMatch("a", "a", { nonegate: false }); } + { const a: boolean = match.isMatch("a", "a", { nonull: false }); } + { const a: boolean = match.isMatch("a", "a", { nullglob: false }); } + { const a: boolean = match.isMatch("a", "a", { snapdragon: {} }); } + { const a: boolean = match.isMatch("a", "a", { sourcemap: false }); } + { const a: boolean = match.isMatch("a", "a", { unescape: false }); } + { const a: boolean = match.isMatch("a", "a", { unixify: false }); } + + { const a: boolean = match.some(["a"], ["a"]); } + { const a: boolean = match.some("a", "a"); } + { const a: boolean = match.some("a", "a", {}); } + { const a: boolean = match.some("a", "a", { basename: false }); } + { const a: boolean = match.some("a", "a", { bash: false }); } + { const a: boolean = match.some("a", "a", { cache: false }); } + { const a: boolean = match.some("a", "a", { dot: true }); } + { const a: boolean = match.some("a", "a", { failglob: false }); } + { const a: boolean = match.some("a", "a", { ignore: "a" }); } + { const a: boolean = match.some("a", "a", { ignore: ["a"] }); } + { const a: boolean = match.some("a", "a", { matchBase: false }); } + { const a: boolean = match.some("a", "a", { nobrace: true }); } + { const a: boolean = match.some("a", "a", { nocase: false }); } + { const a: boolean = match.some("a", "a", { nodupes: true }); } + { const a: boolean = match.some("a", "a", { noext: false }); } + { const a: boolean = match.some("a", "a", { noglobstar: true }); } + { const a: boolean = match.some("a", "a", { nonegate: false }); } + { const a: boolean = match.some("a", "a", { nonull: false }); } + { const a: boolean = match.some("a", "a", { nullglob: false }); } + { const a: boolean = match.some("a", "a", { snapdragon: {} }); } + { const a: boolean = match.some("a", "a", { sourcemap: false }); } + { const a: boolean = match.some("a", "a", { unescape: false }); } + { const a: boolean = match.some("a", "a", { unixify: false }); } + + { const a: boolean = match.every(["a"], ["a"]); } + { const a: boolean = match.every("a", "a"); } + { const a: boolean = match.every("a", "a", {}); } + { const a: boolean = match.every("a", "a", { basename: false }); } + { const a: boolean = match.every("a", "a", { bash: false }); } + { const a: boolean = match.every("a", "a", { cache: false }); } + { const a: boolean = match.every("a", "a", { dot: true }); } + { const a: boolean = match.every("a", "a", { failglob: false }); } + { const a: boolean = match.every("a", "a", { ignore: "a" }); } + { const a: boolean = match.every("a", "a", { ignore: ["a"] }); } + { const a: boolean = match.every("a", "a", { matchBase: false }); } + { const a: boolean = match.every("a", "a", { nobrace: true }); } + { const a: boolean = match.every("a", "a", { nocase: false }); } + { const a: boolean = match.every("a", "a", { nodupes: true }); } + { const a: boolean = match.every("a", "a", { noext: false }); } + { const a: boolean = match.every("a", "a", { noglobstar: true }); } + { const a: boolean = match.every("a", "a", { nonegate: false }); } + { const a: boolean = match.every("a", "a", { nonull: false }); } + { const a: boolean = match.every("a", "a", { nullglob: false }); } + { const a: boolean = match.every("a", "a", { snapdragon: {} }); } + { const a: boolean = match.every("a", "a", { sourcemap: false }); } + { const a: boolean = match.every("a", "a", { unescape: false }); } + { const a: boolean = match.every("a", "a", { unixify: false }); } + + { const a: boolean = match.any(["a"], ["a"]); } + { const a: boolean = match.any("a", "a"); } + { const a: boolean = match.any("a", "a", {}); } + { const a: boolean = match.any("a", "a", { basename: false }); } + { const a: boolean = match.any("a", "a", { bash: false }); } + { const a: boolean = match.any("a", "a", { cache: false }); } + { const a: boolean = match.any("a", "a", { dot: true }); } + { const a: boolean = match.any("a", "a", { failglob: false }); } + { const a: boolean = match.any("a", "a", { ignore: "a" }); } + { const a: boolean = match.any("a", "a", { ignore: ["a"] }); } + { const a: boolean = match.any("a", "a", { matchBase: false }); } + { const a: boolean = match.any("a", "a", { nobrace: true }); } + { const a: boolean = match.any("a", "a", { nocase: false }); } + { const a: boolean = match.any("a", "a", { nodupes: true }); } + { const a: boolean = match.any("a", "a", { noext: false }); } + { const a: boolean = match.any("a", "a", { noglobstar: true }); } + { const a: boolean = match.any("a", "a", { nonegate: false }); } + { const a: boolean = match.any("a", "a", { nonull: false }); } + { const a: boolean = match.any("a", "a", { nullglob: false }); } + { const a: boolean = match.any("a", "a", { snapdragon: {} }); } + { const a: boolean = match.any("a", "a", { sourcemap: false }); } + { const a: boolean = match.any("a", "a", { unescape: false }); } + { const a: boolean = match.any("a", "a", { unixify: false }); } + + { const a: boolean = match.all("a", "a"); } + { const a: boolean = match.all("a", ["a"]); } + { const a: boolean = match.all(["a"], "a"); } + { const a: boolean = match.all(["a"], "a", {}); } + { const a: boolean = match.all(["a"], ["a"], { basename: false }); } + { const a: boolean = match.all(["a"], ["a"], { bash: false }); } + { const a: boolean = match.all(["a"], ["a"], { cache: false }); } + { const a: boolean = match.all(["a"], ["a"], { dot: true }); } + { const a: boolean = match.all(["a"], ["a"], { failglob: false }); } + { const a: boolean = match.all(["a"], ["a"], { ignore: "a" }); } + { const a: boolean = match.all(["a"], ["a"], { ignore: ["a"] }); } + { const a: boolean = match.all(["a"], ["a"], { matchBase: false }); } + { const a: boolean = match.all(["a"], ["a"], { nobrace: true }); } + { const a: boolean = match.all(["a"], ["a"], { nocase: false }); } + { const a: boolean = match.all(["a"], ["a"], { nodupes: true }); } + { const a: boolean = match.all(["a"], ["a"], { noext: false }); } + { const a: boolean = match.all(["a"], ["a"], { noglobstar: true }); } + { const a: boolean = match.all(["a"], ["a"], { nonegate: false }); } + { const a: boolean = match.all(["a"], ["a"], { nonull: false }); } + { const a: boolean = match.all(["a"], ["a"], { nullglob: false }); } + { const a: boolean = match.all(["a"], ["a"], { snapdragon: {} }); } + { const a: boolean = match.all(["a"], ["a"], { sourcemap: false }); } + { const a: boolean = match.all(["a"], ["a"], { unescape: false }); } + { const a: boolean = match.all(["a"], ["a"], { unixify: false }); } + + { const a: string[] = match.not(["a"], ["a"]); } + { const a: string[] = match.not(["a"], "a"); } + { const a: string[] = match.not(["a"], "a", {}); } + { const a: string[] = match.not(["a"], "a", { basename: false }); } + { const a: string[] = match.not(["a"], "a", { bash: false }); } + { const a: string[] = match.not(["a"], "a", { cache: false }); } + { const a: string[] = match.not(["a"], "a", { dot: true }); } + { const a: string[] = match.not(["a"], "a", { failglob: false }); } + { const a: string[] = match.not(["a"], "a", { ignore: "a" }); } + { const a: string[] = match.not(["a"], "a", { ignore: ["a"] }); } + { const a: string[] = match.not(["a"], "a", { matchBase: false }); } + { const a: string[] = match.not(["a"], "a", { nobrace: true }); } + { const a: string[] = match.not(["a"], "a", { nocase: false }); } + { const a: string[] = match.not(["a"], "a", { nodupes: true }); } + { const a: string[] = match.not(["a"], "a", { noext: false }); } + { const a: string[] = match.not(["a"], "a", { noglobstar: true }); } + { const a: string[] = match.not(["a"], "a", { nonegate: false }); } + { const a: string[] = match.not(["a"], "a", { nonull: false }); } + { const a: string[] = match.not(["a"], "a", { nullglob: false }); } + { const a: string[] = match.not(["a"], "a", { snapdragon: {} }); } + { const a: string[] = match.not(["a"], "a", { sourcemap: false }); } + { const a: string[] = match.not(["a"], "a", { unescape: false }); } + { const a: string[] = match.not(["a"], "a", { unixify: false }); } + + { const a: boolean = match.contains("a", "a"); } + { const a: boolean = match.contains("a", ["a"]); } + { const a: boolean = match.contains("a", ["a"], {}); } + { const a: boolean = match.contains("a", ["a"], { basename: false }); } + { const a: boolean = match.contains("a", ["a"], { bash: false }); } + { const a: boolean = match.contains("a", ["a"], { cache: false }); } + { const a: boolean = match.contains("a", ["a"], { dot: true }); } + { const a: boolean = match.contains("a", ["a"], { failglob: false }); } + { const a: boolean = match.contains("a", ["a"], { ignore: "a" }); } + { const a: boolean = match.contains("a", ["a"], { ignore: ["a"] }); } + { const a: boolean = match.contains("a", ["a"], { matchBase: false }); } + { const a: boolean = match.contains("a", ["a"], { nobrace: true }); } + { const a: boolean = match.contains("a", ["a"], { nocase: false }); } + { const a: boolean = match.contains("a", ["a"], { nodupes: true }); } + { const a: boolean = match.contains("a", ["a"], { noext: false }); } + { const a: boolean = match.contains("a", ["a"], { noglobstar: true }); } + { const a: boolean = match.contains("a", ["a"], { nonegate: false }); } + { const a: boolean = match.contains("a", ["a"], { nonull: false }); } + { const a: boolean = match.contains("a", ["a"], { nullglob: false }); } + { const a: boolean = match.contains("a", ["a"], { snapdragon: {} }); } + { const a: boolean = match.contains("a", ["a"], { sourcemap: false }); } + { const a: boolean = match.contains("a", ["a"], { unescape: false }); } + { const a: boolean = match.contains("a", ["a"], { unixify: false }); } + + { const a: object = match.matchKeys({}, "a"); } + { const a: object = match.matchKeys({}, ["a"]); } + { const a: object = match.matchKeys({}, ["a"], {}); } + { const a: object = match.matchKeys({}, ["a"], { basename: false }); } + { const a: object = match.matchKeys({}, ["a"], { bash: false }); } + { const a: object = match.matchKeys({}, ["a"], { cache: false }); } + { const a: object = match.matchKeys({}, ["a"], { dot: true }); } + { const a: object = match.matchKeys({}, ["a"], { failglob: false }); } + { const a: object = match.matchKeys({}, ["a"], { ignore: "a" }); } + { const a: object = match.matchKeys({}, ["a"], { ignore: ["a"] }); } + { const a: object = match.matchKeys({}, ["a"], { matchBase: false }); } + { const a: object = match.matchKeys({}, ["a"], { nobrace: true }); } + { const a: object = match.matchKeys({}, ["a"], { nocase: false }); } + { const a: object = match.matchKeys({}, ["a"], { nodupes: true }); } + { const a: object = match.matchKeys({}, ["a"], { noext: false }); } + { const a: object = match.matchKeys({}, ["a"], { noglobstar: true }); } + { const a: object = match.matchKeys({}, ["a"], { nonegate: false }); } + { const a: object = match.matchKeys({}, ["a"], { nonull: false }); } + { const a: object = match.matchKeys({}, ["a"], { nullglob: false }); } + { const a: object = match.matchKeys({}, ["a"], { snapdragon: {} }); } + { const a: object = match.matchKeys({}, ["a"], { sourcemap: false }); } + { const a: object = match.matchKeys({}, ["a"], { unescape: false }); } + { const a: object = match.matchKeys({}, ["a"], { unixify: false }); } + + { const a: (s: string) => boolean = match.matcher("a"); } + { const a: (s: string) => boolean = match.matcher(["a"]); } + { const a: (s: string) => boolean = match.matcher(["a"], {}); } + { const a: (s: string) => boolean = match.matcher(["a"], { basename: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { bash: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { cache: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { dot: true }); } + { const a: (s: string) => boolean = match.matcher(["a"], { failglob: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { ignore: "a" }); } + { const a: (s: string) => boolean = match.matcher(["a"], { ignore: ["a"] }); } + { const a: (s: string) => boolean = match.matcher(["a"], { matchBase: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { nobrace: true }); } + { const a: (s: string) => boolean = match.matcher(["a"], { nocase: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { nodupes: true }); } + { const a: (s: string) => boolean = match.matcher(["a"], { noext: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { noglobstar: true }); } + { const a: (s: string) => boolean = match.matcher(["a"], { nonegate: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { nonull: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { nullglob: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { snapdragon: {} }); } + { const a: (s: string) => boolean = match.matcher(["a"], { sourcemap: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { unescape: false }); } + { const a: (s: string) => boolean = match.matcher(["a"], { unixify: false }); } + + { const a: string[] | null = match.capture("a", "a"); } + { const a: string[] | null = match.capture("a", "a", {}); } + { const a: string[] | null = match.capture("a", "a", { basename: false }); } + { const a: string[] | null = match.capture("a", "a", { bash: false }); } + { const a: string[] | null = match.capture("a", "a", { cache: false }); } + { const a: string[] | null = match.capture("a", "a", { dot: true }); } + { const a: string[] | null = match.capture("a", "a", { failglob: false }); } + { const a: string[] | null = match.capture("a", "a", { ignore: "a" }); } + { const a: string[] | null = match.capture("a", "a", { ignore: ["a"] }); } + { const a: string[] | null = match.capture("a", "a", { matchBase: false }); } + { const a: string[] | null = match.capture("a", "a", { nobrace: true }); } + { const a: string[] | null = match.capture("a", "a", { nocase: false }); } + { const a: string[] | null = match.capture("a", "a", { nodupes: true }); } + { const a: string[] | null = match.capture("a", "a", { noext: false }); } + { const a: string[] | null = match.capture("a", "a", { noglobstar: true }); } + { const a: string[] | null = match.capture("a", "a", { nonegate: false }); } + { const a: string[] | null = match.capture("a", "a", { nonull: false }); } + { const a: string[] | null = match.capture("a", "a", { nullglob: false }); } + { const a: string[] | null = match.capture("a", "a", { snapdragon: {} }); } + { const a: string[] | null = match.capture("a", "a", { sourcemap: false }); } + { const a: string[] | null = match.capture("a", "a", { unescape: false }); } + { const a: string[] | null = match.capture("a", "a", { unixify: false }); } + + { const a: RegExp = match.makeRe("a"); } + { const a: RegExp = match.makeRe("a", {}); } + { const a: RegExp = match.makeRe("a", { basename: false }); } + { const a: RegExp = match.makeRe("a", { bash: false }); } + { const a: RegExp = match.makeRe("a", { cache: false }); } + { const a: RegExp = match.makeRe("a", { dot: true }); } + { const a: RegExp = match.makeRe("a", { failglob: false }); } + { const a: RegExp = match.makeRe("a", { ignore: "a" }); } + { const a: RegExp = match.makeRe("a", { ignore: ["a"] }); } + { const a: RegExp = match.makeRe("a", { matchBase: false }); } + { const a: RegExp = match.makeRe("a", { nobrace: true }); } + { const a: RegExp = match.makeRe("a", { nocase: false }); } + { const a: RegExp = match.makeRe("a", { nodupes: true }); } + { const a: RegExp = match.makeRe("a", { noext: false }); } + { const a: RegExp = match.makeRe("a", { noglobstar: true }); } + { const a: RegExp = match.makeRe("a", { nonegate: false }); } + { const a: RegExp = match.makeRe("a", { nonull: false }); } + { const a: RegExp = match.makeRe("a", { nullglob: false }); } + { const a: RegExp = match.makeRe("a", { snapdragon: {} }); } + { const a: RegExp = match.makeRe("a", { sourcemap: false }); } + { const a: RegExp = match.makeRe("a", { unescape: false }); } + { const a: RegExp = match.makeRe("a", { unixify: false }); } + + { const a: string[] = match.braces("a"); } + { const a: string[] = match.braces("a", {}); } + { const a: string[] = match.braces("a", {}); } + { const a: string[] = match.braces("a", { basename: false }); } + { const a: string[] = match.braces("a", { bash: false }); } + { const a: string[] = match.braces("a", { cache: false }); } + { const a: string[] = match.braces("a", { dot: true }); } + { const a: string[] = match.braces("a", { failglob: false }); } + { const a: string[] = match.braces("a", { ignore: "a" }); } + { const a: string[] = match.braces("a", { ignore: ["a"] }); } + { const a: string[] = match.braces("a", { matchBase: false }); } + { const a: string[] = match.braces("a", { nobrace: true }); } + { const a: string[] = match.braces("a", { nocase: false }); } + { const a: string[] = match.braces("a", { nodupes: true }); } + { const a: string[] = match.braces("a", { noext: false }); } + { const a: string[] = match.braces("a", { noglobstar: true }); } + { const a: string[] = match.braces("a", { nonegate: false }); } + { const a: string[] = match.braces("a", { nonull: false }); } + { const a: string[] = match.braces("a", { nullglob: false }); } + { const a: string[] = match.braces("a", { snapdragon: {} }); } + { const a: string[] = match.braces("a", { sourcemap: false }); } + { const a: string[] = match.braces("a", { unescape: false }); } + { const a: string[] = match.braces("a", { unixify: false }); } + + { const a: object = match.create("a"); } + { const a: object = match.create("a", {}); } + { const a: object = match.create("a", { basename: false }); } + { const a: object = match.create("a", { bash: false }); } + { const a: object = match.create("a", { cache: false }); } + { const a: object = match.create("a", { dot: true }); } + { const a: object = match.create("a", { failglob: false }); } + { const a: object = match.create("a", { ignore: "a" }); } + { const a: object = match.create("a", { ignore: ["a"] }); } + { const a: object = match.create("a", { matchBase: false }); } + { const a: object = match.create("a", { nobrace: true }); } + { const a: object = match.create("a", { nocase: false }); } + { const a: object = match.create("a", { nodupes: true }); } + { const a: object = match.create("a", { noext: false }); } + { const a: object = match.create("a", { noglobstar: true }); } + { const a: object = match.create("a", { nonegate: false }); } + { const a: object = match.create("a", { nonull: false }); } + { const a: object = match.create("a", { nullglob: false }); } + { const a: object = match.create("a", { snapdragon: {} }); } + { const a: object = match.create("a", { sourcemap: false }); } + { const a: object = match.create("a", { unescape: false }); } + { const a: object = match.create("a", { unixify: false }); } + { const a: object = match.create("a"); } + + { const a: object = match.parse("a", {}); } + { const a: object = match.parse("a", { basename: false }); } + { const a: object = match.parse("a", { bash: false }); } + { const a: object = match.parse("a", { cache: false }); } + { const a: object = match.parse("a", { dot: true }); } + { const a: object = match.parse("a", { failglob: false }); } + { const a: object = match.parse("a", { ignore: "a" }); } + { const a: object = match.parse("a", { ignore: ["a"] }); } + { const a: object = match.parse("a", { matchBase: false }); } + { const a: object = match.parse("a", { nobrace: true }); } + { const a: object = match.parse("a", { nocase: false }); } + { const a: object = match.parse("a", { nodupes: true }); } + { const a: object = match.parse("a", { noext: false }); } + { const a: object = match.parse("a", { noglobstar: true }); } + { const a: object = match.parse("a", { nonegate: false }); } + { const a: object = match.parse("a", { nonull: false }); } + { const a: object = match.parse("a", { nullglob: false }); } + { const a: object = match.parse("a", { snapdragon: {} }); } + { const a: object = match.parse("a", { sourcemap: false }); } + { const a: object = match.parse("a", { unescape: false }); } + { const a: object = match.parse("a", { unixify: false }); } + + { const a: object = match.compile("a", {}); } + { const a: object = match.compile({}, {}); } + { const a: object = match.compile("a", { basename: false }); } + { const a: object = match.compile({}, { basename: false }); } + { const a: object = match.compile("a", { bash: false }); } + { const a: object = match.compile({}, { bash: false }); } + { const a: object = match.compile("a", { cache: false }); } + { const a: object = match.compile({}, { cache: false }); } + { const a: object = match.compile("a", { dot: true }); } + { const a: object = match.compile({}, { dot: true }); } + { const a: object = match.compile("a", { failglob: false }); } + { const a: object = match.compile({}, { failglob: false }); } + { const a: object = match.compile("a", { ignore: "a" }); } + { const a: object = match.compile({}, { ignore: "a" }); } + { const a: object = match.compile("a", { ignore: ["a"] }); } + { const a: object = match.compile({}, { ignore: ["a"] }); } + { const a: object = match.compile("a", { matchBase: false }); } + { const a: object = match.compile({}, { matchBase: false }); } + { const a: object = match.compile("a", { nobrace: true }); } + { const a: object = match.compile({}, { nobrace: true }); } + { const a: object = match.compile("a", { nocase: false }); } + { const a: object = match.compile({}, { nocase: false }); } + { const a: object = match.compile("a", { nodupes: true }); } + { const a: object = match.compile({}, { nodupes: true }); } + { const a: object = match.compile("a", { noext: false }); } + { const a: object = match.compile({}, { noext: false }); } + { const a: object = match.compile("a", { noglobstar: true }); } + { const a: object = match.compile({}, { noglobstar: true }); } + { const a: object = match.compile("a", { nonegate: false }); } + { const a: object = match.compile({}, { nonegate: false }); } + { const a: object = match.compile("a", { nonull: false }); } + { const a: object = match.compile({}, { nonull: false }); } + { const a: object = match.compile("a", { nullglob: false }); } + { const a: object = match.compile({}, { nullglob: false }); } + { const a: object = match.compile("a", { snapdragon: {} }); } + { const a: object = match.compile({}, { snapdragon: {} }); } + { const a: object = match.compile("a", { sourcemap: false }); } + { const a: object = match.compile({}, { sourcemap: false }); } + { const a: object = match.compile("a", { unescape: false }); } + { const a: object = match.compile({}, { unescape: false }); } + { const a: object = match.compile("a", { unixify: false }); } + { const a: object = match.compile({}, { unixify: false }); } + + { const a: number = match.MAX_LENGTH; } + match.clearCache(); + match.resizeCache(10050); + { const a: object = match.getCache(); } + } + + namespace iconv { + const { + iconv + } = util; + + let str: string; + let buf: Buffer; + let bool: boolean; + + str = iconv.decode(Buffer.from("hello"), "CP1251"); + str = iconv.decode(Buffer.from("hello"), "CP1251", {}); + + buf = iconv.encode("привет", "CP1251"); + buf = iconv.encode("привет", "CP1251", {}); + + bool = iconv.encodingExists("cp1251"); + } } diff --git a/types/adone/test/glosses/vault.ts b/types/adone/test/glosses/vault.ts new file mode 100644 index 0000000000..1423a46715 --- /dev/null +++ b/types/adone/test/glosses/vault.ts @@ -0,0 +1,203 @@ +namespace adoneTests.vault { + const { + is, + vault + } = adone; + + let num: number; + let bool: boolean; + let obj: object; + let str: string; + + namespace Vault { + const { + Vault + } = vault; + + new Vault({ + location: "a" + }); + new Vault({ + location: "a", + ValuableClass: vault.Valuable + }); + + const v = new Vault({ + location: "a" + }); + + v.addTag("hello").then((x) => { + if (!is.null(x)) { + num = x; + } + }); + v.clear().then((x) => { + num = x; + }); + v.close().then(); + v.create("hello").then((x) => { + x.set("a", "b"); + }); + v.create("hello", ["a", "b"]).then((x) => { + x.set("a", "b"); + }); + v.delete("a").then(); + v.deleteTag("a").then((x) => { + bool = x; + }); + v.entries().then((x) => { + obj = x; + }); + v.get("a").then((x) => { + x.set("a", "b"); + }); + str = v.getNotes(); + bool = v.has("a"); + str = v.keys()[0]; + str = v.location(); + v.open().then(() => {}); + v.release("name"); + v.setNotes("asd").then(); + str = v.tagNames()[0]; + str = v.tagNames([1])[0]; + obj = v.tags()[0]; + obj = v.toJSON(); + v.toJSON({ valuable: { includeId: true } }).then((x) => { + obj = x.valuables[0]; + }); + v.toJSON({ includeStats: true }).then((x) => { + num = x.stats.created; + num = x.stats.updated; + str = x.stats.location; + }); + v.values().then((x) => { + x[0]; + }); + } + + namespace Valuable { + new vault.Vault({ location: "a" }).get("a").then((v) => { + v.addTag("a").then(); + v.clear().then((x) => { + num = x; + }); + v.clear({ includeNotes: true }).then((x) => { + num = x; + }); + v.clear({ includeTags: true }).then((x) => { + num = x; + }); + v.delete("a").then((x) => { + num = x; + }); + v.deleteAllTags(); + v.entries().then((x) => { + obj = x; + }); + v.entries({ entriesAsArray: true }).then((x) => { + obj = x; + }); + v.entries({ includeEntryId: true }).then((x) => { + obj = x; + }); + v.fromJSON({}).then((x) => { + num = x; + }); + v.get("a").then(); + str = v.getNotes(); + bool = v.has("a"); + bool = v.hasTag("a"); + num = v.internalId(); + str = v.keys()[0]; + str = v.name(); + v.set("a", "b").then((x) => { + num = x; + }); + v.set("a", "b", "wtf").then((x) => { + num = x; + }); + v.setMulti({ a: "1", b: "2" }).then(); + v.setNotes("a").then(); + obj = v.tags(); + obj = v.toJSON(); + obj = v.toJSON({ entriesAsArray: true }); + obj = v.toJSON({ includeEntryId: true }); + obj = v.toJSON({ includeId: false }); + obj = v.toJSON({ tags: "normal" }); + obj = v.toJSON({ tags: "none" }); + obj = v.toJSON({ tags: "onlyId" }); + obj = v.toJSON({ tags: "onlyName" }); + v.type("a"); + }); + } + + namespace slice { + new vault.Vault({ location: "a" }).get("a").then((valuable) => { + vault.slice(valuable, "s"); + vault.slice(valuable, ["s"]); + vault.slice(valuable, ["s"], "a"); + vault.slice(valuable, ["s"], "a"); + const v = vault.slice(valuable, "s"); + v.addTag("a").then(); + v.delete("a").then((x) => { + num = x; + }); + v.deleteAllTags().then(); + v.deleteTag("a").then((x) => { + bool = x; + }); + v.entries().then((x) => { + obj = x; + }); + v.entries({}).then((x) => { + obj = x; + }); + v.entries({ entriesAsArray: true }).then((x) => { + obj = x; + }); + v.entries({ includeEntryId: true }).then((x) => { + obj = x; + }); + v.fromJSON({}).then((x) => { + num = x; + }); + v.get("a").then(); + str = v.getNotes(); + bool = v.has("a"); + bool = v.hasTag("a"); + num = v.internalId(); + str = v.keys()[0]; + str = v.name(); + v.set("a", "b").then((x) => { + num = x; + }); + v.set("a", "b", "wtf").then((x) => { + num = x; + }); + v.setMulti({}).then(); + v.setNotes("a").then((x) => { + num = x; + }); + obj = v.tags()[0]; + obj = v.toJSON(); + obj = v.toJSON({}); + obj = v.toJSON({ entriesAsArray: true }); + obj = v.toJSON({ includeEntryId: true }); + obj = v.toJSON({ includeId: true }); + obj = v.toJSON({ tags: "none" }); + obj = v.toJSON({ tags: "normal" }); + obj = v.toJSON({ tags: "onlyId" }); + obj = v.toJSON({ tags: "onlyName" }); + v.type("a"); + }); + } + + namespace open { + vault.open({ location: "a" }).then((x) => { + x.get("a").then((x) => x.setMulti({})); + }); + vault.open({ location: "a", ValuableClass: vault.Valuable }).then((x) => { + x.get("a").then((x) => x.setMulti({})); + }); + } +} diff --git a/types/adone/test/index.ts b/types/adone/test/index.ts index a9de1ab34b..ac012b9535 100644 --- a/types/adone/test/index.ts +++ b/types/adone/test/index.ts @@ -1,23 +1,32 @@ namespace AdoneRootTests { - { const a: symbol = adone.null; } + let num: number; + let sym: symbol; + let str: string; + let numarr: number[]; + let obj: object; + let bool: boolean; + + sym = adone.null; adone.noop(); - { const a: number = adone.identity(2); } - { const a: string = adone.identity("2"); } - { const a: number[] = adone.identity([1, 2]); } - { adone.truly() === true; } - { adone.falsely() === false; } - { const a: string = adone.ok; } - { const a: string = adone.bad; } - { const a: string[] = adone.exts; } + + num = adone.identity(2); + str = adone.identity("3"); + numarr = adone.identity([1, 2]); + + adone.truly() === true; + adone.falsely() === false; + + str = adone.ok; + str = adone.bad; adone.log(); - adone.fatal(); - adone.error(); - adone.warn(); - adone.info(); - adone.debug(); - adone.trace(); - { const a: object = adone.o(); } - { const a: object = adone.o({}); } + adone.logFatal(); + adone.logError(); + adone.logWarn(); + adone.logInfo(); + adone.logDebug(); + adone.logTrace(); + obj = adone.o(); + obj = adone.o({}); { const a: typeof Date = adone.Date; } { const a: typeof process.hrtime = adone.hrtime; } { const a: typeof global.setTimeout = adone.setTimeout; } @@ -26,6 +35,7 @@ namespace AdoneRootTests { { const a: typeof clearInterval = adone.clearInterval; } { const a: typeof global.setImmediate = adone.setImmediate; } { const a: typeof clearImmediate = adone.clearImmediate; } + adone.lazify({}); adone.lazify({}, {}); adone.lazify({}, {}, () => { }); @@ -33,40 +43,15 @@ namespace AdoneRootTests { adone.lazify({}, {}, () => { }, { configurable: true }); adone.lazify({}, {}, () => { }, { writable: false }); adone.lazify({}, {}, () => { }, { mapper: (key: string, obj: any) => null }); + adone.tag.set({}, "123"); - { const a: boolean = adone.tag.has({}, "123"); } + bool = adone.tag.has({}, "123"); adone.tag.define("12"); adone.tag.define("123", "456"); - { const a: symbol = adone.tag.SUBSYSTEM; } - { const a: symbol = adone.tag.APPLICATION; } - { const a: symbol = adone.tag.TRANSFORM; } - { const a: symbol = adone.tag.CORE_STREAM; } - { const a: symbol = adone.tag.LOGGER; } - { const a: symbol = adone.tag.LONG; } - { const a: symbol = adone.tag.BIGNUMBER; } - { const a: symbol = adone.tag.EXBUFFER; } - { const a: symbol = adone.tag.EXDATE; } - { const a: symbol = adone.tag.CONFIGURATION; } - { const a: symbol = adone.tag.GENESIS_NETRON; } - { const a: symbol = adone.tag.GENESIS_PEER; } - { const a: symbol = adone.tag.NETRON; } - { const a: symbol = adone.tag.NETRON_PEER; } - { const a: symbol = adone.tag.NETRON_ADAPTER; } - { const a: symbol = adone.tag.NETRON_DEFINITION; } - { const a: symbol = adone.tag.NETRON_DEFINITIONS; } - { const a: symbol = adone.tag.NETRON_REFERENCE; } - { const a: symbol = adone.tag.NETRON_INTERFACE; } - { const a: symbol = adone.tag.NETRON_STUB; } - { const a: symbol = adone.tag.NETRON_REMOTESTUB; } - { const a: symbol = adone.tag.NETRON_STREAM; } - { const a: symbol = adone.tag.FAST_STREAM; } - { const a: symbol = adone.tag.FAST_FS_STREAM; } - { const a: symbol = adone.tag.FAST_FS_MAP_STREAM; } - { const a: object = adone.bind("library"); } // hmm - { const a: string = adone.getAssetAbsolutePath("asset"); } + str = adone.getAssetAbsolutePath("asset"); { const a: Buffer | string = adone.loadAsset("asset"); } - { const a: object = adone.require("path"); } - { const a: object = adone.package; } + obj = adone.require("path"); + obj = adone.package; { const a: typeof adone.assertion.assert = adone.assert; } { const a: typeof adone.assertion.expect = adone.expect; } } diff --git a/types/adone/tsconfig.json b/types/adone/tsconfig.json index c23bf82155..6e6b3fe1c3 100644 --- a/types/adone/tsconfig.json +++ b/types/adone/tsconfig.json @@ -15,53 +15,142 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "experimentalDecorators": true, + "esModuleInterop": true }, "files": [ - "index.d.ts", + "adone-tests.ts", "adone.d.ts", + "glosses/archives.d.ts", + "glosses/assertion.d.ts", + "glosses/collections/array_set.d.ts", + "glosses/collections/async_queue.d.ts", + "glosses/collections/avl_tree.d.ts", + "glosses/collections/binary_search_tree.d.ts", + "glosses/collections/buffer_list.d.ts", + "glosses/collections/byte_array.d.ts", + "glosses/collections/default_map.d.ts", + "glosses/collections/fast_lru.d.ts", + "glosses/collections/index.d.ts", + "glosses/collections/linked_list.d.ts", + "glosses/collections/lru.d.ts", + "glosses/collections/map_cache.d.ts", + "glosses/collections/ns_cache.d.ts", + "glosses/collections/priority_queue.d.ts", + "glosses/collections/queue.d.ts", + "glosses/collections/rb_tree.d.ts", + "glosses/collections/refcounted_cache.d.ts", + "glosses/collections/set.d.ts", + "glosses/collections/stack.d.ts", + "glosses/collections/timedout_map.d.ts", + "glosses/compressors.d.ts", + "glosses/crypto/asn1.d.ts", + "glosses/crypto/ed25519.d.ts", + "glosses/crypto/index.d.ts", + "glosses/crypto/secp256k1.d.ts", + "glosses/data.d.ts", + "glosses/datetime.d.ts", + "glosses/events.d.ts", + "glosses/errors.d.ts", + "glosses/fake.d.ts", + "glosses/fast.d.ts", + "glosses/fs.d.ts", + "glosses/is.d.ts", "glosses/math/index.d.ts", "glosses/math/matrix.d.ts", "glosses/math/simd.d.ts", - "glosses/std.d.ts", - "glosses/utils.d.ts", - "glosses/assertion.d.ts", + "glosses/meta.d.ts", + "glosses/net/http/client.d.ts", + "glosses/net/http/index.d.ts", + "glosses/net/index.d.ts", + "glosses/pretty/json.d.ts", + "glosses/pretty/size.d.ts", + "glosses/pretty/table.d.ts", + "glosses/pretty/time.d.ts", "glosses/promise.d.ts", - "glosses/shani.d.ts", + "glosses/regex.d.ts", + "glosses/semver.d.ts", "glosses/shani-global.d.ts", - "glosses/collections.d.ts", - "glosses/events.d.ts", - "glosses/fs.d.ts", - "glosses/is.d.ts", - "glosses/exceptions.d.ts", + "glosses/shani.d.ts", + "glosses/std.d.ts", "glosses/streams.d.ts", - "glosses/fast.d.ts", - "glosses/data.d.ts", - "glosses/datetime.d.ts", - "glosses/compressors.d.ts", - "glosses/archives.d.ts", - "adone-tests.ts", - "test/index.ts", - "test/index-import.ts", + "glosses/system/env.d.ts", + "glosses/system/index.d.ts", + "glosses/system/process.d.ts", + "glosses/system/user.d.ts", + "glosses/templating/dot.d.ts", + "glosses/templating/index.d.ts", + "glosses/templating/nunjucks.d.ts", + "glosses/text/index.d.ts", + "glosses/text/spinners.d.ts", + "glosses/text/table.d.ts", + "glosses/text/unicode.d.ts", + "glosses/utils.d.ts", + "glosses/vault.d.ts", + "index.d.ts", + "test/glosses/application.ts", + "test/glosses/archives.ts", + "test/glosses/assertion.ts", + "test/glosses/collections/array_set.ts", + "test/glosses/collections/async_queue.ts", + "test/glosses/collections/avl_tree.ts", + "test/glosses/collections/binary_search_tree.ts", + "test/glosses/collections/buffer_list.ts", + "test/glosses/collections/byte_array.ts", + "test/glosses/collections/default_map.ts", + "test/glosses/collections/fast_lru.ts", + "test/glosses/collections/linked_list.ts", + "test/glosses/collections/lru.ts", + "test/glosses/collections/map_cache.ts", + "test/glosses/collections/ns_cache.ts", + "test/glosses/collections/priority_queue.ts", + "test/glosses/collections/queue.ts", + "test/glosses/collections/rb_tree.ts", + "test/glosses/collections/refcounted_cache.ts", + "test/glosses/collections/set.ts", + "test/glosses/collections/stack.ts", + "test/glosses/collections/timedout_map.ts", + "test/glosses/compressors.ts", + "test/glosses/crypto/asn1.ts", + "test/glosses/crypto/ed25519.ts", + "test/glosses/crypto/secp256k1.ts", + "test/glosses/data.ts", + "test/glosses/datetime.ts", + "test/glosses/events.ts", + "test/glosses/errors.ts", + "test/glosses/fake.ts", + "test/glosses/fast.ts", + "test/glosses/fs.ts", + "test/glosses/is.ts", "test/glosses/math/index.ts", "test/glosses/math/matrix.ts", "test/glosses/math/simd.ts", - "test/glosses/std.ts", - "test/glosses/utils.ts", - "test/glosses/assertion.ts", + "test/glosses/meta.ts", + "test/glosses/net/http/client.ts", + "test/glosses/pretty/json.ts", + "test/glosses/pretty/size.ts", + "test/glosses/pretty/table.ts", + "test/glosses/pretty/time.ts", "test/glosses/promise.ts", - "test/glosses/shani.ts", + "test/glosses/regex.ts", + "test/glosses/semver.ts", "test/glosses/shani-global.ts", - "test/glosses/collections.ts", - "test/glosses/events.ts", - "test/glosses/fs.ts", - "test/glosses/is.ts", - "test/glosses/exceptions.ts", + "test/glosses/shani.ts", + "test/glosses/std.ts", "test/glosses/streams.ts", - "test/glosses/fast.ts", - "test/glosses/data.ts", - "test/glosses/datetime.ts", - "test/glosses/compressors.ts", - "test/glosses/archives.ts" + "test/glosses/system/env.ts", + "test/glosses/system/process.ts", + "test/glosses/system/user.ts", + "test/glosses/templating/dot.ts", + "test/glosses/templating/nunjucks.ts", + "test/glosses/text/index.ts", + "test/glosses/text/spinners.ts", + "test/glosses/text/table.ts", + "test/glosses/text/unicode.ts", + "test/glosses/utils.ts", + "test/glosses/vault.ts", + "test/index-import.ts", + "test/index.ts" ] } \ No newline at end of file diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index 803318a754..0da1ed0ef5 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -16,16 +16,13 @@ declare var AFRAME: AFrame.AFrameGlobal; declare var hasNativeWebVRImplementation: boolean; -interface NodeSelector { - querySelector(selectors: 'a-scene'): AFrame.Scene; +interface Document { + createElement(tagName: string): AFrame.Entity; + querySelector(selectors: 'a-scene'): AFrame.Scene; querySelector>(selectors: string): T; querySelectorAll(selectors: string): NodeListOf | Element>; } -interface Document { - createElement(tagName: string): AFrame.Entity; -} - // Interfaces declare namespace AFrame { interface ObjectMap { diff --git a/types/agenda/agenda-tests.ts b/types/agenda/agenda-tests.ts index 964eb1b836..bbf945bd62 100644 --- a/types/agenda/agenda-tests.ts +++ b/types/agenda/agenda-tests.ts @@ -1,10 +1,10 @@ -import * as Agenda from "agenda"; +import Agenda = require("agenda"); +import { Db, Server } from "mongodb"; var mongoConnectionString = "mongodb://127.0.0.1/agenda"; var agenda = new Agenda({ db: { address: mongoConnectionString } }); - agenda.define('delete old users', (job, done) => { }); @@ -102,4 +102,9 @@ job.remove(function(err) { if (!err) console.log("Successfully removed job from collection"); }) +class ExtendedAgenda extends Agenda { + async start() { } +} +const extendedAgenda: ExtendedAgenda = new ExtendedAgenda() + .mongo(new Db('some-database', new Server('host.name', 0))) diff --git a/types/agenda/index.d.ts b/types/agenda/index.d.ts index 426b187d7c..12b0b76c38 100644 --- a/types/agenda/index.d.ts +++ b/types/agenda/index.d.ts @@ -31,57 +31,57 @@ declare class Agenda extends EventEmitter { /** * Connect to the specified MongoDB server and database. */ - database(url: string, collection?: string, options?: any, cb?: ResultCallback): Agenda; + database(url: string, collection?: string, options?: any, cb?: ResultCallback): this; /** * Initialize agenda with an existing MongoDB connection. */ - mongo(db: Db, collection?: string, cb?: ResultCallback): Agenda; + mongo(db: Db, collection?: string, cb?: ResultCallback): this; /** * Sets the agenda name. */ - name(value: string): Agenda; + name(value: string): this; /** * Sets the interval with which the queue is checked. A number in milliseconds or a frequency string. */ - processEvery(interval: string | number): Agenda; + processEvery(interval: string | number): this; /** * Takes a number which specifies the max number of jobs that can be running at any given moment. By default it * is 20. * @param value The value to set. */ - maxConcurrency(value: number): Agenda; + maxConcurrency(value: number): this; /** * Takes a number which specifies the default number of a specific job that can be running at any given moment. * By default it is 5. * @param value The value to set. */ - defaultConcurrency(value: number): Agenda; + defaultConcurrency(value: number): this; /** * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is * 0 for no max. * @param value The value to set. */ - lockLimit(value: number): Agenda; + lockLimit(value: number): this; /** * Takes a number which specifies the default number of a specific job that can be locked at any given moment. * By default it is 0 for no max. * @param value The value to set. */ - defaultLockLimit(value: number): Agenda; + defaultLockLimit(value: number): this; /** * Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This * can be overridden by specifying the lockLifetime option to a defined job. * @param value The value to set. */ - defaultLockLifetime(value: number): Agenda; + defaultLockLifetime(value: number): this; /** * Returns an instance of a jobName with data. This does NOT save the job in the database. See below to learn diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 02def0b4d6..56278df11c 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -1,14 +1,15 @@ -// Type definitions for Alexa SDK for Node.js 1.0 +// Type definitions for Alexa SDK for Node.js 1.1 // Project: https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs // Definitions by: Pete Beegle // Huw // pascalwhoop // Ben // rk-7 +// Alex Malcoci // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -export function handler(event: RequestBody, context: Context, callback?: (err: any, response: any) => void): AlexaObject; +export function handler(event: RequestBody, context: Context, callback?: (err: any, response: any) => void): AlexaObject; export function CreateStateHandler(state: string, obj: any): any; export let StateString: string; export type ConfirmationStatuses = "NONE" | "DENIED" | "CONFIRMED"; @@ -23,6 +24,8 @@ export type CardType = "Standard" | "Simple" | "LinkAccount" | "AskForPermission export type HintType = "PlainText"; export type DirectiveTypes = "AudioPlayer.Play" | "AudioPlayer.Stop" | "AudioPlayer.ClearQueue" | "Display.RenderTemplate" | "Hint" | "VideoApp.Launch"; export type TextContentType = "PlainText" | "RichText"; +export type MediaErrorType = "MEDIA_ERROR_UNKNOWN" | "MEDIA_ERROR_INVALID_REQUEST" | "MEDIA_ERROR_SERVICE_UNAVAILABLE" | "MEDIA_ERROR_INTERNAL_SERVER_ERROR" | "MEDIA_ERROR_INTERNAL_DEVICE_ERROR"; +export type SystemErrorType = "INVALID_RESPONSE" | "DEVICE_COMMUNICATION_ERROR" | "INTERNAL_ERROR"; //#region Types export interface CardImage { @@ -84,7 +87,7 @@ export interface Template { listItems?: ListItem[]; } -export interface AlexaObject extends Handler { +export interface AlexaObject extends Handler { _event: any; _context: any; _callback: any; @@ -98,11 +101,11 @@ export interface AlexaObject extends Handler { execute: () => void; } -export interface Handlers { +export interface Handlers { [intent: string]: (this: Handler) => void; } -export interface Handler { +export interface Handler { on: any; emit(event: string, ...args: any[]): boolean; emitWithState: any; @@ -141,7 +144,7 @@ export interface System { apiEndpoint: string; application: Application; device: any; - user: any; + user: SessionUser; } export interface AudioPlayer { token: string; @@ -151,10 +154,32 @@ export interface AudioPlayer { */ playerActivity: AudioPlayerActivity; } -export interface RequestBody { + +export interface Display { + token: string; +} + +export interface Device { + deviceId: string; + supportedInterfaces: DeviceInterfaces; +} + +export interface DeviceInterfaces { + AudioPlayer: any; + Display: any; +} + +export interface RequestContext { + AudioPlayer?: AudioPlayer; + Display?: Display; + System: System; +} + +export interface RequestBody { version: string; session: Session; request: T; + context: RequestContext; } export interface Session { @@ -187,8 +212,94 @@ export interface SessionEndedRequest extends Request { reason?: string; } +export interface AudioPlayerPlaybackRequest extends Request { + token: string; + offsetInMilliseconds: number; +} + +export interface AudioPlayerPlaybackFailedRequest extends Request { + token: string; + error: MediaError; + currentPlaybackState: AudioPlayer; +} + +export interface MediaError { + type: MediaErrorType; + message: string; +} + +export interface SystemExceptionEncounteredRequest extends Request { + error: SystemError; + cause: ErrorCause; +} + +export interface SystemError { + type: SystemErrorType; + message: string; +} + +export interface ErrorCause { + requestId: string; +} + +export interface SkillAccountRequest extends Request { + body: SkillAccountBody; +} + +export interface SkillAccountBody { + accessToken: string; +} + +export interface SkillPermissionRequest extends Request { + body: SkillPermissionBody; +} + +export interface SkillPermissionBody { + acceptedPermissions: PermissionScope[]; +} + +export interface PermissionScope { + scope: string; +} + +export interface ListEventRequest extends Request { + body: ListEventBody; +} + +export interface ListEventBody { + listId: string; + listItemIds?: string[]; +} + export interface Request { - type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest"; + type: "LaunchRequest" + | "IntentRequest" + | "SessionEndedRequest" + + | "System.ExceptionEncountered" + + | "AudioPlayer.PlaybackStarted" + | "AudioPlayer.PlaybackFinished" + | "AudioPlayer.PlaybackStopped" + | "AudioPlayer.PlaybackNearlyFinished" + + | "PlaybackController.NextCommandIssued" + | "PlaybackController.PauseCommandIssued" + | "PlaybackController.PlayCommandIssued" + | "PlaybackController.PreviousCommandIssued" + + | "AlexaSkillEvent.SkillAccountLinked" + | "AlexaSkillEvent.SkillEnabled" + | "AlexaSkillEvent.SkillDisabled" + | "AlexaSkillEvent.SkillPermissionAccepted" + | "AlexaSkillEvent.SkillPermissionChanged" + + | "AlexaHouseholdListEvent.ListCreated" + | "AlexaHouseholdListEvent.ListUpdated" + | "AlexaHouseholdListEvent.ListDeleted" + | "AlexaHouseholdListEvent.ItemsCreated" + | "AlexaHouseholdListEvent.ItemsUpdated" + | "AlexaHouseholdListEvent.ItemsDeleted"; requestId: string; timestamp: string; locale?: string; @@ -296,7 +407,7 @@ export interface ListItemObject { /** * item version (Positive integer) */ - version?: number | string; + version: number; /** * created time (ISO 8601 time format with time zone) */ @@ -348,6 +459,38 @@ export interface ListObject { * Items that belong to this list. */ items: ListItemObject[]; + + next?: ListLinks; +} + +export interface ListLinks { + next: string; +} + +export interface ListCollection { + lists: ListObject[]; +} + +export interface CreateListParams { + name: string; + state: "active"; +} + +export interface UpdateListParams { + name: string; + state: ListObjectState; + version: number; +} + +export interface CreateListItemParams { + value: string; + status: ListItemObjectStatus; +} + +export interface UpdateListItemParams { + value: string; + status: ListItemObjectStatus; + version: number; } //#endregion @@ -545,7 +688,7 @@ export namespace templateBuilders { //#region services export namespace services { - interface ApiClient { + class ApiClient { /** * Make a POST API call to the specified uri with headers and optional body * @param uri http(s?) endpoint to call @@ -582,7 +725,7 @@ export namespace services { * Create an instance of DeviceAddressService * @param [apiClient=new ApiClient()] ApiClient */ - constructor(apiClient: ApiClient); + constructor(apiClient?: ApiClient); /** * Get full address information from Alexa Device Address API @@ -607,7 +750,7 @@ export namespace services { * Creates an instance of DirectiveService. * @param [apiClient=new ApiClient()] ApiClient */ - constructor(apiClient: ApiClient); + constructor(apiClient?: ApiClient); /** * Send the specified directiveObj to Alexa directive service @@ -624,7 +767,7 @@ export namespace services { * Create an instance of ListManagementService * @param apiClient apiClient */ - constructor(apiClient: ApiClient); + constructor(apiClient?: ApiClient); /** * Set apiEndpoint address, default is "https://api.amazonalexa.com" @@ -642,80 +785,80 @@ export namespace services { /** * Retrieve the metadata for all customer lists, including the customer's default lists * @param token bearer token for list management permission - * @returns Promise + * @returns Promise */ - getListsMetadata(token: string): Promise; + getListsMetadata(token: string): Promise; /** * Create a custom list. The new list name must be different than any existing list name - * @param listObject listObject + * @param params params * @param token bearer token for list management permission - * @returns Promise + * @returns Promise */ - createList(listObject: ListObject, token: string): Promise; + createList(params: CreateListParams, token: string): Promise; /** * Retrieve list metadata including the items in the list with requested status * @param listId unique Id associated with the list * @param itemStatus itemsStatus can be either "active" or "completed" * @param token bearer token for list management permission - * @returns Promise + * @returns Promise */ - getList(listId: string, itemStatus: ListItemObjectStatus, token: string): Promise; + getList(listId: string, itemStatus: ListItemObjectStatus, token: string): Promise; /** * Update a custom list. Only the list name or state can be updated * @param listId unique Id associated with the list - * @param listObject listObject + * @param params params * @param token bearer token for list management permission * @returns Promise */ - updateList(listId: string, listObject: ListObject, token: string): Promise; + updateList(listId: string, params: UpdateListParams, token: string): Promise; /** * Delete a custom list * @param listId unique Id associated with the list * @param token bearer token for list management permission - * @returns Promise + * @returns Promise */ - deleteList(listId: string, token: string): Promise; + deleteList(listId: string, token: string): Promise; /** * Create an item in an active list or in a default list * @param listId unique Id associated with the list - * @param listItemObject listItemObject + * @param params params * @param token bearer token for list management permission - * @returns Promise + * @returns Promise */ - createListItem(listId: string, listItemObject: ListItemObject, token: string): Promise; + createListItem(listId: string, params: CreateListItemParams, token: string): Promise; /** * Retrieve single item within any list by listId and itemId * @param listId unique Id associated with the list * @param itemId unique Id associated with the item * @param token bearer token for list management permission - * @returns Promise + * @returns Promise */ - getListItem(listId: string, itemId: string, token: string): Promise; + getListItem(listId: string, itemId: string, token: string): Promise; /** * Update an item value or item status * @param listId unique Id associated with the list * @param itemId unique Id associated with the item - * @param listItemObject listItemObject + * @param params params * @param token bearer token for list management permission - * @returns Promise + * @returns Promise */ - updateListItem(listId: string, itemId: string, listItemObject: ListItemObject, token: string): Promise; + updateListItem(listId: string, itemId: string, params: UpdateListItemParams, token: string): Promise; /** * Delete an item in the specified list * @param listId unique Id associated with the list * @param itemId unique Id associated with the item * @param token bearer token for list management permission - * @returns Promise + * @returns Promise */ - deleteListItem(listId: string, itemId: string, token: string): Promise; + deleteListItem(listId: string, itemId: string, token: string): Promise; } } //#endregion diff --git a/types/alexa-sdk/tsconfig.json b/types/alexa-sdk/tsconfig.json index d1932fa469..acc11c8263 100644 --- a/types/alexa-sdk/tsconfig.json +++ b/types/alexa-sdk/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "alexa-sdk-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index c56b0f8a9f..5c7026d70e 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -376,7 +376,7 @@ declare namespace algoliasearch { * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObjects(objects: [{}], cb: (err: Error, res: any) => void): void; + addObjects(objects: {}[], cb: (err: Error, res: any) => void): void; /** * Add or replace a specific object * @param object @@ -405,7 +405,7 @@ declare namespace algoliasearch { * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ partialUpdateObjects( - objects: [{}], + objects: {}[], cb: (err: Error, res: any) => void ): void; /** @@ -701,7 +701,7 @@ declare namespace algoliasearch { * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObjects(objects: [{}]): Promise; + addObjects(objects: {}[]): Promise; /** * Add or replace a specific object * @param object @@ -729,7 +729,7 @@ declare namespace algoliasearch { * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObjects(objects: [{}]): Promise; + partialUpdateObjects(objects: {}[]): Promise; /** * Delete a specific object * @param objectID @@ -1387,6 +1387,12 @@ Interface describing options available for gettings the logs * https://github.com/algolia/algoliasearch-client-js#unretrievableattributes */ unretrievableAttributes?: string[]; + /** + * List of attributes you want to use for textual search + * default: [] + * https://github.com/algolia/algoliasearch-client-js#searchableattributes + */ + searchableAttributes?: string[]; /** * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer * default: * @@ -1602,7 +1608,7 @@ Interface describing options available for gettings the logs * default: [] * https://github.com/algolia/algoliasearch-client-js#altcorrections */ - altCorrections?: [{}]; + altCorrections?: {}[]; /** * Configure the precision of the proximity ranking criterion * default: 1 diff --git a/types/algoliasearch/tsconfig.json b/types/algoliasearch/tsconfig.json index 4d7e52dd8b..3358732ba3 100644 --- a/types/algoliasearch/tsconfig.json +++ b/types/algoliasearch/tsconfig.json @@ -1,16 +1,23 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": ["es6"], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": ["../"], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": ["index.d.ts", "algoliasearch-tests.ts"] -} + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "algoliasearch-tests.ts" + ] +} \ No newline at end of file diff --git a/types/alt/index.d.ts b/types/alt/index.d.ts index 2d4c6e259f..0c69e4020a 100644 --- a/types/alt/index.d.ts +++ b/types/alt/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/goatslacker/alt // Definitions by: Michael Shearer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 /// diff --git a/types/amphtml-validator/amphtml-validator-tests.ts b/types/amphtml-validator/amphtml-validator-tests.ts new file mode 100644 index 0000000000..4160f7a451 --- /dev/null +++ b/types/amphtml-validator/amphtml-validator-tests.ts @@ -0,0 +1,28 @@ +import * as ampHtmlValidator from "amphtml-validator"; + +(async () => { + const validator = await ampHtmlValidator.getInstance(); + const result = validator.validateString(""); + const { status, errors } = result; + if (status === "FAIL" || status === "UNKNOWN") { + const errs = errors.map(err => { + const { + severity, + line, + col, + message, + specUrl, + category, + code, + params + } = err; + return err; + }); + } +})(); + +(() => { + const validator = ampHtmlValidator.newInstance(""); + const result = validator.validateString(""); + const { status, errors } = result; +})(); diff --git a/types/amphtml-validator/index.d.ts b/types/amphtml-validator/index.d.ts new file mode 100644 index 0000000000..bcf8e5d66e --- /dev/null +++ b/types/amphtml-validator/index.d.ts @@ -0,0 +1,156 @@ +// Type definitions for amphtml-validator 1.0 +// Project: https://github.com/ampproject/amphtml/tree/master/validator/nodejs +// Definitions by: Kevin Tjiam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Context, Script } from "vm"; + +export interface ValidationError { + severity: ValidationErrorSeverity; + line: number; + col: number; + message: string; + specUrl: string | null; + category: ErrorCategoryCode; + code: ValidationErrorCode; + params: string[]; +} + +export interface ValidationResult { + status: ValidationResultStatus; + errors: ValidationError[]; +} + +export class Validator extends Script { + sandbox: Context; + validateString(stringToValidate: string): ValidationResult; +} + +export function getInstance( + validatorJs?: string, + userAgent?: string +): Promise; +export function newInstance(validatorJsContents: string): Validator; + +/** + * Enums from protobufs + * https://github.com/ampproject/amphtml/blob/master/validator/validator.proto + */ +export type ValidationResultStatus = "UNKNOWN" | "PASS" | "FAIL"; + +export type ValidationErrorSeverity = "UNKNOWN_SEVERITY" | "ERROR" | "WARNING"; + +export type ErrorCategoryCode = + | "UNKNOWN" + | "GENERIC" + | "DISALLOWED_HTML_WITH_AMP_EQUIVALENT" + | "DISALLOWED_HTML" + | "AUTHOR_STYLESHEET_PROBLEM" + | "MANDATORY_AMP_TAG_MISSING_OR_INCORRECT" + | "AMP_TAG_PROBLEM" + | "CUSTOM_JAVASCRIPT_DISALLOWED" + | "AMP_LAYOUT_PROBLEM" + | "AMP_HTML_TEMPLATE_PROBLEM" + | "DEPRECATION"; + +export type ValidationErrorCode = + | "UNKNOWN_CODE" + | "MANDATORY_TAG_MISSING" + | "TAG_REQUIRED_BY_MISSING" + | "WARNING_TAG_REQUIRED_BY_MISSING" + | "WARNING_EXTENSION_UNUSED" + | "EXTENSION_UNUSED" + | "WARNING_EXTENSION_DEPRECATED_VERSION" + | "ATTR_REQUIRED_BUT_MISSING" + | "DISALLOWED_TAG" + | "GENERAL_DISALLOWED_TAG" + | "DISALLOWED_SCRIPT_TAG" + | "DISALLOWED_ATTR" + | "DISALLOWED_STYLE_ATTR" + | "INVALID_ATTR_VALUE" + | "DUPLICATE_ATTRIBUTE" + | "ATTR_VALUE_REQUIRED_BY_LAYOUT" + | "IMPLIED_LAYOUT_INVALID" + | "SPECIFIED_LAYOUT_INVALID" + | "MANDATORY_ATTR_MISSING" + | "MANDATORY_ONEOF_ATTR_MISSING" + | "DUPLICATE_DIMENSION" + | "DUPLICATE_UNIQUE_TAG" + | "DUPLICATE_UNIQUE_TAG_WARNING" + | "WRONG_PARENT_TAG" + | "STYLESHEET_TOO_LONG" + | "MANDATORY_CDATA_MISSING_OR_INCORRECT" + | "CDATA_VIOLATES_BLACKLIST" + | "NON_WHITESPACE_CDATA_ENCOUNTERED" + | "DEPRECATED_ATTR" + | "DEPRECATED_TAG" + | "MANDATORY_PROPERTY_MISSING_FROM_ATTR_VALUE" + | "INVALID_PROPERTY_VALUE_IN_ATTR_VALUE" + | "MISSING_URL" + | "INVALID_URL" + | "INVALID_URL_PROTOCOL" + | "DISALLOWED_DOMAIN" + | "DISALLOWED_RELATIVE_URL" + | "DISALLOWED_PROPERTY_IN_ATTR_VALUE" + | "MUTUALLY_EXCLUSIVE_ATTRS" + | "UNESCAPED_TEMPLATE_IN_ATTR_VALUE" + | "TEMPLATE_PARTIAL_IN_ATTR_VALUE" + | "TEMPLATE_IN_ATTR_NAME" + | "INCONSISTENT_UNITS_FOR_WIDTH_AND_HEIGHT" + | "DISALLOWED_TAG_ANCESTOR" + | "MANDATORY_LAST_CHILD_TAG" + | "MANDATORY_TAG_ANCESTOR" + | "MANDATORY_TAG_ANCESTOR_WITH_HINT" + | "ATTR_DISALLOWED_BY_IMPLIED_LAYOUT" + | "ATTR_DISALLOWED_BY_SPECIFIED_LAYOUT" + | "INCORRECT_NUM_CHILD_TAGS" + | "INCORRECT_MIN_NUM_CHILD_TAGS" + | "DISALLOWED_CHILD_TAG_NAME" + | "DISALLOWED_FIRST_CHILD_TAG_NAME" + | "DISALLOWED_MANUFACTURED_BODY" + | "CHILD_TAG_DOES_NOT_SATISFY_REFERENCE_POINT" + | "MANDATORY_REFERENCE_POINT_MISSING" + | "DUPLICATE_REFERENCE_POINT" + | "TAG_NOT_ALLOWED_TO_HAVE_SIBLINGS" + | "TAG_REFERENCE_POINT_CONFLICT" + | "CHILD_TAG_DOES_NOT_SATISFY_REFERENCE_POINT_SINGULAR" + | "BASE_TAG_MUST_PRECEED_ALL_URLS" + | "MISSING_REQUIRED_EXTENSION" + | "ATTR_MISSING_REQUIRED_EXTENSION" + | "DOCUMENT_TOO_COMPLEX" + | "INVALID_UTF8" + | "CSS_SYNTAX" + | "CSS_SYNTAX_INVALID_AT_RULE" + | "CSS_SYNTAX_STRAY_TRAILING_BACKSLASH" + | "CSS_SYNTAX_UNTERMINATED_COMMENT" + | "CSS_SYNTAX_UNTERMINATED_STRING" + | "CSS_SYNTAX_BAD_URL" + | "CSS_SYNTAX_EOF_IN_PRELUDE_OF_QUALIFIED_RULE" + | "CSS_SYNTAX_INVALID_DECLARATION" + | "CSS_SYNTAX_INCOMPLETE_DECLARATION" + | "CSS_SYNTAX_ERROR_IN_PSEUDO_SELECTOR" + | "CSS_SYNTAX_MISSING_SELECTOR" + | "CSS_SYNTAX_NOT_A_SELECTOR_START" + | "CSS_SYNTAX_UNPARSED_INPUT_REMAINS_IN_SELECTOR" + | "CSS_SYNTAX_MISSING_URL" + | "CSS_SYNTAX_INVALID_URL" + | "CSS_SYNTAX_INVALID_URL_PROTOCOL" + | "CSS_SYNTAX_DISALLOWED_DOMAIN" + | "CSS_SYNTAX_DISALLOWED_RELATIVE_URL" + | "CSS_SYNTAX_INVALID_ATTR_SELECTOR" + | "CSS_SYNTAX_INVALID_PROPERTY" + | "CSS_SYNTAX_INVALID_PROPERTY_NOLIST" + | "CSS_SYNTAX_QUALIFIED_RULE_HAS_NO_DECLARATIONS" + | "CSS_SYNTAX_DISALLOWED_QUALIFIED_RULE_MUST_BE_INSIDE_KEYFRAME" + | "CSS_SYNTAX_DISALLOWED_KEYFRAME_INSIDE_KEYFRAME" + | "CSS_SYNTAX_MALFORMED_MEDIA_QUERY" + | "CSS_SYNTAX_DISALLOWED_MEDIA_TYPE" + | "CSS_SYNTAX_DISALLOWED_MEDIA_FEATURE" + | "CSS_SYNTAX_DISALLOWED_PROPERTY_VALUE" + | "CSS_SYNTAX_DISALLOWED_PROPERTY_VALUE_WITH_HINT" + | "CSS_SYNTAX_PROPERTY_DISALLOWED_WITHIN_AT_RULE" + | "CSS_SYNTAX_PROPERTY_DISALLOWED_TOGETHER_WITH" + | "CSS_SYNTAX_PROPERTY_REQUIRES_QUALIFICATION"; diff --git a/types/amphtml-validator/tsconfig.json b/types/amphtml-validator/tsconfig.json new file mode 100644 index 0000000000..0c0c91b549 --- /dev/null +++ b/types/amphtml-validator/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", "amphtml-validator-tests.ts"] +} diff --git a/types/expr-eval/tslint.json b/types/amphtml-validator/tslint.json similarity index 100% rename from types/expr-eval/tslint.json rename to types/amphtml-validator/tslint.json diff --git a/types/amqp/index.d.ts b/types/amqp/index.d.ts index ca39ce4404..4e2cd4e288 100644 --- a/types/amqp/index.d.ts +++ b/types/amqp/index.d.ts @@ -96,6 +96,7 @@ export interface ConnectionOptions { authMechanism?: string; vhost?: string; noDelay?: boolean; + heartbeat?: number; ssl?: { enabled: boolean; keyFile?: string; diff --git a/types/amqplib/index.d.ts b/types/amqplib/index.d.ts index 25b0ef04e9..269ed0112e 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for amqplib 0.5 // Project: https://github.com/squaremo/amqp.node -// Definitions by: Michael Nahkies , Ab Reitsma , Nicolás Fantone +// Definitions by: Michael Nahkies , Ab Reitsma , Nicolás Fantone , Nick Zelei // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/amqplib/properties.d.ts b/types/amqplib/properties.d.ts index af90909d8c..9f96b14f5c 100644 --- a/types/amqplib/properties.d.ts +++ b/types/amqplib/properties.d.ts @@ -141,6 +141,52 @@ export namespace Options { export interface Message { content: Buffer; - fields: any; - properties: any; + fields: MessageFields; + properties: MessageProperties; +} + +export interface MessageFields { + deliveryTag: number; + redelivered: boolean; + exchange: string; + routingKey: string; + messageCount: string; +} + +export interface MessageProperties { + contentType: any | undefined; + contentEncoding: any | undefined; + headers: MessagePropertyHeaders; + deliveryMode: any | undefined; + priority: any | undefined; + correlationId: any | undefined; + replyTo: any | undefined; + expiration: any | undefined; + messageId: any | undefined; + timestamp: any | undefined; + type: any | undefined; + userId: any | undefined; + appId: any | undefined; + clusterId: any | undefined; +} + +export interface MessagePropertyHeaders { + "x-first-death-exchange"?: string; + "x-first-death-queue"?: string; + "x-first-death-reason"?: string; + "x-death"?: XDeath[]; + [key: string]: any; +} + +export interface XDeath { + count: number; + reason: "rejected" | "expired" | "maxlen"; + queue: string; + time: { + "!": "timestamp"; + value: number; + }; + exchange: string; + "original-expiration"?: any; + "routing-keys": string[]; } diff --git a/types/analytics-node/analytics-node-tests.ts b/types/analytics-node/analytics-node-tests.ts index 5207fe560b..5dfabb426c 100644 --- a/types/analytics-node/analytics-node-tests.ts +++ b/types/analytics-node/analytics-node-tests.ts @@ -18,6 +18,22 @@ function testIdentify(): void { friends: 42 } }); + + analytics.identify({ + userId: '019mr8mf4r', + traits: { + name: 'Michael Bolton', + email: 'mbolton@initech.com', + plan: 'Enterprise', + friends: 42 + } + }, (err, data) => { + if (err) { + console.error(err); + } else { + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + } + }); } function testTrack(): void { @@ -29,6 +45,21 @@ function testTrack(): void { shippingMethod: '2-day' } }); + + analytics.track({ + userId: '019mr8mf4r', + event: 'Purchased an Item', + properties: { + revenue: 39.95, + shippingMethod: '2-day' + } + }, (err, data) => { + if (err) { + console.error(err); + } else { + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + } + }); } function testPage(): void { @@ -43,6 +74,24 @@ function testPage(): void { referrer: 'https://github.com/segmentio/analytics-node' } }); + + analytics.page({ + userId: '019mr8mf4r', + category: 'Docs', + name: 'Node.js Library', + properties: { + url: 'https://segment.com/docs/libraries/node', + path: '/docs/libraries/node/', + title: 'Node.js Library - Segment', + referrer: 'https://github.com/segmentio/analytics-node' + } + }, (err, data) => { + if (err) { + console.error(err); + } else { + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + } + }); } function testAlias(): void { @@ -65,6 +114,21 @@ function testGroup(): void { description: 'Accounting Software' } }); + + analytics.group({ + userId: '019mr8mf4r', + groupId: '56', + traits: { + name: 'Initech', + description: 'Accounting Software' + } + }, (err, data) => { + if (err) { + console.error(err); + } else { + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + } + }); } function testIntegrations(): void { @@ -77,11 +141,27 @@ function testIntegrations(): void { 'Google Analytics': false } }); + + analytics.track({ + event: 'Upgraded Membershipt', + userId: '97234974', + integrations: { + 'All': false, + 'Vero': true, + 'Google Analytics': false + } + }, (err, data) => { + if (err) { + console.error(err); + } else { + data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`)) + } + }); } function testFlush(): void { analytics.flush(); - analytics.flush(function(err, batch) { + analytics.flush((err, batch) => { 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 fa0b8d6426..a1de134195 100644 --- a/types/analytics-node/index.d.ts +++ b/types/analytics-node/index.d.ts @@ -1,11 +1,36 @@ // Type definitions for Segment's analytics.js for Node.js // Project: https://segment.com/docs/libraries/node/ // Definitions by: Andrew Fong +// Thomas Thiebaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = AnalyticsNode.Analytics; declare namespace AnalyticsNode { + interface Message { + type: string; + context: { + library: { + name: string; + version: string; + }, + [key: string]: any + }; + _metadata: { + nodeVersion: string; + [key: string]: any; + }, + timestamp?: Date; + messageId?: string; + anonymousId: string | number; + userId: string | number; + } + + interface Data { + batch: Message[], + timestamp: Date; + sentAt: Date; + } interface Integrations { [index: string]: boolean; @@ -25,7 +50,7 @@ declare namespace AnalyticsNode { timestamp?: Date; context?: Object; integrations?: Integrations; - }): Analytics; + }, callback?: (err: Error, data: Data) => void): Analytics; /* The track method lets you record the actions your users perform. */ track(message: { @@ -35,7 +60,7 @@ declare namespace AnalyticsNode { timestamp?: Date; context?: Object; integrations?: Integrations; - }): Analytics; + }, callback?: (err: Error, data: Data) => void): Analytics; /* The page method lets you record page views on your website, along with optional extra information about the page being viewed. */ @@ -47,14 +72,14 @@ declare namespace AnalyticsNode { timestamp?: Date; context?: Object; integrations?: Integrations; - }): Analytics; + }, callback?: (err: Error, data: Data) => void): Analytics; /* alias is how you associate one identity with another. */ alias(message: { previousId: string | number; userId: string | number; integrations?: Integrations; - }): Analytics; + }, callback?: (err: Error, data: Data) => void): Analytics; /* Group calls can be used to associate individual users with shared accounts or companies. */ @@ -66,16 +91,9 @@ declare namespace AnalyticsNode { timestamp?: Date; anonymous_id?: string | number; integrations?: Integrations; - }): Analytics; + }, callback?: (err: Error, data: Data) => void): Analytics; /* Flush batched calls to make sure nothing is left in the queue */ - flush(fn?: (err: Error, batch: { - batch: Array<{ - type: string; - }>; - messageId: string; - sentAt: Date; - timestamp: Date; - }) => void): Analytics; + flush(callback?: (err: Error, data: Data) => void): Analytics; } } diff --git a/types/anchor-js/anchor-js-tests.ts b/types/anchor-js/anchor-js-tests.ts new file mode 100644 index 0000000000..a27e09605a --- /dev/null +++ b/types/anchor-js/anchor-js-tests.ts @@ -0,0 +1,16 @@ +anchors.add(); +anchors.add('h1'); +anchors.add().add('h2'); + +anchors.remove(); +anchors.remove('h1'); +anchors.remove().remove('h2'); + +anchors.removeAll(); + +const headerAnchors = new AnchorJS(); + +const footerAnchors = new AnchorJS({ + placement: 'right', +}); +footerAnchors.remove('.links'); diff --git a/types/anchor-js/index.d.ts b/types/anchor-js/index.d.ts new file mode 100644 index 0000000000..1f59c295e2 --- /dev/null +++ b/types/anchor-js/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for anchor-js 4.1 +// Project: https://github.com/bryanbraun/anchorjs +// Definitions by: Brian Surowiec +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace anchorjs { + interface Anchor { + options: AnchorOptions; + + add(selector?: string): Anchor; + remove(selector?: string): Anchor; + removeAll(): void; + } + + type AnchorPlacement = 'left' | 'right'; + type AnchorVisibility = 'always' | 'hover' | 'touch'; + + interface AnchorOptions { + arialabel?: string; + class?: string; + icons?: string; + placement?: AnchorPlacement; + truncate?: number; + visible?: AnchorVisibility; + } + + interface AnchorStatic { + new(options?: AnchorOptions): Anchor; + } +} + +declare const anchors: anchorjs.Anchor; +declare const AnchorJS: anchorjs.AnchorStatic; + +export = AnchorJS; + +export as namespace AnchorJS; + +declare global { + const anchors: anchorjs.Anchor; +} diff --git a/types/anchor-js/tsconfig.json b/types/anchor-js/tsconfig.json new file mode 100644 index 0000000000..19f6891217 --- /dev/null +++ b/types/anchor-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", + "anchor-js-tests.ts" + ] +} diff --git a/types/anchor-js/tslint.json b/types/anchor-js/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/anchor-js/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/angular-desktop-notification/angular-desktop-notification-tests.ts b/types/angular-desktop-notification/angular-desktop-notification-tests.ts new file mode 100644 index 0000000000..0cb41b2317 --- /dev/null +++ b/types/angular-desktop-notification/angular-desktop-notification-tests.ts @@ -0,0 +1,40 @@ +import * as angular from 'angular'; + +angular + .module('app', ['ngDesktopNotification']) + .config(['desktopNotificationProvider', (desktopNotificationProvider: angular.desktopNotification.IDesktopNotificationProvider) => { + desktopNotificationProvider.config({ + autoClose: true, + duration: 5, + showOnPageHidden: false, + }); + }]) + .controller('AppController', ['desktopNotification', (desktopNotification: angular.desktopNotification.IDesktopNotificationService) => { + // Check support and permission + const isNotificationSupported = desktopNotification.isSupported(); + const currentNotificationPermission = desktopNotification.currentPermission(); + + if (currentNotificationPermission === desktopNotification.permissions.granted) { + // Permission granted + } + + // Request permission + desktopNotification.requestPermission().then( + // Permission granted + (permission) => { + // Show notification + desktopNotification.show( + "Notification title", + { + tag: "tag", + body: "Notification body", + icon: "https://www.iconurl.com/icon-name.icon-extension", + onClick: () => { + // Notification clicked + } + }); + }, + () => { + // No permission granted + }); + }]); diff --git a/types/angular-desktop-notification/index.d.ts b/types/angular-desktop-notification/index.d.ts new file mode 100644 index 0000000000..a20d67cd21 --- /dev/null +++ b/types/angular-desktop-notification/index.d.ts @@ -0,0 +1,174 @@ +// Type definitions for angular-desktop-notification 1.1 +// Project: https://github.com/jmsanpascual/angular-desktop-notification#readme +// Definitions by: Davide Donadello +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as angular from 'angular'; + +declare var _: string; +export = _; + +declare module 'angular' { + namespace desktopNotification { + /** + * All options available during show notification according to https://developer.mozilla.org/en-US/docs/Web/API/notification + */ + interface AugmentedNotificationOptions extends NotificationOptions { + /** + * The badge property of the Notification interface returns the URL of the image used to represent the notification + * when there is not enough space to display the notification itself. + * + * This is an experimental technology + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/badge + */ + badge?: USVString; + + /** + * The data read-only property of the Notification interface returns a structured clone of the notification's data, + * as specified in the data option of the Notification() constructor + * + * Note: This feature is available in Web Workers. + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/data + */ + data?: any; + + /** + * The image read-only property of the Notification interface contains the URL of an image to be displayed as part of + * the notification, as specified in the image option of the Notification() constructor. + * + * Note: This feature is available in Web Workers. + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/image + */ + image?: USVString; + + /** + * The renotify read-only property of the Notification interface specifies whether the user should be notified after a + * new notification replaces an old one, as specified in the renotify option of the Notification() constructor + * + * Note: This property is not currently supported in any browser. + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/renotify + */ + renotify?: boolean; + + /** + * The requireInteraction read-only property of the Notification interface returns a Boolean indicating that a notification + * should remain active until the user clicks or dismisses it, rather than closing automatically. + * + * Note: This can be set when the notification is first created by setting the requireInteraction option to true in the + * options object of the Notification.Notification() constructor. + * Note: This feature is available in Web Workers. + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/requireInteraction + */ + requireInteraction?: boolean; + + /** + * The silent read-only property of the Notification interface specifies whether the notification should be silent, i.e. no + * sounds or vibrations should be issued, regardless of the device settings. This is specified in the renotify option of the + * Notification() constructor. + * + * Note: This feature is available in Web Workers. + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/silent + */ + silent?: boolean; + + /** + * The timestamp read-only property of the Notification interface returns a DOMTimeStamp, as specified in the timestamp option of the + * Notification() constructor. + * + * The notification's timestamp can represent the time, in milliseconds since 00:00:00 UTC on 1 January 1970, of the event for which + * the notification was created, or it can be an arbitrary timestamp that you want associated with the notification. For example, a + * timestamp for an upcoming meeting could be set in the future, whereas a timestamp for a missed message could be set in the past. + * + * Note: This feature is available in Web Workers + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/timestamp + */ + timestamp?: number; + + /** + * The title read-only property of the Notification interface indicates the title of the notification, as specified in the title parameter + * of the Notification() constructor. + * + * Note: This feature is available in Web Workers. + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/title + */ + title?: string; + + /** + * The vibrate read-only property of the Notification interface specifies a a vibration pattern for the device's vibration hardware to emit + * when the notification fires. This is specified in the vibrate option of the Notification() constructor. + * + * Note: This property is not currently supported in any browser. + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/vibrate + */ + vibrate?: boolean; + + /** + * The onclick property of the Notification interface specifies an event listener to receive click events. + * These events occur when the user clicks on a displayed Notification. + * + * The default behavior is to move the focus to the viewport of the notification's related browsing context. + * If you don't want that behaviour, call preventDefault() on the event object. + */ + onClick?: (event: MouseEvent) => void; + + /** + * The onerror property of the Notification interface specifies an event listener to receive error events. + * These events occur when something goes wrong with a Notification (in many cases an error preventing the notification from being displayed.) + * + * A function which serves as the event handler for the error event. When an error occurs, the specified function will be called. + * If null, no error handler is in effect. + */ + onError?: EventListener; + } + + // tslint:disable-next-line interface-name + interface IDesktopNotificationOptions { + autoClose?: boolean; + duration?: number; + showOnPageHidden?: boolean; + } + + // tslint:disable-next-line interface-name + interface IDesktopNotificationProvider { + /** + * Set the default app-wide configuration for desktopNotification + */ + config(options: IDesktopNotificationOptions): void; + } + + // tslint:disable-next-line interface-name + interface IDesktopNotificationService { + permissions: { + default: 'default', + denied: 'denied', + granted: 'granted', + }; + + /** + * This method returns true if the browser supports the Notification API, false otherwise + */ + isSupported(): boolean; + + /** + * This method will get the current permission set in the browser which could be one of the ff. + * - desktopNotification.permissions.default + * - desktopNotification.permissions.denied + * - desktopNotification.permissions.granted + */ + currentPermission(): NotificationPermission; + + /** + * This method returns a $q promise, if the user allowed the notification the successCallback will be executed, + * errorCallback will be executed otherwise + */ + requestPermission(): IPromise; + + /** + * This method will display the notification using the parameter values. + * See all available options here at https://developer.mozilla.org/en-US/docs/Web/API/notification#Instance_properties + */ + show(title: string, options?: NotificationOptions | AugmentedNotificationOptions): void; + } + } +} diff --git a/types/angular-desktop-notification/tsconfig.json b/types/angular-desktop-notification/tsconfig.json new file mode 100644 index 0000000000..4398df5f25 --- /dev/null +++ b/types/angular-desktop-notification/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "angular-desktop-notification-tests.ts" + ] +} diff --git a/types/angular-desktop-notification/tslint.json b/types/angular-desktop-notification/tslint.json new file mode 100644 index 0000000000..183bc723ef --- /dev/null +++ b/types/angular-desktop-notification/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/angular-hotkeys/tsconfig.json b/types/angular-hotkeys/tsconfig.json index acb11ff247..81fdf31b45 100644 --- a/types/angular-hotkeys/tsconfig.json +++ b/types/angular-hotkeys/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "angular-hotkeys-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/angular-material/angular-material-tests.ts b/types/angular-material/angular-material-tests.ts index 8d6955c697..ad79cff2db 100644 --- a/types/angular-material/angular-material-tests.ts +++ b/types/angular-material/angular-material-tests.ts @@ -164,8 +164,7 @@ myApp.controller('DialogController', ($scope: TestScope, $mdDialog: ng.material. .controller(function TestController(param) { }) .controller(class { }) .controller(['fakeService', function TestController(fake) { }]) - .controller(['fakeService', class { }]) - ; + .controller(['fakeService', class { }]); const dialogOptions: ng.material.IDialogOptions = {}; @@ -389,3 +388,11 @@ myApp.controller('PanelController', ($scope: TestScope, $mdPanel: ng.material.IP $mdPanel.newPanelAnimation().openFrom({ top: 0, left: 0 }); }; }); + +myApp.controller('StickyController', ($scope: TestScope, $mdSticky: ng.material.IStickyService) => { + const stickyElement = angular.element(new Element()); + const cloneStickyElement = stickyElement.clone(); + + $mdSticky($scope, stickyElement); + $mdSticky($scope, stickyElement, cloneStickyElement); +}); diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 92f6d46751..d77f5ae7ce 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -494,5 +494,7 @@ declare module 'angular' { interface IProgressCircularProvider { configure(options: IProgressCircularConfig): void; } + + type IStickyService = (scope: IScope, element: JQuery, elementClone?: JQuery) => void; } } diff --git a/types/angular-touchspin/angular-touchspin-tests.ts b/types/angular-touchspin/angular-touchspin-tests.ts deleted file mode 100644 index 32396365d9..0000000000 --- a/types/angular-touchspin/angular-touchspin-tests.ts +++ /dev/null @@ -1,29 +0,0 @@ -import angularTouchSpin = require("angular-touchspin"); -import * as angular from 'angular'; - -angular - .module('touchspin-tests', ['nk.touchspin']) - .config(function(touchspinConfigProvider: angular.touchspin.ITouchSpinConfigProvider) { - touchspinConfigProvider.defaults({ - min: 0, - max: 0, - step: 0, - decimals: 0, - stepInterval: 0, - forceStepDivisibility: '', // none | floor | round | ceil - stepIntervalDelay: 0, - verticalButtons: true, - verticalUpClass: '', - verticalDownClass: '', - initVal: 0, - prefix: '', - postfix: '', - prefixExtraClass: '', - postfixExtraClass: '', - mousewheel: true, - buttonDownClass: '', - buttonUpClass: '', - buttonDownTxt: '', - buttonUpTxt: '' - }); - }); diff --git a/types/angular-touchspin/index.d.ts b/types/angular-touchspin/index.d.ts deleted file mode 100644 index 305a033275..0000000000 --- a/types/angular-touchspin/index.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Type definitions for Angular Touchspin v1.0.0 -// Project: https://github.com/nkovacic/angular-touchspin -// Definitions by: Niko Kovačič -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -/// - -declare let angularTouchSpin: string; -export = angularTouchSpin; - -declare module "angular" { - namespace touchspin { - interface ITouchSpinOptions { - min?: number; - max?: number; - step?: number; - decimals?: number; - stepInterval?: number; - forceStepDivisibility?: string; // none | floor | round | ceil - stepIntervalDelay?: number; - verticalButtons?: boolean; - verticalUpClass?: string; - verticalDownClass?: string; - initVal?: number; - prefix?: string; - postfix?: string; - prefixExtraClass?: string; - postfixExtraClass?: string; - mousewheel?: boolean; - buttonDownClass?: string; - buttonUpClass?: string; - buttonDownTxt?: string; - buttonUpTxt?: string; - } - - interface ITouchSpinConfig extends ITouchSpinOptions { } - - interface ITouchSpinConfigProvider { - defaults(touchSpinOptions: ITouchSpinOptions): void; - } - } -} diff --git a/types/angular-translate/index.d.ts b/types/angular-translate/index.d.ts index 55c74629a8..69b1f63d72 100644 --- a/types/angular-translate/index.d.ts +++ b/types/angular-translate/index.d.ts @@ -71,6 +71,7 @@ declare module 'angular' { isReady(): boolean; onReady(): angular.IPromise; resolveClientLocale(): string; + getAvailableLanguageKeys(): string[]; } interface ITranslateProvider extends angular.IServiceProvider { diff --git a/types/angular-websocket/tsconfig.json b/types/angular-websocket/tsconfig.json index 89d5cb9dc3..e4d648dbda 100644 --- a/types/angular-websocket/tsconfig.json +++ b/types/angular-websocket/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "angular-websocket-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index 795e74a058..ca9d2c7568 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -289,25 +289,25 @@ foo.then((x) => { // $q signature tests namespace TestQ { - interface TResult { + interface AbcObject { a: number; b: string; c: boolean; } - interface TValue { + interface EfObject { e: number; f: boolean; } - interface TOther { + interface GhObject { g: string; h: number; } - const tResult: TResult = null; - const promiseTResult: angular.IPromise = null; - const tValue: TValue = null; - const promiseTValue: angular.IPromise = null; - const tOther: TOther = null; - const promiseTOther: angular.IPromise = null; + const abcObject: AbcObject = null; + const abcObjectPromise: angular.IPromise = null; + const efObject: EfObject = null; + const efObjectPromise: angular.IPromise = null; + const ghObject: GhObject = null; + const ghObjectPromise: angular.IPromise = null; const $q: angular.IQService = null; const promiseAny: angular.IPromise = null; @@ -316,11 +316,11 @@ namespace TestQ { // $q constructor { - let result: angular.IPromise; - result = new $q((resolve: (value: TResult) => any) => {}); - result = new $q((resolve: (value: TResult) => any, reject: (value: any) => any) => {}); - result = $q((resolve: (value: TResult) => any) => {}); - result = $q((resolve: (value: TResult) => any, reject: (value: any) => any) => {}); + let result: angular.IPromise; + result = new $q((resolve: (value: AbcObject) => any) => {}); + result = new $q((resolve: (value: AbcObject) => any, reject: (value: any) => any) => {}); + result = $q((resolve: (value: AbcObject) => any) => {}); + result = $q((resolve: (value: AbcObject) => any, reject: (value: any) => any) => {}); } // $q.all @@ -332,8 +332,8 @@ namespace TestQ { $q.all([1, $q.when(2), '3']).then(([ n1, n2, n3 ]) => n1.toFixed() + n2.toFixed() + n3.slice(1)); } { - let result: angular.IPromise; - result = $q.all([promiseAny, promiseAny]); + let result: angular.IPromise; + result = $q.all([promiseAny, promiseAny]); } { let result: angular.IPromise<{[id: string]: any; }>; @@ -356,13 +356,13 @@ namespace TestQ { // $q.defer { - let result: angular.IDeferred; - result = $q.defer(); - result.resolve(tResult); + let result: angular.IDeferred; + result = $q.defer(); + result.resolve(abcObject); const anyValue: any = null; result.reject(anyValue); result.promise.then(result => { - return $q.resolve(result); + return $q.resolve(result); }); } @@ -380,10 +380,10 @@ namespace TestQ { result = $q.resolve(); } { - let result: angular.IPromise; - result = $q.resolve(tResult); - result = $q.resolve(promiseTResult); - const result2: angular.IPromise = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); + let result: angular.IPromise; + result = $q.resolve(abcObject); + result = $q.resolve(abcObjectPromise); + const result2: angular.IPromise = $q.resolve(Math.random() > 0.5 ? abcObject : ghObjectPromise); } // $q.when @@ -392,32 +392,32 @@ namespace TestQ { result = $q.when(); } { - let result: angular.IPromise; - let resultOther: angular.IPromise; + let result: angular.IPromise; + let resultOther: angular.IPromise; - result = $q.when(tResult); - result = $q.when(promiseTResult); + result = $q.when(abcObject); + result = $q.when(abcObjectPromise); - result = $q.when(tValue, (result: TValue) => tResult); - result = $q.when(tValue, (result: TValue) => tResult, (any) => any); - result = $q.when(tValue, (result: TValue) => tResult, (any) => any, (any) => any); + result = $q.when(efObject, (result: EfObject) => abcObject); + result = $q.when(efObject, (result: EfObject) => abcObject, (any) => any); + result = $q.when(efObject, (result: EfObject) => abcObject, (any) => any, (any) => any); - result = $q.when(promiseTValue, (result: TValue) => tResult); - resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther); - resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther); - resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => tOther, (any) => any); - resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther); - resultOther = $q.when(promiseTValue, (result: TValue) => tResult, (any) => promiseTOther, (any) => any); + result = $q.when(efObjectPromise, (result: EfObject) => abcObject); + resultOther = $q.when(efObjectPromise, (result: EfObject) => abcObject, (any) => ghObject); + resultOther = $q.when(efObjectPromise, (result: EfObject) => abcObject, (any) => ghObject); + resultOther = $q.when(efObjectPromise, (result: EfObject) => abcObject, (any) => ghObject, (any) => any); + resultOther = $q.when(efObjectPromise, (result: EfObject) => abcObject, (any) => ghObjectPromise); + resultOther = $q.when(efObjectPromise, (result: EfObject) => abcObject, (any) => ghObjectPromise, (any) => any); - result = $q.when(tValue, (result: TValue) => promiseTResult); - result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any); - result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); + result = $q.when(efObject, (result: EfObject) => abcObjectPromise); + result = $q.when(efObject, (result: EfObject) => abcObjectPromise, (any) => any); + result = $q.when(efObject, (result: EfObject) => abcObjectPromise, (any) => any, (any) => any); - result = $q.when(promiseTValue, (result: TValue) => promiseTResult); - resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther); - resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => tOther, (any) => any); - resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther); - resultOther = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => promiseTOther, (any) => any); + result = $q.when(efObjectPromise, (result: EfObject) => abcObjectPromise); + resultOther = $q.when(efObjectPromise, (result: EfObject) => abcObjectPromise, (any) => ghObject); + resultOther = $q.when(efObjectPromise, (result: EfObject) => abcObjectPromise, (any) => ghObject, (any) => any); + resultOther = $q.when(efObjectPromise, (result: EfObject) => abcObjectPromise, (any) => ghObjectPromise); + resultOther = $q.when(efObjectPromise, (result: EfObject) => abcObjectPromise, (any) => ghObjectPromise, (any) => any); } } @@ -440,41 +440,41 @@ httpFoo.then((response: ng.IHttpResponse) => { // Deferred signature tests namespace TestDeferred { - const any: any = null; + const anything: any = null; - interface TResult { + interface AbcObject { a: number; b: string; c: boolean; } - const tResult: TResult = null; + const abcObject: AbcObject = null; - const deferred: angular.IDeferred = null; + const deferred: angular.IDeferred = null; // deferred.resolve { let result: void; result = deferred.resolve(); - result = deferred.resolve(tResult); + result = deferred.resolve(abcObject); } // deferred.reject { let result: void; result = deferred.reject(); - result = deferred.reject(any); + result = deferred.reject(anything); } // deferred.notify { let result: void; result = deferred.notify(); - result = deferred.notify(any); + result = deferred.notify(anything); } // deferred.promise { - let result: angular.IPromise; + let result: angular.IPromise; result = deferred.promise; } } @@ -517,111 +517,189 @@ namespace TestInjector { // Promise signature tests namespace TestPromise { - const any: any = null; + const anything: any = null; - interface TResult { - kind: 'result'; + interface AbcObject { + kind: 'abc'; a: number; b: string; c: boolean; } - interface TOther { - kind: 'other'; + interface DefObject { + kind: 'def'; d: number; e: string; f: boolean; } - function isTResult(x: TResult | TOther): x is TResult { - return x.kind === 'result'; + function isAbcObject(x: AbcObject | DefObject): x is AbcObject { + return x.kind === 'abc'; } - const tresult: TResult = null; - const tresultPromise: ng.IPromise = null; - const tresultHttpPromise: ng.IHttpPromise = null; + const abcObject: AbcObject = null; + const abcObjectPromise: ng.IPromise = null; + const abcObjectHttpPromise: ng.IHttpPromise = null; - const tother: TOther = null; - const totherPromise: ng.IPromise = null; - const totherHttpPromise: ng.IHttpPromise = null; + const defObject: DefObject = null; + const defObjectPromise: ng.IPromise = null; + const defObjectHttpPromise: ng.IHttpPromise = null; - const promise: angular.IPromise = null; + const promise: angular.IPromise = null; const $q: angular.IQService = null; - const assertPromiseType = (arg: angular.IPromise) => arg; - const reject = $q.reject(); + const rejectedPromise = $q.reject(); // promise.then - assertPromiseType(promise.then((result) => any)); - assertPromiseType(promise.then((result) => any, (any) => any)); - assertPromiseType(promise.then((result) => any, (any) => any, (any) => any)); + // $ExpectType IPromise + promise.then(result => anything); + // $ExpectType IPromise + promise.then(result => anything, any => any); + // $ExpectType IPromise + promise.then(result => anything, any => any, any => any); - assertPromiseType(promise.then((result) => reject)); - assertPromiseType(promise.then((result) => reject, (any) => reject)); - assertPromiseType(promise.then((result) => reject, (any) => reject, (any) => any)); + // $ExpectType IPromise + promise.then(result => rejectedPromise); + // $ExpectType IPromise + promise.then(result => rejectedPromise, any => rejectedPromise); + // $ExpectType IPromise + promise.then(result => rejectedPromise, any => rejectedPromise, any => any); - assertPromiseType(promise.then((result) => result)); - assertPromiseType(promise.then((result) => tresult)); - assertPromiseType(promise.then((result) => tresultPromise)); - assertPromiseType(promise.then((result) => result, (any) => any)); - assertPromiseType(promise.then((result) => result, (any) => any, (any) => any)); - assertPromiseType(promise.then((result) => result, (any) => reject, (any) => any)); + // $ExpectType IPromise + promise.then(result => result); + // $ExpectType IPromise + promise.then(result => abcObject); + // $ExpectType IPromise + promise.then(result => abcObjectPromise); + // $ExpectType IPromise + promise.then(result => result, any => any); + // $ExpectType IPromise + promise.then(result => result, any => Math.random()); + // $ExpectType IPromise + promise.then(result => result, any => any, any => any); + // $ExpectType IPromise + promise.then(result => result, any => Math.random(), any => any); + // $ExpectType IPromise + promise.then(result => result, any => rejectedPromise, any => any); - assertPromiseType | TResult>(promise.then((result) => anyOf2(reject, result))); - assertPromiseType(promise.then((result) => anyOf3(result, tresultPromise, reject))); - assertPromiseType(promise.then( - (result) => anyOf3(reject, result, tresultPromise), - (reason) => anyOf3(reject, tresult, tresultPromise) - )); + // $ExpectType IPromise + promise.then(result => anyOf2(rejectedPromise, result)); + // $ExpectType IPromise + promise.then(result => anyOf3(result, abcObjectPromise, rejectedPromise)); + // $ExpectType IPromise + promise.then( + result => anyOf3(rejectedPromise, result, abcObjectPromise), + reason => anyOf3(rejectedPromise, abcObject, abcObjectPromise) + ); - assertPromiseType>(promise.then((result) => tresultHttpPromise)); + // $ExpectType IPromise> + promise.then(result => abcObjectHttpPromise); - assertPromiseType(promise.then((result) => result, (any) => tother)); - assertPromiseType | angular.IPromise | TOther | angular.IPromise>(promise.then( - (result) => anyOf3(reject, result, totherPromise), - (reason) => anyOf3(reject, tother, tresultPromise) - )); + // $ExpectType IPromise + promise.then(result => result, any => defObject); - assertPromiseType(promise.then( - (result) => anyOf3(tresultPromise, result, totherPromise) - )); + // These are broken and seemingly can't be made to work + // with the current limitations of TypeScript. - assertPromiseType(promise.then((result) => result, (any) => tother, (any) => any)); - assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise)); - assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise, (any) => any)); - assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise)); - assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise, (any) => any)); + // xExpectType IPromise + // promise.then(result => anyOf2(result, defObjectPromise)); + // xExpectType IPromise + // promise.then(result => anyOf3(rejectedPromise, result, defObjectPromise)); + // xExpectType IPromise + // const a4 = promise.then( + // result => anyOf3(rejectedPromise, result, defObjectPromise), + // reason => anyOf3(rejectedPromise, defObject, abcObjectPromise) + // ); - assertPromiseType(promise.then((result) => tother)); - assertPromiseType(promise.then((result) => tother, (any) => any)); - assertPromiseType(promise.then((result) => tother, (any) => any, (any) => any)); - assertPromiseType(promise.then((result) => totherPromise)); - assertPromiseType(promise.then((result) => totherPromise, (any) => any)); - assertPromiseType(promise.then((result) => totherPromise, (any) => any, (any) => any)); - assertPromiseType>(promise.then((result) => totherHttpPromise)); - assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any)); - assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any, (any) => any)); + // $ExpectType IPromise + promise.then(result => + anyOf3(abcObjectPromise, result, defObjectPromise) + ); - assertPromiseType(promise.then((result) => tresult, (any) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); + // $ExpectType IPromise + promise.then(result => result, any => defObject, any => any); + // $ExpectType IPromise + promise.then(result => abcObjectPromise, any => defObjectPromise); + // $ExpectType IPromise + promise.then(result => abcObjectPromise, any => defObjectPromise, any => any); + // $ExpectType IPromise | IHttpResponse> + promise.then(result => abcObjectHttpPromise, any => defObjectHttpPromise); + // $ExpectType IPromise | IHttpResponse> + promise.then(result => abcObjectHttpPromise, any => defObjectHttpPromise, any => any); + + // $ExpectType IPromise + promise.then(result => defObject); + // $ExpectType IPromise + promise.then(result => defObject, any => any); + // $ExpectType IPromise + promise.then(result => defObject, any => any, any => any); + // $ExpectType IPromise + promise.then(result => defObjectPromise); + // $ExpectType IPromise + promise.then(result => defObjectPromise, any => any); + // $ExpectType IPromise + promise.then(result => defObjectPromise, any => any, any => any); + // $ExpectType IPromise> + promise.then(result => defObjectHttpPromise); + // $ExpectType IPromise + promise.then(result => defObjectHttpPromise, any => any); + // $ExpectType IPromise + promise.then(result => defObjectHttpPromise, any => any, any => any); + + // $ExpectType IPromise + promise + .then(result => abcObject, any => defObject) + .then(ambiguous => (isAbcObject(ambiguous) ? ambiguous.c : ambiguous.f)); + + // promise.then + $q.reject: + + // $ExpectType IPromise + $q.resolve(true).then(result => Math.random() > 0.5 ? Math.random() : $q.reject()); + // $ExpectType IPromise + $q.resolve(true).then(result => Math.random() > 0.5 ? Math.random() : $q.reject('a')); + // $ExpectType IPromise + $q.resolve().then(() => $q.reject('a')); + // $ExpectType IPromise + $q.resolve().then(() => { + if (Math.random() > 0.5) $q.reject(); + }); // promise.catch - assertPromiseType(promise.catch((err) => err)); - assertPromiseType(promise.catch((err) => any)); - assertPromiseType(promise.catch((err) => tresult)); - assertPromiseType>(promise.catch((err) => anyOf2(tresult, reject))); - assertPromiseType(promise.catch((err) => anyOf3(tresult, tresultPromise, reject))); - assertPromiseType(promise.catch((err) => tresultPromise)); - assertPromiseType>(promise.catch((err) => tresultHttpPromise)); - assertPromiseType(promise.catch((err) => tother)); - assertPromiseType(promise.catch((err) => totherPromise)); - assertPromiseType>(promise.catch((err) => totherHttpPromise)); + // $ExpectType IPromise + promise.catch(err => err); + // $ExpectType IPromise + promise.catch(err => anything); + // $ExpectType IPromise + promise.catch(err => abcObject); + // $ExpectType IPromise + promise.catch(err => anyOf2(abcObject, rejectedPromise)); + // $ExpectType IPromise + promise.catch(err => anyOf3(abcObject, abcObjectPromise, rejectedPromise)); + // $ExpectType IPromise + promise.catch(err => abcObjectPromise); + // $ExpectType IPromise> + promise.catch(err => abcObjectHttpPromise); + // $ExpectType IPromise + promise.catch(err => defObject); + // $ExpectType IPromise + promise.catch(err => defObjectPromise); + // $ExpectType IPromise> + promise.catch(err => defObjectHttpPromise); - assertPromiseType(promise.catch((err) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); + // $ExpectType IPromise + promise + .catch(err => defObject) + .then( + ambiguous => (isAbcObject(ambiguous) ? ambiguous.c : ambiguous.f) + ); // promise.finally - assertPromiseType(promise.finally(() => any)); - assertPromiseType(promise.finally(() => tresult)); - assertPromiseType(promise.finally(() => tother)); + // $ExpectType IPromise + promise.finally(() => anything); + // $ExpectType IPromise + promise.finally(() => abcObject); + // $ExpectType IPromise + promise.finally(() => defObject); } function test_angular_forEach() { @@ -632,6 +710,24 @@ function test_angular_forEach() { this.push(`${key}: ${value}`); }, log); // expect(log).toEqual(['name: misko', 'gender: male']); + // $ExpectType NodeListOf + angular.forEach(document.getElementsByTagName('img'), (value, key, obj) => { + value; // $ExpectType HTMLImageElement + key; // $ExpectType number + obj; // $ExpectType NodeListOf + }); + // $ExpectType number[] + angular.forEach([1, 2, 3], (value, key, obj) => { + value; // $ExpectType number + key; // $ExpectType number + obj; // $ExpectType number[] + }); + // $ExpectType string + angular.forEach('123', (value, key, obj) => { + value; // $ExpectType string + key; // $ExpectType number + obj; // $ExpectType string + }); } // angular.element() tests @@ -648,12 +744,12 @@ let elementReadyFn = angular.element(() => { // $timeout signature tests namespace TestTimeout { - interface TResult { + interface AbcObject { a: number; b: string; c: boolean; } - const fnTResult: (...args: any[]) => TResult = null; + const abcObjectFn: (...args: any[]) => AbcObject = null; const promiseAny: angular.IPromise = null; const $timeout: angular.ITimeoutService = null; @@ -668,13 +764,13 @@ namespace TestTimeout { result = $timeout(1, true); } { - let result: angular.IPromise; - result = $timeout(fnTResult); - result = $timeout(fnTResult, 1); - result = $timeout(fnTResult, 1, true); - result = $timeout(fnTResult, 1, true, 1); - result = $timeout(fnTResult, 1, true, 1, ''); - result = $timeout(fnTResult, 1, true, 1, '', true); + let result: angular.IPromise; + result = $timeout(abcObjectFn); + result = $timeout(abcObjectFn, 1); + result = $timeout(abcObjectFn, 1, true); + result = $timeout(abcObjectFn, 1, true, 1); + result = $timeout(abcObjectFn, 1, true, 1, ''); + result = $timeout(abcObjectFn, 1, true, 1, '', true); } // $timeout.cancel @@ -1187,6 +1283,24 @@ function NgModelControllerTyping() { }; } +// FormController +angular.module('app').directive('formDebugChecker', () => { + return { + require: '^^form', + link: (scope, el, attrs, ctrl) => { + const form = ctrl as angular.IFormController; + el.on('click', () => { + const report = [] as string[]; + angular.forEach(form.$error, (controls, validationErrorKey) => { + const names = controls.map(control => control.$name); + report.push(`${validationErrorKey}: ${controls.length} control(s) (${names.join(', ')})`); + }); + console.log(`This form has ${report.length} error(s).\n${report.join('\n')}`); + }); + } + }; +}); + let $filter: angular.IFilterService; function testFilter() { diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 5d8b6315b0..4c896eb430 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -100,7 +100,11 @@ declare namespace angular { * @param iterator Iterator function. * @param context Object to become context (this) for the iterator function. */ - forEach(obj: T[], iterator: (value: T, key: number, obj: T[]) => void, context?: any): T[]; + forEach = T[]>( + obj: U, + iterator: (value: U[number], key: number, obj: U) => void, + context?: any + ): U; /** * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. * @@ -357,9 +361,9 @@ declare namespace angular { $valid: boolean; $invalid: boolean; $submitted: boolean; - $error: any; - $name: string; - $pending: any; + $error: { [validationErrorKey: string]: Array }; + $name?: string; + $pending?: { [validationErrorKey: string]: Array }; $addControl(control: INgModelController | IFormController): void; $removeControl(control: INgModelController | IFormController): void; $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController | IFormController): void; @@ -388,6 +392,7 @@ declare namespace angular { $setUntouched(): void; $rollbackViewValue(): void; $commitViewValue(): void; + $processModelValue(): void; $isEmpty(value: any): boolean; $overrideModelOptions(options: INgModelOptions): void; @@ -398,8 +403,8 @@ declare namespace angular { $parsers: IModelParser[]; $formatters: IModelFormatter[]; $viewChangeListeners: IModelViewChangeListener[]; - $error: any; - $name: string; + $error: { [validationErrorKey: string]: boolean }; + $name?: string; $touched: boolean; $untouched: boolean; @@ -407,7 +412,7 @@ declare namespace angular { $validators: IModelValidators; $asyncValidators: IAsyncModelValidators; - $pending: any; + $pending?: { [validationErrorKey: string]: boolean }; $pristine: boolean; $dirty: boolean; $valid: boolean; @@ -1102,28 +1107,43 @@ declare namespace angular { interface IPromise { /** - * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. - * The successCallBack may return IPromise for when a $q.reject() needs to be returned - * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. + * Regardless of when the promise was or will be resolved or rejected, then calls one of + * the success or error callbacks asynchronously as soon as the result is available. The + * callbacks are called with a single argument: the result or rejection reason. + * Additionally, the notify callback may be called zero or more times to provide a + * progress indication, before the promise is resolved or rejected. + * The `successCallBack` may return `IPromise` for when a `$q.reject()` needs to + * be returned. + * This method returns a new promise which is resolved or rejected via the return value + * of the `successCallback`, `errorCallback`. It also notifies via the return value of + * the `notifyCallback` method. The promise can not be resolved or rejected from the + * `notifyCallback` method. */ - then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: null, notifyCallback?: (state: any) => any): IPromise; - then(successCallback: (promiseValue: T) => IPromise|TResult2, errorCallback?: null, notifyCallback?: (state: any) => any): IPromise; - - then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback: (reason: any) => IPromise|TCatch, notifyCallback?: (state: any) => any): IPromise; - then(successCallback: (promiseValue: T) => IPromise|TResult2, errorCallback: (reason: any) => IPromise|TCatch2, notifyCallback?: (state: any) => any): IPromise; + then( + successCallback?: + | ((value: T) => IPromise | IPromise | TResult1) + | null, + errorCallback?: + | ((reason: any) => IPromise | IPromise | TResult2) + | null, + notifyCallback?: (state: any) => any + ): IPromise; /** * Shorthand for promise.then(null, errorCallback) */ - catch(onRejected: (reason: any) => IPromise|TCatch): IPromise; - catch(onRejected: (reason: any) => IPromise|TCatch2): IPromise; + catch( + onRejected?: + | ((reason: any) => IPromise | IPromise | TResult) + | null + ): IPromise; /** * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. * * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. */ - finally(finallyCallback: () => any): IPromise; + finally(finallyCallback: () => void): IPromise; } interface IDeferred { diff --git a/types/angular/tsconfig.json b/types/angular/tsconfig.json index 5ce810f938..46eeb69c7a 100644 --- a/types/angular/tsconfig.json +++ b/types/angular/tsconfig.json @@ -25,4 +25,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} +} \ No newline at end of file diff --git a/types/ansi-colors/tsconfig.json b/types/ansi-colors/tsconfig.json index 8a0f980cbc..ebd56021f9 100644 --- a/types/ansi-colors/tsconfig.json +++ b/types/ansi-colors/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "ansi-colors-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/ansi-regex/tsconfig.json b/types/ansi-regex/tsconfig.json index cf1ac84a5c..4d0c1ff787 100644 --- a/types/ansi-regex/tsconfig.json +++ b/types/ansi-regex/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +20,4 @@ "index.d.ts", "ansi-regex-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/anybar/anybar-tests.ts b/types/anybar/anybar-tests.ts index 6b4ea8ef89..dbc7a5edd6 100644 --- a/types/anybar/anybar-tests.ts +++ b/types/anybar/anybar-tests.ts @@ -1,5 +1,5 @@ -import * as anybar from 'anybar' +import anybar = require('anybar'); -anybar('red', { port: 123 }) +anybar('red', { port: 123 }); -anybar('green') +anybar('green'); diff --git a/types/anybar/index.d.ts b/types/anybar/index.d.ts index 4972f29756..a9a2452b06 100644 --- a/types/anybar/index.d.ts +++ b/types/anybar/index.d.ts @@ -1,10 +1,9 @@ -// Type definitions for anybar 2.0.1 +// Type definitions for anybar 2.0 // Project: https://github.com/sindresorhus/anybar // Definitions by: Chris Khoo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -declare namespace anybar { } +declare function anybar(color: string, options?: { port: number }): void; -declare function anybar(color: string, options?: { port: number }): void - -export = anybar +export = anybar; diff --git a/types/anybar/tsconfig.json b/types/anybar/tsconfig.json index 1dd62548e6..2f04506e12 100644 --- a/types/anybar/tsconfig.json +++ b/types/anybar/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "anybar-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/anybar/tslint.json b/types/anybar/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/anybar/tslint.json +++ b/types/anybar/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/apex.js/apex.js-tests.ts b/types/apex.js/apex.js-tests.ts index 0595ef43ea..f5d96e2c54 100644 --- a/types/apex.js/apex.js-tests.ts +++ b/types/apex.js/apex.js-tests.ts @@ -1,4 +1,4 @@ -import * as λ from "apex.js"; +import λ = require("apex.js"); const handler = λ((event, context) => { console.log("Event: " + JSON.stringify(event)); diff --git a/types/apex.js/index.d.ts b/types/apex.js/index.d.ts index 0998ce794c..20e05d2a5e 100644 --- a/types/apex.js/index.d.ts +++ b/types/apex.js/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/apex/node-apex // Definitions by: Yoriki Yamaguchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// diff --git a/types/aphrodite/index.d.ts b/types/aphrodite/index.d.ts index 0e04b07af7..00d1908d9f 100644 --- a/types/aphrodite/index.d.ts +++ b/types/aphrodite/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Khan/aphrodite // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import * as React from "react"; diff --git a/types/api-error-handler/api-error-handler-tests.ts b/types/api-error-handler/api-error-handler-tests.ts index 67afbb0fce..aa72342d75 100644 --- a/types/api-error-handler/api-error-handler-tests.ts +++ b/types/api-error-handler/api-error-handler-tests.ts @@ -1,4 +1,4 @@ -import * as errorHandler from 'api-error-handler'; +import errorHandler = require('api-error-handler'); import * as express from 'express'; var api = express.Router(); diff --git a/types/app-root-dir/app-root-dir-tests.ts b/types/app-root-dir/app-root-dir-tests.ts new file mode 100644 index 0000000000..bff8969927 --- /dev/null +++ b/types/app-root-dir/app-root-dir-tests.ts @@ -0,0 +1,6 @@ +import * as rootDir from 'app-root-dir'; + +let appRootPath: string; + +rootDir.set('__dirname'); +appRootPath = rootDir.get(); diff --git a/types/app-root-dir/index.d.ts b/types/app-root-dir/index.d.ts new file mode 100644 index 0000000000..8b0bf5bc6a --- /dev/null +++ b/types/app-root-dir/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for app-root-dir 0.1 +// Project: https://github.com/philidem/node-app-root-dir +// Definitions by: shaochenyang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface AppRootDir { + // Get the application's root directory + get(): string; + /** + * Set the application's root directory + * this will set a global so that no matter + * how many instances of app-root-dir module are installed, + * they will all return the same directory + */ + set(dirname: string): void; +} + +declare const AppRootDir: AppRootDir; + +export = AppRootDir; diff --git a/types/app-root-dir/tsconfig.json b/types/app-root-dir/tsconfig.json new file mode 100644 index 0000000000..f378c094db --- /dev/null +++ b/types/app-root-dir/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "app-root-dir-tests.ts" + ] +} diff --git a/types/app-root-dir/tslint.json b/types/app-root-dir/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/app-root-dir/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/appdmg/tsconfig.json b/types/appdmg/tsconfig.json index f4ca0f95c5..452b9a4af3 100644 --- a/types/appdmg/tsconfig.json +++ b/types/appdmg/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "appdmg-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/aqb/aqb-tests.ts b/types/aqb/aqb-tests.ts new file mode 100644 index 0000000000..5e186126fe --- /dev/null +++ b/types/aqb/aqb-tests.ts @@ -0,0 +1,151 @@ +import QB = require("aqb"); + +/* + * Most of these tests are taken directly from the examples + * in the aqbjs Github documentation. + * + * https://github.com/arangodb/aqbjs + */ + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#auto-casting-raw-data + */ +const doc = { + aString: "hello", + aDate: new Date(), + aNumber: 23, + anArray: [1, 2, 3, "potato"] +}; + +QB(doc); +QB.for('x').in('1..5').return('x'); +QB.insert(QB(doc)).into('my_collection'); + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#aql-types + */ +QB.bool(true); +QB.num("12"); +QB.int("1"); +QB.str(23); +QB.list([ 1 , 2 , 3 , 4 , 5]); +QB.obj({'some.name': 'value'}); +QB.ref("users"); + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#aql-expressions + */ +QB.range(1 , 5); +QB.get("property"); +QB.ref("user").get("property"); +QB.expr(QB.for('x').in('1..5').return('x').toAQL()); + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#aql-operations + */ +QB.and("a", "b"); +QB.ref("a").and("b"); +QB.or("a" , "b"); +QB.ref("a").or("b"); +QB.add("a" , "b"); +QB.ref("a").add("b"); +QB.plus("a" , "b"); +QB.ref("a").plus("b"); +QB.sub("a" , "b"); +QB.ref("a").sub("b"); +QB.minus("a" , "b"); +QB.ref("a").minus("b"); +QB.mul("a" , "b"); +QB.ref("a").mul("b"); +QB.times("a" , "b"); +QB.ref("a").times("b"); +QB.div("a" , "b"); +QB.ref("a").div("b"); +QB.mod("a", "b"); +QB.ref("a").mod("b"); +QB.eq("a" , "b"); +QB.ref("a").eq("b"); +QB.neq("a", "b"); +QB.ref("a").neq("b"); +QB.gt("a" , "b"); +QB.ref("a").gt("b"); +QB.gte("a" , "b"); +QB.ref("a").gte("b"); +QB.lt("a" , "b"); +QB.ref("a").lt("b"); +QB.lte("a" , "b"); +QB.ref("a").lte("b"); +QB.in("a" , "b"); +QB.ref("a").in("b"); +QB.not("a"); +QB.ref("a").not(); +QB.notIn("a" , "b"); +QB.ref("a").notIn("b"); +QB.neg("a"); +QB.ref("a").neg(); +QB.if("x" , "y" , "z"); +QB.ref("x").then("y").else("z"); +QB.fn('MY::USER::FUNC')(1, 2, 3); +QB.fn('hello')(); + +/* + * section aqb.js + * https://github.com/arangodb/aqbjs#aql-statements + */ +QB.for('doc').in('my_collection'); +QB.for('doc').in('my_collection').let('foo' , 23); +QB.for('doc').in('my_collection').let('foo' , 23); +// QB.for('doc').in('my_collection').let({a: 1, b: 2, c: 3}); +QB.for('doc').in('my_collection').return('x'); +QB.for('doc').in('my_collection').return({x: 'x'}); +QB.for('doc').in('my_collection').returnDistinct('x'); +QB.for('doc').in('my_collection').filter(QB.eq('a', 'b')); +QB.for('doc').in('my_collection').collectWithCountInto('x'); +QB.for('doc').in('my_collection').collect('x', 'y'); +// QB.for('doc').in('my_collection').collect({x: 'a', y: 'b'}); +QB.for('doc').in('my_collection').collect('x' , 'y').withCountInto('z'); +QB.for('doc').in('my_collection').collect('x' , 'y').into('z').keep('a' , 'b'); +QB.for('doc').in('my_collection').collect('x' , 'y').into('z' , 'Z'); +QB.for('doc').in('my_collection').collect('x' , 'y').into('z'); +QB.for('doc').in('my_collection').collect('x' , 'y').into('z').options('opts'); +QB.for('doc').in('my_collection').collect('x' , 'y').options('opts'); +QB.for('doc').in('my_collection').collect('x' , 'y').keep('a' , 'b'); +QB.for('doc').in('my_collection').collect('x' , 'y').sort('x', 'DESC', 'y', 'ASC'); +QB.for('doc').in('my_collection').collect('x' , 'y').limit(20); +QB.for('doc').in('my_collection').collect('x' , 'y').limit(20 , 20); +QB.for('doc').in('my_collection').remove('x'); +QB.for('doc').in('my_collection').remove('x').in('y'); +QB.for('doc').in('my_collection').remove('x').in('y').returnOld('a'); +QB.for('doc').in('my_collection').remove('x').in('y').options('opts'); +QB.upsert('x').insert('y').replace('z').in('c'); +QB.upsert('x').insert('y').replace('z').in('c').options('opts'); +QB.upsert('x').insert('y').update('z').in('c'); +QB.upsert('x').insert('y').update('z').in('c').options('opts'); +QB.insert('x').into('y'); +QB.insert('x').into('y').options('opts'); +QB.insert('x').into('y').returnNew('z'); +QB.update('x').in('y'); +QB.update('x').into('y'); +QB.update('x').with('y').in('z'); +QB.update('x').with('y').into('z'); +QB.update('x').with('y').into('z').options('opts'); +QB.update('x').in('y').options('opts'); +QB.update('x').with('y').into('z').returnNew('v'); +QB.update('x').with('y').into('z').returnOld('v'); +QB.update('x').in('y').options('opts').returnNew('v'); +QB.update('x').in('y').options('opts').returnOld('v'); + +QB.replace('x').in('y'); +QB.replace('x').into('y'); +QB.replace('x').with('y').in('z'); +QB.replace('x').with('y').into('z'); +QB.replace('x').with('y').into('z').options('opts'); +QB.replace('x').in('y').options('opts'); +QB.replace('x').with('y').into('z').returnNew('v'); +QB.replace('x').with('y').into('z').returnOld('v'); +QB.replace('x').in('y').options('opts').returnNew('v'); +QB.replace('x').in('y').options('opts').returnOld('v'); diff --git a/types/aqb/index.d.ts b/types/aqb/index.d.ts new file mode 100644 index 0000000000..eb529e9c97 --- /dev/null +++ b/types/aqb/index.d.ts @@ -0,0 +1,1105 @@ +// Type definitions for aqbjs 2.1 +// Project: https://github.com/arangodb/aqbjs +// Definitions by: Athenkosi Mase +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +interface AqlError extends Error { + new(message: string): Error; + name: string; +} +interface Operation extends Expression { + new(): Expression; +} +interface BinaryOperation extends Operation { + new(operator: string, value1: any, value2: any): Operation; + toAQL(): string; + _operator: string; +} +interface UnaryOperation extends Expression { + new(operator: string, value: any): Expression; + toAQL(): string; + _operator: string; +} +interface SimpleReference extends Expression { + new(value: string): Expression; + toAQL(): string; + re: RegExp; + _value: string; +} +interface RawExpression extends Expression { + new(value: any): Expression; + toAQL(): string; +} +interface BooleanLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: boolean; +} +interface NumberLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; + re: RegExp; +} +interface IntegerLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: number; +} +interface StringLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; +} +interface ListLiteral extends Expression { + new(...value: any[]): Expression; + toAQL(): string; +} +interface ObjectLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: object; +} +interface NAryOperation extends Operation { + new(operator: string, values: any[]): Operation; + toAQL(): string; + _operator: string; + _values: Expression[]; +} +interface RangeExpression extends Expression { + new(start: any, end?: any): Expression; + toAQL(): string; + _start: number; + _end: number; + re: RegExp; +} +interface PropertyAccess extends Expression { + new(obj: any, keys: any[]): Expression; + toAQL(): string; + _obj: Expression; + _keys: Expression[]; +} +interface TernaryOperation extends Operation { + new(operator1: string, operator2: string, value1: Expression, value2: any, value3: any): Operation; + toAQL(): string; + _operator1: string; + _operator2: string; +} +interface NullLiteral extends Expression { + new(value: any): Expression; + toAQL(): string; +} +interface Keyword extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: string; + re: RegExp; +} +interface Identifier extends Expression { + new(value: any): Expression; + toAQL(): string; + _value: string; +} +interface FunctionCall extends Expression { + new(functionName: string, ...args: any[]): Expression; + toAQL(): string; + _re: RegExp; + _functionName: string; + _args: any[]; +} +interface ForExpression extends PartialStatement { + new(prev: PartialStatement, varname: any, expr: any): PartialStatement; + toAQL(): string; + _varname: Identifier; +} +interface FilterExpression extends PartialStatement { + new(prev: PartialStatement, expr: any): PartialStatement; + toAQL(): string; +} +interface Definitions { + new(...dfns: any[]): any; + toAQL(): string; + _dfns: any[]; +} +interface LetExpression extends PartialStatement { + new(prev: PartialStatement, ...dfns: any[]): PartialStatement; + toAQL(): string; + _prev: PartialStatement; + _dfns: Definitions; +} +interface CollectExpression extends PartialStatement { + new(prev: PartialStatement, dfns: any[], varname: any, intoExpr: any, keepNames: any[], options: any): PartialStatement; + toAQL(): string; + into(...newVarname: any[]): CollectExpression; + keep(...x: any[]): any; + _keep: Identifier[]; + options(newOpts: any): any; + _options: ObjectLiteral; + withCountInto(newVarname: any): CollectWithCountIntoExpression; +} +interface CollectWithCountIntoExpression extends PartialStatement { + new(prev: PartialStatement, dfns: any[], varname: any, options: any): PartialStatement; + toAQL(): string; + options(newOpts: any): any; +} +interface SortExpression extends PartialStatement { + new(prev: PartialStatement, ...args: any[]): PartialStatement; + toAQL(): string; + keywords: string[]; + _args: Keyword[]; +} +interface LimitExpression extends PartialStatement { + new(prev: PartialStatement, offset: any, count?: any): PartialStatement; + toAQL(): string; +} +interface ReturnExpression extends Expression { + new(prev: LetExpression, value: any, distinct: boolean): Expression; + toAQL(): string; + _prev: LetExpression; + _distinct: boolean; +} +interface RemoveExpression extends PartialStatement { + new(prev: PartialStatement, expr: any, collection: any, options: any): PartialStatement; + returnOld(x: any): ReturnExpression; + toAQL(): string; + options(newOpts: any): RemoveExpression; +} +interface UpsertExpression extends PartialStatement { + new(prev: PartialStatement, upsertExpr: any, insertExpr: any, replace: boolean, updateOrReplaceExpr: any, collection: any, options: any): PartialStatement; + returnNew(x: any): ReturnExpression; + returnOld(x: any): ReturnExpression; + toAQL(): string; + _updateOrReplace: string; + options(newOpts: any): UpsertExpression; +} +interface InsertExpression extends PartialStatement { + new(prev: PartialStatement, expr: any, collection: any, options: any): PartialStatement; + returnNew(x: any): ReturnExpression; + toAQL(): string; + options(newOpts: any): InsertExpression; +} +interface UpdateExpression extends PartialStatement { + new(prev: PartialStatement, expr: any, withExpr: any, collection: any, options: any): PartialStatement; + returnNew(x: any): ReturnExpression; + returnOld(x: any): ReturnExpression; + toAQL(): string; + options(newOpts: any): UpdateExpression; +} +interface ReplaceExpression extends PartialStatement { + new(prev: PartialStatement, expr: any, withExpr: any, collection: any, options: any): PartialStatement; + returnNew(x: any): ReturnExpression; + returnOld(x: any): ReturnExpression; + toAQL(): string; + options(newOpts: any): ReplaceExpression; +} +interface Expression extends PartialStatement { + /** + * Equality + * + * Creates an equality comparison from the given values. + * + * qb.eq(a, b): (a == b) + * OR: + * qbValue.eq(b): (a == b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').eq('y'): (x == y) + * + * + */ + eq(x: any, y?: any): BinaryOperation; + /** + * Inequality + * + * Creates an inequality comparison from the given values. + * + * qb.neq(a, b): (a != b) + * OR: + * qbValue.neq(b): (a != b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').neq('y'): (x != y) + * + */ + neq(x: any, y?: any): BinaryOperation; + /** + * Greater Than + * + * Creates a greater-than comparison from the given values. + * + * qb.gt(a, b): (a > b) + * OR + * qbValue.gt(b): (a > b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').gt('y'): (x > y) + * + * + */ + gt(x: any, y?: any): BinaryOperation; + /** + * Greater Than Or Equal To + * + * Creates a greater-than-or-equal-to comparison from the given values. + * + * qb.gte(a, b): (a >= b) + * OR + * qbValue.gte(b): (a >= b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').gte('y'): (x >= y) + * + * + */ + gte(x: any, y?: any): BinaryOperation; + /** + * Less Than + * + * Creates a less-than comparison from the given values. + * + * qb.lt(a, b): (a < b) + * OR + * qbValue.lt(b): (a < b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').lt('y'): (x < y) + * + */ + lt(x: any, y?: any): BinaryOperation; + /** + * Less Than Or Equal To + * + * Creates a less-than-or-equal-to comparison from the given values. + * + * qb.lte(a, b): (a <= b) + * OR + * qbValue.lte(b): (a <= b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').lte('y'): (x <= y) + * + */ + lte(x: any, y?: any): BinaryOperation; + /** + * Contains + * + * Creates an "in" comparison from the given values. + * + * qb.in(a, b): (a in b) + * OR: + * qbValue.in(b): (a in b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * qb.ref('x').in('y'): (x in y) + */ + in(...x: any[]): BinaryOperation; + /** + * Negation + * + * Creates a negation from the given value. + * + * qb.not(a) => !(a) + * OR: + * qbValue.not() => !(a) + * + * If the value is not already an value, it will be converted automatically. + * + * Examples + * + * qb.not('x') => !(x) + */ + not(x?: any): UnaryOperation; + /** + * Negative Value + * + * Creates a negative value expression from the given value. + * + * qb.neg(a) => -(a) + * OR: + * qbValue.neg() => -(a) + * + * If the value is not already an AQL value, it will be converted automatically. + * + * Examples + * + * qb.neg('x') => -(x) + */ + neg(x?: any): UnaryOperation; + /** + * Negated Contains + * + * Creates a "not in" comparison from the given values. + * + * qb.notIn(a, b): (a not in b) + * OR: + * qbValue.notIn(b): (a not in b) + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * + * qb.ref('x').notIn('y'): (x not in y) + */ + notIn(...x: any[]): BinaryOperation; + /** + * Boolean And + * + * Creates an "and" operation from the given values. + * + * qb.and(a, b) =>(a && b) + * OR: + * aqlValue.and(b) =>(a && b) + * + * If the values are not already AQL values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Examples + * + * qb.ref('x').and('y') =>(x && y) + */ + and(...x: any[]): NAryOperation; + /** + * Boolean Or + * + * Creates an "or" operation from the given values. + * + * qb.or(a, b): (a || b) + * OR: + * Value.or(b): (a || b) + * + * If the values are not already values, they will be converted automatically. + * + * This declare function can take any number of arguments. + */ + or(...x: any[]): NAryOperation; + /** + * Addition + * + * Creates an addition operation from the given values. + * + * qb.add(a, b): (a + b) + * OR: + * Value.add(b): (a + b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Alias: qb.plus(a, b) + * + * Examples + * + * qb.ref('x').plus('y'): (x + y) + */ + add(...x: any[]): NAryOperation; + plus(...x: any[]): NAryOperation; + /** + * Subtraction + * + * Creates a subtraction operation from the given values. + * + * qb.sub(a, b): (a - b) + * OR: + * Value.sub(b): (a - b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Alias: qb.minus(a, b) + * + * Examples + * + * qb.ref('x').minus('y'): (x - y) + */ + sub(...x: any[]): NAryOperation; + minus(...x: any[]): NAryOperation; + /** + * Multiplication + * + * Creates a multiplication operation from the given values. + * + * qb.mul(a, b): (a * b) + * OR: + * Value.mul(b): (a * b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Alias: qb.times(a, b) + * + * Examples + * + * qb.ref('x').times('y'): (x * y) + */ + mul(...x: any[]): NAryOperation; + times(...x: any[]): NAryOperation; + /** + * Division + * + * Creates a division operation from the given values. + * + * qb.div(a, b): (a / b) + * OR: + * Value.div(b): (a / b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Examples + * qb.ref('x').div('y'): (x / y) + */ + div(...x: any[]): NAryOperation; + /** + * Modulus + * + * Creates a modulus operation from the given values. + * + * qb.mod(a, b): (a % b) + * OR: + * Value.mod(b): (a % b) + * + * If the values are not already values, they will be converted automatically. + * This declare function can take any number of arguments. + * + * Examples + * qb.ref('x').mod('y'): (x % y) + */ + mod(...x: any[]): NAryOperation; + /** + * Range + * + * Creates a range expression from the given values. + * + * qb.range(value1, value2): value1..value2 + * + * OR: + * + * Value.range(value2): value1..value2 + * + * If the values are not already values, they will be converted automatically. + * Alias: qb.to(value1, value2) + * + * Examples + * + * qb(2).to(5): 2..5 + * + */ + range(...value: number[]): RangeExpression; + /** + * Property Access + * + * Creates a property access expression from the given values. + * + * qb.get(obj, key): obj[key] + * OR: + * Obj.get(key): obj[key] + * + * If the values are not already values, they will be converted automatically. + * + * Examples + * qb.ref('x').get('y'): x[y]` + * + */ + get(value: any): PropertyAccess; + /** + * Ternary(if / else) + * + * Creates a ternary expression from the given values. + * + * qb.if(condition, thenDo, elseDo): (condition ? thenDo: elseDo) + * OR: + * qbValue.then(thenDo).else(elseDo): (condition ? thenDo: elseDo) + * + * If the values are not already values, they will be converted automatically. + * + * Alias: qbValue.then(thenDo).otherwise(elseDo) + * + * Examples + * qb.ref('x').then('y').else('z'): (x ? y: z) + * + */ + then(value: any): ThenRet; +} +interface ThenRet { + else(y: any): TernaryOperation; + else_: TernaryOperation; + otherwise(y: any): TernaryOperation; +} +interface ForRet { + in(expr: any): ForExpression; + in_: ForRet["in"]; +} +/** + * PartialStatement + * + * In addition to the methods documented above, the query builder provides all methods of PartialStatement objects. + * Statement objects have a method toAQL() which returns their representation as a JavaScript string. + * + * Examples + * + * qb.for('doc').in('my_collection').return('doc._key').toAQL() + * // => FOR doc IN my_collection RETURN doc._key + */ +interface PartialStatement { + /** + * FOR expression IN collection + * + * PartialStatement::for(expression).in(collection): PartialStatement + * + * Examples + * + * _.for('doc').in('my_collection'): FOR doc IN my_collection + * + */ + for(varname: any): ForRet; + /** + * FILTER expression + * + * PartialStatement::filter(expression): PartialStatement + * + * Examples + * + * _.filter(qb.eq('a', 'b')): FILTER a == b + * + */ + filter(varname: any): FilterExpression; + /** + * LET varname = expression + * + * PartialStatement::let(varname, expression): PartialStatement + * + * Examples + * + * _.let('foo', 23): LET foo = 23 + * + * LET var1 = expr1, var2 = expr2, …, varn = exprn + * + * PartialStatement::let(definitions): PartialStatement + * + */ + let(varname: {}, expr: any): LetExpression; + /** + * COLLECT + * + * COLLECT WITH COUNT INTO varname + * PartialStatement::collectWithCountInto(varname): CollectExpression + * + * Examples + * + * _.collectWithCountInto('x'): COLLECT WITH COUNT INTO x COLLECT varname = expression + * PartialStatement::collect(varname, expression): CollectExpression + * + * _.collect('x', 'y'): COLLECT x = y COLLECT var1 = expr1, var2 = expr2, …, varn = exprn + * PartialStatement::collect(definitions): CollectExpression + * + * _.collect({x: 'a', y: 'b'}): COLLECT x = a, y = b WITH COUNT INTO varname + * CollectExpression::withCountInto(varname): CollectExpression + * + * _.withCountInto('x'): WITH COUNT INTO x INTO varname + * CollectExpression::into(varname): CollectExpression + * + * _.into('z'): INTO z KEEP ...vars + * CollectExpression::keep(...vars): CollectExpression + * + * _.into('z').keep('a', 'b'): INTO z KEEP a, b INTO varname = expression + * CollectExpression::into(varname, expression): CollectExpression + * + * _.into('x', 'y'): INTO x = y OPTIONS options + * CollectExpression::options(options): CollectExpression + * + * _.options('opts'): OPTIONS opts + * + */ + collect(varname: any, expr: any): CollectExpression; + /** + * COLLECT + * + * COLLECT WITH COUNT INTO varname + * PartialStatement::collectWithCountInto(varname): CollectExpression + * + * Examples + * + * _.collectWithCountInto('x'): COLLECT WITH COUNT INTO x COLLECT varname = expression + * PartialStatement::collect(varname, expression): CollectExpression + * + * _.collect('x', 'y'): COLLECT x = y COLLECT var1 = expr1, var2 = expr2, …, varn = exprn + * PartialStatement::collect(definitions): CollectExpression + * + * _.collect({x: 'a', y: 'b'}): COLLECT x = a, y = b WITH COUNT INTO varname + * CollectExpression::withCountInto(varname): CollectExpression + * + * _.withCountInto('x'): WITH COUNT INTO x INTO varname + * CollectExpression::into(varname): CollectExpression + * + * _.into('z'): INTO z KEEP ...vars + * CollectExpression::keep(...vars): CollectExpression + * + * _.into('z').keep('a', 'b'): INTO z KEEP a, b INTO varname = expression + * CollectExpression::into(varname, expression): CollectExpression + * + * _.into('x', 'y'): INTO x = y OPTIONS options + * CollectExpression::options(options): CollectExpression + * + * _.options('opts'): OPTIONS opts + * + */ + collectWithCountInto(varname: any): CollectWithCountIntoExpression; + /** + * SORT ...args + * + * PartialStatement::sort(...args): PartialStatement + * + * Examples + * + * _.sort('x', 'DESC', 'y', 'ASC'): SORT x DESC, y ASC + * + */ + sort(...args: any[]): SortExpression; + /** + * LIMIT offset, count + * + * PartialStatement::limit([offset,] count): PartialStatement + * + * Examples + * + * _.limit(20): LIMIT 20 + * + * _.limit(20, 20): LIMIT 20, 20 + * + */ + limit(offset: any, count?: any): LimitExpression; + /** + * RETURN expression + * + * PartialStatement::return(expression): ReturnExpression + * + * Examples + * + * _.return('x'): RETURN x + * _.return({x: 'x'}): RETURN {x: x} + * + */ + return(x: any): ReturnExpression; + /** + * RETURN DISTINCT expression + * + * PartialStatement::returnDistinct(expression): ReturnExpression + * + * Examples + * + * _.returnDistinct('x'): RETURN DISTINCT x + * + */ + returnDistinct(x: any): ReturnExpression; + /** + * REMOVE + * + * REMOVE expression IN collection + * PartialStatement::remove(expression).in(collection): RemoveExpression + * + * Alias: remove(expression).into(collection) + * + * Examples + * + * _.remove('x').in('y'): REMOVE x IN y LET varname = OLD RETURN varname + * RemoveExpression::returnOld(varname): ReturnExpression + * + * _.returnOld('z'): LET z = OLD RETURN z OPTIONS options + * RemoveExpression::options(options): RemoveExpression + * + * _.options('opts'): OPTIONS opts + * + */ + remove(expr: any): RemoveRet; + /** + * UPSERT + * + * UPSERT expression1 INSERT expression2 REPLACE expression3 IN collection + * PartialStatement::upsert(expression1).insert(expression2).replace(expression3).in(collection): UpsertExpression + * + * Alias: ….into(collection) + * + * Examples + * + * _.upsert('x').insert('y').replace('z').in('c'): UPSERT x INSERT y REPLACE z IN c + * + * UPSERT expression1 INSERT expression2 UPDATE expression3 IN collection + * PartialStatement::upsert(expression1).insert(expression2).update(expression3).in(collection): UpsertExpression + * + * Alias: ….into(collection) + * + * _.upsert('x').insert('y').update('z').in('c'): UPSERT x INSERT y UPDATE z IN c OPTIONS options + * UpsertExpression::options(options): UpsertExpression + * + * _.options('opts'): OPTIONS opts + * + */ + upsert(expr: any): UpsertRet; + /** + * INSERT + * + * INSERT expression INTO collection + * PartialStatement::insert(expression).into(collection): InsertExpression + * + * Alias: insert(expression).in(collection) + * + * Examples + * + * _.insert('x').into('y'): INSERT x INTO y OPTIONS options + * InsertExpression::options(options): InsertExpression + * + * _.options('opts'): OPTIONS opts LET varname = NEW RETURN varname + * InsertExpression::returnNew(varname): ReturnExpression + * + * _.returnNew('z'): LET z = NEW RETURN z + * + */ + insert(expr: any): InsertRet; + /** + * UPDATE + * + * UPDATE expression IN collection + * PartialStatement::update(expression).in(collection): UpdateExpression + * + * Alias: update(expression).into(collection) + * + * Examples + * + * _.update('x').in('y'): UPDATE x IN y + * + * UPDATE expression1 WITH expression2 IN collection + * PartialStatement::update(expression1).with(expression2).in(collection): UpdateExpression + * + * Alias: update(expression1).with(expression2).into(collection) + * + * _.update('x').with('y').in('z'): UPDATE x WITH y IN z OPTIONS options + * UpdateExpression::options(options): UpdateExpression + * + * _.options('opts'): OPTIONS opts LET varname = NEW RETURN varname + * UpdateExpression::returnNew(varname): ReturnExpression + * + * _.returnNew('z'): LET z = NEW RETURN z LET varname = OLD RETURN varname + * UpdateExpression::returnOld(varname): ReturnExpression + * + * _.returnOld('z'): LET z = OLD RETURN z + * + */ + update(expr: any): UpdateRetWithRet; + /** + * REPLACE + * + * REPLACE expression IN collection + * PartialStatement::replace(expression).in(collection): ReplaceExpression + * + * Alias: replace(expression).into(collection) + * + * Examples + * + * _.replace('x').in('y'): REPLACE x IN y REPLACE expression1 WITH expression2 IN collection + * PartialStatement::replace(expression1).with(expression2).in(collection): ReplaceExpression + * + * Alias: replace(expression1).with(expression2).into(collection) + * + * _.replace('x').with('y').in('z'): REPLACE x WITH y IN z OPTIONS options + * ReplaceExpression::options(options): ReplaceExpression + * + * _.options('opts'): OPTIONS opts LET varname = NEW RETURN varname + * ReplaceExpression::returnOld(varname): ReturnExpression + * + * _.returnNew('z'): LET z = NEW RETURN z LET varname = OLD RETURN varname + * ReplaceExpression::returnNew(varname): ReturnExpression + * + * _.returnOld('z'): LET z = OLD RETURN z + * + */ + replace(expr: any): ReplaceRetWithRet; +} +interface RemoveRet { + into(collection: any): RemoveExpression; + in: RemoveRet["into"]; + in_: RemoveRet["into"]; +} +interface UpsertRet { + insert(insertExpr: any): UpsertRetInsertRet; +} +interface UpsertRetInsertRet { + update(updateOrReplaceExpr: any): UpsertRetInsertRetUpdateRet; + replace: UpsertRetInsertRet["update"]; +} +interface UpsertRetInsertRetUpdateRet { + into(inCollection: any): UpsertExpression; + in: UpsertRetInsertRetUpdateRet["into"]; + in_: UpsertRetInsertRetUpdateRet["into"]; +} +interface InsertRet { + into(collection: any): InsertExpression; + in: InsertRet["into"]; + in_: InsertRet["into"]; +} +interface UpdateRetWithRet { + into(collection: any): UpdateExpression; + in: UpdateRetWithRet["into"]; + in_: UpdateRetWithRet["into"]; +} +interface ReplaceRetWithRet { + into(collection: any): ReplaceExpression; + in: ReplaceRetWithRet["into"]; + in_: ReplaceRetWithRet["into"]; +} +interface RemoveRet { + into(collection: any): RemoveExpression; + in: RemoveRet["into"]; + in_: RemoveRet["into"]; +} +interface UpsertRet { + insert(insertExpr: any): UpsertRetInsertRet; +} +interface UpsertRetInsertRet { + update(updateOrReplaceExpr: any): UpsertRetInsertRetUpdateRet; + replace: UpsertRetInsertRet["update"]; +} +interface UpsertRetInsertRetUpdateRet { + into(inCollection: any): UpsertExpression; + in: UpsertRetInsertRetUpdateRet["into"]; + in_: UpsertRetInsertRetUpdateRet["into"]; +} +interface InsertRet { + into(collection: any): InsertExpression; + in: InsertRet["into"]; + in_: InsertRet["into"]; +} +interface UpdateRetWithRet { + into(collection: any): UpdateExpression; + with(collection: any): UpdateRetWithRet; + in: UpdateRetWithRet["into"]; + in_: UpdateRetWithRet["into"]; +} +interface ReplaceRetWithRet { + into(collection: any): ReplaceExpression; + with(collection: any): ReplaceRetWithRet; + in: ReplaceRetWithRet["into"]; + in_: ReplaceRetWithRet["into"]; +} +declare function toArray(self: Expression, ...args: any[]): any[]; +declare function isQuotedString(str: string): boolean; +declare function wrapAQL(expr: Keyword): string; +declare function isValidNumber(number: number): boolean; +declare function castNumber(number: any): NumberLiteral; +declare function castBoolean(bool: any): BooleanLiteral; +declare function castString(str: any): SimpleReference | Identifier | RangeExpression | StringLiteral | Expression | PartialStatement | NullLiteral; +declare function castObject(obj: any): ObjectLiteral | ListLiteral | Identifier; +declare function autoCastToken(token: any): Expression | PartialStatement | NullLiteral; +/** + * AQLfunctions + * + * If raw JavaScript values are passed to statements, they will be wrapped in a matching declare function automatically. + * JavaScript strings wrapped in quotation marks will be wrapped in strings, all other JavaScript strings will be wrapped as simple references(see ref) + * and throw an Error if they are not well-formed. + */ +interface AQLfunctions extends Expression { + /** + * Boolean + * + * Wraps the given value as an Boolean literal. + * + * qb.bool(value) + * + * If the value is truthy, it will be converted to the Boolean true, otherwise it will be converted to the Boolean false. + * If the value is already an Boolean, its own value will be wrapped instead. + * + */ + bool(value: any): BooleanLiteral; + /** + * Number + * + * Wraps the given value as an Number literal. + * + * qb.num(value) + * + * If the value is not a JavaScript Number, it will be converted first. + * If the value does not represent a finite number, an Error will be thrown. + * If the value is already an Number or Integer, its own value will be wrapped instead. + * + */ + num(value: any): NumberLiteral; + /** + * Integer + * + * Wraps the given value as an Integer literal. + * + * qb.int(value) + * + * If the value is not a JavaScript Number, it will be converted first. + * If the value does not represent a finite integer, an Error will be thrown. + * If the value is already an Number or Integer, its own value will be wrapped instead. + * + */ + int(value: any): IntegerLiteral; + /** + * String + * + * Wraps the given value as an String literal. + * + * qb.str(value) + * + * If the value is not a JavaScript String, it will be converted first. + * If the value is a quoted string, it will be treated as a string literal. + * If the value is an object with a toAQL method, the result of calling that method will be wrapped instead. + * + * Examples + * + * 23 => "23" + * + * "some string" => "some string" + * + * '"some string"' => "\"some string\"" + * + */ + str(value: any): StringLiteral; + /** + * List + * + * Wraps the given value as an List(Array) literal. + * + * qb.list(value) + * + * If the value is not a JavaScript Array, an Error will be thrown. + * If the value is already an List, its own value will be wrapped instead. + * Any list elements that are not already values will be converted automatically. + * + */ + list(value: any[]): ListLiteral; + /** + * Object + * + * Wraps the given value as an Object literal. + * + * qb.obj(value) + * + * If the value is not a JavaScript Object, an Error will be thrown. + * If the value is already an Object, its own value will be wrapped instead. + * Any property values that are not already values will be converted automatically. + * Any keys that are quoted strings will be treated as string literals. + * Any keys that start with the character ":" will be treated as dynamic properties and must be well-formed simple references. + * Any other keys that need escaping will be quoted if necessary. + * If you need to pass in raw JavaScript objects that shouldn't be converted according to these rules, you can use the qb declare function directly instead. + * + * Examples + * + * qb.obj({'some.name': 'value'}): {"some.name": value} + * + * qb.obj({hello: world}): {hello: world} + * + * qb.obj({'"hello"': world}): {"hello": world} + * + * qb.obj({':dynamic': 'props'}): {[dynamic]: props} + * + * qb.obj({': invalid': 'key'}): throws an error(invalid is not a well-formed reference) + * + */ + obj(obj: object): ObjectLiteral; + /** + * Simple Reference + * + * Wraps a given value in an Simple Reference. + * + * qb.ref(value) + * + * If the value is not a JavaScript string or not a well-formed simple reference, an Error will be thrown. + * If the value is an ArangoCollection, its name property will be used instead. + * If the value is already an Simple Reference, its value is wrapped instead. + * + * Examples + * + * Valid values: + * + * foo + * + * foo.bar + * + * foo[*].bar + * + * foo.bar.QUX + * + * _foo._bar._qux + * + * foo1.bar2 + * + * `foo`.bar + * + * foo.`bar` + * + * Invalid values: + * + * 1foo + * + * föö + * + * foo bar + * + * foo[bar] + * + */ + ref(value: string): SimpleReference; + expr(value: any): RawExpression; + /** + * Ternary(if / else) + * + * Creates a ternary expression from the given values. + * + * qb.if(condition, thenDo, elseDo): (condition ? thenDo: elseDo) + * OR: + * qbValue.then(thenDo).else(elseDo): (condition ? thenDo: elseDo) + * + * If the values are not already values, they will be converted automatically. + * + * Alias: qbValue.then(thenDo).otherwise(elseDo) + * + * Examples + * qb.ref('x').then('y').else('z'): (x ? y: z) + * + */ + if(cond: any, then: any, otherwise: any): Expression | number; + /** + * declare Function Call + * + * Creates a functon call for the given name and arguments. + * + * qb.fn(name)(...args) + * + * If the values are not already values, they will be converted automatically. + * For built-in AQLfunctions, methods with the relevant declare function name are already provided by the query builder. + * + * Examples + * + * qb.fn('MY::USER::FUNC')(1, 2, 3): MY::USER::FUNC(1, 2, 3) + * + * qb.fn('hello')(): hello() + * + * qb.RANDOM(): RANDOM() + * + * qb.FLOOR(qb.div(5, 2)): FLOOR((5 / 2)) + * + */ + fn(functionName: string): (...arity: any[]) => FunctionCall; +} +type QBfunc = (obj: any) => AQLfunctions; +declare const QB: AQLfunctions & QBfunc; +export = QB; diff --git a/types/aqb/tsconfig.json b/types/aqb/tsconfig.json new file mode 100644 index 0000000000..44cb0d912f --- /dev/null +++ b/types/aqb/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "lib": [ + "es2015" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aqb-tests.ts" + ] +} \ No newline at end of file diff --git a/types/aqb/tslint.json b/types/aqb/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/aqb/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/archiver/archiver-tests.ts b/types/archiver/archiver-tests.ts index 536afd68c9..752d9cc944 100644 --- a/types/archiver/archiver-tests.ts +++ b/types/archiver/archiver-tests.ts @@ -1,4 +1,4 @@ -import * as Archiver from 'archiver'; +import Archiver = require('archiver'); import * as fs from 'fs'; const options: Archiver.ArchiverOptions = { @@ -30,12 +30,16 @@ archiver.abort(); archiver.pipe(writeStream); archiver.append(readStream, { name: 'archiver.d.ts' }); +archiver.append(readStream, { date: '05/05/1991' }); +archiver.append(readStream, { date: new Date() }); +archiver.append(readStream, { mode: 1 }); +archiver.append(readStream, { mode: 1, stats: new fs.Stats() }); archiver.append(readStream, {name: 'archiver.d.ts'}) .append(readStream, {name: 'archiver.d.ts'}); archiver.directory('./path', './someOtherPath'); -archiver.directory('./', "", {}); +archiver.directory('./', '', {}); archiver.directory('./', false, { name: 'test' }); archiver.directory('./', false, (entry: Archiver.EntryData) => { entry.name = "foobar"; diff --git a/types/archiver/index.d.ts b/types/archiver/index.d.ts index 8cf6eb1e92..df15f9ff65 100644 --- a/types/archiver/index.d.ts +++ b/types/archiver/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for archiver 2.0 +// Type definitions for archiver 2.1 // Project: https://github.com/archiverjs/node-archiver // Definitions by: Esri , Dolan Miu , Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import * as fs from 'fs'; import * as stream from 'stream'; import * as glob from 'glob'; import { ZlibOptions } from 'zlib'; @@ -18,7 +19,9 @@ declare namespace archiver { interface EntryData { name?: string; prefix?: string; - stats?: string; + stats?: fs.Stats; + date?: Date | string; + mode?: number; } /** A function that lets you either opt out of including an entry (by returning false), or modify the contents of an entry as it is added (by returning an EntryData) */ diff --git a/types/argon2-browser/tsconfig.json b/types/argon2-browser/tsconfig.json index a380778b29..c3e9586f3c 100644 --- a/types/argon2-browser/tsconfig.json +++ b/types/argon2-browser/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "argon2-browser-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/arr-union/tsconfig.json b/types/arr-union/tsconfig.json index 64a3b1efed..de2c9671e9 100644 --- a/types/arr-union/tsconfig.json +++ b/types/arr-union/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "arr-union-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/artillery/tsconfig.json b/types/artillery/tsconfig.json index 0ad4bae0ee..02b327a508 100644 --- a/types/artillery/tsconfig.json +++ b/types/artillery/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "artillery-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/assert-equal-jsx/index.d.ts b/types/assert-equal-jsx/index.d.ts index f571020ef8..e017fcf57c 100644 --- a/types/assert-equal-jsx/index.d.ts +++ b/types/assert-equal-jsx/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/thejameskyle/assert-equal-jsx // Definitions by: Josh Toft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import * as React from 'react'; diff --git a/types/assertion-error/assertion-error-tests.ts b/types/assertion-error/assertion-error-tests.ts deleted file mode 100644 index 96eb520f1c..0000000000 --- a/types/assertion-error/assertion-error-tests.ts +++ /dev/null @@ -1,14 +0,0 @@ - -import AssertionError = require('assertion-error'); - -var e: AssertionError; -var str: string; - -function foo () { - -} - -e = new AssertionError(str); -e = new AssertionError(str, {a:1, b:2}); -e = new AssertionError(str, {a:1, b:2}, foo); - diff --git a/types/assertion-error/index.d.ts b/types/assertion-error/index.d.ts deleted file mode 100644 index 8663df799d..0000000000 --- a/types/assertion-error/index.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Type definitions for assertion-error 1.0.0 -// Project: https://github.com/chaijs/assertion-error -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare class AssertionError implements Error { - constructor(message: string, props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; -} -export = AssertionError; diff --git a/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts b/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts index 6851f853f2..b02c707d81 100644 --- a/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts +++ b/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts @@ -1,5 +1,5 @@ import * as webpack from 'webpack'; -import * as AssetsPlugin from 'assets-webpack-plugin'; +import AssetsPlugin = require('assets-webpack-plugin'); const config: webpack.Configuration = { plugins: [ diff --git a/types/assets-webpack-plugin/index.d.ts b/types/assets-webpack-plugin/index.d.ts index 660fbc6052..7644d8f9ad 100644 --- a/types/assets-webpack-plugin/index.d.ts +++ b/types/assets-webpack-plugin/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/sporto/assets-webpack-plugin // Definitions by: Michael Strobel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as webpack from 'webpack'; diff --git a/types/async-lock/async-lock-tests.ts b/types/async-lock/async-lock-tests.ts index 259749d4f0..9e8920ca4b 100644 --- a/types/async-lock/async-lock-tests.ts +++ b/types/async-lock/async-lock-tests.ts @@ -1,4 +1,3 @@ - import * as AsyncLock from "async-lock"; const lock = new AsyncLock(); @@ -6,15 +5,24 @@ lock.acquire("key", (done) => { done(); }, (err, ret) => { /* ... */ }); -lock.acquire("key", (done) => { - done(); -}).then(() => { /* ... */ }); +lock.acquire("key", (done) => { done(); }) + .then(() => { /* ... */ }) + .catch(() => { /* ... */ }); + +lock.acquire("key", () => "stringValue") +// Check returned value's type is inherited properly + .then((str) => str.replace("s", "S")); + +lock.acquire("key", async () => "stringValue") +// Check returned value's type is inherited properly + .then((str) => str.replace("s", "S")); lock.acquire([ "key1", "key2" ], (done) => { done(); }, (err, ret) => { /* ... */ }); lock.isBusy(); +lock.isBusy('key'); const lock2 = new AsyncLock({ timeout : 5000 }); const lock3 = new AsyncLock({ maxPending : 5000 }); diff --git a/types/async-lock/index.d.ts b/types/async-lock/index.d.ts index 4a19590d73..cd2b1e4b40 100644 --- a/types/async-lock/index.d.ts +++ b/types/async-lock/index.d.ts @@ -1,12 +1,12 @@ -// Type definitions for async-lock +// Type definitions for async-lock 1.1 // Project: https://github.com/rain1017/async-lock // Definitions by: Elisée MAURER +// Alejandro +// Anatoly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 - -interface AsyncLockDoneCallback { - (err?: Error, ret?: any): void; -} +type AsyncLockDoneCallback = (err?: Error, ret?: T) => void; interface AsyncLockOptions { timeout?: number; @@ -18,10 +18,15 @@ interface AsyncLockOptions { declare class AsyncLock { constructor(options?: AsyncLockOptions); - acquire(key: string | string[], fn: (done: AsyncLockDoneCallback) => any, cb: AsyncLockDoneCallback, opts?: AsyncLockOptions): void; - acquire(key: string | string[], fn: (done: AsyncLockDoneCallback) => any, opts?: AsyncLockOptions): PromiseLike; + acquire(key: string | string[], + fn: (() => T | PromiseLike) | ((done: AsyncLockDoneCallback) => any), + opts?: AsyncLockOptions): Promise; + acquire(key: string | string[], + fn: (done: AsyncLockDoneCallback) => any, + cb: AsyncLockDoneCallback, + opts?: AsyncLockOptions): void; - isBusy(): boolean; + isBusy(key?: string): boolean; } declare namespace AsyncLock { } diff --git a/types/async-lock/tslint.json b/types/async-lock/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/async-lock/tslint.json +++ b/types/async-lock/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/async-retry/async-retry-tests.ts b/types/async-retry/async-retry-tests.ts new file mode 100644 index 0000000000..29c90b36c8 --- /dev/null +++ b/types/async-retry/async-retry-tests.ts @@ -0,0 +1,20 @@ +import { Options, RetryFunction, retry } from 'async-retry'; + +const o: Options = { + retries: 1, + factor: 2, + minTimeout: 3, + maxTimeout: 4, + randomize: true, + onRetry: (e: Error) => 42 +}; + +retry( + bail => 'hello', + { retries: 3 } +); + +retry( + bail => Promise.resolve(42), + { retries: 3 } +); diff --git a/types/async-retry/index.d.ts b/types/async-retry/index.d.ts new file mode 100644 index 0000000000..38d0d8aeec --- /dev/null +++ b/types/async-retry/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for async-retry 1.1 +// Project: https://github.com/zeit/async-retry#readme +// Definitions by: Albert Wu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function retry(fn: RetryFunction, opts: Options): Promise; + +export interface Options { + retries?: number; + factor?: number; + minTimeout?: number; + maxTimeout?: number; + randomize?: boolean; + onRetry?: (e: Error) => any; +} + +export type RetryFunction = (bail: (e: Error) => A, attempt: number) => A|Promise; diff --git a/types/async-retry/tsconfig.json b/types/async-retry/tsconfig.json new file mode 100644 index 0000000000..c010746fa3 --- /dev/null +++ b/types/async-retry/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", + "async-retry-tests.ts" + ] +} \ No newline at end of file diff --git a/types/localforage-cordovasqlitedriver/tslint.json b/types/async-retry/tslint.json similarity index 100% rename from types/localforage-cordovasqlitedriver/tslint.json rename to types/async-retry/tslint.json diff --git a/types/asynciterator/tsconfig.json b/types/asynciterator/tsconfig.json index 8b8b919abc..c50f09f902 100644 --- a/types/asynciterator/tsconfig.json +++ b/types/asynciterator/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "asynciterator-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/atlaskit__button/atlaskit__button-tests.tsx b/types/atlaskit__button/atlaskit__button-tests.tsx new file mode 100644 index 0000000000..dd592255e9 --- /dev/null +++ b/types/atlaskit__button/atlaskit__button-tests.tsx @@ -0,0 +1,38 @@ +import Button, { ButtonGroup, themeNamespace } from "@atlaskit/button"; + +import * as React from "react"; +import { render } from "react-dom"; + +declare const container: Element; + +render( + + + , + container +); diff --git a/types/atlaskit__button/index.d.ts b/types/atlaskit__button/index.d.ts new file mode 100644 index 0000000000..e9a613fabd --- /dev/null +++ b/types/atlaskit__button/index.d.ts @@ -0,0 +1,93 @@ +// Type definitions for @atlaskit/button 6.4 +// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/ +// Definitions by: Jimmy Luong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { + Component, + ReactNode, + ReactElement, + ComponentClass, + MouseEventHandler +} from "react"; + +export type ButtonAppearances = + | "default" + | "danger" + | "link" + | "primary" + | "subtle" + | "subtle-link" + | "warning" + | "help"; + +export interface ButtonProps { + /** The base styling to apply to the button. */ + readonly appearance?: ButtonAppearances; + /** Pass aria-controls to underlying html button. */ + readonly ariaControls?: string; + /** Pass aria-expanded to underlying html button. */ + readonly ariaExpanded?: boolean; + /** Pass aria-haspopup to underlying html button. */ + readonly ariaHaspopup?: boolean; + /** This button's child nodes. */ + readonly children?: ReactNode; + /** Add a classname to the button. */ + readonly className?: string; + /** A custom component to use instead of the default button. */ + readonly component?: ComponentClass; + /** Name property of a linked form that the button submits when clicked. */ + readonly form?: string; + /** Provides a url for buttons being used as a link. */ + readonly href?: string; + /** Places an icon within the button, after the button's text. */ + readonly iconAfter?: ReactElement; + /** Places an icon within the button, before the button's text. */ + readonly iconBefore?: ReactElement; + /** Pass a reference on to the styled component */ + readonly innerRef?: (instance: any) => void; + /** Provide a unique id to the button. */ + readonly id?: string; + /** Set if the button is disabled. */ + readonly isDisabled?: boolean; + /** Change the style to indicate the button is selected. */ + readonly isSelected?: boolean; + /** Handler to be called on click. */ + readonly onClick?: MouseEventHandler; + /** Set the amount of padding in the button. */ + readonly spacing?: ButtonSpacing; + /** Assign specific tabIndex order to the underlying html button. */ + readonly tabIndex?: number; + /** Pass target down to a link within the button component, if a href is provided. */ + readonly target?: string; + /** Set whether it is a button or a form submission. */ + readonly type?: ButtonType; + /** Option to fit button width to its parent width */ + readonly shouldFitContainer?: boolean; +} + +export type ButtonType = "button" | "submit"; + +export type ButtonSpacing = "compact" | "default" | "none"; + +export interface ButtonState { + readonly isActive: boolean; + readonly isFocus: boolean; + readonly isHover: boolean; +} + +declare class Button extends Component {} + +export interface ButtonGroupProps { + /** The appearance to apply to all buttons. */ + readonly appearance?: ButtonAppearances; + /** The buttons to render. */ + readonly children: ReactNode; +} + +export class ButtonGroup extends Component {} + +export const themeNamespace: string; + +export default Button; diff --git a/types/atlaskit__button/tsconfig.json b/types/atlaskit__button/tsconfig.json new file mode 100644 index 0000000000..3f374a6b3e --- /dev/null +++ b/types/atlaskit__button/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "@atlaskit/button": ["atlaskit__button"] + } + }, + "files": ["index.d.ts", "atlaskit__button-tests.tsx"] +} diff --git a/types/node-waves/tslint.json b/types/atlaskit__button/tslint.json similarity index 100% rename from types/node-waves/tslint.json rename to types/atlaskit__button/tslint.json diff --git a/types/atom-keymap/tsconfig.json b/types/atom-keymap/tsconfig.json index 8a17cc061c..14797a013b 100644 --- a/types/atom-keymap/tsconfig.json +++ b/types/atom-keymap/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "atom-keymap-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/atom-mocha-test-runner/tsconfig.json b/types/atom-mocha-test-runner/tsconfig.json index c6e9fb20c0..40639f83aa 100644 --- a/types/atom-mocha-test-runner/tsconfig.json +++ b/types/atom-mocha-test-runner/tsconfig.json @@ -22,4 +22,4 @@ "index.d.ts", "atom-mocha-test-runner-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/atom/atom-tests.ts b/types/atom/atom-tests.ts index 5fc92880f4..cefa92ef5c 100644 --- a/types/atom/atom-tests.ts +++ b/types/atom/atom-tests.ts @@ -719,6 +719,9 @@ function testDisplayMarker() { // DisplayMarkerLayer ========================================================= function testDisplayMarkerLayer() { + // Properties + str = displayMarkerLayer.id; + // Lifecycle displayMarkerLayer.destroy(); displayMarkerLayer.clear(); @@ -953,7 +956,8 @@ function testFile() { // Reading and Writing async function readFile() { - str = await file.read(); + const res = await file.read(); + if (res !== null) str = res; } const stream = file.createReadStream(); @@ -1274,6 +1278,9 @@ function testMarker() { // MarkerLayer ================================================================ function testMarkerLayer() { + // Properties + str = markerLayer.id; + // Lifecycle markerLayer = markerLayer.copy(); bool = markerLayer.destroy(); @@ -1459,6 +1466,14 @@ function testPackageManager() { bool = atom.packages.isPackageDisabled("Test"); + // Activating and deactivating packages + atom.packages.activatePackage("Test").then((activePack) => { + pack = activePack; + }); + atom.packages.deactivatePackage("Test", true).then(() => { + // package is deactivated + }); + // Accessing active packages packs = atom.packages.getActivePackages(); @@ -2889,7 +2904,6 @@ function testTextEditor() { // Grammars grammar = editor.getGrammar(); - editor.setGrammar(grammar); // Managing Syntax Scopes scopeDescriptor = editor.getRootScopeDescriptor(); diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index 53fa8d5749..df446d50c3 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Atom 1.23 +// Type definitions for Atom 1.24 // Project: https://github.com/atom/atom // Definitions by: GlenCFL // smhxx @@ -7,9 +7,8 @@ // TypeScript Version: 2.3 // NOTE: only those classes exported within this file should be retain that status below. -// https://github.com/atom/atom/blob/v1.23.0/exports/atom.js +// https://github.com/atom/atom/blob/v1.24.0/exports/atom.js -/// /// import { ReadStream, WriteStream } from "fs"; @@ -654,6 +653,9 @@ export interface DisplayMarker { * This API is experimental and subject to change on any release. */ export interface DisplayMarkerLayer { + /** The identifier for the underlying MarkerLayer. */ + id: string; + // Lifecycle /** Destroy this layer. */ destroy(): void; @@ -949,6 +951,9 @@ export interface Marker { /** Experimental: A container for a related set of markers. */ export interface MarkerLayer { + /** The identifier for this MarkerLayer. */ + id: string; + // Lifecycle /** Create a copy of this layer with markers in the same state and locations. */ copy(): MarkerLayer; @@ -1312,6 +1317,12 @@ export class TextEditor { /** Retrieves the current TextBuffer. */ getBuffer(): TextBuffer; + /** Sets the read-only state for the editor. */ + setReadOnly(readonly: boolean): void; + + /** Whether or not this editor is in read-only mode. */ + isReadOnly(): boolean; + /** * Calls your callback when a Gutter is added to the editor. Immediately calls * your callback for each existing gutter. @@ -1911,7 +1922,7 @@ export class TextEditor { getCursors(): Cursor[]; /** - * Get all Cursorss, ordered by their position in the buffer instead of the + * Get all Cursors, ordered by their position in the buffer instead of the * order in which they were added. */ getCursorsOrderedByBufferPosition(): Cursor[]; @@ -2260,12 +2271,6 @@ export class TextEditor { /** Get the current Grammar of this editor. */ getGrammar(): Grammar; - /** - * Set the current Grammar of this editor. - * Assigning a grammar will cause the editor to re-tokenize based on the new grammar. - */ - setGrammar(grammar: Grammar): void; - // Managing Syntax Scopes /** * Returns a ScopeDescriptor that includes this editor's language. @@ -2519,6 +2524,10 @@ export interface TextEditorRegistry { observe(callback: (editor: TextEditor) => void): Disposable; } +export interface JQueryCompatible extends Iterable { + jquery: string; +} + export type TooltipPlacement = |"top"|"bottom"|"left"|"right" |"auto"|"auto top"|"auto bottom"|"auto left"|"auto right"; @@ -2526,7 +2535,7 @@ export type TooltipPlacement = /** Associates tooltips with HTML elements or selectors. */ export interface TooltipManager { /** Add a tooltip to the given element. */ - add(target: HTMLElement, options: { + add(target: HTMLElement | JQueryCompatible, options: { item?: object, } | { title?: string|(() => string), @@ -3341,7 +3350,7 @@ export class Directory { getEntriesSync(): Array; /** Reads file entries in this directory from disk asynchronously. */ - getEntries(callback: (error: Error, entries: Array) => void): void; + getEntries(callback: (error: Error|null, entries: Array) => void): void; /** * Determines if the given path (real or symbolic) is inside this directory. This @@ -3547,7 +3556,7 @@ export class File { // Reading and Writing /** Reads the contents of the file. */ - read(flushCache?: boolean): Promise; + read(flushCache?: boolean): Promise; /** Returns a stream to read the content of the file. */ createReadStream(): ReadStream; @@ -3847,6 +3856,51 @@ export interface GrammarRegistry { * @return An array of Token instances decoded from the given tags. */ decodeTokens(lineText: string, tags: Array): GrammarToken[]; + + /** + * Set a TextBuffer's language mode based on its path and content, and continue + * to update its language mode as grammars are added or updated, or the buffer's + * file path changes. + * @param buffer The buffer whose language mode will be maintained. + * @return A Disposable that can be used to stop updating the buffer's + * language mode. + */ + maintainLanguageMode(buffer: TextBuffer): Disposable; + + /** + * Force a TextBuffer to use a different grammar than the one that would otherwise + * be selected for it. + * @param buffer The buffer whose grammar will be set. + * @param languageId The identifier of the desired language. + * @return Returns a boolean that indicates whether the language was successfully + * found. + */ + assignLanguageMode(buffer: TextBuffer, languageId: string): boolean; + + /** + * Remove any language mode override that has been set for the given TextBuffer. + * This will assign to the buffer the best language mode available. + */ + autoAssignLanguageMode(buffer: TextBuffer): void; + + /** + * Select a grammar for the given file path and file contents. + * + * This picks the best match by checking the file path and contents against + * each grammar. + * @param filePath A string file path. + * @param fileContents A string of text for that file path. + */ + selectGrammar(filePath: string, fileContents: string): Grammar; + + /** + * Returns a number representing how well the grammar matches the + * `filePath` and `contents`. + * @param grammar The grammar to score. + * @param filePath A string file path. + * @param contents A string of text for that file path. + */ + getGrammarScore(grammar: Grammar, filePath: string, contents: string): number; } /** Represents a gutter within a TextEditor. */ @@ -4111,6 +4165,9 @@ export interface PackageManager { /** Activate a single package by name or path. */ activatePackage(nameOrPath: string): Promise; + /** Deactivate a single package by name or path. */ + deactivatePackage(nameOrPath: string, suppressSerialization?: boolean): Promise; + /** Triggers the given package activation hook. */ triggerActivationHook(hook: string): void; @@ -4363,7 +4420,7 @@ export interface PathWatcher extends DisposableLike { /** * Unsubscribe all subscribers from filesystem events. Native resources will be - * release asynchronously, but this watcher will stop broadcasting events + * released asynchronously, but this watcher will stop broadcasting events * immediately. */ dispose(): void; @@ -4388,7 +4445,11 @@ export interface Project { onDidChangeFiles(callback: (events: FilesystemChangeEvent) => void): Disposable; // Accessing the Git Repository - /** Get an Array of GitRepositorys associated with the project's directories. */ + /** + * Get an Array of GitRepositorys associated with the project's directories. + * + * This method will be removed in 2.0 because it does synchronous I/O. + */ getRepositories(): GitRepository[]; /** Get the repository for a given directory asynchronously. */ @@ -4810,7 +4871,8 @@ export class Task { * Throws an error if this task has already been terminated or if sending a * message to the child process fails. */ - send(message: string): void; + // tslint:disable-next-line:no-any + send(message: string | number | boolean | object | null | any[]): void; /** Call a function when an event is emitted by the child process. */ // tslint:disable-next-line:no-any @@ -5071,7 +5133,7 @@ export class TextBuffer { /** * Get a MarkerLayer by id. - * Returns a MarkerLayer or `` if no layer exists with the given id. + * Returns a MarkerLayer or undefined if no layer exists with the given id. */ getMarkerLayer(id: string): MarkerLayer|undefined; @@ -5309,7 +5371,7 @@ export interface ThemeManager { /** Returns an Array of all the loaded themes. */ getLoadedThemes(): Package[]|undefined; - // Accessing Active Themes + // Managing Enabled Themes /** Returns an Array of strings all the active theme names. */ getActiveThemeNames(): string[]|undefined; @@ -5691,7 +5753,7 @@ export interface TextEditorObservedEvent { // information under certain contexts. // NOTE: the config schema with these defaults can be found here: -// https://github.com/atom/atom/blob/v1.23.0/src/config-schema.js +// https://github.com/atom/atom/blob/v1.24.0/src/config-schema.js /** * Allows you to strongly type Atom configuration variables. Additional key:value * pairings merged into this interface will result in configuration values under @@ -6695,7 +6757,7 @@ export interface Tooltip { enabled: boolean; timeout: number; hoverState: "in"|"out"|null; - element: JQuery|HTMLElement; + element: HTMLElement; getTitle(): string; getTooltipElement(): HTMLElement; diff --git a/types/atom/linter/index.d.ts b/types/atom/linter/index.d.ts index bf085d9859..72f378af26 100644 --- a/types/atom/linter/index.d.ts +++ b/types/atom/linter/index.d.ts @@ -5,6 +5,10 @@ import { Disposable, Point, Range, TextEditor } from "../index"; +export interface Config { + name: string; +} + export interface ReplacementSolution { title?: string; position: Range; @@ -60,6 +64,9 @@ export interface Message { * do things like HTTP requests. */ description?: string|(() => Promise|string); + + /** Optionally override the displayed linter name. Defaults to provider name. */ + linterName?: string; } export interface IndieDelegate { @@ -73,10 +80,14 @@ export interface IndieDelegate { dispose(): void; } +export type LintResult = Message[] | null; + export interface LinterProvider { name: string; scope: "file"|"project"; lintsOnChange: boolean; grammarScopes: string[]; - lint(textEditor: TextEditor): Message[]|void|Promise; + lint(editor: TextEditor): LintResult | Promise; } + +export type IndieProvider = (register: (config: Config) => IndieDelegate) => void; diff --git a/types/atom/tsconfig.json b/types/atom/tsconfig.json index a58ec7b74c..35ece9c1dd 100644 --- a/types/atom/tsconfig.json +++ b/types/atom/tsconfig.json @@ -24,4 +24,4 @@ "linter/index.d.ts", "status-bar/index.d.ts" ] -} +} \ No newline at end of file diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 6110f2fe52..c7224599bd 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -590,7 +590,7 @@ export interface Auth0UserProfile { given_name?: string; family_name?: string; email?: string; - email_verified?: string; + email_verified?: boolean; clientID: string; gender?: string; locale?: string; diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index c2107b11e4..119bbb3c37 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -204,6 +204,19 @@ const selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = { new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptionsWithCallbacks); +// test checkbox-field additional sign up field + +const checkboxFieldOptions : Auth0LockConstructorOptions = { + additionalSignUpFields: [{ + type: "checkbox", + name: "remember", + placeholder: "Remember Me", + prefill: "false" + }] + }; + + new Auth0Lock(CLIENT_ID, DOMAIN, checkboxFieldOptions); + // test Avatar options const avatarOptions : Auth0LockConstructorOptions = { diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 8ed6b50c87..352d9c71a9 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -2,6 +2,7 @@ // Project: http://auth0.com // Definitions by: Brian Caruso // Dan Caddigan +// Larry Faudree // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -23,16 +24,37 @@ type Auth0LockAdditionalSignUpFieldPrefillCallback = type Auth0LockAdditionalSignUpFieldPrefillFunction = (callback: Auth0LockAdditionalSignUpFieldPrefillCallback) => void; -interface Auth0LockAdditionalSignUpField { +interface Auth0LockAdditionalTextSignUpField { + type?: "text"; icon?: string; name: string; options?: Auth0LockAdditionalSignUpFieldOption[] | Auth0LockAdditionalSignUpFieldOptionsFunction; placeholder: string; prefill?: string | Auth0LockAdditionalSignUpFieldPrefillFunction; - type?: "select" | "text"; validator?: (input: string) => { valid: boolean; hint?: string }; } +interface Auth0LockAdditionalSelectSignUpField { + type?: "select"; + icon?: string; + name: string; + options?: Auth0LockAdditionalSignUpFieldOption[] | Auth0LockAdditionalSignUpFieldOptionsFunction; + placeholder: string; + prefill?: string | Auth0LockAdditionalSignUpFieldPrefillFunction; + validator?: (input: string) => { valid: boolean; hint?: string }; +} + +interface Auth0LockAdditionalCheckboxSignUpField { + type?: "checkbox"; + icon?: string; + name: string; + placeholder: string; + prefill: "true" | "false"; + validator?: (input: string) => { valid: boolean, hint?: string }; +} + +type Auth0LockAdditionalSignUpField = Auth0LockAdditionalSelectSignUpField |Auth0LockAdditionalTextSignUpField |Auth0LockAdditionalCheckboxSignUpField; + type Auth0LockAvatarUrlCallback = (error: auth0.Auth0Error, url: string) => void; type Auth0LockAvatarDisplayNameCallback = (error: auth0.Auth0Error, displayName: string) => void; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index e9e347cc69..0572c2b0e7 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -131,3 +131,13 @@ const retryableManagementClient = new auth0.ManagementClient({ enabled : true } }); + +management.createPasswordChangeTicket({ + connection_id: 'con_id', + email: 'test@me.co', + new_password: 'password', + result_url: 'https://www.google.com/', + ttl_sec: 86400, +}, (err: Error, data) => { + console.log(data.ticket); +}); diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index aea5d92e24..58013848f8 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for auth0 2.6 +// Type definitions for auth0 2.7 // Project: https://github.com/auth0/node-auth0 // Definitions by: Wilson Hobbs , Seth Westphal , Amiram Korach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -99,7 +99,6 @@ export interface Rule { order?: number; } - export interface Client { /** * The name of the client. @@ -178,6 +177,10 @@ export interface Client { } export interface ResourceServer { + /** + * The identifier of the resource server. + */ + identifier?: string; scopes?: { description: string, value: string }[]; /** * The algorithm used to sign tokens. @@ -217,7 +220,7 @@ export interface CreateResourceServer extends ResourceServer { /** * The identifier of the client. */ - identifier?: string; + identifier: string; } export interface CreateClientGrant { @@ -253,6 +256,66 @@ export interface CreateClientGrant { scope: string[]; } +export type Strategy = + 'ad' | 'adfs' | 'amazon' | 'dropbox' | 'bitbucket' | 'aol' | 'auth0-adldap' | 'auth0-oidc' | + 'auth0' | 'baidu' | 'bitly' | 'box' | 'custom' | 'daccount' | 'dwolla' | 'email' | + 'evernote-sandbox' | 'evernote' | 'exact' | 'facebook' | 'fitbit' | 'flickr' | 'github' | + 'google-apps' | 'google-oauth2' | 'guardian' | 'instagram' | 'ip' | 'linkedin' | 'miicard' | + 'oauth1' | 'oauth2' | 'office365' | 'paypal' | 'paypal-sandbox' | 'pingfederate' | + 'planningcenter' | 'renren' | 'salesforce-community' | 'salesforce-sandbox' | 'salesforce' | + 'samlp' | 'sharepoint' | 'shopify' | 'sms' | 'soundcloud' | 'thecity-sandbox' | 'thecity' | + 'thirtysevensignals' | 'twitter' | 'untappd' | 'vkontakte' | 'waad' | 'weibo' | 'windowslive' | + 'wordpress' | 'yahoo' | 'yammer' | 'yandex'; + +export interface UpdateConnection { + options?: any; + /** + * The identifiers of the clients for which the connection is to + * be enabled. If the array is empty or the property is not + * specified, no clients are enabled. + */ + enabled_clients?: string[]; + /** + * Defines the realms for which the connection will be used + * (ie: email domains). If the array is empty or the property is + * not specified, the connection name will be added as realm. + */ + realms?: string[]; + metadata?: any; + /** + * True if the connection is domain level. + */ + is_domain_connection?: boolean; +} + +export interface Connection extends UpdateConnection { + /** + * The connection's identifier. + */ + id?: string; + /** + * The name of the connection. + */ + name?: string; + /** + * The type of the connection, related to the identity provider. + */ + strategy?: Strategy; +} + +export interface CreateConnection extends UpdateConnection { + /** + * The name of the connection. Must start and end with an + * alphanumeric character and can only contain alphanumeric + * characters and '-'. Max length 128. + */ + name: string; + /** + * The identity provider identifier for the connection. + */ + strategy: Strategy; +} + export interface User { email?: string; email_verified?: boolean; @@ -425,10 +488,16 @@ export interface UserIdParams { } export interface PasswordChangeTicketParams { - result_url: string; - user_id: string; - email: string; - new_password: string; + result_url?: string; + user_id?: string; + new_password?: string; + connection_id?: string; + email?: string; + ttl_sec?: number; +} + +export interface PasswordChangeTicketResponse { + ticket: string; } export interface EmailVerificationTicketOptions { @@ -484,23 +553,20 @@ export class ManagementClient { getClientInfo(): ClientInfo; // Connections - getConnections(): Promise; - getConnections(cb: (err: Error, data: any) => void): void; + getConnections(): Promise; + getConnections(cb: (err: Error, connections: Connection[]) => void): void; - createConnection(data: ObjectWithId): Promise; - createConnection(data: ObjectWithId, cb: (err: Error, data: any) => void): void; + createConnection(data: CreateConnection): Promise; + createConnection(data: CreateConnection, cb: (err: Error, connection: Connection) => void): void; - getConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void; - getConnection(params: ObjectWithId): Promise; + getConnection(params: ObjectWithId, cb: (err: Error, connection: Connection) => void): void; + getConnection(params: ObjectWithId): Promise; - deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void; - deleteConnection(params: ObjectWithId): Promise; + deleteConnection(params: ObjectWithId, cb: (err: Error) => void): void; + deleteConnection(params: ObjectWithId): Promise; - deleteConnection(params: ObjectWithId, cb: (err: Error, data: any) => void): void; - deleteConnection(params: ObjectWithId): Promise; - - updateConnection(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void; - updateConnection(params: ObjectWithId, data: Data): Promise; + updateConnection(params: ObjectWithId, data: UpdateConnection, cb: (err: Error, connection: Connection) => void): void; + updateConnection(params: ObjectWithId, data: UpdateConnection): Promise; // Clients @@ -651,8 +717,8 @@ export class ManagementClient { sendEmailVerification(data: UserIdParams, cb?: (err: Error, data: any) => void): void; // Tickets - createPasswordChangeTicket(params: PasswordChangeTicketParams): Promise; - createPasswordChangeTicket(params: PasswordChangeTicketParams, cb?: (err: Error, data: any) => void): void; + createPasswordChangeTicket(params: PasswordChangeTicketParams): Promise; + createPasswordChangeTicket(params: PasswordChangeTicketParams, cb?: (err: Error, data: PasswordChangeTicketResponse) => void): void; createEmailVerificationTicket(data: EmailVerificationTicketOptions): Promise; createEmailVerificationTicket(data: EmailVerificationTicketOptions, cb?: (err: Error, data: any) => void): void; diff --git a/types/auto-sni/auto-sni-tests.ts b/types/auto-sni/auto-sni-tests.ts index 6be54148fb..8cd17af850 100644 --- a/types/auto-sni/auto-sni-tests.ts +++ b/types/auto-sni/auto-sni-tests.ts @@ -1,4 +1,4 @@ -import * as autosni from "auto-sni"; +import autosni = require("auto-sni"); const a = autosni({ agreeTos: true, email: '', diff --git a/types/autosuggest-highlight/autosuggest-highlight-tests.ts b/types/autosuggest-highlight/autosuggest-highlight-tests.ts new file mode 100644 index 0000000000..50283a24bd --- /dev/null +++ b/types/autosuggest-highlight/autosuggest-highlight-tests.ts @@ -0,0 +1,11 @@ +import match = require('autosuggest-highlight/match'); +import parse = require('autosuggest-highlight/parse'); + +function matchTest() { + let matches = match('some text', 'te'); // $ExpectType number[] | number[][] + matches = match('some sweet text', 's s'); // $ExpectType number[] | number[][] +} + +function parseTest() { + const parts = parse('Pretty cool text', [[7, 9], [12, 13]]); // $ExpectType { text: string; highlight: boolean; }[] +} diff --git a/types/autosuggest-highlight/index.d.ts b/types/autosuggest-highlight/index.d.ts new file mode 100644 index 0000000000..e05c30d608 --- /dev/null +++ b/types/autosuggest-highlight/index.d.ts @@ -0,0 +1,5 @@ +// Type definitions for autosuggest-highlight 3.1 +// Project: https://github.com/moroshko/autosuggest-highlight#readme +// Definitions by: Artur Sianiuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 diff --git a/types/autosuggest-highlight/match/index.d.ts b/types/autosuggest-highlight/match/index.d.ts new file mode 100644 index 0000000000..19d18c48b3 --- /dev/null +++ b/types/autosuggest-highlight/match/index.d.ts @@ -0,0 +1,3 @@ +declare function match(text: string, query: string): number[] | number[][]; + +export = match; diff --git a/types/autosuggest-highlight/parse/index.d.ts b/types/autosuggest-highlight/parse/index.d.ts new file mode 100644 index 0000000000..01038cd116 --- /dev/null +++ b/types/autosuggest-highlight/parse/index.d.ts @@ -0,0 +1,3 @@ +declare function parse(text: string, matches: number[] | number[][]): Array<{ text: string; highlight: boolean; }>; + +export = parse; diff --git a/types/autosuggest-highlight/tsconfig.json b/types/autosuggest-highlight/tsconfig.json new file mode 100644 index 0000000000..8201d360ec --- /dev/null +++ b/types/autosuggest-highlight/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "autosuggest-highlight-tests.ts", + "match/index.d.ts", + "parse/index.d.ts" + ] +} diff --git a/types/rollup/tslint.json b/types/autosuggest-highlight/tslint.json similarity index 61% rename from types/rollup/tslint.json rename to types/autosuggest-highlight/tslint.json index ba7f6bc7ae..946997cb87 100644 --- a/types/rollup/tslint.json +++ b/types/autosuggest-highlight/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "semicolon": [true, "never"] + "no-useless-files": false } } diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 1d756f21e0..2b7b375576 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -1,29 +1,35 @@ -var str: string = "any string"; -var date: Date = new Date(); -var anyObj: any = { abc: 123 }; -var num: number = 5; -var error: Error = new Error(); -var b: boolean = true; -var apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; -var apiGwEvt: AWSLambda.APIGatewayEvent; -var customAuthorizerEvt: AWSLambda.CustomAuthorizerEvent; -var clientCtx: AWSLambda.ClientContext; -var clientContextEnv: AWSLambda.ClientContextEnv; -var clientContextClient: AWSLambda.ClientContextClient; -var context: AWSLambda.Context; -var identity: AWSLambda.CognitoIdentity; -var proxyResult: AWSLambda.ProxyResult; -var authResponse: AWSLambda.AuthResponse; -var policyDocument: AWSLambda.PolicyDocument; -var statement: AWSLambda.Statement; -var authResponseContext: AWSLambda.AuthResponseContext; -var snsEvt: AWSLambda.SNSEvent; -var snsEvtRecs: AWSLambda.SNSEventRecord[]; -var snsEvtRec: AWSLambda.SNSEventRecord; -var snsMsg: AWSLambda.SNSMessage; -var snsMsgAttr: AWSLambda.SNSMessageAttribute; -var snsMsgAttrs: AWSLambda.SNSMessageAttributes; -var S3EvtRec: AWSLambda.S3EventRecord = { +declare let str: string; +declare let strOrNull: string | null; +declare let strOrUndefined: string | undefined; +declare let date: Date; +declare let anyObj: any; +declare let num: number; +declare let error: Error; +declare let bool: boolean; +declare let boolOrUndefined: boolean | undefined; +declare let apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; +declare let apiGwEvt: AWSLambda.APIGatewayEvent; +declare let customAuthorizerEvt: AWSLambda.CustomAuthorizerEvent; +declare let clientCtx: AWSLambda.ClientContext; +declare let clientCtxOrUndefined: AWSLambda.ClientContext | undefined; +declare let clientContextEnv: AWSLambda.ClientContextEnv; +declare let clientContextClient: AWSLambda.ClientContextClient; +declare let context: AWSLambda.Context; +declare let identity: AWSLambda.CognitoIdentity; +declare let identityOrUndefined: AWSLambda.CognitoIdentity | undefined; +declare let proxyResult: AWSLambda.ProxyResult; +declare let authResponse: AWSLambda.AuthResponse; +declare let policyDocument: AWSLambda.PolicyDocument; +declare let statement: AWSLambda.Statement; +declare let authResponseContext: AWSLambda.AuthResponseContext; +declare let authResponseContextOpt: AWSLambda.AuthResponseContext | null | undefined; +declare let snsEvt: AWSLambda.SNSEvent; +declare let snsEvtRecs: AWSLambda.SNSEventRecord[]; +declare let snsEvtRec: AWSLambda.SNSEventRecord; +declare let snsMsg: AWSLambda.SNSMessage; +declare let snsMsgAttr: AWSLambda.SNSMessageAttribute; +declare let snsMsgAttrs: AWSLambda.SNSMessageAttributes; +const S3EvtRec: AWSLambda.S3EventRecord = { eventVersion: '2.0', eventSource: 'aws:s3', awsRegion: 'us-east-1', @@ -32,7 +38,7 @@ var S3EvtRec: AWSLambda.S3EventRecord = { userIdentity: { principalId: 'AIDAJDPLRKLG7UEXAMPLE' }, - requestParameters:{ + requestParameters: { sourceIPAddress: '127.0.0.1' }, responseElements: { @@ -59,60 +65,61 @@ var S3EvtRec: AWSLambda.S3EventRecord = { } }; -var S3CreateEvent: AWSLambda.S3CreateEvent = { +const S3CreateEvent: AWSLambda.S3CreateEvent = { Records: [S3EvtRec] }; -var cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent; -var cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent; -var cloudformationCustomResourceResponse: AWSLambda.CloudFormationCustomResourceResponse; -var cloudwatchLogsEvent: AWSLambda.CloudWatchLogsEvent; -var cloudwatchLogsDecodedData: AWSLambda.CloudWatchLogsDecodedData; +declare const cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent; +declare const cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent; +declare const cloudformationCustomResourceResponse: AWSLambda.CloudFormationCustomResourceResponse; +declare const cloudwatchLogsEvent: AWSLambda.CloudWatchLogsEvent; +declare const cloudwatchLogsDecodedData: AWSLambda.CloudWatchLogsDecodedData; +declare const scheduledEvent: AWSLambda.ScheduledEvent; /* API Gateway Event request context */ str = apiGwEvtReqCtx.accountId; str = apiGwEvtReqCtx.apiId; -authResponseContext = apiGwEvtReqCtx.authorizer; +authResponseContextOpt = apiGwEvtReqCtx.authorizer; str = apiGwEvtReqCtx.httpMethod; -str = apiGwEvtReqCtx.identity.accessKey; -str = apiGwEvtReqCtx.identity.accountId; -str = apiGwEvtReqCtx.identity.apiKey; -str = apiGwEvtReqCtx.identity.caller; -str = apiGwEvtReqCtx.identity.cognitoAuthenticationProvider; -str = apiGwEvtReqCtx.identity.cognitoAuthenticationType; -str = apiGwEvtReqCtx.identity.cognitoIdentityId; -str = apiGwEvtReqCtx.identity.cognitoIdentityPoolId; +strOrNull = apiGwEvtReqCtx.identity.accessKey; +strOrNull = apiGwEvtReqCtx.identity.accountId; +strOrNull = apiGwEvtReqCtx.identity.apiKey; +strOrNull = apiGwEvtReqCtx.identity.caller; +strOrNull = apiGwEvtReqCtx.identity.cognitoAuthenticationProvider; +strOrNull = apiGwEvtReqCtx.identity.cognitoAuthenticationType; +strOrNull = apiGwEvtReqCtx.identity.cognitoIdentityId; +strOrNull = apiGwEvtReqCtx.identity.cognitoIdentityPoolId; str = apiGwEvtReqCtx.identity.sourceIp; -str = apiGwEvtReqCtx.identity.user; -str = apiGwEvtReqCtx.identity.userAgent; -str = apiGwEvtReqCtx.identity.userArn; +strOrNull = apiGwEvtReqCtx.identity.user; +strOrNull = apiGwEvtReqCtx.identity.userAgent; +strOrNull = apiGwEvtReqCtx.identity.userArn; str = apiGwEvtReqCtx.stage; str = apiGwEvtReqCtx.requestId; str = apiGwEvtReqCtx.resourceId; str = apiGwEvtReqCtx.resourcePath; /* API Gateway Event */ -str = apiGwEvt.body; +strOrNull = apiGwEvt.body; str = apiGwEvt.headers["example"]; str = apiGwEvt.httpMethod; -b = apiGwEvt.isBase64Encoded; +bool = apiGwEvt.isBase64Encoded; str = apiGwEvt.path; -str = apiGwEvt.pathParameters["example"]; -str = apiGwEvt.queryStringParameters["example"]; -str = apiGwEvt.stageVariables["example"]; +str = apiGwEvt.pathParameters!["example"]; +str = apiGwEvt.queryStringParameters!["example"]; +str = apiGwEvt.stageVariables!["example"]; apiGwEvtReqCtx = apiGwEvt.requestContext; str = apiGwEvt.resource; /* API Gateway CustomAuthorizer Event */ str = customAuthorizerEvt.type; str = customAuthorizerEvt.methodArn; -str = customAuthorizerEvt.authorizationToken; -str = apiGwEvt.pathParameters["example"]; -str = apiGwEvt.queryStringParameters["example"]; -str = apiGwEvt.stageVariables["example"]; +strOrUndefined = customAuthorizerEvt.authorizationToken; +str = apiGwEvt.pathParameters!["example"]; +str = apiGwEvt.queryStringParameters!["example"]; +str = apiGwEvt.stageVariables!["example"]; apiGwEvtReqCtx = apiGwEvt.requestContext; /* DynamoDB Stream Event */ -var dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = { +const dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = { Records: [ { eventID: '1', @@ -233,17 +240,17 @@ str = snsMsgAttr.Value; /* Lambda Proxy Result */ num = proxyResult.statusCode; -proxyResult.headers["example"] = str; -proxyResult.headers["example"] = b; -proxyResult.headers["example"] = num; -b = proxyResult.isBase64Encoded; +proxyResult.headers!["example"] = str; +proxyResult.headers!["example"] = bool; +proxyResult.headers!["example"] = num; +boolOrUndefined = proxyResult.isBase64Encoded; str = proxyResult.body; /* API Gateway CustomAuthorizer AuthResponse */ authResponseContext = { stringKey: str, numberKey: num, - booleanKey: b + booleanKey: bool }; statement = { @@ -265,13 +272,13 @@ policyDocument = { authResponse = { principalId: str, - policyDocument: policyDocument, + policyDocument, context: authResponseContext }; authResponse = { principalId: str, - policyDocument: policyDocument + policyDocument, }; // CognitoUserPoolEvent @@ -290,38 +297,45 @@ cognitoUserPoolEvent.triggerSource === "CustomMessage_Authentication"; cognitoUserPoolEvent.triggerSource === "DefineAuthChallenge_Authentication"; cognitoUserPoolEvent.triggerSource === "CreateAuthChallenge_Authentication"; cognitoUserPoolEvent.triggerSource === "VerifyAuthChallengeResponse_Authentication"; +cognitoUserPoolEvent.triggerSource === "PreSignUp_AdminCreateUser"; +cognitoUserPoolEvent.triggerSource === "PostConfirmation_ConfirmForgotPassword"; +cognitoUserPoolEvent.triggerSource === "TokenGeneration_HostedAuth"; +cognitoUserPoolEvent.triggerSource === "TokenGeneration_Authentication"; +cognitoUserPoolEvent.triggerSource === "TokenGeneration_NewPasswordChallenge"; +cognitoUserPoolEvent.triggerSource === "TokenGeneration_AuthenticateDevice"; +cognitoUserPoolEvent.triggerSource === "TokenGeneration_RefreshTokens"; str = cognitoUserPoolEvent.region; str = cognitoUserPoolEvent.userPoolId; -str = cognitoUserPoolEvent.userName; +strOrUndefined = cognitoUserPoolEvent.userName; str = cognitoUserPoolEvent.callerContext.awsSdkVersion; str = cognitoUserPoolEvent.callerContext.clientId; str = cognitoUserPoolEvent.request.userAttributes["email"]; -str = cognitoUserPoolEvent.request.validationData["k1"]; -str = cognitoUserPoolEvent.request.codeParameter; -str = cognitoUserPoolEvent.request.usernameParameter; -b = cognitoUserPoolEvent.request.newDeviceUsed; -cognitoUserPoolEvent.request.session[0].challengeName === "CUSTOM_CHALLENGE"; -cognitoUserPoolEvent.request.session[0].challengeName === "PASSWORD_VERIFIER"; -cognitoUserPoolEvent.request.session[0].challengeName === "SMS_MFA"; -cognitoUserPoolEvent.request.session[0].challengeName === "DEVICE_SRP_AUTH"; -cognitoUserPoolEvent.request.session[0].challengeName === "DEVICE_PASSWORD_VERIFIER"; -cognitoUserPoolEvent.request.session[0].challengeName === "ADMIN_NO_SRP_AUTH"; -b = cognitoUserPoolEvent.request.session[0].challengeResult; -str = cognitoUserPoolEvent.request.session[0].challengeMetaData; -str = cognitoUserPoolEvent.request.challengeName; -str = cognitoUserPoolEvent.request.privateChallengeParameters["answer"]; -str = cognitoUserPoolEvent.request.challengeAnswer["answer"]; -b = cognitoUserPoolEvent.response.answerCorrect; -str = cognitoUserPoolEvent.response.smsMessage; -str = cognitoUserPoolEvent.response.emailMessage; -str = cognitoUserPoolEvent.response.emailSubject; -str = cognitoUserPoolEvent.response.challengeName; -b = cognitoUserPoolEvent.response.issueTokens; -b = cognitoUserPoolEvent.response.failAuthentication; -str = cognitoUserPoolEvent.response.publicChallengeParameters["captchaUrl"]; -str = cognitoUserPoolEvent.response.privateChallengeParameters["answer"]; -str = cognitoUserPoolEvent.response.challengeMetaData; -b = cognitoUserPoolEvent.response.answerCorrect; +str = cognitoUserPoolEvent.request.validationData!["k1"]; +strOrUndefined = cognitoUserPoolEvent.request.codeParameter; +strOrUndefined = cognitoUserPoolEvent.request.usernameParameter; +boolOrUndefined = cognitoUserPoolEvent.request.newDeviceUsed; +cognitoUserPoolEvent.request.session![0].challengeName === "CUSTOM_CHALLENGE"; +cognitoUserPoolEvent.request.session![0].challengeName === "PASSWORD_VERIFIER"; +cognitoUserPoolEvent.request.session![0].challengeName === "SMS_MFA"; +cognitoUserPoolEvent.request.session![0].challengeName === "DEVICE_SRP_AUTH"; +cognitoUserPoolEvent.request.session![0].challengeName === "DEVICE_PASSWORD_VERIFIER"; +cognitoUserPoolEvent.request.session![0].challengeName === "ADMIN_NO_SRP_AUTH"; +bool = cognitoUserPoolEvent.request.session![0].challengeResult; +strOrUndefined = cognitoUserPoolEvent.request.session![0].challengeMetaData; +strOrUndefined = cognitoUserPoolEvent.request.challengeName; +str = cognitoUserPoolEvent.request.privateChallengeParameters!["answer"]; +str = cognitoUserPoolEvent.request.challengeAnswer!["answer"]; +boolOrUndefined = cognitoUserPoolEvent.response.answerCorrect; +strOrUndefined = cognitoUserPoolEvent.response.smsMessage; +strOrUndefined = cognitoUserPoolEvent.response.emailMessage; +strOrUndefined = cognitoUserPoolEvent.response.emailSubject; +strOrUndefined = cognitoUserPoolEvent.response.challengeName; +boolOrUndefined = cognitoUserPoolEvent.response.issueTokens; +boolOrUndefined = cognitoUserPoolEvent.response.failAuthentication; +str = cognitoUserPoolEvent.response.publicChallengeParameters!["captchaUrl"]; +str = cognitoUserPoolEvent.response.privateChallengeParameters!["answer"]; +strOrUndefined = cognitoUserPoolEvent.response.challengeMetaData; +boolOrUndefined = cognitoUserPoolEvent.response.answerCorrect; // CloudFormation Custom Resource switch (cloudformationCustomResourceEvent.RequestType) { @@ -345,13 +359,22 @@ switch (cloudformationCustomResourceEvent.RequestType) { anyObj = cloudformationCustomResourceResponse.Data; str = cloudformationCustomResourceResponse.LogicalResourceId; str = cloudformationCustomResourceResponse.PhysicalResourceId; -str = cloudformationCustomResourceResponse.Reason; +strOrUndefined = cloudformationCustomResourceResponse.Reason; str = cloudformationCustomResourceResponse.RequestId; str = cloudformationCustomResourceResponse.StackId; str = cloudformationCustomResourceResponse.Status; +/* ScheduledEvent */ +str = scheduledEvent.account; +anyObj = scheduledEvent.detail; +str = scheduledEvent.id; +str = scheduledEvent.region; +str = scheduledEvent.resources[0]; +str = scheduledEvent.source; +str = scheduledEvent.time; + /* Context */ -b = context.callbackWaitsForEmptyEventLoop; +bool = context.callbackWaitsForEmptyEventLoop; str = context.functionName; str = context.functionVersion; str = context.invokedFunctionArn; @@ -359,8 +382,8 @@ num = context.memoryLimitInMB; str = context.awsRequestId; str = context.logGroupName; str = context.logStreamName; -identity = context.identity; -clientCtx = context.clientContext; +identityOrUndefined = context.identity; +clientCtxOrUndefined = context.clientContext; /* CognitoIdentity */ str = identity.cognitoIdentityId; @@ -403,7 +426,7 @@ function callback(cb: AWSLambda.Callback) { cb(null); cb(error); cb(null, anyObj); - cb(null, b); + cb(null, bool); cb(null, str); cb(null, num); } @@ -425,67 +448,67 @@ function customAuthorizerCallback(cb: AWSLambda.CustomAuthorizerCallback) { } /* CloudFront events, see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */ -var CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { - "Records": [ +const CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { + Records: [ { - "cf": { - "config": { - "distributionId": "EDFDVBD6EXAMPLE", - "requestId": "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" + cf: { + config: { + distributionId: "EDFDVBD6EXAMPLE", + requestId: "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" }, - "request": { - "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", - "method": "GET", - "uri": "/picture.jpg", - "querystring": "size=large", - "headers": { - "host": [ + request: { + clientIp: "2001:0db8:85a3:0:0:8a2e:0370:7334", + method: "GET", + uri: "/picture.jpg", + querystring: "size=large", + headers: { + host: [ { - "key": "Host", - "value": "d111111abcdef8.cloudfront.net" + key: "Host", + value: "d111111abcdef8.cloudfront.net" } ], "user-agent": [ { - "key": "User-Agent", - "value": "curl/7.51.0" + key: "User-Agent", + value: "curl/7.51.0" } ] }, - "origin": { - "custom": { - "customHeaders": { + origin: { + custom: { + customHeaders: { "my-origin-custom-header": [ { - "key": "My-Origin-Custom-Header", - "value": "Test" + key: "My-Origin-Custom-Header", + value: "Test" } ] }, - "domainName": "example.com", - "keepaliveTimeout": 5, - "path": "/custom_path", - "port": 443, - "protocol": "https", - "readTimeout": 5, - "sslProtocols": [ + domainName: "example.com", + keepaliveTimeout: 5, + path: "/custom_path", + port: 443, + protocol: "https", + readTimeout: 5, + sslProtocols: [ "TLSv1", "TLSv1.1" ] }, - "s3": { - "authMethod": "origin-access-identity", - "customHeaders": { + s3: { + authMethod: "origin-access-identity", + customHeaders: { "my-origin-custom-header": [ { - "key": "My-Origin-Custom-Header", - "value": "Test" + key: "My-Origin-Custom-Header", + value: "Test" } ] }, - "domainName": "my-bucket.s3.amazonaws.com", - "path": "/s3_path", - "region": "us-east-1" + domainName: "my-bucket.s3.amazonaws.com", + path: "/s3_path", + region: "us-east-1" } } } @@ -494,52 +517,52 @@ var CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { ] }; -var CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = { - "Records": [ +const CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = { + Records: [ { - "cf": { - "config": { - "distributionId": "EDFDVBD6EXAMPLE", - "requestId": "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE==" + cf: { + config: { + distributionId: "EDFDVBD6EXAMPLE", + requestId: "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE==" }, - "request": { - "clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334", - "method": "GET", - "uri": "/picture.jpg", - "querystring": "size=large", - "headers": { - "host": [ + request: { + clientIp: "2001:0db8:85a3:0:0:8a2e:0370:7334", + method: "GET", + uri: "/picture.jpg", + querystring: "size=large", + headers: { + host: [ { - "key": "Host", - "value": "d111111abcdef8.cloudfront.net" + key: "Host", + value: "d111111abcdef8.cloudfront.net" } ], "user-agent": [ { - "key": "User-Agent", - "value": "curl/7.18.1" + key: "User-Agent", + value: "curl/7.18.1" } ] } }, - "response": { - "status": "200", - "statusDescription": "OK", - "headers": { - "server": [ + response: { + status: "200", + statusDescription: "OK", + headers: { + server: [ { - "key": "Server", - "value": "MyCustomOrigin" + key: "Server", + value: "MyCustomOrigin" } ], "set-cookie": [ { - "key": "Set-Cookie", - "value": "theme=light" + key: "Set-Cookie", + value: "theme=light" }, { - "key": "Set-Cookie", - "value": "sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT" + key: "Set-Cookie", + value: "sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT" } ] } @@ -561,8 +584,80 @@ context.fail(str); /* Handler */ let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; + +// async methods return Promise, test assignability let asyncHandler: AWSLambda.Handler = async (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; + +let inferredHandler: AWSLambda.S3Handler = (event, context, cb) => { + // $ExpectType S3Event + event; + str = event.Records[0].eventName; + // $ExpectType Context + context; + str = context.functionName; + // $ExpectType Callback + cb; + cb(); + cb(null); + cb(new Error()); + // $ExpectError + cb(null, { }); +}; + +// Test using default Callback type still works. +let defaultCallbackHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; + +// Specific types +let s3Handler: AWSLambda.S3Handler = (event: AWSLambda.S3Event, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +// Test old name +let s3CreateHandler: AWSLambda.S3Handler = (event: AWSLambda.S3CreateEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +s3Handler = s3CreateHandler; + +let dynamoDBStreamHandler: AWSLambda.DynamoDBStreamHandler = (event: AWSLambda.DynamoDBStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; + +let snsHandler: AWSLambda.SNSHandler = (event: AWSLambda.SNSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; + +let cognitoUserPoolHandler: AWSLambda.CognitoUserPoolTriggerHandler = (event: AWSLambda.CognitoUserPoolEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; + +let cloudFormationCustomResourceHandler: AWSLambda.CloudFormationCustomResourceHandler = + (event: AWSLambda.CloudFormationCustomResourceEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; + +let cloudWatchLogsHandler: AWSLambda.CloudWatchLogsHandler = (event: AWSLambda.CloudWatchLogsEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; + +let scheduledHandler: AWSLambda.ScheduledHandler = (event: AWSLambda.ScheduledEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; + +let apiGtwProxyHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayProxyEvent, context: AWSLambda.Context, cb: AWSLambda.APIGatewayProxyCallback) => { }; +// Test old names let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { }; -let asyncProxyHandler: AWSLambda.ProxyHandler = async (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { }; +apiGtwProxyHandler = proxyHandler; + +let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { + cb(); + cb(null); + cb(new Error('')); + cb(null, { clientIp: str, method: str, uri: str, querystring: str, headers: { } }); + cb(null, { status: str }); + // $ExpectError + cb(null, { }); +}; + +let cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { }; + let customAuthorizerHandler: AWSLambda.CustomAuthorizerHandler = (event: AWSLambda.CustomAuthorizerEvent, context: AWSLambda.Context, cb: AWSLambda.CustomAuthorizerCallback) => { }; -let asyncCustomAuthorizerHandler: AWSLambda.CustomAuthorizerHandler = async (event: AWSLambda.CustomAuthorizerEvent, context: AWSLambda.Context, cb: AWSLambda.CustomAuthorizerCallback) => { }; + +interface CustomEvent { eventString: string; eventBool: boolean; } +interface CustomResult { resultString: string; resultBool?: boolean; } +type CustomCallback = AWSLambda.Callback; +let customHandler: AWSLambda.Handler = (event, context, cb) => { + // $ExpectType CustomEvent + event; + str = event.eventString; + bool = event.eventBool; + // $ExpectType Context + context; + // $ExpectType Callback + cb; + cb(null, { resultString: str, resultBool: bool }); + // $ExpectError + cb(null, { resultString: bool }); +}; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 320cf562f8..eccc96ba3e 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -12,14 +12,18 @@ // Daniel Cottone // Kostya Misura // Markus Tacker +// Palmi Valgeirsson +// Danilo Raisi +// Simon Buchan +// David Hayden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 // API Gateway "event" request context -interface APIGatewayEventRequestContext { +export interface APIGatewayEventRequestContext { accountId: string; apiId: string; - authorizer?: AuthResponseContext | null | undefined; + authorizer?: AuthResponseContext | null; httpMethod: string; identity: { accessKey: string | null; @@ -34,15 +38,16 @@ interface APIGatewayEventRequestContext { user: string | null; userAgent: string | null; userArn: string | null; - }, + }; stage: string; requestId: string; + requestTimeEpoch: number; resourceId: string; resourcePath: string; } // API Gateway "event" -interface APIGatewayEvent { +export interface APIGatewayProxyEvent { body: string | null; headers: { [name: string]: string }; httpMethod: string; @@ -54,9 +59,10 @@ interface APIGatewayEvent { requestContext: APIGatewayEventRequestContext; resource: string; } +export type APIGatewayEvent = APIGatewayProxyEvent; // Old name // API Gateway CustomAuthorizer "event" -interface CustomAuthorizerEvent { +export interface CustomAuthorizerEvent { type: string; methodArn: string; authorizationToken?: string; @@ -68,22 +74,22 @@ interface CustomAuthorizerEvent { // Context // http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_AttributeValue.html -interface AttributeValue { +export interface AttributeValue { B?: string; - BS?: Array; + BS?: string[]; BOOL?: boolean; - L?: Array; + L?: AttributeValue[]; M?: { [id: string]: AttributeValue }; N?: string; - NS?: Array; + NS?: string[]; NULL?: boolean; S?: string; - SS?: Array; + SS?: string[]; } // Context // http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_StreamRecord.html -interface StreamRecord { +export interface StreamRecord { ApproximateCreationTime?: number; Keys?: { [key: string]: AttributeValue }; NewImage?: { [key: string]: AttributeValue }; @@ -95,7 +101,7 @@ interface StreamRecord { // Context // http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_Record.html -interface DynamoDBRecord { +export interface DynamoDBRecord { awsRegion?: string; dynamodb?: StreamRecord; eventID?: string; @@ -109,21 +115,21 @@ interface DynamoDBRecord { // AWS Lambda Stream event // Context // http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ddb-update -interface DynamoDBStreamEvent { - Records: Array; +export interface DynamoDBStreamEvent { + Records: DynamoDBRecord[]; } // SNS "event" -interface SNSMessageAttribute { +export interface SNSMessageAttribute { Type: string; Value: string; } -interface SNSMessageAttributes { +export interface SNSMessageAttributes { [name: string]: SNSMessageAttribute; } -interface SNSMessage { +export interface SNSMessage { SignatureVersion: string; Timestamp: string; Signature: string; @@ -137,37 +143,37 @@ interface SNSMessage { Subject: string; } -interface SNSEventRecord { +export interface SNSEventRecord { EventVersion: string; EventSubscriptionArn: string; EventSource: string; Sns: SNSMessage; } -interface SNSEvent { - Records: Array; +export interface SNSEvent { + Records: SNSEventRecord[]; } /** * S3Create event * https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html */ -interface S3EventRecord { +export interface S3EventRecord { eventVersion: string; eventSource: string; - awsRegion: string + awsRegion: string; eventTime: string; eventName: string; userIdentity: { principalId: string; - }, + }; requestParameters: { sourceIPAddress: string; - }, + }; responseElements: { 'x-amz-request-id': string; 'x-amz-id-2': string; - }, + }; s3: { s3SchemaVersion: string; configurationId: string; @@ -185,20 +191,42 @@ interface S3EventRecord { versionId: string; sequencer: string; } - } + }; } -interface S3CreateEvent { - Records: Array; +export interface S3Event { + Records: S3EventRecord[]; } +export type S3CreateEvent = S3Event; // old name /** * Cognito User Pool event * http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html */ -interface CognitoUserPoolEvent { +export interface CognitoUserPoolTriggerEvent { version: number; - triggerSource: "PreSignUp_SignUp" | "PostConfirmation_ConfirmSignUp" | "PreAuthentication_Authentication" | "PostAuthentication_Authentication" | "CustomMessage_SignUp" | "CustomMessage_AdminCreateUser" | "CustomMessage_ResendCode" | "CustomMessage_ForgotPassword" | "CustomMessage_UpdateUserAttribute" | "CustomMessage_VerifyUserAttribute" | "CustomMessage_Authentication" | "DefineAuthChallenge_Authentication" | "CreateAuthChallenge_Authentication" | "VerifyAuthChallengeResponse_Authentication"; + triggerSource: + | "PreSignUp_SignUp" + | "PostConfirmation_ConfirmSignUp" + | "PreAuthentication_Authentication" + | "PostAuthentication_Authentication" + | "CustomMessage_SignUp" + | "CustomMessage_AdminCreateUser" + | "CustomMessage_ResendCode" + | "CustomMessage_ForgotPassword" + | "CustomMessage_UpdateUserAttribute" + | "CustomMessage_VerifyUserAttribute" + | "CustomMessage_Authentication" + | "DefineAuthChallenge_Authentication" + | "CreateAuthChallenge_Authentication" + | "VerifyAuthChallengeResponse_Authentication" + | "PreSignUp_AdminCreateUser" + | "PostConfirmation_ConfirmForgotPassword" + | "TokenGeneration_HostedAuth" + | "TokenGeneration_Authentication" + | "TokenGeneration_NewPasswordChallenge" + | "TokenGeneration_AuthenticateDevice" + | "TokenGeneration_RefreshTokens"; region: string; userPoolId: string; userName?: string; @@ -212,11 +240,11 @@ interface CognitoUserPoolEvent { codeParameter?: string; usernameParameter?: string; newDeviceUsed?: boolean; - session?: { + session?: Array<{ challengeName: "CUSTOM_CHALLENGE" | "PASSWORD_VERIFIER" | "SMS_MFA" | "DEVICE_SRP_AUTH" | "DEVICE_PASSWORD_VERIFIER" | "ADMIN_NO_SRP_AUTH"; challengeResult: boolean; challengeMetaData?: string; - }[]; + }>; challengeName?: string; privateChallengeParameters?: {[key: string]: string}; challengeAnswer?: {[key: string]: string}; @@ -235,12 +263,13 @@ interface CognitoUserPoolEvent { answerCorrect?: boolean; }; } +export type CognitoUserPoolEvent = CognitoUserPoolTriggerEvent; /** * CloudFormation Custom Resource event and response * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref.html */ -type CloudFormationCustomResourceEventCommon = { +export interface CloudFormationCustomResourceEventCommon { ServiceToken: string; ResponseURL: string; StackId: string; @@ -250,14 +279,14 @@ type CloudFormationCustomResourceEventCommon = { ResourceProperties: { ServiceToken: string; [Key: string]: any; - } + }; } -type CloudFormationCustomResourceCreateEvent = CloudFormationCustomResourceEventCommon & { +export interface CloudFormationCustomResourceCreateEvent extends CloudFormationCustomResourceEventCommon { RequestType: "Create"; } -type CloudFormationCustomResourceUpdateEvent = CloudFormationCustomResourceEventCommon & { +export interface CloudFormationCustomResourceUpdateEvent extends CloudFormationCustomResourceEventCommon { RequestType: "Update"; PhysicalResourceId: string; OldResourceProperties: { @@ -265,47 +294,61 @@ type CloudFormationCustomResourceUpdateEvent = CloudFormationCustomResourceEvent }; } -type CloudFormationCustomResourceDeleteEvent = CloudFormationCustomResourceEventCommon & { +export interface CloudFormationCustomResourceDeleteEvent extends CloudFormationCustomResourceEventCommon { RequestType: "Delete"; PhysicalResourceId: string; } export type CloudFormationCustomResourceEvent = CloudFormationCustomResourceCreateEvent | CloudFormationCustomResourceUpdateEvent | CloudFormationCustomResourceDeleteEvent; -type CloudFormationCustomResourceResponseCommon = { +export interface CloudFormationCustomResourceResponseCommon { PhysicalResourceId: string; StackId: string; RequestId: string; LogicalResourceId: string; Data?: { [Key: string]: any; - } + }; } -type CloudFormationCustomResourceSuccessResponse = CloudFormationCustomResourceResponseCommon & { +export interface CloudFormationCustomResourceSuccessResponse extends CloudFormationCustomResourceResponseCommon { Status: "SUCCESS"; Reason?: string; } -type CloudFormationCustomResourceFailedResponse = CloudFormationCustomResourceResponseCommon & { +export interface CloudFormationCustomResourceFailedResponse extends CloudFormationCustomResourceResponseCommon { Status: "FAILED"; Reason: string; } export type CloudFormationCustomResourceResponse = CloudFormationCustomResourceSuccessResponse | CloudFormationCustomResourceFailedResponse; +/** + * See https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-scheduled-event + */ +export interface ScheduledEvent { + account: string; + region: string; + detail: any; + "detail-type": string; + source: string; + time: string; + id: string; + resources: string[]; +} + /** * See http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-cloudwatch-logs */ -interface CloudWatchLogsEvent { +export interface CloudWatchLogsEvent { awslogs: CloudWatchLogsEventData; } -interface CloudWatchLogsEventData { +export interface CloudWatchLogsEventData { data: string; } -interface CloudWatchLogsDecodedData { +export interface CloudWatchLogsDecodedData { owner: string; logGroup: string; logStream: string; @@ -317,17 +360,15 @@ interface CloudWatchLogsDecodedData { /** * See http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html#LambdaFunctionExample */ -interface CloudWatchLogsLogEvent { +export interface CloudWatchLogsLogEvent { id: string; timestamp: number; message: string; } - - // Context // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html -interface Context { +export interface Context { // Properties callbackWaitsForEmptyEventLoop: boolean; functionName: string; @@ -346,25 +387,23 @@ interface Context { // Functions for compatibility with earlier Node.js Runtime v0.10.42 // For more details see http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-using-old-runtime.html#nodejs-prog-model-oldruntime-context-methods done(error?: Error, result?: any): void; - fail(error: Error): void; - fail(message: string): void; - succeed(message: string): void; - succeed(object: any): void; + fail(error: Error | string): void; + succeed(messageOrObject: any): void; succeed(message: string, object: any): void; } -interface CognitoIdentity { +export interface CognitoIdentity { cognitoIdentityId: string; cognitoIdentityPoolId: string; } -interface ClientContext { +export interface ClientContext { client: ClientContextClient; Custom?: any; env: ClientContextEnv; } -interface ClientContextClient { +export interface ClientContextClient { installationId: string; appTitle: string; appVersionName: string; @@ -372,7 +411,7 @@ interface ClientContextClient { appPackageName: string; } -interface ClientContextEnv { +export interface ClientContextEnv { platformVersion: string; platform: string; make: string; @@ -380,30 +419,32 @@ interface ClientContextEnv { locale: string; } -interface ProxyResult { +export interface APIGatewayProxyResult { statusCode: number; headers?: { [header: string]: boolean | number | string; - }, + }; body: string; isBase64Encoded?: boolean; } +export type ProxyResult = APIGatewayProxyResult; // Old name /** * API Gateway CustomAuthorizer AuthResponse. * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output */ -interface AuthResponse { +export interface CustomAuthorizerResult { principalId: string; policyDocument: PolicyDocument; context?: AuthResponseContext; } +export type AuthResponse = CustomAuthorizerResult; /** * API Gateway CustomAuthorizer AuthResponse.PolicyDocument. * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output */ -interface PolicyDocument { +export interface PolicyDocument { Version: string; Statement: [Statement]; } @@ -412,7 +453,7 @@ interface PolicyDocument { * API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement. * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output */ -interface Statement { +export interface Statement { Action: string | string[]; Effect: string; Resource: string | string[]; @@ -422,58 +463,71 @@ interface Statement { * API Gateway CustomAuthorizer AuthResponse.PolicyDocument.Statement. * http://docs.aws.amazon.com/apigateway/latest/developerguide/use-custom-authorizer.html#api-gateway-custom-authorizer-output */ -interface AuthResponseContext { - [name: string]: string | number | boolean; +export interface AuthResponseContext { + [name: string]: any; } /** * CloudFront events * http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */ -type CloudFrontHeaders = { - [name: string]: { - key: string; - value: string; - }[] -}; +export interface CloudFrontHeaders { + [name: string]: Array<{ + key: string; + value: string; + }>; +} -type CloudFrontResponse = { +export interface CloudFrontResponse { status: string; statusDescription: string; headers: CloudFrontHeaders; -}; +} -type CloudFrontRequest = { +export interface CloudFrontRequest { clientIp: string; method: string; uri: string; querystring: string; headers: CloudFrontHeaders; -}; +} -type CloudFrontEvent = { +export interface CloudFrontEvent { config: { distributionId: string; requestId: string; - } + }; } -export type CloudFrontResponseEvent = { - Records: { +// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-generating-http-responses.html#lambda-generating-http-responses-object +export interface CloudFrontResultResponse { + status: string; + statusDescription?: string; + headers?: CloudFrontHeaders; + bodyEncoding?: 'text' | 'base64'; + body?: string; +} + +export interface CloudFrontResponseEvent { + Records: Array<{ cf: CloudFrontEvent & { request: CloudFrontRequest; response: CloudFrontResponse; } - }[] -}; + }>; +} -export type CloudFrontRequestEvent = { - Records: { +export type CloudFrontRequestResult = undefined | null | CloudFrontResultResponse | CloudFrontRequest; + +export interface CloudFrontRequestEvent { + Records: Array<{ cf: CloudFrontEvent & { request: CloudFrontRequest; } - }[] -}; + }>; +} + +export type CloudFrontResponseResult = undefined | null | CloudFrontResultResponse; /** * AWS Lambda handler function. @@ -483,9 +537,7 @@ export type CloudFrontRequestEvent = { * @param context – runtime information of the Lambda function that is executing. * @param callback – optional callback to return information to the caller, otherwise return value is null. */ -export type Handler = (event: any, context: Context, callback?: Callback) => Promise | void; -export type ProxyHandler = (event: APIGatewayEvent, context: Context, callback?: ProxyCallback) => Promise | void; -export type CustomAuthorizerHandler = (event: CustomAuthorizerEvent, context: Context, callback?: CustomAuthorizerCallback) => Promise | void; +export type Handler = (event: TEvent, context: Context, callback: Callback) => void; /** * Optional callback parameter. @@ -494,8 +546,58 @@ export type CustomAuthorizerHandler = (event: CustomAuthorizerEvent, context: Co * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. */ -export type Callback = (error?: Error | null, result?: object | boolean | number | string) => void; -export type ProxyCallback = (error?: Error | null, result?: ProxyResult) => void; -export type CustomAuthorizerCallback = (error?: Error | null, result?: AuthResponse) => void; +export type Callback = (error?: Error | null, result?: TResult) => void; + +// Begin defining Handler and Callback types for each API trigger type. +// Ordered by https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html +// though that list is incomplete. + +export type S3Handler = Handler; + +export type DynamoDBStreamHandler = Handler; + +export type SNSHandler = Handler; + +// No SESHandler: SES event source is delivered as SNS notifications +// https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html#supported-event-source-ses + +// Result type is weird: docs and samples say to return the mutated event, but it only requires an object +// with a "response" field, the type of which is specific to the event.triggerType. Leave as any for now. +export type CognitoUserPoolTriggerHandler = Handler; +// TODO: Different event/handler types for each event trigger so we can type the result? + +// TODO: CognitoSync + +export type CloudFormationCustomResourceHandler = Handler; + +// TODO: CloudWatchEvents + +export type CloudWatchLogsHandler = Handler; + +// TODO: CodeCommit + +export type ScheduledHandler = Handler; + +// TODO: AWS Config + +// TODO: Alexa + +export type APIGatewayProxyHandler = Handler; +export type APIGatewayProxyCallback = Callback; +export type ProxyHandler = APIGatewayProxyHandler; // Old name +export type ProxyCallback = APIGatewayProxyCallback; // Old name + +// TODO: IoT + +export type CloudFrontRequestHandler = Handler; +export type CloudFrontRequestCallback = Callback; + +export type CloudFrontResponseHandler = Handler; +export type CloudFrontResponseCallback = Callback; + +// TODO: Kinesis (should be very close to DynamoDB stream?) + +export type CustomAuthorizerHandler = Handler; +export type CustomAuthorizerCallback = Callback; export as namespace AWSLambda; diff --git a/types/aws-lambda/tsconfig.json b/types/aws-lambda/tsconfig.json index f4f2cc28f6..79e058b7ab 100644 --- a/types/aws-lambda/tsconfig.json +++ b/types/aws-lambda/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/aws-lambda/tslint.json b/types/aws-lambda/tslint.json index a41bf5d19a..bafaae7817 100644 --- a/types/aws-lambda/tslint.json +++ b/types/aws-lambda/tslint.json @@ -1,79 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-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 + // TODO + "dt-header": false } } diff --git a/types/aws-serverless-express/aws-serverless-express-tests.ts b/types/aws-serverless-express/aws-serverless-express-tests.ts index 4770163b3b..9bfd1b0e99 100644 --- a/types/aws-serverless-express/aws-serverless-express-tests.ts +++ b/types/aws-serverless-express/aws-serverless-express-tests.ts @@ -1,5 +1,5 @@ import * as awsServerlessExpress from 'aws-serverless-express'; -import * as express from 'express'; +import express = require('express'); import { eventContext } from 'aws-serverless-express/middleware'; const app = express(); diff --git a/types/azure-sb/tsconfig.json b/types/azure-sb/tsconfig.json index 09c9a2a9e4..6e015480dc 100644 --- a/types/azure-sb/tsconfig.json +++ b/types/azure-sb/tsconfig.json @@ -38,5 +38,4 @@ "azure-sb-tests.ts", "index.d.ts" ] -} - +} \ No newline at end of file diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index cbed3e076c..b1de338923 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -422,7 +422,7 @@ export interface ExportNamedDeclaration extends Node { type: "ExportNamedDeclaration"; declaration: Declaration; specifiers: ExportSpecifier[]; - source: StringLiteral; + source: StringLiteral | null; } export interface ExportSpecifier extends Node { diff --git a/types/babel-webpack-plugin/tsconfig.json b/types/babel-webpack-plugin/tsconfig.json index 3e73343283..b7aadac43d 100644 --- a/types/babel-webpack-plugin/tsconfig.json +++ b/types/babel-webpack-plugin/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "babel-webpack-plugin-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/babel__code-frame/babel__code-frame-tests.ts b/types/babel__code-frame/babel__code-frame-tests.ts new file mode 100644 index 0000000000..380134532e --- /dev/null +++ b/types/babel__code-frame/babel__code-frame-tests.ts @@ -0,0 +1,26 @@ +import codeFrame, { codeFrameColumns } from "@babel/code-frame"; + +const code = ` + const number = 1; + var string = 'foo'; + + function print(name: string) { + console.log(string + name); + } +`; + +codeFrame(code, 5, 22); +codeFrame(code, 5, 22, { forceColor: true }); +codeFrame(code, 2, 2, { highlightCode: true }); + +codeFrameColumns(code, { start: { line: 5, column: 22 } }); +codeFrameColumns( + code, + { start: { line: 5, column: 22 } }, + { forceColor: true } +); +codeFrameColumns( + code, + { start: { line: 2, column: 2 } }, + { highlightCode: true } +); diff --git a/types/babel__code-frame/index.d.ts b/types/babel__code-frame/index.d.ts new file mode 100644 index 0000000000..5a32040bb2 --- /dev/null +++ b/types/babel__code-frame/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for @babel/code-frame 7.0 +// Project: https://github.com/babel/babel/tree/master/packages/babel-code-frame +// Definitions by: Mohsen Azimi +// Forbes Lindesay +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface SourceLocation { + start: { line: number; column?: number }; + end?: { line: number; column?: number }; +} +export function codeFrameColumns( + rawLines: string, + location: SourceLocation, + options?: BabelCodeFrameOptions +): string; + +export interface BabelCodeFrameOptions { + /** Syntax highlight the code as JavaScript for terminals. default: false */ + highlightCode?: boolean; + /** The number of lines to show above the error. default: 2 */ + linesAbove?: number; + /** The number of lines to show below the error. default: 3 */ + linesBelow?: number; + /** + * Forcibly syntax highlight the code as JavaScript (for non-terminals); + * overrides highlightCode. + * default: false + */ + forceColor?: boolean; + /** + * Pass in a string to be displayed inline (if possible) next to the + * highlighted location in the code. If it can't be positioned inline, + * it will be placed above the code frame. + * default: nothing + */ + message?: string; +} + +/** + * Generate errors that contain a code frame that point to source locations. + * + * @param rawLines Raw lines to frame + * @param lineNumber Line number (1 indexed) + * @param colNumber Column number + * @param options Additional options + * + * @returns Framed code + */ +export default function codeFrame( + rawLines: string, + lineNumber: number, + colNumber: number, + options?: BabelCodeFrameOptions +): string; diff --git a/types/babel__code-frame/tsconfig.json b/types/babel__code-frame/tsconfig.json new file mode 100644 index 0000000000..49bd833b58 --- /dev/null +++ b/types/babel__code-frame/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@babel/code-frame": ["babel__code-frame"] + } + }, + "files": ["index.d.ts", "babel__code-frame-tests.ts"] +} diff --git a/types/xhr-mock/tslint.json b/types/babel__code-frame/tslint.json similarity index 100% rename from types/xhr-mock/tslint.json rename to types/babel__code-frame/tslint.json diff --git a/types/base64topdf/base64topdf-tests.ts b/types/base64topdf/base64topdf-tests.ts new file mode 100644 index 0000000000..109ec5fbff --- /dev/null +++ b/types/base64topdf/base64topdf-tests.ts @@ -0,0 +1,8 @@ +import * as base64topdf from 'base64topdf'; + +base64topdf.base64Encode('index.ts'); // $ExpectType void +base64topdf.base64Decode('decodethis', 'test.b64'); // $ExpectType void +base64topdf.rtfToText('rtf'); // $ExpectType string +base64topdf.textToRtf('text'); // $ExpectType string +base64topdf.strToBase64('str'); // $ExpectType string +base64topdf.base64ToStr('base64'); // $ExpectType string diff --git a/types/base64topdf/index.d.ts b/types/base64topdf/index.d.ts new file mode 100644 index 0000000000..97f9af7077 --- /dev/null +++ b/types/base64topdf/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for base64topdf 1.1 +// Project: https://github.com/rpsankar001 +// Definitions by: Lucas Riondel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace base64topdf; + +export function base64Encode(file: string): void; +export function base64Decode(base64str: string, file: string): void; +export function rtfToText(rtfStr: string): string; +export function textToRtf(textStr: string): string; +export function strToBase64(str: string): string; +export function base64ToStr(base64Str: string): string; diff --git a/types/base64topdf/tsconfig.json b/types/base64topdf/tsconfig.json new file mode 100644 index 0000000000..29fb459eb9 --- /dev/null +++ b/types/base64topdf/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", + "base64topdf-tests.ts" + ] +} diff --git a/types/base64topdf/tslint.json b/types/base64topdf/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/base64topdf/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bash-glob/tsconfig.json b/types/bash-glob/tsconfig.json index 6a45a2d74d..d62dc6e114 100644 --- a/types/bash-glob/tsconfig.json +++ b/types/bash-glob/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "bash-glob-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/beats/tsconfig.json b/types/beats/tsconfig.json index 89bd0b5995..7b360083c1 100644 --- a/types/beats/tsconfig.json +++ b/types/beats/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "beats-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/bech32/tsconfig.json b/types/bech32/tsconfig.json index 886ec79796..501b2438b2 100644 --- a/types/bech32/tsconfig.json +++ b/types/bech32/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "bech32-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts index 43d78e1503..34ee6808c3 100644 --- a/types/better-sqlite3/better-sqlite3-tests.ts +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -1,4 +1,4 @@ -import * as Database from 'better-sqlite3'; +import Database = require('better-sqlite3'); const integer = Database.Integer(1); const err = new Database.SqliteError('ok', 'ok'); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts index 530f5c3e53..899a85a2e2 100644 --- a/types/better-sqlite3/index.d.ts +++ b/types/better-sqlite3/index.d.ts @@ -4,9 +4,7 @@ // Mathew Rumsey // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -import * as Integer from 'integer'; +import Integer = require('integer'); interface RunResult { changes: number; diff --git a/types/big.js/index.d.ts b/types/big.js/index.d.ts index 37f51a54bd..405622f7ee 100644 --- a/types/big.js/index.d.ts +++ b/types/big.js/index.d.ts @@ -295,6 +295,7 @@ export const Big: BigConstructor; export type Big_ = Big; export type BigConstructor_ = BigConstructor; export type BigSource_ = BigSource; +export default Big; declare global { namespace BigJs { diff --git a/types/big.js/test/big.js-import-default-tests.ts b/types/big.js/test/big.js-import-default-tests.ts new file mode 100644 index 0000000000..52841986be --- /dev/null +++ b/types/big.js/test/big.js-import-default-tests.ts @@ -0,0 +1,12 @@ +/* + + This file contains tests for the named export definitions of big.js. + Import the default Big constructor from 'big.js' + +*/ + +import Big from 'big.js'; + +function constructorTests() { + const x = new Big(9); // '9' +} diff --git a/types/big.js/tsconfig.json b/types/big.js/tsconfig.json index 950e8b410f..20fae3a55f 100644 --- a/types/big.js/tsconfig.json +++ b/types/big.js/tsconfig.json @@ -19,6 +19,7 @@ "files": [ "index.d.ts", "test/big.js-module-tests.ts", - "test/big.js-global-tests.ts" + "test/big.js-global-tests.ts", + "test/big.js-import-default-tests.ts" ] } \ No newline at end of file diff --git a/types/big.js/tslint.json b/types/big.js/tslint.json index f93cf8562a..3224b40b8b 100644 --- a/types/big.js/tslint.json +++ b/types/big.js/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-const-enum": false + } } diff --git a/types/binary-parser/tsconfig.json b/types/binary-parser/tsconfig.json index cb361f52c5..5e720245df 100644 --- a/types/binary-parser/tsconfig.json +++ b/types/binary-parser/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "binary-parser-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/bindings/tsconfig.json b/types/bindings/tsconfig.json index fb9350642a..787b28c3d0 100644 --- a/types/bindings/tsconfig.json +++ b/types/bindings/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "bindings-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/bingmaps/Autosuggest.d.ts b/types/bingmaps/Autosuggest.d.ts deleted file mode 100644 index 7d83ca6e4b..0000000000 --- a/types/bingmaps/Autosuggest.d.ts +++ /dev/null @@ -1,112 +0,0 @@ -declare module Microsoft.Maps { - /** Options used to customize the autosuggest functionality. */ - export interface IAutosuggestOptions { - /** Specifies if street address suggestions should be returned. Default: true */ - addressSuggestions?: boolean; - - /** - * Specifies if the user’s location should be auto detected using their IP address, if no location information is provided - * in the userLocation property. Default: true - */ - autoDetectLocation?: boolean; - - /** - * A bounding box that is used to help influence the results such that locations that are in or near this bounding box - * are given more weight than they would normally. - */ - bounds?: LocationRect; - - /** - * A reference to a map instance. If the useMapView property is set to true, the bounding box of the map view will be used - * to influence the weight of suggestions. - */ - map?: Map; - - /** The maximum number of results to return. Can be any value between 1 and 10. Default: 5 */ - maxResults?: number; - - /** Specifies if place suggestions (city, landmark, etc.) should be returned. Default: true */ - placeSuggestions?: boolean; - - /** - * Indicates if the maps bounding box should be used to influence the suggested results. Ignored if the bounds property is - * set. Default: true - */ - useMapView?: boolean; - - /** A coordinate indicating where the user is located. This will influence the results to be more relevant to the user. */ - userLocation?: Location; - } - - /** Represents the suggestion result from the Autosuggest manager. */ - export interface ISuggestionResult { - /** A structured address object for the result. */ - address: IAddress; - - /** A LocationRect that can be used to set the map view over the result. */ - bestView: LocationRect; - - /** Unique entity id to be used for searching the entity. */ - entityId: string; - - /** The type of the result; Address, Place */ - entityType: string; - - /** The sub type of result; Address, RoadBlock, PopulatedPlace, CountryRegion, etc. */ - entitySubType: string; - - /** A nicely formatted suggestion string for the result based on market. */ - formattedSuggestion: string; - - /** - * The coordinate of the result. This value is only returned for place (city, landmarks) results and not for addresses. - * Street addresses will need to be geocoded to get their location. - */ - location: Location; - - /** A secondary title that provides additional context to the title value of the suggestion. **/ - subtitle: string; - - /** The display title for the result (i.e. “Redmond”). */ - title: string; - } - - /** - * The AutosuggestManager is the primary class in the Autosuggest module that powers the autosuggest functionality. - * @requires The Microsoft.Maps.Autosuggest module. - */ - export class AutosuggestManager { - /** - * @constructor - * @requires The Microsoft.Maps.Autosuggest module. - * @param options The options to use with the autosuggest manager. - */ - constructor(options?: IAutosuggestOptions); - - /** - * Attaches the Autosuggest functionality to an input box. - * @param suggestionBoxId The HTML element identifier of the input box. - * @param suggestionContainerId The Id of container where suggestions will be displayed. - * @param selectedSuggestionCallback A reference to a callback function that will be called when a user selects a suggestion from the Autosuggest UI. - */ - public attachAutosuggest(suggestionBoxId: string, suggestionContainerId: string, selectedSuggestionCallback: (result: ISuggestionResult) => void) : void; - - /** Detaches the autosuggest functionality from the input box, freeing any resources it has or events it has tied to. */ - public detachAutosuggest(): void; - - /** Disposes the Autosuggest object, freeing any resources it has or events it has tied to. */ - public dispose(): void; - - /** - * Gets the options currently used by the autosuggest manager. - * @returns The options currently used by the autosuggest manager. - */ - public getOptions(): IAutosuggestOptions; - - /** - * Sets the options currently used by the autosuggest manager. - * @param options The options to use with the autosuggest manager. - */ - public setOptions(options?: IAutosuggestOptions): void; - } -} \ No newline at end of file diff --git a/types/bingmaps/Clustering.d.ts b/types/bingmaps/Clustering.d.ts deleted file mode 100644 index 17c9425933..0000000000 --- a/types/bingmaps/Clustering.d.ts +++ /dev/null @@ -1,142 +0,0 @@ -declare module Microsoft.Maps { - /** The options used to customize how the ClusterLayer functions. */ - export interface IClusterLayerOptions { - /** - * A callback function that is fired after the clustering for a map view has completed. This is useful if you want to generate a list of locations based on what is in the current view. - */ - callback?: () => void; - - /** - * A callback function that allows you to process a clustered pushpin before it is added to a layer. This is useful if you want to add events or set style options on the clustered pushpin. - */ - clusteredPinCallback?: (pin: ClusterPushpin) => void; - - /** - * Indicates if the layer should cluster the locations or not. Default: true - */ - clusteringEnabled?: boolean; - - /** - * Defines how clusters are positioned on the map. Default: MeanAverage - */ - clusterPlacementType?: ClusterPlacementType; - - /** - * The width and height of the gird cells used for clustering in pixels. Default: 45 - */ - gridSize?: number; - - /** - * Offsets the placement of clustered pushpins by a set number of pixels. This option is only available when the placement type is set to GridCenter. - * This is useful if you have multiple cluster layers on the map and you want to offset the clustered pushpins between the layers so that they are visible, - * otherwise the clusters from the different layers would overlap completely. - */ - layerOffset?: Point; - - /** - * A boolean indicating if the layer is visible or not. - */ - visible?: boolean; - - /** - * The z-index of the layer. - */ - zIndex?: number; - } - - /** - * Used to specify how a clustered pushpin should be positioned relative to the pushpins it contains. - * @requires The Microsoft.Maps.Clustering module. - */ - export enum ClusterPlacementType { - /** - * Mean Average placement calculates the average position of a group of coordinates. This method creates a more realistic representation of the data, - * however requires more processing power and increases the chances of pushpins overlapping. - */ - MeanAverage, - - /** - * This method is the simplest way to represent a cluster. It places the cluster at the first location in the cluster. This method may not accurately - * represent the data but requires little processing power. - */ - FirstLocation - } - - /** - * This class extends the Pushpin class and has all the same methods and properties plus the following properties. - * @requires The Microsoft.Maps.Clustering module. - */ - export class ClusterPushpin extends Pushpin { - /** An array of all the pushpins that are in the cluster. */ - containedPushpins: Pushpin[]; - - /** - * The grid cell key that can be used retrieve the clustered pushpin(s) from the clustering layer. This is useful when creating a clickable list that - * link items in the list to clusters or pushpins on the map. Your list just needs to store the gridKey value. - */ - gridKey: number; - } - - /** - * This class allows you to easily add in client side clustering to your application. Client Side Clustering is a method where pushpins that are close - * together are grouped and represented as a single pushpin, often using a different icon to indicate the cluster. This is a great way to improve both - * the user experience and performance of the map. - * @requires The Microsoft.Maps.Clustering module. - */ - export class ClusterLayer implements IDataLayer { - /** - * @constructor - * @requires The Microsoft.Maps.Clustering module. - * @param pushpins An array of pushpins to cluster in the layer. - * @param options The options used to customize how the ClusterLayer functions. - */ - constructor(pushpins: Pushpin[], options?: IClusterLayerOptions); - - /** Clears all the data in the cluster layer. */ - public clear(): void; - - /** - * Gets all the pushpins that are in the current map view. If clustering is disabled, all pushpins in the clustering layer are returned. - * @returns All the pushpins that are in the current map view. If clustering is disabled, all pushpins in the clustering layer are returned. - */ - public getDisplayedPushpins(): Pushpin[]; - - /** - * Gets the current options used by the cluster layer. - * @returns The current options used by the cluster layer. - */ - public getOptions(): IClusterLayerOptions; - - /** - * Gets all pushpins that are in the layers. - * @returns An array of all the pushpins that are in the layers. - */ - public getPushpins(): Pushpin[]; - - /** - * Gets the original pushpins that are in the specified grid cell. - * @param The gridKey index to retrieve the pushpins for. - * @returns The original pushpins that are in the specified grid cell. - */ - public getPushpinsByGridKey(gridKey: number): Pushpin[]; - - /** - * Gets the pushpin in the specified cluster grid cell which can be either a ClusterPushpin if there are multiple pushpins in a cell or a single Pushpin. - * @param The gridKey index to retrieve the pushpins for. - * @returns The pushpin in the specified cluster grid cell which can be either a ClusterPushpin if there are multiple pushpins in a cell or a single Pushpin. - */ - public getClusterPushpinByGridKey(gridKey: number): ClusterPushpin | Pushpin; - - /** - * Sets the clustering options to use in the layer. - * @params options The clustering options to use in the layer. - */ - public setOptions(options: IClusterLayerOptions): void; - - /** - * Sets the array of pushpins that are used in the clustering layer. - * @param pushpins An array of pushpins that are to be used by the clustering layer. - */ - public setPushpins(pushpins: Pushpin[]): void; - } -} \ No newline at end of file diff --git a/types/bingmaps/Contour.d.ts b/types/bingmaps/Contour.d.ts deleted file mode 100644 index cd2d9767c7..0000000000 --- a/types/bingmaps/Contour.d.ts +++ /dev/null @@ -1,87 +0,0 @@ -declare module Microsoft.Maps { - - /** - * The contour layer options - */ - interface IContourLayerOptions { - /** The z-index of this layer */ - zIndex?: number; - - /** Whether the layer is visible */ - visible?: boolean; - - /** A callback function which defines the color of the contour line fill. */ - colorCallback?: (contourValue: number | string) => string | Color; - - /** The polygon options that apply to all contour lines of this layer */ - polygonOptions?: IPolygonOptions; - } - - /** - * The contour line of a contour layer - */ - export class ContourLine extends Polygon { - /** The contour lines that are directly nested inside this contour line */ - public innerContourLines: ContourLine[]; - - /** The outer/parent contour line of this contour */ - public outerContourLine: ContourLine; - - /** The data value associated with this contour line */ - public contourValue: number | string; - - /** - * @constructor - * @param boundary The boundary of this contour line - * @param contourValue The value associated with this contour line - */ - constructor(boundary: Location[], contourValue?: number | string); - } - - /** - * The contour layer class. - */ - export class ContourLayer extends Layer { - /** - * @constructor - * @param contourLines The contour lines that compose this layer. - * @param options The contour layer options. - */ - constructor(contourLines: ContourLine[], options?: IContourLayerOptions); - - /** - * Clears all data on the contour layer. - */ - public clear(): void; - - /** - * Gets the contour lines of this layer. - * @returns The contour lines of this layer. - */ - public getContourLines(): ContourLine[]; - - /** - * Gets the polygons that were generated from the contour lines in this layer. - * @returns The polygons that were generated from the contour lines in this layer. - */ - public getContourPolygons(): Polygon[]; - - /** - * Retrieves the options of this contour layer. - * @returns The options of this contour layer. - */ - public getOptions(): IContourLayerOptions; - - /** - * Sets the contour lines used to calculate the polygon areas of this layer. - * @param contourLines The contour lines used to calculate the polygon areas of this layer. - */ - public setContourLines(contourLines: ContourLine[]): void; - - /** - * Sets the options of the contour layer. - * @param options The new options to update the layer. - */ - public setOptions(options: IContourLayerOptions): void; - } -} \ No newline at end of file diff --git a/types/bingmaps/DataBinning.d.ts b/types/bingmaps/DataBinning.d.ts deleted file mode 100644 index e33b2d5113..0000000000 --- a/types/bingmaps/DataBinning.d.ts +++ /dev/null @@ -1,148 +0,0 @@ -/// - -declare module Microsoft.Maps { - - /** - * Specifies the shape of data bin rendered in the layer. - */ - export enum DataBinType { - /* Renders data bins as circles in a square grid. */ - circle, - - /* Renders data bins as hexagons with a flat top edge. */ - hexagon, - - /* Renders data bins as circles in a hexagonal grid. */ - hexCircle, - - /* Renders data bins as hexagons with a pointy top corner. */ - pointyHexagon, - - /* Renders data bins as a square grid. */ - square - } - - /** - * A set options the define how a data binning layer is rendered. - */ - export interface IDataBinningOptions { - /* The name of a property in the Pushpin.metadata object on which to perform calculations (average, count, sum) against the pushpins in each data bin. */ - aggregationProperty?: string; - - /* - * A callback function which defines the color a data bin polygon should be. This callback recieves data bin information - * along with the min and max calculated metrics for the data set. If set, this callback function must return a color value. - */ - colorCallback?: (binInfo: IDataBinInfo, min: IDataBinMetrics, max: IDataBinMetrics) => string | Color; - - /* The shape of the data bin to generate. Default: hexagon */ - dataBinType?: DataBinType; - - /* The distance units of the radius option. Default: meters */ - distanceUnits?: SpatialMath.DistanceUnits; - - /* The default options used for rendering the data bin polygons. */ - polygonOptions?: IPolygonOptions; - - /* - * A spatial distance which will be converted into a pixel distance at the equater and used to generate symetrically sized data bins - * that have the apprimate spatial distance radius. Default: 1000 - */ - radius?: number; - - /* - * A callback function which defines how much to scale a data bins size. This callback recieves data bin information - * along with the min and max calculated metrics for the data set. If set, this callback function must return a number between 0 and 1. - */ - scaleCallback?: (binInfo: IDataBinInfo, min: IDataBinMetrics, max: IDataBinMetrics) => number; - } - - /** - * A set of values calculated from the pushpins in a data bin. - */ - export interface IDataBinMetrics { - - /* The average value of the aggregation property of the pushpins in a data bin. */ - average?: number; - - /* The number of pushpins in a data bin. */ - count?: number; - - /* The number of pushpins in the data bin who's aggregation property has a value. */ - countNotBlank?: number; - - /* The number of pushpins in the data bin who's aggregation property is a valid number. */ - countNumbers?: number; - - /* The sum of the aggregation property of the pushpins in a data bin. */ - sum?: number; - } - - /** - * The result of a calculated data bin. - */ - export interface IDataBinInfo { - /* An array of all the pushpins that are in the data bin. */ - containedPushpins: Microsoft.Maps.Pushpin[]; - - /* A set of calculated metric values determined using the aggregationProperty value of all the pushpins contained in the data bin. */ - metrics: IDataBinMetrics; - } - - /** - * A polygon which represents a data bin on the map and contains the data bin information. - */ - - export class DataBinPolygon extends Polygon { - /* Information about the data bin; the contained pushpins and calculated metrics. */ - public dataBinInfo: IDataBinInfo; - } - - /** - * This class provides a data binning visualization for the map. It takes in an array of pushpins, groups them into - * symmetrical shapes that fit together in a grid such as hexagons. Aggregation of data values are done and can be - * used to customize how the data bins are rendered on the map (i.e. scale / color) . - */ - export class DataBinningLayer extends Layer { - /** - * Initializes the data binning layer. - * @param pushpins The array of pushpins that are used to generate the data bins. - * @param options The options used for calculating and rendering the data bins. - */ - constructor(pushpins?: Pushpin[], options?: IDataBinningOptions); - - /** - * Gets the options used for calculating and rendering the data bins. - * @returns The options used for calculating and rendering the data bins. - */ - public getOptions(): IDataBinningOptions; - - /** - * Gets all pushpins that are in the layers. - * @returns All pushpins that are in the layers. - */ - public getPushpins(): Pushpin[]; - - /** - * Sets the array of pushpins that are used to generate the data bins. - * @param pushpins The array of pushpins that are used to generate the data bins. - */ - public setPushpins(pushpins: Pushpin[]): void; - - /** - * Clears all the data in the data binning layer. - */ - public clear(): void; - - /** - * Cleans up any resources this object is consuming. - */ - public dispose(): void; - - /** - * Sets the options used for calculating and rendering the data bins. - * @param options The options used for calculating and rendering the data bins. - */ - public setOptions(options: IDataBinningOptions): void; - } -} \ No newline at end of file diff --git a/types/bingmaps/Directions.d.ts b/types/bingmaps/Directions.d.ts deleted file mode 100644 index 3663fc8c21..0000000000 --- a/types/bingmaps/Directions.d.ts +++ /dev/null @@ -1,611 +0,0 @@ -declare module Microsoft.Maps.Directions { - ///////////////////////////////////// - /// Enumerations - //////////////////////////////////// - - /** Distance units for calculating the directions in. */ - export enum DistanceUnit { - - /** A distance in Kilometers. */ - km, - - /** A distance in Miles. */ - miles - } - - /** Defines the type of route to calculate. */ - export enum RouteMode { - /** Driving directions are calculated. */ - driving, - - /** Transit directions are calculated. */ - transit, - - /** Walking directions are calculated. */ - walking - } - - /** Defines features to avoid when calculating the route. */ - export enum RouteAvoidance { - /** Calculate the best route using any travel option available. */ - none = 0, - - /** Reduce the use of limited access highways when calculating the route. */ - minimizeHighways = 1, - - /** Reduce the use of roads with tolls when calculating the route. */ - minimizeToll = 2, - - /** Avoid using limited access highways when calculating the route. */ - avoidHighways = 4, - - /** Avoid using roads with tolls when calculating the route. */ - avoidToll = 8, - - /** Avoid using express trains when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */ - avoidExpressTrain = 16, - - /** Avoid using airlines when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */ - avoidAirline = 32, - - /** Avoid using bullet trains when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */ - avoidBulletTrain = 64 - } - - /** Response codes for a route calculation request. */ - export enum RouteResponseCode { - /** The route was successfully calculated. */ - success = 0, - - /** An unknown error has occurred. */ - unknownError = 1, - - /** A nearby road cannot be found for one or more of the route waypoints. */ - cannotFindNearbyRoad = 2, - - /** - * The distance between two route waypoints, or the total length of the route exceeds the limit of the route mode. - * Modify the waypoint locations so that they are closer together. - */ - tooFar = 3, - - /** - * A route cannot be calculated for the specified waypoints. For example, this code is returned when a route between - * “Seattle, WA” and “Honolulu, HI” is requested. - */ - noSolution = 4, - - /** There is no route data for the specified waypoints. */ - dataSourceNotFound = 5, - - /** There are no transit options available for the specified time. */ - noAvailableTransitTrip = 7, - - /** The transit stops are so close that walking is always a better option. */ - transitStopsTooClose = 8, - - /** The transit stops are so close that walking is a better option. */ - walkingBestAlternative = 9, - - /** - * There is no transit data available for the route or for one or more of the specified waypoints, - * or the waypoints are in different transit areas that do not overlap. - */ - outOfTransitBounds = 10, - - /** The directions calculation request has timed out. */ - timeOut = 11, - - /** - * One or more waypoints need to be disambiguated. This error does not occur if the - * autoDisplayDisambiguation directions render option is set to true. - */ - waypointDisambiguation = 12, - - /** One or more waypoints do not have an address or location specified. */ - hasEmptyWaypoint = 13, - - /** The maximum number of waypoints, which is 25, has been exceeded. */ - exceedMaxWaypointLimit = 14, - - /** At least two waypoints are required to calculate a route. */ - atleastTwoWaypointRequired = 15, - - /** The first or last waypoint is a via point, which is not allowed. */ - firstOrLastStoppointIsVia = 16, - - /** The search service failed to return results. */ - searchServiceFailed = 17, - - /** The credentials passed to the Directions module are invalid. */ - invalidCredentials = 18 - } - - /** Defines optimization options for calculating directions. */ - export enum RouteOptimization { - /** Calculate a route the shortest time. */ - shortestTime = 0, - - /** Calculate a route with the shortest distance. */ - shortestDistance = 1, - - /** The route is calculated to minimize the time and uses current traffic information. */ - timeWithTraffic = 2, - - /** The route is calculated to minimize the time and avoid road closures. Traffic information is not used in the calculation. */ - timeAvoidClosure = 3, - - /** Minimize the cost when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/ - minimizeMoney = 4, - - /** Minimize transit transfers when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/ - minimizeTransfers = 5, - - /** Minimize the amount of walking when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/ - minimizeWalking = 6 - } - - /** An enumeration that specifies the releance of a dateTime when calculating a route. */ - export enum TimeType { - /** The dateTime parameter contains the desired arrival time for a transit request. */ - arrival, - - /** The dateTime parameter contains the desired departure time for a transit request. */ - departure, - - /** The dateTime parameter should be ignored and the first available transit taken. */ - firstAvailable, - - /** The dateTime parameter contains the latest departure time available for a transit request. */ - lastAvailable - } - - ///////////////////////////////////// - /// Interfaces - //////////////////////////////////// - - /** Contains the arguments for directions events. */ - export interface IDirectionsEventArgs { - /** The calculated route (or routes, if the route mode is transit). */ - route: IRoute[]; - - /** The route summary (or summaries) of the route(s) defined in the route property. */ - routeSummary: IRouteSummary[]; - } - - /** Contains arguments for directions error events. */ - export interface IDirectionsErrorEventArgs { - /** The code which identifies the error that occurred. */ - responseCode: RouteResponseCode; - - /** The error message. */ - message: string; - } - - /** Represents one direction in a set of route directions. */ - export interface IDirectionsStep { - /** The child direction items for this directions step. */ - childItineraryItems: IDirectionsStep[]; - - /** The location of the start of the direction. */ - coordinate: Location; - - /** The total distance of the step in the unit specified in the distanceUnit property of the DirectionsRequestOptions. */ - distance: string; - - /** The total time, in seconds, of the direction step. */ - durationInSeconds: number; - - /** The HTML formatted route instruction associated with the step. */ - formattedText: string; - - /** A boolean indicating whether the maneuver image is a road shield image. */ - isImageRoadShield: boolean; - - /** The name of the maneuver image. */ - maneuverImageName: string; - - /** An array of strings, where each string is a hint to help determine when to move to the next direction step. Not all direction steps have hints. */ - postIntersectionHints: string[]; - - /** An array of strings, where each string is a hint to help determine when you have arrived at this direction step. Not all direction steps have hints. */ - preIntersectionHints: string[]; - - /** The name of the transit stop where this step originates. */ - startStopName: string; - - /** The transit line associated with this step. */ - transitLine: ITransitLine; - - /** The URL of the image to use for transit direction steps. */ - transitStepIcon: string; - - /** The ID of the transit stop. */ - transitStopId: string; - - /** The name of the transit line end. */ - transitTerminus: string; - } - - /** Represents a route. */ - export interface IRoute { - /** The legs of the route. Each route leg represents the route between two waypoints. */ - routeLegs: IRouteLeg[]; - - /** An array of locations that makes up the path of the route. */ - routePath: Location[]; - } - - /** Represents a leg of a route. A route leg is the part of the route between two stop waypoints. */ - export interface IRouteLeg { - /** The end time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit. */ - endTime: Date; - - /** The location of the last waypoint of this leg. */ - endWaypointLocation: Location; - - /** The directions steps associated with this route leg. */ - itineraryItems: IDirectionsStep[]; - - /** The index of the route to which this route leg belongs. */ - originalRouteIndex: number; - - /** The start time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit. */ - startTime: Date; - - /** The location of the first waypoint of this route leg. */ - startWaypointLocation: Location; - - /** The sub legs of this route leg. A sub leg of a route is the part of the route between a stop point and a via point or between two via points.*/ - subLegs: IRouteSubLeg[]; - - /** The summary which describes this route leg. */ - summary: IRouteSummary; - } - - /** Represents a route sub leg. A route sub leg is the part of the route between a stop point and a via point or between two via points. */ - export interface IRouteSubLeg { - /** The location of the last waypoint of the sub leg. */ - actualEnd: Location; - - /** The location of the first waypoint of the sub leg. */ - actualStart: Location; - - /** The description of the last waypoint of the sub leg. */ - endDescription: string; - - /** The description of the first waypoint of the sub leg. */ - startDescription: string; - } - - /** Represents a route summary. */ - export interface IRouteSummary { - /** The total travel distance of the route */ - distance: number; - - /** The cost of the route. This property is only returned if the routeMode of the IDirectionsRequestOptions is set to transit and the map culture is set to ja-jp. */ - monetaryCost: number; - - /** The location of the northeast corner of bounding box that defines the best map view of the route. */ - northEast: Location; - - /** The location of the southwest corner of bounding box that defines the best map view of the route. */ - southWest: Location; - - /** The total travel time, in seconds, for the route. */ - time: number; - - /** - * The total travel time, in seconds, taking into account traffic delays, for the route. - * This property is 0 if the avoidTraffic property of the IDirectionsRequestOptions is set to false. - */ - timeWithTraffic: number; - } - - /** Contains information about a transit line. */ - export interface ITransitLine { - /** The short name for the transit line. */ - abbreviatedName: string; - - /** The ID of the agency that owns the transit line. */ - agencyId: number; - - /** The name of the agency that owns the transit line. */ - agencyName: string; - - /** The URL of the website of the agency that owns the transit line. */ - agencyUrl: string; - - /** Phone number for the transit agency. */ - phoneNumber: string; - - /** Information about the provider of this transit line data. */ - providerInfo: string; - - /** The uri for the transit agencies website. */ - uri: string; - - /** The full name of this transit line. */ - verboseName: string; - } - - /** Options that can be used to define a waypoint. */ - export interface IWaypointOptions { - /** - * The address string of the waypoint. For example, the following strings are valid for this parameter: "Seattle", "1 Microsoft Way, Redmond, WA". Either the address or location property must be specified. - */ - address?: string; - - /** - * A boolean indicating whether the waypoint is a via point. A via point is a point along the route that is not a stop point. Set this property to - * true if you just want the route to pass through this location. Default: false - */ - isViaPoint?: boolean; - - /** The location of the waypoint. Either the address or location property must be specified. */ - location?: Location; - } - - /** Contains options for the directions to calculate. */ - export interface IDirectionsRequestOptions { - /** The unit to use when displaying direction distances. */ - distanceUnit?: DistanceUnit; - - /** The number of routes to calculate. */ - maxRoutes?: number; - - /** The features to avoid when calculating the route. */ - routeAvoidance?: RouteAvoidance[]; - - /** A boolean indicating whether the route line on the map can be dragged with the mouse cursor. */ - routeDraggable?: boolean; - - /** If multiple routes are returned, the index of the route and directions to display. */ - routeIndex?: number; - - /** The type of directions to calculate. */ - routeMode?: RouteMode; - - /** The optimization setting for the route calculation. */ - routeOptimization?: RouteOptimization; - - /** The type of the time specified. The default value is departure. */ - timeType?: TimeType; - - /** The time to use when calculating the route. If this property is set to null, the current time is used */ - time?: Date; - } - - /** Represents render options for a route. */ - export interface IDirectionsRenderOptions { - /** A boolean indicating whether to automatically set the map view to the best map view of the calculated route. Default: true */ - autoUpdateMapView?: boolean; - - /** A boolean indicating whether to display the disclaimer about the accuracy of the directions. Default: true */ - displayDisclaimer?: boolean; - - /** A boolean indicating whether to display the icons for each direction maneuver. Default: true */ - displayManeuverIcons?: boolean; - - /** A boolean indicating whether to display direction hints that describe when a direction step was missed. Default: true */ - displayPostItineraryItemHints?: boolean; - - /** - * A boolean indicating whether to display direction hints that describe what to look for before you come to the next - * direction step. The default value is true. - */ - displayPreItineraryItemHints?: boolean; - - /** A boolean indicating whether to display the route selector control. Default: true */ - displayRouteSelector?: boolean; - - /** A boolean indicating whether to display direction warnings. Default: true */ - displayStepWarnings?: boolean; - - /** A boolean indicating whether to display a warning about walking directions. Default: true */ - displayWalkingWarning?: boolean; - - /** The polyline options that define how to draw the route line on the map, if the RouteMode is driving. */ - drivingPolylineOptions?: IPolylineOptions; - - /** The pushpin options that define how the first waypoint should be rendered. */ - firstWaypointPushpinOptions?: IPushpinOptions; - - /** The DOM element inside which the directions itinerary will be rendered. */ - itineraryContainer?: HTMLElement; - - /** The pushpin options that define how the last waypoint should be rendered. */ - lastWaypointPushpinOptions?: IPushpinOptions; - - /** A boolean indicating whether to show the input panel. Default: false */ - showInputPanel?: boolean; - - /** The options that define how to draw the route line on the map, if the RouteMode is transit. */ - transitPolylineOptions?: IPolylineOptions; - - /** The options that define how to draw the route line on the map, if the RouteMode is walking. */ - walkingPolylineOptions?: IPolylineOptions; - - /** The options that define the pushpin to use for all route waypoints by default. The first and last waypoints in the route will be overriden by firstWaypointPushpinOptions and lastWaypointPushpinOptions if set. */ - waypointPushpinOptions?: IPushpinOptions; - } - - ///////////////////////////////////// - /// Classes - //////////////////////////////////// - - /** An object used to define a start, end or stop location along a route. */ - export class Waypoint { - /** - * @constructor - * @param options: Options used to define the Waypoint. - */ - constructor(options: IWaypointOptions); - - /** Releases any resources associated with the waypoint. */ - public dispose(): void; - - /** - * Gets the address associated with the waypoint. - * @returns The address associated with the waypoint. - */ - public getAddress(): string; - - /** - * Gets the location of the waypoint. - * @returns The location of the waypoint. - */ - public getLocation(): Location; - - /** - * Gets a boolean value indicating whether the waypoint is a via point. - * @returns A boolean value indicating whether the waypoint is a via point. - */ - public isViapoint(): boolean; - - /** - * Sets options for the waypoint. For these options to take effect, you must recalculate the route. - * @param options Options used to define the Waypoint. - */ - public setOptions(options: IWaypointOptions): void; - } - - /** The main class in the Directions module that process direction calculations and rendering. */ - export class DirectionsManager { - - /** - * @constructor - * @param map A map to calculate directions for. - * @param waypoints An array of waypoints to be added to the route. - */ - constructor(map: Map, waypoints?: Waypoint[]); - - /** - * Adds a waypoint to the route at the given index, if specified. If an index is not specified, the waypoint is added as the last waypoint in the route. The maximum number of walking or driving waypoints is 25. The maximum number of transit waypoints is 2. Up to 10 via points are allowed between two stop waypoints. To recalculate the route, use calculateDirections. - * @param waypoint The waypoint to be added to the directions manager. - * @param index An index at which the waypoint is to be added. - */ - public addWaypoint(waypoint: Waypoint, index?: number): void; - - /** - * Calculates directions based on request and render options set - */ - public calculateDirections(): void; - - /** Clears the directions request and render options and removes all waypoints */ - public clearAll(): void; - - /** - * Clears the directions displayed and removes the route line from the map. - * This method does not remove waypoints from the route and retains all calculated direction information and option settings. - */ - public clearDisplay(): void; - - /** Deletes the DirectionsManager object and releases any associated resources. */ - public dispose(): void; - - /** - * Gets all the waypoints in the directions manager. - * @returns All the waypoints in the directions manager. - */ - public getAllWaypoints(): Waypoint[]; - - /** - * Gets the currently displayed route information. - * @returns The currently displayed route information. - */ - public getCurrentRoute(): IRoute; - - /** - * Gets the route render options. - * @returns The route render options - */ - public getRenderOptions(): IDirectionsRenderOptions; - - /** - * Gets the directions request options. - * @returns The directions request options. - */ - public getRequestOptions(): IDirectionsRequestOptions; - - /** - * Gets the current calculated route(s) - * @returns The current calculated route(s). If the route was not successfully calculated, null is returned. - */ - public getRouteResult(): IRoute[]; - - /** - * Removes the given waypoint or the waypoint identified by the given index from the route. - * @param waypointOrIndex A Waypoint object to be removed or the index of the waypoint to be removed - */ - public removeWaypoint(waypointOrIndex: Waypoint | number): void; - - /** - * Sets the specified render options for the route. - * @param options The options that customize the rendering of the calculated route. - */ - public setRenderOptions(options: IDirectionsRenderOptions): void; - - /** - * Sets the specified route calculation options. - * @param options The route calculation options. - */ - public setRequestOptions(options: IDirectionsRequestOptions): void; - - /** - * Displays an input panel for calculating directions in the specified container. Provides autosuggest for location inputs. - * @param inputContainerId The id name of the HTML container in which to render the directions input panel. - */ - public showInputPanel(inputContainerId: string): void; - } -} - -declare module Microsoft.Maps { - /** A static class that manages events within the map SDK. */ - module Events { - ///////////////////////////////////// - /// addHandler Definitions - //////////////////////////////////// - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * • directionsError - * • directionsUpdated - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void): IHandlerId; - - ///////////////////////////////////// - /// addOne Definitions - //////////////////////////////////// - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * • directionsError - * • directionsUpdated - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void): void; - - ///////////////////////////////////// - /// addThrottledHandler Definitions - //////////////////////////////////// - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * • directionsError - * • directionsUpdated - * @param handler The callback function to handle the event when triggered. - * @param throttleInterval throttle interval (in ms) - * @returns The handler id. - */ - export function addThrottledHandler(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void, throttleInterval: number): IHandlerId; - } -} diff --git a/types/bingmaps/DrawingTools.d.ts b/types/bingmaps/DrawingTools.d.ts deleted file mode 100644 index bd5c938e4e..0000000000 --- a/types/bingmaps/DrawingTools.d.ts +++ /dev/null @@ -1,234 +0,0 @@ -declare module Microsoft.Maps { - /** An object that contains the event arguments for when the drawing mode changes in the drawing tools. **/ - export interface IDrawingModeChangedData { - - /** The shape being modified by the drawing tools. **/ - shape: IPrimitive; - - /** The new drawing mode. **/ - mode: DrawingTools.DrawingMode; - } - - /** - * The DrawingManager class manages the ability to draw and edit multiple shapes on the map. Shapes managed by this class are rendered on a separate drawing layer. - * User can use a mouse or a touch screen to draw on the map. When they are done, pressing the escape button or any button on the toolbar will exit the current drawing mode. - * This class does not have a publicly accessible constructor and can only be accessed using the showDrawingManager of the DrawingTools class. - */ - export interface DrawingManager { - /** - * Adds a shapes to the layer, at the specified index if specified. - • @param data The shape(s) to be added to the layer. - • @param index The index at which to insert the shape into the layer. - */ - add(data: IPrimitive | IPrimitive[], index?: number): void; - - /** - * Disposes the drawing manager instance. - */ - dispose(): void; - - /** - * Resets the drawing manager and clears all shapes in the drawing layer. - */ - clear(): void; - - /** - * Gets the current drawing mode of the drawing manager. - * @returns The current drawing mode of the drawing manager. - */ - getDrawingMode(): DrawingTools.DrawingMode; - - /** - * Gets an array of shapes that are in the layer. This can be used to iterate over the individual shapes. - * @returns An array of shapes that are in the layer. This can be used to iterate over the individual shapes. - */ - getPrimitives(): IPrimitive[]; - - /** - * Returns the index of the shape in the drawing layer. - * @param primitive The shape to find the index of. - * @param fromIndex The index to start the search from. - * @returns The index of the shape in the drawing layer. Returns -1 if shape is not found. - */ - indexOf(primitive: IPrimitive, fromIndex?: number): number; - - /** - * Removes a shape from the layer and returns it. - * @param primitive The shape to remove from the layer. - * @returns The shape that was removed from the layer. - */ - remove(primitive: IPrimitive): IPrimitive; - - /** - * Removes a shape from the layer at the specified index. - * @param index The index of the shape to remove from the layer. - * @returns The shape that was removed from the layer. - */ - removeAt(index: number): IPrimitive; - - /** - * Sets the drawing mode of the drawing manager. - * @param mode The drawing mode to set the DrawingManager to. - */ - setDrawingMode(mode: DrawingTools.DrawingMode): void; - - /** - * Replaces all shapes in the layer with the new array of shapes that have been provided. - * @param primitives An array of shapes to add to the drawing layer. - */ - setPrimitives(primitives: IPrimitive[]): void; - } - - /** - * Provides a set of tools for drawing and editing shapes on top of the map. - * @requires The Microsoft.Maps.DrawingTools module. - */ - export class DrawingTools { - /** - * @constructor - * @requires The Microsoft.Maps.DrawingTools module. - * @param map A map instanct to attach the drawing tools to. - */ - constructor(map: Map); - - /** - * Initializes the drawing layer and instructs it to create a new shape of a given type. - * @param shapeType The type of new shape to create. - * @param created A callback function that is fired after the initial shape is created. - */ - public create(shapeType: DrawingTools.ShapeType, created?: (shape: IPrimitive) => void): void; - - /** Disposes the instance of the DrawingTools class. */ - public dispose(): void; - - /** - * Adds a shape to the drawing layer and puts it into edit mode. - * @param shape A shape to put into editting mode. - */ - public edit(shape: IPrimitive): void; - - /** - * Finishes any shape create / edit operation currently in progress, and returns the shape that was created or editted through a specified callback function. - * @param finished A callback function to return the completed shape with. - */ - public finish(finished?: (shape: IPrimitive) => void): void; - - /** - * Creates a drawing manager which allows multi-shape editing and displays the toolbar. - * @param callback A callback function that is triggered after the DrawingTools have loaded. - */ - public showDrawingManager(callback?: (manager: DrawingManager) => void): void; - } - - export module Events { - ///////////////////////////////////// - /// addHandler Definitions - //////////////////////////////////// - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void): IHandlerId; - - ///////////////////////////////////// - /// addOne Definitions - //////////////////////////////////// - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): void; - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void): void; - - ///////////////////////////////////// - /// addThrottledHandler Definitions - //////////////////////////////////// - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addThrottledHandler(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted - * @param handler The callback function to handle the event when triggered. - * @param throttleInterval throttle interval (in ms) - * @returns The handler id. - */ - export function addThrottledHandler(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void, throttleInterval: number): IHandlerId; - } - -} - -declare module Microsoft.Maps.DrawingTools { - /** - * The different drawing modes that the drawing manager can be set to. - * @requires The Microsoft.Maps.DrawingTools module. - */ - export enum DrawingMode { - /** Edit an existing shape. Click on a shape to edit it. */ - edit, - - /** Erase and existing shape. Click on the shapes to erase them. */ - erase, - - /** Sets the drawing manager into an idle mode. */ - none, - - /** Allow the user to draw a polygon. */ - polygon, - - /** Allow the user to draw a polyline. */ - polyline, - - /** Allow the user to draw a pushpin. */ - pushpin - } - - /** - * The different types of shapes that are created or edited by the drawing tools. - * @requires The Microsoft.Maps.DrawingTools module. - */ - export enum ShapeType { - /** A polygon shape type. */ - polygon, - - /** A polyline shape type. */ - polyline - } -} \ No newline at end of file diff --git a/types/bingmaps/GeoJson.d.ts b/types/bingmaps/GeoJson.d.ts deleted file mode 100644 index 94726ab542..0000000000 --- a/types/bingmaps/GeoJson.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -declare module Microsoft.Maps { - - /** GeoJSON object definition */ - export interface IGeoJsonObject { - /** - * Type of the object - * could be one of the following: - * Point - * LineString - * Polygon - * MultiPoint - * MultiLineString - * MultiPolygon - * GeometryCollection - * Feature - * FeatureCollection - */ - type: string; - - /** Geometric coordinates of the object */ - coordinates?: number[] | number[][] | number[][][] | number[][][][]; - - /** Additional properties of the object as a key,value pair */ - properties?: any; - - /** Set of features (only applicable if the type is 'featurecollection') */ - features?: IGeoJsonObject[]; - - /** Set of geometries (only applicable if the type is 'geometrycollection') */ - geometries?: IGeoJsonObject[]; - - /** Geometry (only applicable if the type is 'feature') */ - geometry?: IGeoJsonObject; - - /** identifier of a feature (only applicable if the type is 'feature') */ - id?: any; - } - - /** - * Class responsible for reading/writing geo data in GeoJson format - * @requires The Microsoft.Maps.GeoJson module. - */ - export module GeoJson { - /** - * Reads the data from a given url and returns the shapes. - * @param url GeoJson download url. - * @param callback Callback function that needs to be called once the data is downloaded and parsed. - * @param jsonpQueryParam The name of the url query param to make a jsonp request. - * @param styles Styles that needs to be applied. - */ - export function readFromUrl(url: string, callback: (data: IPrimitive | IPrimitive[]) => void, jsonpQueryParam?: string, styles?: IStylesOptions): void; - - /** - * Reads the data in geoJson format and returns the shapes. - * @param geoJson GeoJson data object that needs to be parsed into shapes. - * @param styles Styles that needs to be applied. - * @returns An array of shapes. - */ - export function read(geoJson: IGeoJsonObject | string, styles?: IStylesOptions): IPrimitive | IPrimitive[]; - - /** - * Writes the data into geoJson format. - * @param data Data that needs to be serialized. - * @returns A geoJson formatted string. - */ - export function write(data: IPrimitive | IPrimitive[]): IGeoJsonObject; - } -} \ No newline at end of file diff --git a/types/bingmaps/HeatMapLayer.d.ts b/types/bingmaps/HeatMapLayer.d.ts deleted file mode 100644 index c90813b00d..0000000000 --- a/types/bingmaps/HeatMapLayer.d.ts +++ /dev/null @@ -1,106 +0,0 @@ -declare module Microsoft.Maps { - /** A standard dictionary object (associative array). */ - export interface IDictionary { - [K: string]: T; - } - - /** Options for customizing how the heat map is rendered. */ - export interface IHeatMapLayerOptions { - /** - * The temperature gradient that is used to colorize the map. Default gradient: - * { - * '0.00': 'rgb(255,0,255)', // Magenta - * '0.25': 'rgb(0,0,255)', // Blue - * '0.50': 'rgb(0,255,0)', // Green - * '0.75': 'rgb(255,255,0)', // Yellow - * '1.00': 'rgb(255,0,0)' // Red - * } - */ - colorGradient?: IDictionary; - - /** - * The intensity of each heat point. This is a decimal value between 0 and 1. This is used to specify how "hot" a single data point should be. Default: 0.5 - */ - intensity?: number; - - /** - * The opacity of the HeatMapLayer canvas. Value should be a decimal between 0 and 1. Default: 1 - */ - opacity?: number; - - /** - * The radius to draw each data point on the map. Default: 10 - */ - radius?: number; - - /** - * The distance units of the radius. Possible values are: - * - * • 'pixels' (defualt) - * • 'meters' - * - * When set to pixels the size of each data point will always be the same radius, regardless of zoom level. When set to meters, the size of the data points - * will scale based on zoom level so as to ensure that the radius is spatially accurate. - */ - unit?: 'meters' | 'pixel'; - - /** A boolean indicating if the heat map layer is visible or not. **/ - visible?: boolean; - } - - /** - * Class for rendering data as a heat map layer. - * @requires The Microsoft.Maps.Heatmap module. - */ - export class HeatMapLayer implements IDataLayer { - /** - * @constructor - * @requires The Microsoft.Maps.Heatmap module. - * @param locations Set of locations to visualize as a heat map. - * @param options Options for customizing how the heat map is rendered. - */ - constructor(locations: (Location | Pushpin)[], options?: IHeatMapLayerOptions); - - /** Clears all data in the heat map layer. */ - public clear(): void; - - /** Disposes the heat map layer. */ - public dispose(): void; - - /** - * Gets a boolean indicating if the heat map layer is visible or not. - * @returns A boolean indicating if the heat map layer is visible or not. - */ - public getVisible(): boolean; - - /** - * @deprecated - * Hides the heat map layer. - */ - public hide(): void; - - /** - * Specifies the locations to use when generating the heat map. - * @param locations Set of locations. - */ - public setLocations(locations: (Location | Pushpin)[]): void; - - /** - * Sets the options to use with the heat map layer. - * @param options Set of heat map layer options. - */ - public setOptions(options: IHeatMapLayerOptions): void; - - /** - * Sets the visibility of the heat map layer. - * @param visible A boolean indicating if the heat map layer is visible or not. - */ - public setVisible(visible: boolean): void; - - /** - * @deprecated - * Shows the heat map layer. - */ - public show(): void; - } -} \ No newline at end of file diff --git a/types/bingmaps/Search.d.ts b/types/bingmaps/Search.d.ts deleted file mode 100644 index 0d799c7078..0000000000 --- a/types/bingmaps/Search.d.ts +++ /dev/null @@ -1,228 +0,0 @@ -/** - * Provides an easy method for geocoding address and searching for points of interest from JavaScript. - * @requires The Microsoft.Maps.Search module. - */ -declare module Microsoft.Maps.Search { - /** - * Defines the match precision of a geocdoed result. - * @requires The Microsoft.Maps.Search module. - */ - export enum LocationPrecision { - /** The geocode result was matched to a point on a road using interpolation. */ - interpolated, - - /** - * The geocode result was matched to a point on a road using interpolation with an additional offset to shift the - * Location to the side of the street. - */ - InterpolatedOffset, - - /** The geocode result was matched to the center of a parcel (property boundary). */ - parcel, - - /** The geocode result was matched to the rooftop of a building. */ - rooftop - } - - /** - * Defines the geocoding level of the location match found by the geocoder. - * @requires The Microsoft.Maps.Search module. - */ - export enum MatchCode { - /** No match was found. */ - none, - - /** The match was good. */ - good, - - /** The match was ambiguous. Multiple results were returned. */ - ambiguous, - - /** The match was found by a broader search. */ - upHierarchy, - - /** The match was found, but possibly using a modified query. */ - modified - } - - /** - * Defines the confidence of the location match found by the geocoding service. - * @requires The Microsoft.Maps.Search module. - */ - export enum MatchConfidence { - /** The confidence of the match is high. */ - high, - - /** The confidence of the match is medium. */ - medium, - - /** The confidence of the match is low. */ - low, - - /** The confidence of the match is unknown. */ - unknown - } - - /** A object that represents a geocoded location. */ - export interface IGeocodeLocation { - /** The map location of this geocode location match. */ - location: Location; - - /** The name of this geocode location match. */ - name: string; - - /** The precision of this geocode location match. */ - precision: string | LocationPrecision; - } - - /** An object that represents an place result. */ - export interface IPlaceResult { - /** The geocoded address of the place result. */ - address: IAddress; - - /** The location rectangle that defines the boundaries of the best map view of the place result. */ - bestView: LocationRect; - - /** The classification of the geographic entity returned, such as PopulatedPlace. */ - entityType: string; - - /** The geocoded location of the best result. */ - location: Location; - - /** The geocoded locations. */ - locations: IGeocodeLocation[]; - - /** The match code of the best result. */ - matchCode: string | MatchCode; - - /** The match confidence of the best result. */ - matchConfidence: string | MatchConfidence; - - /** The name of the place result, if one exists. */ - name: string; - } - - /** An object that represents a geocode result returned by REST service. */ - export interface IGeocodeResult { - /** An array of geocode results. */ - results: IPlaceResult[]; - } - - /** The options for a geocode request. */ - export interface IGeocodeRequestOptions { - /** - * A location rectangle that defines the boundaries of the area in which to search for - * location results. The default is the bounds of the map view associated with this - * instance of the SearchManager, which is usually the current map view. - */ - bounds?: LocationRect; - - /** - * The name of the function to call when a successful result is returned from the - * geocode request. The callback function must accept two parameters: result, which is - * a GeocodeResult type, and a userData object. - */ - callback: (geocodeResult: IGeocodeResult, userData: any) => void; - - /** The maximum number of results to return. Required. The maximum number than can be returned is 20. */ - count?: number; - - /** - * The name of the function to call when the request is returned with an error. The - * error callback function must accept an IGeocodeRequestOptions object. - */ - errorCallback?: (geocodeRequestOptions: IGeocodeRequestOptions) => void; - - /** Specifies to include the two-letter ISO country code. */ - includeCountryIso2?: boolean; - - /** Specifies to include the neighborhood in the response when it is available. */ - includeNeighborhood?: boolean; - - /** A number indicating how long to wait, in seconds, for the geocode request to return. The default value is 5 seconds. */ - timeout?: number; - - /** An object containing any data that needs to be passed to the callback when the request is completed. */ - userData?: any; - - /** A string containing the address or place to be matched to a location on the map. */ - where: string; - } - - /** The options for a reverse geocode request. */ - export interface ReverseGeocodeRequestOptions { - /** - * A reference to a function to call when a successful result is returned from the geocode request. The callback function - * will receive a PlaceResult object as an argument. - */ - callback: (placeResult: IPlaceResult, userData: any) => void; - - /** - * A reference to a function to call when the request is returned with an error. The error callback function will receive - * an object containing the geocode request options used in the request. - */ - errorCallback?: (reverseGeocodeRequestOptions: ReverseGeocodeRequestOptions) => void; - - /** Specifies to include the two-letter ISO country code. Default: false */ - includeCountryIso2?: boolean; - - /** - * An array of entity types selected from the following options. - * • Address - * • Neighborhood - * • PopulatedPlace - * • Postcode1 - * • AdminDivision1 - * • AdminDivision2 - * • CountryRegion - * These entity types are ordered from the most specific entity to the least specific entity. When entities of more than one entity type are found, only the most specific - * entity is returned. For example, if you specify Address and AdminDistrict1 as entity types and entities were found for both types, only the Address entity information is - * returned in the response. One exception to this rule is when both PopulatedPlace and Neighborhood entity types are specified and information is found for both. In this case, - * the information for both entity types is returned. Also, more than one Neighborhood may be returned because the area covered by two different neighborhoods can overlap. - */ - includeEntityTypes?: string[]; - - /** - * Specifies to include the neighborhood in the response when it is available. Note: This feature isn’t - * available in all locations. - */ - includeNeighborhood?: boolean; - - /** The location to use to match to geographic entities and addresses. */ - location: Location; - - /** A number indicating how long to wait, in seconds, for the reverse geocode request to return. The default value is 5 seconds. */ - timeout?: number; - - /** An object containing any data that needs to be passed to the callback when the request is completed. */ - userData?: any; - } - - /** - * A class that contains methods for returning search and location results. - * @requires The Microsoft.Maps.Search module. - */ - export class SearchManager { - /** - * @constructor - * @requires The Microsoft.Maps.Search module. - * @param map A Map object - */ - constructor(map: Map); - - /** - * Matches the address or place query in the specified request - * options to a location and returns the results to the request - * options callback function. - * @param request Options for sending geocode request - */ - public geocode(request: IGeocodeRequestOptions): void; - - /** - * Matches the specified location to an address and returns the - * address results to the specified request options callback function. - * @param request Options for sending reverse geocode request - */ - public reverseGeocode(request: ReverseGeocodeRequestOptions): void; - } -} \ No newline at end of file diff --git a/types/bingmaps/SpatialDataService.d.ts b/types/bingmaps/SpatialDataService.d.ts deleted file mode 100644 index 627ab7cbad..0000000000 --- a/types/bingmaps/SpatialDataService.d.ts +++ /dev/null @@ -1,440 +0,0 @@ -/** - * This module wraps the Query and GeoData REST API’s in the Bing Spatial Dara Services and expose them as an easy to use JavaScript library. - * @requires The Microsoft.Maps.SpatialDataService module. - */ -declare module Microsoft.Maps.SpatialDataService { - - ////////////////////////////////////////////// - /// GeoData API - ////////////////////////////////////////////// - - /** Represents the options for requests boundary data from the GeoData API in the Bing Spatial Data Services. */ - export interface IGetBoundaryRequestOptions { - /** - * The level of detail for the boundary polygons returned. An integer between 0 and 3, where 0 specifies the coarsest level of boundary detail and 3 - * specifies the best. Default: 0 - */ - lod?: number; - - /** - * The entity type to return. Default: CountryRegion - * Supported entity types: - * AdminDivision1, AdminDivision2, CountryRegion, eighborhood, PopulatedPlace, Postcode1, Postcode2, Postcode3, Postcode4 - * Note: Not all entity types are available in all areas. - */ - entityType?: string; - - /** - * Specifies the preferred language to use for any metadata text about the entity or polygons. Defaults to the culture used by the map control, which - * usually automatically detected based on user's browser settings. Setting this property will override the default value. - */ - culture?: string; - - /** - * Specifies whether the response should include all of the boundary polygons for the requested entity or just return a single polygon that represents - * the main outline of the entity. Default: false - */ - getAllPolygons?: boolean; - - /** - * Specifies whether the response should include metadata about the entity, such as AreaSqKm and others. Default: false - */ - getEntityMetadata?: boolean; - - /** - * Specifies the user’s home country or region.Defaults to the region setting of the user who loads the map. - * Warning: Setting this property will override the default value, which is the region the user is actually in, and will allow the user to see boundaries - * which may not align with the views of their region.This could result in geopolitically sensitive borders being returned. - */ - userRegion?: string; - } - - /** Represents the primitive object for a boundary returned by the GeoData API. */ - export interface IGeoDataPrimitive { - /** A unique ID associated with this polygon primitive. */ - PrimitiveID: string; - - /** - * A comma-delimited sequence starting with the version number of the polygon set followed by a list of compressed polygon - * "rings" (closed paths represented by sequences of latitude and-longitude points). - */ - Shape: string; - - /** The number of vertex points used to define the polygon. */ - NumPoints: string; - - /** - * An ID identifying the data provider that supplied the data. This ID number will reference one of the sources listed in the - * array of CopyrightSources in the Copyright property of the GeoDataResultSet object. - */ - SourceID: string; - } - - /** Represents the copyright source object for a boundary returned by the GeoData API. */ - export interface ICopyrightSource { - /** The copyright string from the source. */ - Copyright: string; - - /** An ID identifying the data provider that supplied the data. */ - SourceID: string; - - /** The name of the data provider represented by this Source element. */ - SourceName: string; - } - - /** Represents the copyright object for a boundary returned by the GeoData API. */ - export interface ICopyright { - /** The copyright URL for the GeoData service. */ - CopyrightURL: string; - - /** A collection of CopyrightSource objects that give information about the sources of the polygon data that is returned. */ - Sources: ICopyrightSource[]; - } - - /** Represents the name object for a boundary returned by the GeoData API. */ - export interface IName { - /** The name of boundary. Example: "United States" */ - EntityName: string; - - /** The culture of the region. */ - Culture: string; - - /** An ID identifying the data provider that supplied the data. */ - SourceID: string; - } - - /** Represents the metadata object for a boundary returned by the GeoData API. Not all properties will be returned for all results. */ - export interface IMetadata { - /** The approximate total surface area (in square kilometers) covered by all the polygons that comprise this entity. */ - AreaSqKm: string; - - /** - * An area on the Earth that provides the best map view for this entity. This area is defined as a bounding box in the format of a - * “MULTIPOINT ((WestLongitude SouthLatitude), (EastLongitude NorthLatitude))”. - */ - BestMapViewBox: string; - - /** The culture associated with this entity. Example: en */ - OfficialCulture: string; - - /** The approximate population within this entity. Example: PopClass20000to99999 */ - PopulationClass: string; - - /** The regional culture associated with this entity. */ - RegionalCulture: string; - } - - /** Represents a single result object returned by the GeoData API. */ - export interface IGeoDataResult { - /** Copyright information for the returned boundary data. */ - Copyright: ICopyright; - - /** A unique ID number associated with this entity. */ - EntityID: string; - - /** - * A collection of metadata information associated with the entity. The getEntityMetadata option of the request must be set - * to true. Note, not all boundaries will return this metadata. - */ - EntityMetadata: IMetadata; - - /** Information about the name of the boundary location. */ - Name: IName; - - /** A Polygon object that has been generated from the data in the Primitives property. */ - Polygons: Polygon[]; - - /** An array of objects that contain the polygon information for the boundary. */ - Primitives: IGeoDataPrimitive[]; - } - - /** Represents the set of results returned by the GeoData API. */ - export interface IGeoDataResultSet { - /** Copyright information for the GeoData API. */ - Copyright: string; - - /** The location provided in the query that generated this result. */ - location: string |  Location; - - /** Results of the boundary data. */ - results: IGeoDataResult[]; - } - - /** - * This is a static class that provides the ability to request polygons that describe the boundaries of a geographic entities, such as an AdminDivision1 - * (such as a state or province) or a Postcode1 (such as a zip code) that contain a given point (latitude and longitude) or address. This uses the GeoData - * API in the Bing Spatial Data Services. - * @requires The Microsoft.Maps.SpatialDataService module. - */ - export module GeoDataAPIManager { - /** - * Gets a boundary for the specified request. If the specified location value is a string, it will be geocoded and the coordinates of the result will - * be used to find a boundary of the specified entityType that intersects with this coordinate. - * @requires The Microsoft.Maps.SpatialDataService module. - * @param locations The locations to retrieve boundaries for. If the specified location value is a string, it will be geocoded and the coordinates of - * the result will be used to find a boundary of the specified entityType that intersects with this coordinate. - * @param request The request options for retrieving a boundary. - * @param credentials A bing maps key or a map instance which can be used to provide credentials to access the data source. Note that the map will need - * to be loaded with a bing maps key that has access to the data source. - * @param callback A callback function to return the results to. If an array of locations are specified the callback function will be triggered for each location in the array. - */ - export function getBoundary(locations: string | Location | (string | Location)[], request: IGetBoundaryRequestOptions, credentials: string | Map, callback: (results: IGeoDataResultSet) => void): void; - } - - ////////////////////////////////////////////// - /// Query API - ////////////////////////////////////////////// - - /** - * An enumeration that defines how to compare the filters value against the corresponding property value. - * @requires The Microsoft.Maps.SpatialDataService module. - */ - export enum FilterCompareOperator { - /** Determines if a string value ends with a specified string value. */ - endsWith, - - /** Determines if two values are equal. */ - equals, - - /** Determines if a first value is greater than a second value. */ - greaterThan, - - /** Determines if a first value is greater than or equal to a second value. */ - greaterThanOrEqual, - - /** Determines if a value is within an array. */ - isIn, - - /** Determines if a first value is less than a second value. */ - lessThan, - - /** Determines if a first value is less than or equal a second value. */ - lessThanOrEqual, - - /** Determines if a string value does not end with a specified string value. */ - notEndsWith, - - /** Determines if two values are not equal. */ - notEquals, - - /** Determines if a string value does not start with a specified string value. */ - notStartsWith, - - /** Determines if a string value starts with a specified string value. */ - startsWith - } - - /** - * An enumeration that defines how two or more filters are linked together. - * @requires The Microsoft.Maps.SpatialDataService module. - */ - export enum FilterLogicalOperator { - /** Connects two or more filters that both must be true. */ - and, - - /** Connects two or more filters where one of them must be true. */ - or - } - - /** - * A Fitler object that defines the logic behind a filter expression that can be executed against a JSON object or generate - * a filter string that can be used with the Bing Spatial Data Services. - */ - export interface IFilter { - /** - * Executes the filter logic against a JSON object and returns a boolean indicating if the object meets the requirements of the Filter. - * @returns A boolean indicating if the specified object meets the requirements of the Filter. - */ - execute(object: any): boolean; - - /** - * Converts the filter logic into a string format that is compatible with the Bing Spatial Data Services. - * @returns A filter string that is formatted such that it is compatible with the Bing Spatial Data Services. - */ - toString(): string; - } - - /** - * The Fitler class defines the logic behind a filter expression that can be executed against a JSON object or generate - * a filter string that can be used with the Bing Spatial Data Services. - * @requires The Microsoft.Maps.SpatialDataService module. - */ - export class Filter implements IFilter { - /** - * @constructor - * @requires The Microsoft.Maps.SpatialDataService module. - * @param propertyName The name of the property in the object to test against. Can also provide child properties i.e. 'root.child'. - * @param operator The operator to use when comparing the specified property to value to the provided value. - * @param value A value to compare against. - */ - constructor(propertyName: string, operator: string | FilterCompareOperator, value: any); - - /** - * Executes the filter logic against a JSON object and returns a boolean indicating if the object meets the requirements of the Filter. - * @returns A boolean indicating if the specified object meets the requirements of the Filter. - */ - public execute(object: any): boolean; - - /** - * Converts the filter logic into a string format that is compatible with the Bing Spatial Data Services. - * @returns A filter string that is formatted such that it is compatible with the Bing Spatial Data Services. - */ - public toString(): string; - } - - /** - * A class that groups two or more logical filters or filter groups together. It can be executed against a JSON or generate - * a filter string that can be used with the Bing Spatial Data Services. - * @requires The Microsoft.Maps.SpatialDataService module. - */ - export class FilterGroup implements IFilter { - /** - * @constructor - * @requires The Microsoft.Maps.SpatialDataService module. - * @param filters An array consisting of Filter or FilterGroup objects to combine. - * @param operator The logical operator for combining the filters together. - * @param not A boolean is the logical inverse should of the filter should be used. - */ - constructor(filters: IFilter[], operator: FilterLogicalOperator, not?: boolean) - - /** - * Executes the filter logic against a JSON object and returns a boolean indicating if the object meets the requirements of the Filter. - * @returns A boolean indicating if the specified object meets the requirements of the Filter. - */ - public execute(object: any): boolean; - - /** - * Converts the filter logic into a string format that is compatible with the Bing Spatial Data Services. - * @returns A filter string that is formatted such that it is compatible with the Bing Spatial Data Services. - */ - public toString(): string; - } - - /** Options for find near route query API. */ - export interface ISpatialFilterOptions { - /** - * One of the following values: - * • nearby – Searches in a radius around a location. - * • nearRoute – Searches for results that are within 1 mile of a route. - * • intersects – Searches for results that intersect with the specified geometry. - * Note: Note that the NavteqNA and NavteqEU data sources only support nearby queries. - */ - spatialFilterType: string; - - /** Location at which the filter should be applied (only for nearby filter). */ - location?: string | Location; - - /** - * Radius to use when performing a nearby search. The distance in kilometers and must be between 0.16 and 1000 kilometers - * (only for nearby filter). - */ - radius?: number; - - /** Start location of the route (only for nearroute filter). */ - start?: string | Location; - - /** End location of the route (only for nearroute filter). */ - end?: string | Location; - - /** Intersection object. Can be a well known text string or a LocationRect object (only for intersects filter). */ - intersects?: string | LocationRect | IPrimitive; - } - - /** Options for find near route query API. */ - export interface IFindNearRouteOptions extends ISpatialFilterOptions { - /** - * One of the following values: - * • Driving [default] - * • Walking - */ - travelMode?: string; - - /** - * An integer value between 0 and 359 that represents degrees from north - * where north is 0 degrees and the heading is specified clockwise from north. - * For example, setting the heading of 270 degrees creates a route that initially heads west - */ - heading?: number; - - /** - * An integer distance specified in meters. - * Use this parameter to make sure that the moving vehicle has enough distance - * to make the first turn - */ - distanceBeforeFirstTurn?: number; - - /** - * A list of values that limit the use of highways and toll roads in the route. - * Use one of the following values: - * • highways - Avoids the use of highways in the route. - * • tolls - Avoids the use of toll roads in the route. - * • minimizeHighways - Minimizes (tries to avoid) the use of highways in the route. - * • minimizeTolls - Minimizes (tries to avoid) the use of toll roads in the route. - */ - avoid?: string[]; - - /** - * One of the following values: - * • distance - The route is calculated to minimize the distance.Traffic information is not used. - * • time[default] - The route is calculated to minimize the time.Traffic information is not used. - * • timeWithTraffic - The route is calculated to minimize the time and uses current traffic information. - */ - optimize?: string; - } - - /** Set of options that can be specified for query APIs. */ - export interface IQueryAPIOptions { - /** A queryurl containing the access id, data source name and the entity type name. */ - queryUrl: string; - - /** Specifies a conditional expression for a list of properties and values. */ - filter?: IFilter; - - /** Specifies whether or not to return a count of the results in the response. Default: false */ - inlineCount?: boolean; - - /** Specifies to query the staged version of the data source instead of the published version. Default: false */ - isStaging?: boolean; - - /** - * Specifies one or more properties to use to sort the results of a query. - * You can specify up to three (3) properties. Results are sorted in ascending order. - * Note: You cannot use the latitude and longitude properties to sort results. You can use the elevation property. - */ - orderBy?: string[]; - - /** - * Specifies the data source properties to return in the response. If the $select query option is not specified or - * if it is set to "" ($select=), all data source properties are returned. Default: "*,_distance" - */ - select?: string[]; - - /** Specifies to not return a specified number of query results. */ - skip?: number; - - /** Spatial filter options to apply. */ - spatialFilter?: ISpatialFilterOptions | IFindNearRouteOptions; - - /** Specifies the maximum number of results to return in the query response. Default: 25 */ - top?: number; - } - - /** - * This is a static class that provides that ability to query data sources that are hosted by the Bing Spatial Data Services using the Query API. - * @requires The Microsoft.Maps.SpatialDataService module. - */ - export module QueryAPIManager { - /** - * Perform a search - * @requires The Microsoft.Maps.SpatialDataService module. - * @param queryOptions - Options for the query - * @param credentials - Credentials for the query - * @param callback - The function to call once the results are retrieved - * @param styles - (Optional) Styles of the data that needs to be rendered on map - */ - export function search(queryOptions: IQueryAPIOptions, - credentials: string | Map, - callback: (data: IPrimitive[], inlineCount?: number) => void, - styles?: IStylesOptions): void; - } -} \ No newline at end of file diff --git a/types/bingmaps/SpatialMath.d.ts b/types/bingmaps/SpatialMath.d.ts deleted file mode 100644 index 4fe3b4ea12..0000000000 --- a/types/bingmaps/SpatialMath.d.ts +++ /dev/null @@ -1,530 +0,0 @@ -////////////////////////////////////////////// -/// Core Library -////////////////////////////////////////////// - -/** - * This module provides a bunch of useful spatial math calculations. - * @requires The Microsoft.Maps.SpatialMath module. - */ -declare module Microsoft.Maps.SpatialMath { - - /** - * Distance Unit enumerator - * @requires The Microsoft.Maps.SpatialMath module. - **/ - export enum DistanceUnits { - /** A distance in meters */ - Meters, - - /** A distance in kilometers */ - Kilometers, - - /** A distance in miles */ - Miles, - - /** A distance in Feet */ - Feet, - - /** A distance in Yards */ - Yards, - - /** A distance in Nautical Miles */ - NauticalMiles - } - - /** - * Area units enumerator - * @requires The Microsoft.Maps.SpatialMath module. - **/ - export enum AreaUnits { - /** Area in square meters */ - SquareMeters, - - /** Area in square kilometers */ - SquareKilometers, - - /** Area in square miles */ - SquareMiles, - - /** Area in square Feet */ - SquareFeet, - - /** Area in square Yards */ - SquareYards, - - /** Area in Acres */ - Acres, - - /** Area in Hectares */ - Hectares - } - - ////////////////////////////////////////////// - /// Core Calculations - ////////////////////////////////////////////// - - /** - * Converts an area from one area units to another. - * @param area A number that represents an area to convert. - * @param fromUnits The area units the original area is in. - * @param toUnits The area units to convert to. - * @returns An area in the new units. - **/ - export function convertArea(area: number, fromUnits: AreaUnits, toUnits: AreaUnits): number; - - /** - * Converts a distance from one distance units to another. - * @param distance A number that represents a distance to convert. - * @param fromUnits The distance units the original distance is in. - * @param toUnits The disired distance units to convert to. - * @returns A distance in the new units. - **/ - export function convertDistance(distance: number, fromUnits: DistanceUnits, toUnits: DistanceUnits): number; - - /** - * Calculates an array of locations that form a cardinal spline between the specified array of locations. - * @param locations The array of locations to calculate the spline through. - * @param tension A number that indicates the tightness of the curve. Can be any number, although a value between 0 and 1 is usually used. Default: 0.5 - * @param nodeSize Number of nodes to insert between each Location. Default: 15 - * @param close A boolean indicating if the spline should be a closed ring or not. Default: false - * @returns An array of locations that form a cardinal spline between the specified array of locations. - */ - export function getCardinalSpline(locations: Location[], tension ?: number, nodeSize ?: number, close ?: boolean): Location[]; - - /** - * Calculates a destination Location based on a starting Location, a heading, a distance, and a distance unit type. - * @param origin Location that the destination is relative to. - * @param bearing A heading angle between 0 - 360 degrees. 0 - North, 90 - East, 180 - South, 270 - West. - * @param distance Distance that destination is away. - * @param units Unit of distance measurement. Default is Meters. - * @returns A Location that is the specified distance away from the origin. - **/ - export function getDestination(origin: Location, bearing: number, distance: number, units?: DistanceUnits): Location; - - /** - * Calculate the distance between two Location objects on the surface of the earth using the Haversine formula. - * @param origin First Location to calculate distance between. - * @param destination Second Location to calculate distance between. - * @param units Unit of distance measurement. Default is Meters. - * @param highAccuracy When set enabled, will use the slower but more accurate Vincenty formula for calculating distances, rather than the Haversine formula. - * @returns The shortest distance between two Locations in the specifed units. - **/ - export function getDistanceTo(origin: Location, destination: Location, units?: DistanceUnits, highAccuracy?: boolean): number; - - /** - * Retrieves the radius of the earth in a specific distance unit for WGS84. - * @param units Unit of distance measurement. Default: Meters - * @returns A number that represents the radius of the earth in a specific distance unit. - **/ - export function getEarthRadius(units?: DistanceUnits): number; - - /** - * Takes an array of Locations objects and fills in the space between them with accurately positioned Locations to form an approximated Geodesic path. - * @param path Array of Location objects that form a path to fill in. - * @param nodeSize Number of nodes to insert between each Location. Default: 15 - * @returns An array of Location objects that form a geodesic paths. - **/ - export function getGeodesicPath(path: Location[], nodeSize?: number): Location[]; - - /** - * Calculates the heading from one Location object to another. - * @param origin Point of origin. - * @param destination Destination to calculate relative heading to. - * @returns A heading in degrees between 0 and 360. 0 degrees points due North. - **/ - export function getHeading(origin: Location, destination: Location): number; - - /** - * Calculates the distance between all Location objects in an array. - * @param path The array of Location objects that make up the path to calculate the length of. - * @param units Unit of distance measurement. Default: Meters - * @param highAccuracy If set to true, uses the more accurate Vincenty algorithm for calcuating distances. Otherwise the faster Haversine formula is used. - * @returns The distance between all Locations in between all Location objects in an array on the surface of a earth in the specifed units. - **/ - export function getLengthOfPath(path: Location[], units?: DistanceUnits, highAccuracy?: boolean): number; - - /** - * Calculates the Location object on a path that is a specified distance away from the start of the path. If the specified distance is longer - * than the length of the path, the last Location of the path will be returned. - * @param path A polyline or array of Location coordinates that form a path. - * @param distance The distance along the path (from the start) to calculate the location for. - * @param units Unit of distance measurement. Default is Meters. - * @returns A Location object that is the specified distance away from the start of the path when following the path. - **/ - export function getLocationAlongPath(path: Polyline | Location[], distance: number, units?: DistanceUnits): Location; - - /** - * Calculates an array of Location objects that are an equal distance away from a central point to create a regular polygon. - * @param origin Center of the regular polygon. - * @param radius Radius of the regular polygon. - * @param numberOfPoints Number of points the polygon should have. - * @param units Unit of distance measurement for radius. Default is Meters. - * @param offset An offset to rotate the polygon clockwise in degrees. When 0 the first Location will align with North. - * @returns An array of Location objects that form a regular polygon. - **/ - export function getRegularPolygon(origin: Location, radius: number, numberOfPoints: number, units?: DistanceUnits, offset?: number): Location[]; - - /** - * Calculates a Location object that is a fractional distance between two Location objects. - * @param origin First Location to calculate mid-point between. - * @param destination Second Location to calculate mid-point between. - * @param fraction The fractional parameter to calculate a mid-point for. Default 0.5. - * @returns A Location that lies a fraction of the distance between two Location objects, relative to the first Location object. - **/ - export function interpolate(origin: Location, destination: Location, fraction?: number): Location; - - /** - * Takes a LocationRect and converts it to a polygon. - * @param bounds The LocationRect to convert to a Polygon. - * @returns A polygon representation of the LocationRect. - **/ - export function locationRectToPolygon(bounds: LocationRect): Polygon; - - /** - * Takes a Location object and converts it into a Degree Minute Seconds string in the format. For example: 40° 26′ 46″ N 79° 58′ 56″ W - * @param loc The Location object to convert into a Degree Minute Seconds string. - * @returns A string in Degree Minute Seconds format or null if invalid Location object is provided. - */ - export function toDegMinSec(loc: Location): string; - - /** - * Tries to parse the given string that is in Degree Minute Seconds format. For Example: 35° 26′ 31″ E or 40° 26′ 46″ N 79° 58′ 56″ W - * @param input A string in Degree Minute Seconds format to parse. - * @returns Returns a decimal degree value if only a single angle is provided. If two angles provided in the string, then a - * Location object is returned. If string is in an invalid format, null is returned. - */ - export function tryParseDegMinSec(input: string): number | Location; -} - - -////////////////////////////////////////////// -/// Tile Calculations -////////////////////////////////////////////// - -/** -* A colleciton of mathematical algorithms based on the tile pyramid used by Bign Maps. -* @requires The Microsoft.Maps.SpatialMath module. -*/ -declare module Microsoft.Maps.SpatialMath.Tiles { - //Based on https://msdn.microsoft.com/en-us/library/bb259689.aspx - - /** - * Calculates the full width of the map in pixels at a specific zoom level from -180 degrees to 180 degrees. - * @param zoom Zoom level to calculate width at. - * @param tileWidth Width of tile. - * @returns Width of map in pixels. - **/ - export function mapSize(zoom: number): number; - - /** - * Calculates the Ground resolution at a specific degree of latitude in the specified units per pixel. - * @param latitude Degree of latitude to calculate resolution at. - * @param zoom Zoom level to calculate resolution at. - * @param units Distance unit type to calculate resolution in. - * @returns Ground resolution in distance unit per pixels. - **/ - export function groundResolution(latitude: number, zoom: number, units?: SpatialMath.DistanceUnits): number; - - /** - * Converts a Pixel coordinate into a Geospatial Location at a specified zoom level. - * Global Pixel coordinates are relative to the top left corner of the map (90, -180) - * @param point Pixel coordinate. - * @param zoom Zoom level. - * @returns A Location that is at the specified pixel location at a specified zoom level. - **/ - export function globalPixelToLocation(point: Point, zoom: number): Location; - - /** - * Converts a point from latitude/longitude WGS-84 Location (in degrees) - * into pixel XY coordinates at a specified level of detail. - * @param loc Location to convert to a global pixel. - * @param zoom Level of detail, from 1 (lowest detail) to 23 (highest detail). - * @returns Point object containing the the global pixel location of a Location. - **/ - export function locationToGlobalPixel(loc: Location, zoom: number): Point; - - /** - * Calculates the PyramidTileId that a global pixel intersects with at a specific zoom level. - * @param pixel The pixel coordinate to calculate the tile for. - * @param zoom The zoom level to calculate the tile for. - * @returns A PyramidTileId that a global pixel intersects with at a specific zoom level. - **/ - export function globalPixelToTile(pixel: Point, zoom: number): PyramidTileId; - - /** - * Converts a PyramidTileId into a global pixel coordinates of the upper-left pixel of the specified tile. - * @param tile A PyramidTileId to calculate the upper-left pixel for. - * @returns Global pixel coordinate of the top left corner of a tile. - **/ - export function tileToGlobalPixel(tile: PyramidTileId): Point; - - /** - * Calculates the PyramidTileId that a Location object intersects with at a specific zoom level. - * @param loc The location to calulate the tile for. - * @param zoom The zoom level to use to calculate the tile. - * @returns A PyramidTileId that a Location object intersects with at a specific zoom level. - **/ - export function locationToTile(loc: Location, zoom: number): PyramidTileId; - - /** - * Calculates all the PyramidTileId's that are within a LocationRect at a specific zoom level. - * @param bounds A LocationRect to search for tiles in. - * @param zoom The zoom level to calculate tiles for. - * @returns A list of PyramidTileId's that are within the specified LocationRect and zoom level. - **/ - export function getTilesInBounds(bounds: LocationRect, zoom: number): PyramidTileId[]; - - /** - * Calculates the LocationRect (bounding box) of a PyramidTileId. - * @param tile A PyramidTileId to calculate the LocationRect of. - * @returns The bounding box of a tile. - **/ - export function tileToLocationRect(tile: PyramidTileId): LocationRect; -} - - -////////////////////////////////////////////// -/// Geometry Calculations -////////////////////////////////////////////// - -/** -* A colleciton of geometry calculations that can be performed against Bing Maps shapes. -* @requires The Microsoft.Maps.SpatialMath module. -*/ -declare module Microsoft.Maps.SpatialMath.Geometry { - - /** Defines how the end of a line should be buffered. */ - export enum BufferEndCap { - /** Adds a rounded end to a buffered line. */ - Round, - - /** Adds a flat end to a buffered line that touches the end of the line. */ - Flat, - - /** Adds a square end to a buffered line that has a buffer area at the end of the line. */ - Square - } - - /** - * Calculates the area of a shape. - * @param shape The shape to calculate the area of. - * @param areaUnits The unit of measurement to calculate the area in. - * @returns The area of a shape in the specified unit of measurement. - */ - export function area(shape: IPrimitive | IPrimitive[], areaUnits?: AreaUnits): number; - - /** - * Calculates a bounding box that encloses a set of shapes and/or locations. - * @param shapes The shape(s) to calculate the bounding box for. - * @returns A location rect that encloses the shapes and/or locations. - */ - export function bounds(shapes: Location | IPrimitive | (Location | IPrimitive)[]): LocationRect; - - /** - * Calcuates a shape with an updated boundary that has been inflated/deflated by a speicifed distance. - * @param shape The shape to buffer. - * @param distance The distance to buffer the shape by. - * @param units The distance units to buffer the shape by. - * @param endCapType The type of end cap to use for the joints of the buffer, default value is round. - * @param options A set of polygon options to apply to the generated shape. - * @returns A buffered version of the shape. - */ - export function buffer(shape: Location | IPrimitive | (Location | IPrimitive)[], distance: number, units?: DistanceUnits, endCapType?: BufferEndCap, options?: IPolygonOptions): IPrimitive | IPrimitive[]; - - /** - * Calculates the center of a shape. - * @param shape The shape to calculate the center of. - * @returns The center of the specified shape. - */ - export function centroid(shape: IPrimitive | IPrimitive[]): Location; - - /** - * Calculates an approximate concave hull that best fits the data. - * A concave hull is a shape that represents that a possible concave geometry that encloses all shapes in the specified data set. - * If a single unique Location is in the data set, a Pushpin is returned. If only two unique Locations are provided, or if all Locations form a line, a Polyline is returned. - * If 3 or more unique Locations are in the data set a Polygon, or array of Polygons will be returned. - * @param shapes Shape(s) whose Location(s) or Location(s) are to be used to generate a concave hull. - * @param allowMultiPolygons A boolean indicating if the resulting concave hull can be a MultiPolygon. Default: false - * @param allowHoles A boolean indicating if the polygons in the resulting concave hull can have holes in them. Default: false - * @param options A set of polygon options to apply to the generated shape. - * @returns An approximate concave hull that best fits the data. - * If a single unique Location is in the data set, a Pushpin is returned. If only two unique Locations are provided, or if all Locations form a line, a Polyline is returned. - * If 3 or more unique Locations are in the data set a Polygon, or array of Polygons will be returned. - */ - export function concaveHull(shapes: Location | IPrimitive | (Location | IPrimitive)[], allowMultiPolygons?: boolean, allowHoles?: boolean, options?: IPolygonOptions): IPrimitive | IPrimitive[]; - - /** - * Given two shapes, determines if the first one contains the second one - * (or, the second shape is a subset of the first shape) or not. - * @param shapeA The first shape to test against the second. - * @param shapeB The second shape to test against the first. - * @returns A boolean indicating if the first shape contains the second shape. - */ - export function contains(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[]): boolean; - - /** - * Calculates a convex hull. A convex hull is a shape that represents that minimum convex geometry that encloses all shapes in the specified data set. - * @param shapes Shape(s) whose Location(s) or Location(s) are to be used to generate a convex hull. - * @param options A set of polygon options to apply to the generated shape. - * @returns An array of locations that form a convex hull that encloses all locations of the shapes provided in an array. - */ - export function convexHull(shapes: Location | IPrimitive | (Location | IPrimitive)[], options?: IPolygonOptions): IPrimitive | IPrimitive[]; - - /** - * Creates Delaunay Triangles from the Location objects of the provided shapes. - * @param shapes Location(s) of shape(s) or Location(s) to generate a Delaunay Triangles from. - * @param options A set of polyline or polygon options to apply to the generated shape. - * @returns An array of shapes that form the polygon triangles of the delaunay triangles. - */ - export function delaunayTriangles(shapes: Location | IPrimitive | (Location | IPrimitive)[], options?: IPolygonOptions): Polygon[]; - - /** - * Returns an object that represents area of an initial shape subtracted by the overlapping area of a second shape. - * @param shapeA The first shape. - * @param shapeB The second shape to subtract from the first. - * @returns A set of shapes that represent the area of the first shape that is not overlapped by the second shape. - */ - export function difference(shapeA: IPrimitive | IPrimitive[], shapeB: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; - - /** - * Calculates the approximate shortest distance between any two shapes. - * @param shapeA The first shape to calculate the distance from. - * @param shapeB The second shape to calculate the distance to. - * @param units Unit of distance measurement. Default: Meters - * @param highAccuracy If set to true, uses the more accurate Vincenty algorithm for calcuating distances. Otherwise the faster Haversine formula is used. - * @returns The shorested distance between the shapes in the specified units. - */ - export function distance(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[], units?: DistanceUnits, highAccuracy?: boolean): number; - - /** - * Returns an object that represents the area where two shapes intersect. - * @param shapeA The first shape. - * @param shapeB The second shape. - * @returns A set of shapes that represents the area where two shapes intersect. - */ - export function intersection(shapeA: IPrimitive | IPrimitive[], shapeB: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; - - /** - * Determines if two shapes intersect or not. - * @param shapeA The first shape to test against the second. - * @param shapeB The second shape to test against the first. - * @returns A boolean indicating if the two shapes intersect. - */ - export function intersects(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[]): boolean; - - /** - * Tests to see if the shape is valid and meets the requirements of an SQL Geography type and other OGC compliant systems. Polylines & Polygons can't be self intersecting. For Polygons, - * coordinates in an exterior rings have a counter-clockwise orientation, while holes have a clockwise orientation. - * @param shape The shape to test for validity. - * @returns Returns a boolean indicting if the specified shape(s) is valid or not. - */ - export function isValid(shape: IPrimitive | IPrimitive[]): boolean; - - /** - * Calculates the distance between all Locations in a shape. If the shape is a polygon, the length of the perimeter of all rings is calculated. - * @param shape The shape to calculate the length of. - * @param units Unit of distance measurement. Default: Meters - * @param highAccuracy If set to true, uses the more accurate Vincenty algorithm for calcuating distances. Otherwise the faster Haversine formula is used. - * @returns The distance between all Locations in a polyline or the perimeter of a ploygon on the surface of a earth in the specifed units. - */ - export function calculateLength(shape: IPrimitive | IPrimitive[], units ?: DistanceUnits, highAccuracy ?: boolean): number; - - /** - * Takes a shape and returns a copy of it that meets the requirements of an SQL Geography type and other OGC compliant systems. Polylines & Polygons can't be self intersecting. For Polygons, - * coordinates in an exterior rings have a counter-clockwise orientation, while holes have a clockwise orientation. - * @param shape The shape to make valid. - * @returns Valiated version of the provided shape. May be a different shape type than what was provided. i.e. A polygon may be broken up into an array of polygons (MultiPolygon). - */ - export function makeValid(shape: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; - - /** - * Calculates the nearest Location objects between to shapes that lie on the shapes. - * If the shapes do not overlap, this calculates a location on each shape that is closest to the other shape. - * If the shapes overlap, a location that is within the intersection area of the shapes will be added twice to an array, once for each shape, and returned. - * @param shapeA The first shape. - * @param shapeB The second shape. - * @returns An array of two Location objects that represent the nearest points between two shapes. - * The Location objects are in the same order as the input shapes. - * Returns null if nearest points were unable to be computed. - */ - export function nearestLocations(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[]): Location[]; - - /** - * Reduces the resolution of a shape using the Douglas-Peucker algorithm. - * @param shape The shape to reduce the resolution of. - * @param tolerance A tolerance distance in meters used by the reduction algorithms. - * @returns A version of the specified shape that has been reduced. - */ - export function reduce(shape: IPrimitive | IPrimitive[], tolerance: number): IPrimitive | IPrimitive[]; - - /** - * Rotates a shape around a given Location for the specified angle of rotation. If an origin is not provided, the centroid of the shape is used. - * @param shape The shape to be rotated. - * @param angle The amount to rotate the shape in degrees. - * @param origin The location to rotate the shape around. Defaults to the centroid of the shape. - */ - export function rotate(shape: IPrimitive | IPrimitive[], angle: number, origin?: Location): void; - - /** - * Calculates the shortest path that between two shapes and returns a Polyline. - * @param shapeA The first shape. - * @param shapeB The second shape. - * @param options A set of polyline options to apply to the generated polyline. - * @returns A polyline that represents the shortest path between two shapes. - */ - export function shortestLineTo(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[], options?: IPolylineOptions): Polyline; - - /** - * Snaps the locations of one shape that are within the specified tolerance distance away from another shape. - * @param locs The locations to snap to the shape. - * @param shape The shape to snap the locations to. - * @param tolerance A maximum distance (in the specified units) that the snapped location can be from the input location. Default: Infinity - * @param toleranceUnits The distance units of the tolerance value. Default: Meters - * @returns A snapped location if only one location is provided, otherwise returns an array of snapped locations. - */ - export function snapLocationsToShape(locs: Location | Location[], shape: IPrimitive | IPrimitive[], tolerance?: number, toleranceUnits?: DistanceUnits): Location | Location[]; - - /** - * Snaps the locations of one shape that are within the specified tolerance distance away from another shape. - * @param shapeToSnap The shape to snap the locations of. - * @param shape The shape to snap the locations to. - * @param tolerance A maximum distance (in the specified units) that the snapped location can be from the input location. Default: Infinity - * @param toleranceUnits The distance units of the tolerance value. Default: Meters - */ - export function snapShapeToShape(shapeToSnap: IPrimitive | IPrimitive[], shape: IPrimitive | IPrimitive[], tolerance?: number, toleranceUnits?: DistanceUnits): void; - - /** - * Returns an object that represents all points that are either in one shape instance or another, but not those points that lie in both instances. - * "Sym" stands for Symmetric. symDifference is an OGC standard name for this calculation used in most spatial math libraries, including SQL. - * @param shapeA The first shape. - * @param shapeB The second shape. - * @returns A shape that represents the symetric difference between two shapes. - */ - export function symDifference(shapeA: IPrimitive | IPrimitive[], shapeB: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; - - /** - * Returns an object that represents the union of two shapes. If shapes don't overlap, an array of each individual shapes will be returned. - * @param shapeA The first shape. - * @param shapeB The second shape. - * @returns A shape that represents the union of two shapes. - */ - export function union(shapeA: IPrimitive | IPrimitive[], shapeB: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; - - /** - * Performs a union operation on a set of shapes. - * If a shape doesn't overlap with the rest, the returned result will be an array of shapes containing this shape and the union of the rest. - * @param shapes An array of shapes to union together. - * @returns A shape that represents the union of all specified shapes. - */ - export function unionAggregate(shapes: IPrimitive[]): IPrimitive | IPrimitive[]; - - /** - * Creates a Voronoi diagram from the Location objects of the provided shapes. The diagram is returned as an array of Polygons. - * If a clip region is specified, the diagram will be clipped accordingly. - * @param shapes Location(s) of shape(s) or Location(s) to generate a Voronoi diagram. - * @param clipRegion A region to clip the voronoi diagram to. - * @param options A set of polygon options to apply to the generated shape. - * @returns An array of polygons that form a Voronoi diagram. - */ - export function voronoiDiagram(shapes: Location | IPrimitive | (Location | IPrimitive)[], clipRegion?: LocationRect | Polygon, options?: IPolygonOptions): Polygon[]; -} \ No newline at end of file diff --git a/types/bingmaps/Traffic.d.ts b/types/bingmaps/Traffic.d.ts deleted file mode 100644 index 1c78256053..0000000000 --- a/types/bingmaps/Traffic.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Adds a traffic incident and flow data to the map. - * @requires The Microsoft.Maps.Traffic module. - */ -declare module Microsoft.Maps.Traffic { - /** Options that can be customized in the Traffic manager. */ - export interface ITrafficOptions { - /** Displays the traffic flow layer. */ - flowVisible?: boolean; - - /** Displays all traffic incidents. */ - incidentsVisible?: boolean; - - /** Displays the traffic legend. */ - legendVisible?: boolean; - - /** - * Sets the opacity of the traffic flow tile layer. Must be a number between 0 and 1. The default is 1 unless the map - * mode is set to lite, in which case the default is set to 0.7. - */ - opacity?: number; - } - - /** - * The TrafficManager class provides the ability to show traffic flow and incident data on top of the map. When creating an - * instance of the TrafficManager class the map must be passed as an argument to the constructor. - * @requires The Microsoft.Maps.Traffic module. - */ - export class TrafficManager { - /** - * @constructor - * @requires The Microsoft.Maps.Traffic module. - * @param map A map instnce to attach the traffic manager to. - */ - constructor(map: Map); - - /** Hides all traffic data. */ - public hide(): void; - - /** Hides the traffic flow layer. */ - public hideFlow(): void; - - /** Hides all traffic incidents. */ - public hideIncidents(): void; - - /** Hides the traffic legend. */ - public hideLegend(): void; - - /** - * Sets the options for the traffic manager. - * @param options The options for the traffic manager. - */ - public setOptions(options: ITrafficOptions): void; - - /** Displays all traffic data. */ - public show(): void; - - /** Displays the traffic flow layer. */ - public showFlow(): void; - - /** Displays all traffic incidents. */ - public showIncidents(): void; - - /** Displays the traffic legend. */ - public showLegend(): void; - - } -} \ No newline at end of file diff --git a/types/bingmaps/WellKnownText.d.ts b/types/bingmaps/WellKnownText.d.ts deleted file mode 100644 index 51c42203ce..0000000000 --- a/types/bingmaps/WellKnownText.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -declare module Microsoft.Maps { - /** - * Class responsible for readon/writing geo data in well known text format - * @requires The Microsoft.Maps.WellKnownText module. - */ - export module WellKnownText { - /** - * Reads the data in wellknowntext format and returns the shapes. Multi-Geometry type shapes are returned as an array of shapes. - * @param wkt The well known text string that needs to be parsed into shapes. - * @param styles Styles to apply to the shapes. - * @returns One of more shapes. - */ - export function read(wkt: string, styles?: IStylesOptions): IPrimitive | IPrimitive[]; - - /** - * Writes the data into wellknowntext format. - * @param data The data that needs to be serialized. - * @returns Well known text formatted string. - */ - export function write(data: IPrimitive | IPrimitive[]): string; - } -} \ No newline at end of file diff --git a/types/bingmaps/bingmaps-tests.ts b/types/bingmaps/bingmaps-tests.ts deleted file mode 100644 index 962c3047fa..0000000000 --- a/types/bingmaps/bingmaps-tests.ts +++ /dev/null @@ -1,83 +0,0 @@ -namespace BingMapsTests { - - // An interactive set of Bing Maps AJAX control usages can be found at http://www.bingmapsportal.com/isdk/ajaxv7 - // A full API description can be found at http://msdn.microsoft.com/en-us/library/gg427610.aspx - export class TestFixture { - - public createMap( - // This key can be acquired at http://www.microsoft.com/maps/create-a-bing-maps-key.aspx - bingMapsApiKey: string, - // This is the HTML container that the map will be drawn inside of - target: HTMLElement, - // These positions will be placed as pushpins onto the map - mapPositions: Array, - // This will fire if the geolocation fails and will pass the original target (parameter 2) - onFailure: (element: HTMLElement) => any) { - - var self = this; - var map: Microsoft.Maps.Map; - - navigator.geolocation.getCurrentPosition((position: Position) => { - - var locations: Array = new Array(); - var options: Microsoft.Maps.IMapLoadOptions; - - function loadMap() { - options = { - credentials: bingMapsApiKey, - enableClickableLogo: false, - showDashboard: false, - showScalebar: false, - center: self.toLocation(position), - zoom: 16, - mapTypeId: Microsoft.Maps.MapTypeId.road - }; - - target.innerHTML = ""; - - map = new Microsoft.Maps.Map(target, options); - - for (var i = 0; i < mapPositions.length; ++i) { - - var mapPosition: Position = mapPositions[i]; - var location: Microsoft.Maps.Location = self.createPushpin(map, mapPosition); - - locations.push(location); - } - - // Sets the view of the map to the smallest size that contains all of the - // specified locations (in this case the pusphin locations) - map.setView({ bounds: Microsoft.Maps.LocationRect.fromLocations(locations) }); - } - - if ((window).Windows != undefined) { - // Running in Win8 app - Microsoft.Maps.loadModule("Microsoft.Maps.Map", { callback: loadMap }); - } else { - // Running anywhere else - loadMap(); - } - }, () => onFailure(target), { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }); - - } - - // Converts a standard HTML geolocation Position to a Location - private toLocation(position: Position): Microsoft.Maps.Location { - return new Microsoft.Maps.Location(position.coords.latitude, position.coords.longitude); - } - - // Creates a pushpin on a specified map and returns the Location for potentially setting the map view - private createPushpin(map: Microsoft.Maps.Map, position: Position): Microsoft.Maps.Location { - - var location: Microsoft.Maps.Location; - var pushpin: Microsoft.Maps.Pushpin; - - location = this.toLocation(position); - pushpin = new Microsoft.Maps.Pushpin(location, null); - - map.entities.push(pushpin); - - return location; - } - } -} diff --git a/types/bingmaps/index.d.ts b/types/bingmaps/index.d.ts deleted file mode 100644 index b629e3b903..0000000000 --- a/types/bingmaps/index.d.ts +++ /dev/null @@ -1,2850 +0,0 @@ -// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) -// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions -// Definitions by: Ricky Brundritt -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// - -/** - * The Bing Maps V8 developer API. - */ -declare module Microsoft.Maps { - - ////////////////////////////////////////////// - /// Custom Map Styles - ////////////////////////////////////////////// - - /** The styles options that can be applied to map elements. */ - export interface IMapElementStyle { - /** - * Hex color used for filling polygons, the background of point icons, and for the center of lines if they have split. - */ - fillColor?: string; - - /** - * The hex color of a map label. - */ - labelColor?: string; - - /** - * The outline hex color of a map label. - */ - labelOutlineColor?: string; - - /** - * Species if a map label type is visible or not. - */ - labelVisible?: boolean; - - /** - * Hex color used for the outline around polygons, the outline around point icons, and the color of lines. - */ - strokeColor?: string; - - /** - * Specifies if the map element is visible or not. - */ - visible?: boolean; - } - - /** The style options that can be appliction to bordered map elements. */ - export interface IBorderedMapElementStyle extends IMapElementStyle { - /** - * Secondary/casing line hex color of the border of a filled polygon. - */ - borderOutlineColor?: string; - - /** - * Primary line hex color of the border of a filled polygon. - */ - borderStrokeColor?: string; - - /** - * Specifies if a border is visible or not. - */ - borderVisible?: boolean; - } - - /** Global style settings */ - export interface ISettingsStyle { - /** A hex color value that all land is first flushed to before things are drawn on it. */ - landColor?: string; - - /** Specifies whether or not to draw elevation shading on the map. */ - shadedReliefVisible?: boolean; - } - - /** Map Elements which can be styled. */ - export interface IMapElements { - - /** Admin1, state, province, etc. */ - adminDistrict?: IBorderedMapElementStyle; - - /** Icon representing the capital of a state/province. */ - adminDistrictCapital?: IMapElementStyle; - - /** Area of land encompassing an airport. */ - airport?: IMapElementStyle; - - /** Area of land use, not to be confused with Structure */ - area?: IMapElementStyle; - - /** An arterial road is a high-capacity urban road. Its primary function is to deliver traffic from collector roads to freeways or expressways, and between urban centers efficiently. */ - arterialRoad?: IMapElementStyle; - - /** A structure such as a house, store, factory. */ - building?: IMapElementStyle; - - /** Restaurant, hospital, school, etc. */ - business?: IMapElementStyle; - - /** Icon representing the capital populated place. */ - capital?: IMapElementStyle; - - /** Area of a cemetery */ - cemetery?: IMapElementStyle; - - /** Area of a whole continent */ - continent?: IMapElementStyle; - - /** A controlled-access highway is a type of road which has been designed for high-speed vehicular traffic, with all traffic flow and ingress/egress regulated. Also known as a highway, freeway, motorway, expressway, interstate, parkway. */ - controlledAccessHighway?: IMapElementStyle; - - /** A country or independent sovereign state. */ - countryRegion?: IBorderedMapElementStyle; - - /** Icon representing the capital of a country/region. */ - countryRegionCapital?: IMapElementStyle; - - /** Admin2, county, etc. */ - district?: IBorderedMapElementStyle; - - /** An area of land used for educational purposes such as a school campus. */ - education?: IMapElementStyle; - - /** A school or other educational building. */ - educationBuilding?: IMapElementStyle; - - /** Restaurant, caf�, etc. */ - foodPoint?: IMapElementStyle; - - /** Area of forest land. */ - forest?: IMapElementStyle; - - /** An area of land where the game of golf is played. */ - golfCourse?: IMapElementStyle; - - /** Lines representing ramps typically alongside ControlledAccessHighways */ - highSpeedRamp?: IMapElementStyle; - - /** A highway. */ - highway?: IMapElementStyle; - - /** An area of land reserved for Indigenous people. */ - indigenousPeoplesReserve?: IMapElementStyle; - - /** Labeling of area of an island. */ - island?: IMapElementStyle; - - /** Major roads. */ - majorRoad?: IMapElementStyle; - - /** The base map element in which all other map elements inherit from. */ - mapElement?: IMapElementStyle; - - /** Area of land used for medical purposes. Generally, hospital campuses. */ - medical?: IMapElementStyle; - - /** A building which provides medical services. */ - medicalBuilding?: IMapElementStyle; - - /** A military area. */ - military?: IMapElementStyle; - - /** A natural point of interest. */ - naturalPoint?: IMapElementStyle; - - /** Area of land used for nautical purposes. */ - nautical?: IMapElementStyle; - - /** Area defined as a neighborhood. Labels only. */ - neighborhood?: IMapElementStyle; - - /** Area of any kind of park. */ - park?: IMapElementStyle; - - /** Icon representing the peak of a mountain. */ - peak?: IMapElementStyle; - - /** All point features that are rendered with an icon of some sort */ - point?: IMapElementStyle; - - /** Restaurant, hospital, school, marina, ski area, etc. */ - pointOfInterest?: IMapElementStyle; - - /** A political border. */ - political?: IBorderedMapElementStyle; - - /** Icon representing size of populated place (city, town, etc). */ - populatedPlace?: IMapElementStyle; - - /** Railway lines */ - railway?: IMapElementStyle; - - /** Line representing the connecting entrance/exit to a highway. */ - ramp?: IMapElementStyle; - - /** Area of nature reserve. */ - reserve?: IMapElementStyle; - - /** River, stream, or other passage. Note that this may be a line or polygon and may connect to non-river water bodies. */ - river?: IMapElementStyle; - - /** Lines that represent all roads */ - road?: IMapElementStyle; - - /** Icon representing the exit, typically from a controlled access highway. */ - roadExit?: IMapElementStyle; - - /** Sign representing a compact name for a road. For example, I-5. */ - //roadShield?: IMapElementStyle; - - /** Land area covered by a runway. See also Airport for the land area of the whole airport. */ - runway?: IMapElementStyle; - - /** Area generally used for beaches, but could be used for sandy areas/golf bunkers in the future. */ - sand?: IMapElementStyle; - - /** A shopping center or mall. */ - shoppingCenter?: IMapElementStyle; - - /** Area of a stadium. */ - stadium?: IMapElementStyle; - - /** A street. */ - street?: IMapElementStyle; - - /** Buildings and other building-like structures */ - structure?: IMapElementStyle; - - /** A toll road. */ - tollRoad?: IMapElementStyle; - - /** Walking trail, either through park or hiking trail */ - trail?: IMapElementStyle; - - /** Icon representing a bus stop, train stop, airport, etc. */ - transit?: IMapElementStyle; - - /** A transit building. */ - transitBuilding?: IMapElementStyle; - - /** Lines that are part of the transportation network (roads, trains, ferries, etc) */ - transportation?: IMapElementStyle; - - /** An unpaved street. */ - unpavedStreet?: IMapElementStyle; - - /** Forests, grassy areas, etc. */ - vegetation?: IMapElementStyle; - - /** Icon representing the peak of a volcano. */ - volcanicPeak?: IMapElementStyle; - - /** Anything that looks like water */ - water?: IMapElementStyle; - - /** Icon representing a water feature location such as a waterfall. */ - waterPoint?: IMapElementStyle; - - /** Ferry route lines */ - waterRoute?: IMapElementStyle; - } - - /** Defines a custom map style. */ - export interface ICustomMapStyle { - /** A list of map elements to be styled. */ - elements?: IMapElements; - - /** Global Settings. */ - settings?: ISettingsStyle; - - /** The version of the style syntax used. */ - version: string; - } - - ////////////////////////////////////////////// - /// Enumerations - ////////////////////////////////////////////// - - /** This enumeration defines how the map labels are displayed. */ - export enum LabelOverlay { - /** - * Map labels are hidden. Note that this will have no effect on road maps unless the allowHidingLabelsOfRoad map option - * is set to true. - */ - hidden, - - /** Map labels are visible. */ - visible - } - - /** This enumeration is used to specify the type of map style that should be displayed by the map. */ - export enum MapTypeId { - /** The aerial map type which uses top-down satellite & airplane imagery. */ - aerial, - - /** High resolution aerial imagery taken at 45 degrees to the ground, from 4 different directions. */ - birdseye, - - /** A darker version of the road maps. */ - canvasDark, - - /** A lighter version of the road maps which also has some of the details such as hill shading disabled. */ - canvasLight, - - /** A grayscale version of the road maps. */ - grayscale, - - /** Displays a blank canvas that uses the mercator map project. It basically removed the base maps layer. */ - mercator, - - /** Ordnance survey map type (en-gb only). */ - ordnanceSurvey, - - /** Road map type. */ - road, - - /** Provides streetside panoramas from the street level. */ - streetside - } - - /** The NavigationBarMode can be used to customize the layout and style of the navigation bar. */ - export enum NavigationBarMode { - /** - * A compact navigation bar that includes a smaller drop down for the map type and zoom buttons. Recommended for small - * maps or screen such as a mobile device. - */ - compact, - - /** - * The default navigation bar that has a drop down for the map type, a locate me button, and zoom buttons. Recommended for - * medium to large maps in desktop browsers. - */ - default, - - /** - * A minified navigation bar that has a button to toggle between road and aerial maps, zoom buttons, and a button to turn - * traffic information on and off. Recommended for small maps or screen such as a mobile device. - */ - minified - } - - /** The NavigationBarOrientation enumeration is used to define how the navigation bar controls are laid out. */ - export enum NavigationBarOrientation { - /** Repositions the buttons in the navigation bar such that they are aligned horizontally. */ - horizontal, - - /** Repositions the buttons in the navigation bar such that they are aligned vertically. */ - vertical - } - - /** This enumeration is used to specify how the overview map for the streetside map mode should be displayed. */ - export enum OverviewMapMode { - /** Shows the overview map in an expanded state. */ - expanded, - - /** Hides the overview map. */ - hidden, - - /** Shows the overview map in a minimized state. */ - minimized - } - - /** Contains enum to show how pixels are defined. */ - export enum PixelReference { - /** The pixel is defined relative to the map control�s root element, where the top left corner of the map control is (0, 0). */ - control, - - /** The pixel is defined relative to the page, where the top left corner of the HTML page is (0, 0). */ - page, - - /** The pixel is defined in viewport coordinates, relative to the center of the map, where the center of the map is (0, 0). */ - viewport - } - - ////////////////////////////////////////////// - /// Interfaces - ////////////////////////////////////////////// - - /** Represents a structured address object. */ - export interface IAddress { - /** - * The street line of an address. The addressLine property is the most precise, official line for an address relative to the postal agency - * servicing the area specified by the locality or postalCode properties. - */ - addressLine: string; - - /** - * The subdivision name within the country or region for an address. This element is also commonly treated as the first order administrative - * subdivision. An example is a US state, such as �Oregon�. - */ - adminDistrict: string; - - /** The country or region name of the address. */ - countryRegion: string; - - /** A string specifying the two-letter ISO country code. */ - countryRegionISO2: string; - - /** The second, third, or fourth order subdivision within a country, dependency, or region. An example is a US county, such as �King�. */ - district: string; - - /** A nicely formatted address string for the result. */ - formattedAddress: string; - - /** The locality, such as the primary city, that corresponds to an address. An example is �Seattle�. */ - locality: string; - - /** The post code, postal code, or ZIP code of an address. An example is a US ZIP code, such as �98152�. */ - postalCode: string; - } - - /** The event args for when a layer frame is being loaded in an AnimtedTileLayer. **/ - export interface IAnimatedFrameEventArgs { - /** The animated tile layer that the frame belongs to. **/ - animatedTileLayer: AnimatedTileLayer; - - /** The index of the frame being loaded. **/ - index: number; - } - - /** An object that defines the options for an AnimatedTileLayer. **/ - export interface IAnimatedTileLayerOptions { - /** A boolean that specifies whether the animation should auto-start when it is added to the map or not. Default: true **/ - autoPlay?: boolean; - - /** The number of miliseconds between two layer frames. Default: 1000 **/ - frameRate?: number; - - /** A custom loading screen to show on the map when the map tiles are being fetched. **/ - loadingScreen?: CustomOverlay; - - /** The max amount of total loading time of all tiles in a viewport in milliseconds. Default: 15000 **/ - maxTotalLoadTime?: number; - - /** The array of tile layer sources to animate through. **/ - mercator: TileSource[]; - - /** A boolean specifying if the animated tile layer is visible or not. **/ - visible?: boolean; - } - - /** Represents the options that can be used when initializing a custom overlay. **/ - export interface ICustomOverlayOptions { - /** - * Specifies if the custom overlay should eb rendered above or below the label layer of the map. When above, - * elements in the overlay can be clickable. Default: True - */ - beneathLabels?: boolean; - } - - /** Base data layer interface. */ - export interface IDataLayer extends ILayer { - /** Clears all data in the layer. */ - clear(): void; - } - - /** Event args included in entity collection events. */ - export interface IEntityCollectionChangedEventArgs { - /** The entity collection the event was triggered from. */ - collection: EntityCollection; - - /** The IPrimitive object that the event occurred for. */ - data: IPrimitive; - } - - /** An object the identifies an event that has been attached to an object. */ - export interface IHandlerId { - } - - /** Base layer interface. */ - export interface ILayer { - } - - /** - * @deprecated use IMouseEventArgs - * A LayerMouseEventArgs object is returned by many the mouse event handlers attached to a Layer. - */ - export interface ILayerMouseEventArgs { - /** - * @deprecated use target - * The IPrimitive shape (pushpin, polyline, polygon) that the event occurred on. - */ - primitive: IPrimitive; - } - - /** The options that can be used to customize an infobox. */ - export interface IInfoboxOptions { - /** - * @deprecated Use HTML buttons and links in description instead. - */ - actions?: IInfoboxActions[]; - - /** The string displayed inside the infobox. */ - description?: string; - - /** - * The HTML that represents the infobox. Note that infobox options are ignored if custom HTML is set. Also, if custom HTML is used to represent the - * infobox, the infobox is anchored at the top-left corner. - */ - htmlContent?: string; - - /** The location on the map where the infobox�s anchor is attached. */ - location?: Location; - - /** The maximium size that the infobox height can expand to based on it�s content. Default: 126 **/ - maxHeight?: number; - - /** The maximium size that the infobox width can expand to based on it�s content. Default: 256 **/ - maxWidth?: number; - - /** - * The amount the infobox pointer is shifted from the location of the infobox, or if showPointer is false, then it is the amount the info box bottom - * left edge is shifted from the location of the infobox. If custom HTML is set, it is the amount the top-left corner of the infobox is shifted from - * its location. The default offset value is (0,0), which means there is no offset. - */ - offset?: Point; - - /** - * A boolean indicating whether to show the close dialog button on the infobox. The default value is true. By default, the close button is displayed - * as an X in the top right corner of the infobox. This property is ignored if custom HTML is used to represent the infobox. - */ - showCloseButton?: boolean; - - /** - * A boolean indicating whether to display the infobox with a pointer. The default value is true. In this case the infobox is anchored at the bottom - * point of the pointer. If this property is set to false, the infobox is anchored at the bottom left corner. This property is ignored if custom HTML - * is used to represent the infobox. - */ - showPointer?: boolean; - - /** The title of the infobox. */ - title?: string; - - /** - * A boolean indicating whether to show or hide the infobox. The default value is true. A value of false indicates that the infobox is hidden, - * although it is still an entity on the map. - */ - visible?: boolean; - - /** The z-index of the infobox with respect to other items on the map. */ - zIndex?: number; - } - - /** - * @deprecated Use HTML buttons and links in description instead. - */ - export interface IInfoboxActions { - /** The text to display for the action. */ - label: string; - - /** The function to call when the label is clicked. */ - eventHandler: (eventArg?: MouseEvent) => void; - } - - /** An object that contains information about an infobox event. **/ - export interface IInfoboxEventArgs { - /** The event that occurred. **/ - eventName: string; - - /** The x-value of the pixel coordinate on the page of the mouse cursor. **/ - pageX: number; - - /** The y-value of the pixel coordinate on the page of the mouse cursor. **/ - pageY: number; - - /** The infobox object that fired the event. **/ - target: Infobox; - - /** The type of the object that fired the event.This will always be 'infobox'. **/ - targetType: string; - - /** Original mouse event from the browser. */ - originalEvent?: MouseEvent; - } - - /** Map or View options */ - export interface IMapLoadOptions extends IMapOptions, IViewOptions { - /** The Bing Maps Key used to authenticate the application. This property can only be set when using the Map constructor. */ - credentials: string; - } - - /** - * An object that can be used to customize the map. Some of the map options can be changed after the map has loaded by using - * the setOptions function on the map. - */ - export interface IMapOptions { - - /** - * A boolean that, when set to true, allows the road labels to be hidden. Default: false - * This property can only be set when using the Map constructor. This property can only be set when using the Map constructor. - */ - allowHidingLabelsOfRoad?: boolean; - - /** A boolean indicating if the infobox is allowed to overflow outside the bounds of the map. Default: false. */ - allowInfoboxOverflow?: boolean; - - /** The color to use for the map control background. The default color is #EAE8E1. This property can only be set when using the Map constructor. */ - backgroundColor?: string | Color; - - /** Custom map styles used to modify the look and feel of the base map. */ - customMapStyle?: ICustomMapStyle; - - /** A boolean value indicating whether to disable the user�s ability to control the using the keyboard. Default: false */ - disableKeyboardInput?: boolean; - - /** A boolean value indicating if mousing over the map type selector should open it or not. Default: true */ - disableMapTypeSelectorMouseOver?: boolean; - - /** A boolean value indicating whether to disable the user's ability to pan the map. Default: false */ - disablePanning?: boolean; - - /** - * Scrolling the mouse wheel over the map will zoom it in or out, but will not scroll the page. - * Setting this property to true disables the zooming of the map and instead reverts back to scrolling the page instea. - * Default: false - */ - disableScrollWheelZoom?: boolean; - - /** - * A boolean indicating whether to disable streetside mode.If this property is set to true, streetside will be removed from - * the navigation bar, and the automatic coverage overlay will be disabled when zoomed in at lower zoom levels. Default false - * This property can only be set when using the Map constructor. - */ - disableStreetside?: boolean; - - /** - * A boolean indicating whether to disable the automatic streetside coverage layer that appears when zoomed in at lower zoom - * levels. Default false - * This property can only be set when using the Map constructor. - **/ - disableStreetsideAutoCoverage?: boolean; - - /** A boolean value indicating whether to disable the user's ability to zoom in or out. Default: false */ - disableZooming?: boolean; - - /** - * A boolean value indicating whether the Bing(TM) logo on the map is clickable. Default: true. - * This property can only be set when using the Map constructor. - */ - enableClickableLogo?: boolean; - - /** - * A boolean value indicating whether to use the inertia animation effect during map navigation. Default: true - * This property can only be set when using the Map constructor. - */ - enableInertia?: boolean; - - /** - * A boolean that indicates if the map should be rendered using lite mode. When set to true vector map labels are - * disabled and map labels are rendered directly into the map tiles. This offers improved performance, but will result - * in the labels being rendered behind data on the map and the labels will also not use collision dection with pushpins. - * If this property is not set, the map set this value based on the target device and browser as vector labels perform - * better in some scenrarios than others. - * This property can only be set when using the Map constructor. - */ - liteMode?: boolean; - - /** A bounding area that restricts the map view. */ - maxBounds?: LocationRect; - - /** The maximum zoom level that the map can be zoomed into. */ - maxZoom?: number; - - /** The minimum zoom level that the map cab be zoomed out to. */ - minZoom?: number; - - /** Specifies how the navigation bar should be rendered on the map. */ - navigationBarMode?: NavigationBarMode; - - /** A boolean whether what orientation should be used when laying out the navigation controls. */ - navigationBarOrientation?: NavigationBarOrientation; - - /** - * A boolean value indicating whether to display the �breadcrumb control�. The breadcrumb control shows the current center location�s geography hierarchy. - * The default value is false. Requires the showLocateMeButton map option to be set to true. The breadcrumb control displays best when the width of the map - * is at least 400 pixels. - */ - showBreadcrumb?: boolean; - - /** - * A boolean value indicating whether to show the map navigation control. Default: true�This property can only be set when using the Map constructor. - */ - showDashboard?: boolean; - - /** - * A boolean value indicating whether to show a button that centers the map over the user's location in the map navigation control. Default: true - * This property can only be set when using the Map constructor. - */ - showLocateMeButton?: boolean; - - /** - * A boolean value indicating whether or not to show the map Bing logo. The default value is true. - * This property can only be set when using the Map constructor. - */ - showLogo?: boolean; - - /** - * A boolean value indicating whether to show the map type selector in the map navigation control. Default: true - * This property can only be set when using the Map constructor. - */ - showMapTypeSelector?: boolean; - - /** - * A boolean value indicating whether to show the scale bar. Default: true - * This property can only be set when using the Map constructor. - */ - showScalebar?: boolean; - - /** When using the minified navigation bar, a traffic button is displayed. Setting this option to false will hide this button. */ - showTrafficButton?: boolean; - - /** - * A boolean value indicating whether to show a link to the End User Terms of Use, which appears to the right of the copyrights, or not. Default: true - * This property can only be set when using the Map constructor. - */ - showTermsLink?: boolean; - - /** - * A boolean value indicating whether to show the zoom buttons in the map navigation control. Default: true - * This property can only be set when using the Map constructor. - */ - showZoomButtons?: boolean; - - /** A set of properties for the streetside mode of the map. */ - streetsideOptions?: IStreetsideOptions; - - /** Additional support map types that should be added to the navigaiton bar such as canvasDark, canvasLight, and grayscale.*/ - supportedMapTypes?: MapTypeId[]; - } - - /** A MapTypeChangeEventArgs object is returned by the map when using the mapTypeChanged event. */ - export interface IMapTypeChangeEventArgs { - /** The map type that map has changed to. */ - newMapTypeId: MapTypeId; - - /** The map type that the map has changed from. */ - oldMapTypeId: MapTypeId; - - /** The map instance the event occured on */ - target: Map; - - /** The type of object the event was attached to. Should always be "map" */ - targetType: string; - } - - /** Interface for module options. */ - export interface IModuleOptions { - /** A callback function that is fired after the module has loaded. */ - callback?: () => void; - - /** A function that is called if there is an error loading the module. */ - errorCallback?: () => void; - - /** A Bing Maps key that is used with the module when the module is loaded without a map. */ - credentials?: string; - } - - /** A MouseEventArgs object is returned by many the mouse event handlers. */ - export interface IMouseEventArgs extends ILayerMouseEventArgs { - /** The event that occurred. */ - eventName: string; - - /** A boolean indicating if the primary button, such as the left mouse button or a tap on a touch screen, was used during a mouse down or up event. */ - isPrimary: boolean; - - /** A boolean indicating if the secondary mouse button, such as the right mouse button, was used during a mouse down or up event. */ - isSecondary: boolean; - - /** If the target is a shape, this will be the layer that the shape is in. */ - layer: Layer; - - /** The map location of where the event occurred. */ - location: Location; - - /** The x-value of the pixel coordinate on the page of the mouse cursor. */ - pageX: number; - - /** The y-value of the pixel coordinate on the page of the mouse cursor. */ - pageY: number; - - /** The pixel coordinate of the mouse cusrsor relative to the top left corner of the map div. */ - point: Point; - - /** The object that triggered the event. */ - target: Map | IPrimitive; - - /** The type of the object that the event is attached to. Valid values include the following: �map�, 'layer', �polygon�, �polyline�, or �pushpin� */ - targetType: string; - - /** - * Returns the x-value of the pixel coordinate, relative to the map, of the mouse. - * @returns The x-value of the pixel coordinate, relative to the map, of the mouse. - */ - getX(): number; - - /** - * Returns the y-value of the pixel coordinate, relative to the map, of the mouse. - * @returns The y-value of the pixel coordinate, relative to the map, of the mouse. - */ - getY(): number; - } - - /** - * An object tthat contains information about a streetside scene. - */ - export interface IPanoramaInfo { - /** The capture date of the streetside scene. */ - cd?: string; - } - - /** - * All shapes; Pushpins, Polylines and Polygons, derive from the IPrimitive interface. This means that they can be - * passed into any function that takes in an IPrimitive object. Also, any function that returns an IPrimitive is capable - * of returning any of these shapes. - */ - export interface IPrimitive { - /** Optional property to store any additional metadata for this primitive. */ - metadata?: any; - - /** - * Gets the css cursor value when the primitive has events on it. - * @returns css cursor string when primitive has events on it. - */ - getCursor(): string; - - /** - * Gets whether the primitive is visible. - * @returns A boolean indicating whether the primitive is visible or not. - */ - getVisible(): boolean; - - /** - * Sets the options for customizing the IPrimitive. - * @param options The options for customizing the IPrimitive. - */ - setOptions(options: IPrimitiveOptions): void; - } - - /** A IPrimitiveChangedEventArgs object is returned by the changed event on IPrimitive shapes. */ - export interface IPrimitiveChangedEventArgs { - /** The IPrimitive shape the event occured on. */ - sender: IPrimitive; - - /** The name of the change that occured; 'locations' or 'options'. */ - name: string; - } - - /** Options used for customizing IPrimitive objects. */ - export interface IPrimitiveOptions { - /** The css cursor to show when the IPrimitive has mouse events on it. Default value is pointer (hand). */ - cursor?: string; - - /** Boolean indicating whether the IPrimitive is visible. */ - visible?: boolean; - } - - /** Options used for customizing Polylines. */ - export interface IPolylineOptions extends IPrimitiveOptions { - /** Indicates if drawn shape should be generalized based on the zoom level to improve rendering performance. Default true **/ - generalizable?: boolean; - - /** CSS string or Color object as the poly's color. */ - strokeColor?: string | Color; - - /** An array of numbers separated by spaces, or a string separated by spaces/commas specifying the repetitive stroke pattern. */ - strokeDashArray?: number[] | string; - - /** The thickness of the poly stroke. */ - strokeThickness?: number; - } - - /** Options used for customizing Polygons. */ - export interface IPolygonOptions extends IPolylineOptions { - /** CSS string or Color object as the polygon's filling color. */ - fillColor?: string | Color; - } - - /** Options used for customizing Pushpins. */ - export interface IPushpinOptions extends IPrimitiveOptions { - /** The point on the pushpin icon, in pixels, which is anchored to the pushpin location. An anchor of (0,0) is the top left corner of the icon. */ - anchor?: Point; - - /** Specifies what color to make the default pushpin. */ - color?: string | Color; - - /** A boolean indicating whether the pushpin can be dragged to a new position with the mouse or by touch. */ - draggable?: boolean; - - /** Specifies whether to enable the clicked style on the pushpin. */ - enableClickedStyle?: boolean; - - /** Specifies whether to enable the hover style on the pushpin. */ - enableHoverStyle?: boolean; - - /** - * Defines the the icon to use for the pushpin.This can be a URL to an Image or SVG file, an image data URI, or an inline SVG string. - * Tip: When using inline SVG, you can pass in placeholders `{color}` and `{text}` in your SVG string. This placeholder will be replaced by the pushpins color or text property value when rendered. - */ - icon?: string; - - /** Whether the clickable area of pushpin should be an ellipse instead of a rectangle. */ - roundClickableArea?: boolean; - - /** - * A secondary title label value to display under the pushpin. Uses label collision detection. This label automatically changes color between white - * and dark grey depending on which map style is selected. Requires the title label to be set. - */ - subTitle?: string; - - /** - * The title label value to display under the pushpin. This label automatically changes color between white and dark grey depending on which map - * style is selected. Pushpin Titles support label collision detection, as described below. - */ - title?: string; - - /** A short string of text that is overlaid on top of the pushpin. */ - text?: string; - - /** The amount the text is shifted from the pushpin icon. The default value is (0,5). */ - textOffset?: Point; - } - - /** An object that represents a min and max value range. */ - export interface IRange { - /** The minimum value. */ - min: number; - - /** The maximum value. */ - max: number; - } - - /** The options that can be used to customize how the streetside map mode is displayed to the user. */ - export interface IStreetsideOptions { - /** A boolean indicating if the ability to navigate between image bubbles should be disabled in streetside map mode. Default: false */ - disablePanoramaNavigation?: boolean; - - /** The location that the streetside panorama should be looking towards. This can be used instead of a heading. */ - locationToLookAt?: Location; - - /** A callback function that is triggered after the streetside view has not loaded successfully. */ - onErrorLoading?: () => void; - - /** A callback function that is triggered after the streetside view has loaded successfully. */ - onSuccessLoading?: () => void; - - /** - * Specifies how to render the overview map when in streetside mode. - * Default: Microsoft.Maps.OverviewMapMode.expanded - */ - overviewMapMode?: OverviewMapMode; - - /** - * Information for a streetside panorama scene to load. - */ - panoramaInfo?: IPanoramaInfo; - - /** The radius to search in for available streetside panoramas. */ - panoramaLookupRadius?: number; - - /** A boolean indicating if the current address being viewed should be hidden when in streetside map mode. Default: true */ - showCurrentAddress?: boolean; - - /** A boolean indicating if the exit button should be hidden when in streetside map mode. Default: true */ - showExitButton?: boolean; - - /** A boolean indicating if the heading compass button is hidden when in streetside map mode. Default: true */ - showHeadingCompass?: boolean; - - /** A boolean indicating if the link to report a problem with a streetside image is hidden when in streetside map mode. Default: true */ - showProblemReporting?: boolean; - - /** A boolean indicating if the zoom buttons should be displayed when in streetside map mode. Default: true */ - showZoomButtons?: boolean; - } - - /** Defines a set of styles for pushpins, polylines, and polygons. */ - export interface IStylesOptions { - /** Sets the options for all pushpins. */ - pushpinOptions?: IPushpinOptions; - - /** Sets the options for all polylines. */ - polylineOptions?: IPolylineOptions; - - /** Sets the options for all polygons. */ - polygonOptions?: IPolygonOptions; - } - - /** Interface to specify style css while registering a module */ - export interface IStyleUrl { - /** List of style css urls o be downloaded */ - styleURLs: string[]; - } - - /** Represents options that can be used to customize a tile layer. */ - export interface ITileLayerOptions { - - /** - * The number of milliseconds allowed for the tile layer image download. If the timeout occurs before the image is fully - * downloaded, the map control considers the download a failure. The default value is 10000. - */ - downloadTimeout?: number; - - /** The tile source for the tile layer. */ - mercator: TileSource; - - /** The opacity of the tile layer, defined by a number between 0 (not visible) and 1. */ - opacity?: number; - - /** - * A boolean indicating whether to show or hide the tile layer. The default value is true. A value of false indicates that - * the tile layer is hidden, although it is still an entity on the map. - */ - visible?: boolean; - - /** The z-index of the tile layer. */ - zIndex?: number; - } - - /** Represents options that can be used to define a tile source. */ - export interface ITileSourceOptions { - /** - * A bounding box that specifies where tiles are available. - * Note: This will not crop tiles to the specific bounding box, it limits the tiles it loads to those that intersect this bounding box. - */ - bounds?: LocationRect; - - /** The maximum zoom level tiles that tiles should be rendered at. */ - maxZoom?: number; - - /** The minimum zoom level tiles that tiles should be rendered at. */ - minZoom?: number; - - /** - * Required. This can be a string or a callback function that constructs the URLs used to retrieve tiles from the tile source. - * When using a string, the uriConstructor will allow you to specify placeholders that will be replaced with the tiles value (i.e. {quadkey}). - * See the Tile URL Parameters section for a list of supported parameters. - * Besides using formatted tile URLs, you can also specify a callback function as the uriConstructor. This is useful if you need to be able to - * build custom tile URL�s that may require some additional calculations for a tile. - */ - uriConstructor: string | ((tile: PyramidTileId) => string); - } - - /** Represents options that can be used to set the view of the map. */ - export interface IViewOptions { - /** The bounding rectangle of the map view. If both bounds and center are specified, bounds takes precedence over center. */ - bounds?: LocationRect; - - /** The location of the center of the map view. If both bounds and center are specified, bounds takes precedence over center. */ - center?: Location; - - /** - * The directional heading of the map. The heading is represented in geometric degrees with 0 or 360 = North, 90 = East, - * 180 = South, and 270 = West. - */ - heading?: number; - - /** Indicates how the map labels are displayed. */ - labelOverlay?: LabelOverlay; - - /** The map type of the view. */ - mapTypeId?: MapTypeId; - - /** The amount of padding in pixels to be added to each side of the bounds of the map view. */ - padding?: number; - - /** The angle relative to the horizon to tilt a streetside panorama image. */ - pitch?: number; - - /** The zoom level of the map view. */ - zoom?: number; - } - - ////////////////////////////////////////////// - /// Modular Framework - ////////////////////////////////////////////// - - /** - * Loads the specified registered module, making its functionality available. You can provide the name of a single module or an array of names in. - * Options or a callback function that is called when the module is loaded can be specified. - * @param moduleName Name of the module to load. Can be the name of a custom module or a built in module name. Built in modules: - * Microsoft.Maps.Autosuggest, Microsoft.Maps.Clustering, Microsoft.Maps.Directions, Microsoft.Maps.DrawingTools, Microsoft.Maps.GeoJSON, - * Microsoft.Maps.HeatMap, Microsoft.Maps.Search, Microsoft.Maps.SpatialDataService, Microsoft.Maps.SpatialMath, Microsoft.Maps.Traffic, - * Microsoft.Maps.WellKnownText - * @param options A callback function or options containing additional information and a callback to call once a module is loaded - */ - export function loadModule(moduleName: string | string[], options?: (() => void) | IModuleOptions): void; - - /** - * Registers a module with the map control. The name of the module is specified in moduleKey, the module script is defined in scriptURL, and the - * options provides the location of a *.css file to load with the module. - * @param moduleName Name of the module to load. - * @param url Url to where the module code is located. - * @param styles List of css files to download. - */ - export function registerModule(moduleName: string, url: string, styles?: IStyleUrl): void; - - /** - * Signals that the specified module has been loaded and if specified, calls the callback function in loadModule. Call this method at the end of your custom module script. - * @param moduleName Name of the module that is loaded. - */ - export function moduleLoaded(moduleName: string): void; - - ////////////////////////////////////////////// - /// Classes - ////////////////////////////////////////////// - - /** - * Provides a layer which can smoothly animate through an array of tile layer sources. - */ - export class AnimatedTileLayer { - /** - * @contstructor - * @param options Options that define how to animate between the specified tile layers. - */ - constructor(options?: IAnimatedTileLayerOptions); - - /** - * Gets the frame rate of this animated tile layer. - * @returns The frame rate of this animated tile layer. - **/ - public getFrameRate(): number; - - /** - * Gets the loading screen overlay when tiles are being fetched. - * @returns The loading screen overlay when tiles are being fetched. - **/ - public getLoadingScreen(): CustomOverlay; - - /** - * Gets the maximum total tile fetching time of this animated tile layer. - * @returns The maximum total tile fetching time of this animated tile layer - **/ - public getMaxTotalLoadTime(): number; - - /** - * Gets the tile sources associated with this layer. - * @returns The tile sources associated with this layer. - **/ - public getTileSources(): TileSource[]; - - /** - * Gets the visibility of this animated tile layer. - * @returns The visibility of this animated tile layer. - **/ - public getVisible(): boolean; - - /** Pause the tile layer animation. **/ - public pause(): void; - - /** Play the animation either from start or where it was paused. **/ - public play(): void; - - /** - * Sets the options for the animated tile layer. - * @params Options that define how to animate between the specified tile layers. - **/ - public setOptions(options: IAnimatedTileLayerOptions): void; - - /** Stop the layer animation, hide layer, and reset frame to the beginning. **/ - public stop(): void; - } - - /** Class that represents a color */ - export class Color { - /** The opacity of the color. The range of valid values are an interger between 0 and 255, or a decimal between 0 and 1. */ - public a: number; - - /** The red value of the color. The range of valid values is 0 to 255 */ - public r: number; - - /** The green value of the color. The range of valid values is 0 to 255 */ - public g: number; - - /** The blue value of the color. The range of valid values is 0 to 255 */ - public b: number; - - /** - * @constructor - * @param a The alpha value in argb format - * @param r The r value in argb format - * @param g The g value in argb format - * @param b The b value in argb format - */ - constructor(a: number, r: number, g: number, b: number); - - /** - * Clones the color. - * @param color The color class that needs to be clones. - * @returns The colne of the color. - */ - public static clone(color: Color): Color; - - /** - * Creates the color from a hex string. - * @param hex The color represented as '#rrggbb' format. - * @returns The color object. - */ - public static fromHex(hex: string): Color; - - /** - * Clones the color. - * @returns The clone of the color. - */ - public clone(): Color; - - /** - * Gets the opacity of this color. - * @returns The opacity between 0 and 1 of this color. - */ - public getOpacity(): number; - - /** - * Converts the color to hex notation. - * @returns The hex notation as '#rrggbb' (ignores a). - */ - public toHex(): string; - - /** - * Converts the color to rgba notation. - * @returns The rgba notation as rgba(rr, gg, bb, aa) - */ - public toRgba(): string; - } - - /** - * You can use this class to create custom overlays on top of the map. These can be static overlays such as custom - * navigation bars, or dynamic overlays such as custom visualization layers. CustomOverlays can be added to the map - * just like any other layer using the map.layers property. - */ - export class CustomOverlay implements ILayer { - /** A reference the the map instance that the overlay was added to. This will be null until the onLoad function has fired. **/ - _map: Map; - - /** - * @constructor - * @param options The options to use when initializing the custom overlay. - */ - constructor(options?: ICustomOverlayOptions); - - /** - * Gets the html element of this custom overlay. - * @returns The htmlElement of this overlay. - */ - public getHtmlElement(): HTMLElement; - - /** - * Gets the map that this overlay is attached to. - * @returns The map that this overlay is attached to. - */ - public getMap(): Map; - - /** - * Updates the html element of this custom overlay. - * @param htmlElement The new htmlElement to set for the overlay. - */ - public setHtmlElement(htmlElement: HTMLElement): void; - - /** - * Implement this method to perform any task that should be done when the overlay is added to the map. - */ - public onAdd(): void; - - /** - * Implement this methof to perform any task that should be done after the overlay has been added to the map. - */ - public onRemove(): void; - - /** - * Implement this method to perform any tasks that should be done when the overlay is removed from the map. - */ - public onLoad(): void; - } - - /** - * Use the Layer class. - * @deprecated in V8 - */ - export class EntityCollection extends Layer { - /** - * @constructor Deprecated. Use the Layer class. - * @deprecated in V8 - */ - constructor(); - - /** - * Removes all shapes from the collection. - */ - public clear(): void; - - /** - * Gets the item at a specified index. - * @param index Index of the item to get. - * @returns The item at a specified index. - */ - public get(index: number): IPrimitive; - - /** - * Gets the number of items in this collection. - * @returns The count of the items. - */ - public getLength(): number; - - /** - * Gets the index of the item in the list. - * @param primitive The item to get the index of. - * @returns The index of the item in the list. - */ - public indexOf(primitive: IPrimitive): number; - - /** - * Inserts the item into the list at a specific index. - * @param primitive The item to insert. - * @param index Index of the item to be inserted. - */ - public insert(primitive: IPrimitive, index: number): void; - - /** - * Returns the last element in the list after removing it. - * @returns The last element in the list after removing it. - */ - public pop(): IPrimitive; - - /** - * Adds the item to the end of the list. - * @param primitive Item to be added. - */ - public push(primitive: IPrimitive | IPrimitive[]): void; - - /** - * Removes the item from the list. - * @param primitive Item to be removed. - * @returns The item to be removed. - */ - public remove(primitive: IPrimitive): IPrimitive; - - /** - * Removes the item from the list at a specified index. - * @param index Index of the item that needs to be removed. - * @returns The item to be removed at a specified index. - */ - public removeAt(index: number): IPrimitive; - } - - /** A static class that manages events within the map SDK. */ - export module Events { - ///////////////////////////////////// - /// addHandler Definitions - //////////////////////////////////// - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported events: - * click, dblclick, maptypechanged, mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel, rightclick, viewchange, viewchangeend, viewchangestart - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: Map, eventName: string, handler: (eventArg?: IMouseEventArgs | IMapTypeChangeEventArgs) => void): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * changed, click, dblclick, drag, dragend, dragstart, mousedown, mouseout, mouseover, mouseup - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: Pushpin, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * changed, click, dblclick, mousedown, mouseout, mouseover, mouseup - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: Polyline | Polygon, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * click, infoboxChanged, mouseenter, mouseleave - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: Infobox, eventName: string, handler: (eventArg?: IInfoboxEventArgs) => void): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: Layer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * � entityadded - * � entityremoved - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: EntityCollection, eventName: string, handler: (eventArg?: IEntityCollectionChangedEventArgs) => void): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addHandler(target: any, eventName: string, handler: (eventArg?: any) => void): IHandlerId; - - ///////////////////////////////////// - /// addOne Definitions - //////////////////////////////////// - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported events: - * click, dblclick, maptypechanged, mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel, rightclick, viewchange, viewchangeend, viewchangestart - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: Map, eventName: string, handler: (eventArg?: IMouseEventArgs | IMapTypeChangeEventArgs) => void): void; - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * changed, click, dblclick, drag, dragend, dragstart, mousedown, mouseout, mouseover, mouseup - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: Pushpin, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): void; - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * changed, click, dblclick, mousedown, mouseout, mouseover, mouseup - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: Polyline | Polygon, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): void; - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * click, infoboxChanged, mouseenter, mouseleave - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: Infobox, eventName: string, handler: (eventArg?: IInfoboxEventArgs) => void): void; - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: Layer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void): void; - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * � entityadded - * � entityremoved - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: EntityCollection, eventName: string, handler: (eventArg?: IEntityCollectionChangedEventArgs) => void): void; - - /** - * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. - * @param handler The callback function to handle the event when triggered. - */ - export function addOne(target: any, eventName: string, handler: (eventArg?: any) => void): void; - - ///////////////////////////////////// - /// addThrottledHandler Definitions - //////////////////////////////////// - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported events: - * click, dblclick, maptypechanged, mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel, rightclick, viewchange, viewchangeend, viewchangestart - * @param handler The callback function to handle the event when triggered. - * @param throttleInterval throttle interval (in ms) - * @returns The handler id. - */ - export function addThrottledHandler(target: Map, eventName: string, handler: (eventArg?: IMouseEventArgs | IMapTypeChangeEventArgs) => void, throttleInterval: number): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * changed, click, dblclick, drag, dragend, dragstart, mousedown, mouseout, mouseover, mouseup - * @param handler The callback function to handle the event when triggered. - * @param throttleInterval throttle interval (in ms) - * @returns The handler id. - */ - export function addThrottledHandler(target: Pushpin, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void, throttleInterval: number): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * changed, click, dblclick, mousedown, mouseout, mouseover, mouseup - * @param handler The callback function to handle the event when triggered. - * @param throttleInterval throttle interval (in ms) - * @returns The handler id. - */ - export function addThrottledHandler(target: Polyline | Polygon, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void, throttleInterval: number): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * click, infoboxChanged, mouseenter, mouseleave - * @param handler The callback function to handle the event when triggered. - * @returns The handler id. - */ - export function addThrottledHandler(target: Infobox, eventName: string, handler: (eventArg?: IInfoboxEventArgs) => void): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick - * @param handler The callback function to handle the event when triggered. - * @param throttleInterval throttle interval (in ms) - * @returns The handler id. - */ - export function addThrottledHandler(target: Layer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void, throttleInterval: number): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. Supported Events: - * � entityadded - * � entityremoved - * @param handler The callback function to handle the event when triggered. - * @param throttleInterval throttle interval (in ms) - * @returns The handler id. - */ - export function addThrottledHandler(target: EntityCollection, eventName: string, handler: (eventArg?: IEntityCollectionChangedEventArgs) => void, throttleInterval: number): IHandlerId; - - /** - * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. - * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. - * @param eventName The type of event to attach. - * @param handler The callback function to handle the event when triggered. - * @param throttleInterval throttle interval (in ms) - * @returns The handler id. - */ - export function addThrottledHandler(target: any, eventName: string, handler: (eventArg?: any) => void, throttleInterval: number): IHandlerId; - - ///////////////////////////////////// - /// All other definitions - //////////////////////////////////// - - /** - * Checks if the target has any attached event handler. - * @param target The object to check if an event is attached to it. - * @param eventName The name of the event to check to see is attached. - * @returns A boolean indicating if the specified event type is attached to the object. - */ - export function hasHandler(target: any, eventName: string): boolean; - - /** - * Invokes an event on the target. This causes all handlers for the specified event name to be called. - * @param target The object to invoke the event on. - * @param eventName The name of the event to invoke. - * @param args Arguments for the event handler. - */ - export function invoke(target: any, evenName: string, args: any): void; - - /** - * Detaches the specified handler from the event. The handlerId is returned by the addHandler and addThrottledHandler methods. - * @param handlerId The handler id of the event to remove. - */ - export function removeHandler(handlerId: IHandlerId): void; - } - - /** - * Standard compass headings; north, south, east, west. - */ - export class Heading { - /** A heading pointing north, 0 degrees. */ - static North: number; - - /** A heading pointing south, 180 degrees. */ - static South: number; - - /** A heading pointing east, 90 degrees. */ - static East: number; - - /** A heading pointing west, 270 degrees. */ - static West: number; - } - - /** - * An infobox, also sometimes refer to as an info window or popup, is a simple panel that displays information over top the map. This is - * often used to display information linked to a location after clicking on a pushpin. - */ - export class Infobox { - - /** - * @constructor - * @param location The location to display the infobox at. - * @param options Options for rendering the infobox. - */ - constructor(location: Location, options?: IInfoboxOptions); - - /** - * @deprecated Use HTML buttons and links in description instead. - */ - public getActions(): IInfoboxActions[]; - - /** - * Gets the point on the infobox which is anchored to the map. An anchor of (0,0) is the top left corner of the infobox. - * @returns The anchor point of the infobox. - */ - public getAnchor(): Point; - - /** - * Gets the string that is printed inside the infobox. - * @returns The description value of the infobox options. - */ - public getDescription(): string; - - /** - * Gets the height of the infobox. - * @returns The height of the infobox. - */ - public getHeight(): number; - - /** - * Gets the infobox as HTML. - * @returns The HTML string used to create a custom infobox. - */ - public getHtmlContent(): string; - - /** - * Gets the location on the map where the infobox�s anchor is attached. - * @returns The location of the infobox. - */ - public getLocation(): Location; - - /** - * Gets the maximium height setting for the infobox. - * @returns the maximium height setting for the infobox. - */ - public getMaxHeight(): number; - - /** - * Gets the maximium width setting for the infobox. - * @returns the maximium width setting for the infobox. - */ - public getMaxWidth(): number; - - /** - * Gets the amount the infobox pointer is shifted from the location of the infobox, or if showPointer is false, then it is the amount the infobox - * bottom left edge is shifted from the location of the infobox. The default value is (0,0), which means there is no offset. - * @returns The offset of the infobox. - */ - public getOffset(): Point; - - /** - * Gets the infobox options. - * @returns The infobox options currently used by the infobox. - */ - public getOptions(): IInfoboxOptions; - - /** - * Gets a boolean indicating whether the infobox close button is shown. - * @returns A boolean indicating if the close button is shown or not. - */ - public getShowCloseButton(): boolean; - - /** - * Gets a boolean indicating whether the infobox is drawn with a pointer. - * @returns A boolean indicating if the pointer of the infobox is shown or not. - */ - public getShowPointer(): boolean; - - /** - * Gets a string that is the title of the infobox. - * @returns The title property of the infobox. - */ - public getTitle(): string; - - /** - * Gets whether the infobox is visible. A value of false indicates that the infobox is hidden, although it is still an entity on the map. - * @returns A boolean indicating if the infobox is visible or not. - */ - public getVisible(): boolean; - - /** - * Gets the width of the infobox. - * @returns The width of the infobox. - */ - public getWidth(): number; - - /** - * Gets the z-index of the infobox. - * @returns The z-index of the infobox. - */ - public getZIndex(): number; - - /** - * Sets the HTML content of the infobox. You can use this method to change the look of the infobox. Note that infobox options are ignored if - * custom HTML is set. Also, when custom HTML is used to represent the infobox, the infobox is anchored at the bottom-left corner. - * @param content The HTML string to use to generate the infobox. - */ - public setHtmlContent(content: string): void; - - /** - * Sets the location on the map where the anchor of the infobox is attached. - * @param loc The location to display the infobox at. - */ - public setLocation(loc: Location): void; - - /** - * Adds the infobox to the map. To remove an Infobox from the map, simply pass null into this function. - * @param map A map instance to display the infoboox on, or null if removing infobox from map. - */ - public setMap(map: Map): void; - - /** - * Sets options for the infobox. - * @param options The options to assign to the infobox. - */ - public setOptions(options: IInfoboxOptions): void; - } - - /** - * The Layer class makes it easy to organize groups of data by storing them in separate layers on the map. Grouping your data into layers - * provides a number of benefits such as the ability to hide or attach events to all IPrimitive shapes in a layer with a single line of code, - * while also providing providing a performance benefit over manually looping through each shape and performing these tasks. - */ - export class Layer implements IDataLayer { - - /** Optional property to store any additional metadata for this layer. */ - public metadata: any; - - /** - * @constructor - * @param id Unique string identifier for the layer. - */ - constructor(id?: string); - - /** - * Adds a shapes to the layer, at the specified index if specified. - * @param primitive The shape(s) to be added to the layer. - * @param index The index at which to insert the shape into the layer. - */ - public add(primitive: IPrimitive | IPrimitive[], index?: number): void; - - /** - * Clears all the data - */ - public clear(): void; - - /** - * Cleans up any resources this object is consuming - */ - public dispose(): void; - - /** - * Gets the id of the layer. - * @returns The id assigned to the layer. - */ - public getId(): string; - - /** - * Gets an array of shapes that are in the layer. This can be used to iterate over the individual shapes. - * @returns An array of shapes that are in the layer. - */ - public getPrimitives(): IPrimitive[]; - - /** - * Gets a value indicating whether the layer is visible or not. - * @returns A boolean indicating if the layer is visible or not. - */ - public getVisible(): boolean; - - /** - * Gets the zIndex of the layer. - * @returns The zIndex of the layer. - */ - public getZIndex(): number; - - /** - * Removes a primitive - * @param primitive primitive that needs to be removed - * @returns The primitive that needs to be removed - */ - public remove(primitive: IPrimitive): IPrimitive; - - /** - * Removes a primitive at a specified index - * @param index index of the primitive that needs to be removed - * @returns The primitive that needs to be removed at this index - */ - public removeAt(index: number): IPrimitive; - - /** - * Replaces all shapes in the layer with the new array of shapes that have been provided. - * @param primitives The array of shapes to add to the layer. - */ - public setPrimitives(primitives: IPrimitive[]): void; - - /** - * Sets whether the layer is visible or not. - * @param value A value indicating if the layer should be displayed or not. - */ - public setVisible(value: boolean): void; - - /** - * Sets the zIndex of the layer. - * @param zIndex The zIndex value to assign to the layer. - */ - public setZIndex(zIndex: number): void; - } - - /** - * The layers property of the map is a LayerCollection object and contains all the layers that have been added to the map. - * Note: This class is only exposed in the map.layers property. No other instance of this class can be created. - */ - export class LayerCollection extends Array { - /** The number of layers in the collection. */ - public length: number; - - /** - * Removes all layers from the map. - */ - public clear(): void; - - /** - * Gets the index of a layer in the collection. - * @param layer The layer to get the index of. - * @returns The index of the specified layer. - */ - public indexOf(layer: ILayer): number; - - /** - * Adds a layer to the map. - * @param layer The layer to insert into the collection. - */ - public insert(layer: ILayer): void; - - /** - * Adds an array of layers to the map. - * @param layers The layers to insert into the collection. - */ - public insertAll(layers: ILayer[]): void; - - /** - * Removes a layer from the map. - * @param layer The layer to remove from the collection. - */ - public remove(layer: ILayer): void; - - /** - * Removes a layer from the map at the specified index in the collection. - * @param idx The index of the layer to remove. - */ - public removeAt(idx: number): void; - } - - /** - * This class stores the coordinate information needed to mark locations on a map. The Location class consists of two properties: - * latitude and longitude. - */ - export class Location { - /** The location north or south of the equator from +90 to -90 */ - public latitude: number; - - /** The location east or west of the prime meridian +180 to -180 */ - public longitude: number; - - /** - * @constructor - * @param latitude The location north or south of the equator from +90 to -90 - * @param longitude The location east or west of the prime meridian +180 to -180 - */ - constructor(latitude: any, longitude: any); - - /** - * Determines if two locations are equal. - * @param location1 The first location to test. - * @param location2 The second location to test. - * @returns True if both locations are equivalent. - */ - static areEqual(location1: Location, location2: Location): boolean; - - /** - * Creates a deep copy of the map location. - * @returns A deep copy of the map location. - */ - public clone(): Location; - - /** - * Creates a proper Location from an object that has the same signature. - * @param source A Location or Location-like object that contains the same properties. - * @returns A copy of the map location. - */ - static cloneFrom(source: Location): Location; - - /** - * Normalizes the longitude by wrapping it around the earth. - * @param longitude The input longitude. - * @returns The longitude normalized to within -180 and +180. - */ - static normalizeLongitude(longitude: number): number; - - /** - * Parses a location string of the form "lat,long". - * @param str The location string. - * @returns The parsed location or null otherwise. - */ - static parseLatLong(str: string): Location; - - /** - * Converts the Location to a string representation. - * @returns A string representation of the location. - */ - public toString(): string; - } - - /** - * The LocationRect class, also known as a bounding box, consists of a set of coordinates that are used to represent rectangular area on the map. - */ - export class LocationRect { - /** The location that defines the center of the rectangle. */ - public center: Location; - - /** The height, in degrees, of the rectangle. */ - public height: number; - - /** The width, in degrees, of the rectangle. */ - public width: number; - - /** - * @constructor - * @param center The center of the LocationRect. - * @param width The width of the LocationRect in degrees. - * @param height The height of the LocationRect in degrees. - */ - constructor(center: Location, width: number, height: number); - - /** - * Gets a LocationRect using the specified locations for the northwest and southeast corners. - * @param northwest The north west corner of the LocationRect. - * @param southeast The south east corner of the LocationRect. - * @returns A LocationRect using the specified locations for the northwest and southeast corners. - */ - static fromCorners(northwest: Location, southeast: Location): LocationRect; - - /** - * Gets a LocationRect using the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries. - * @param north The northern latitude of the LocationRect. - * @param west The western longitude of the LocationRect. - * @param south The southern latitude of the LocationRect. - * @param east The eastern longitude of the LocationRect. - * @returns A LocationRect defined by the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries. - */ - static fromEdges(north: number, west: number, south: number, east: number): LocationRect; - - /** - * Gets a LocationRect using a list of locations. - * @param locations A list of locations. - * @returns A LocationRect that encloses all the specified locations. - */ - static fromLocations(...locations: Location[]): LocationRect; - - /** - * Gets a LocationRect using an array of locations. - * @param locations An array of locations. - * @returns A LocationRect that encloses all the specified locations. - */ - static fromLocations(locations: Location[]): LocationRect; - - /** - * Creates a LocationRect from a string with the following format: "north,west,south,east". North, west, south and east specify the coordinate number values. - * @param str A string that repsents a LocationRect with the format "north,west,south,east". - * @returns A LocationRect defined by the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries that have been parsed by the string. - */ - static fromString(str: string): LocationRect; - - /** - * Gets a copy of the LocationRect object. - * @retruns A copy of the LocationRect object. - */ - public clone(): LocationRect; - - /** - * Gets whether the specified Location is within the LocationRect. - * @returns A boolean indicating if a location is within a LocationRect. - */ - public contains(location: Location): boolean; - - /** - * Determines if the LocationRect crosses the 180th meridian. - * @returns A boolean indicating if the LocationRect crosses the international date line (-180/180 degrees longitude). - */ - public crossesInternationalDateLine(): boolean; - - /** - * Gets the longitude that defines the eastern edge of the LocationRect. - * @returns The eastern longitude value of the LocationRect. - */ - public getEast(): number; - - /** - * Gets the latitude that defines the northern edge of the LocationRect. - * @returns The northern latitude value of the LocationRect. - */ - public getNorth(): number; - - /** - * Gets the Location that defines the northwest corner of the LocationRect. - * @returns The northwest corner location of the LocationRect. - */ - public getNorthwest(): Location; - - /** - * Gets the latitude that defines the southern edge of the LocationRect. - * @returns The southern latitude value of the LocationRect. - */ - public getSouth(): number; - - /** - * Gets the Location that defines the southeast corner of the LocationRect. - * @returns The southeast corner location of the LocationRect. - */ - public getSoutheast(): Location; - - /** - * Gets the latitude that defines the western edge of the LocationRect. - * @returns The western longitude value of the LocationRect. - */ - public getWest(): number; - - /** - * Gets whether the specified LocationRect intersects with this LocationRect. - * @param rect A second LocationRect to test for intersection with. - * @returns A boolean indicating if a second LocationRect interests with this LocationRect. - */ - public intersects(rect: LocationRect): boolean; - - /** - * Scales the size of a LocationRect by multiplying the width and height properties by a percentage. - * @param percentage A percentage value to increase the size of the LocationRect by. - */ - public inflate(percentage: number): void; - - /** - * If a LocationRect crosses the international date line, this method splits it into two LocationRect objects and returns them as an array. - * @returns An array of LocationRects, that are split by the international date line (-180/180 degrees longitude) - */ - public splitByInternationalDateLine(): LocationRect[]; - - /** - * Converts the LocationRect object to a string. - * @returns A string version of the LocationRect. - */ - public toString(): string; - } - - /** The map object generates an interactive map within a specified DOM element. */ - export class Map { - /** Entities of the map */ - public entities: EntityCollection; - - /** Set of map layers */ - public layers: LayerCollection; - - /** - * @constructor - * @param parentElement The parent element of the map as a CSS selector string or HTMLElement. - * @param options Options used when creating the map. - */ - constructor(parentElement: string | HTMLElement, options: IMapLoadOptions); - - /** - * Gets the streetside panorama information closest to the specified bounding box and returns using a success callback function. - * This information can then be used to set the map view to that streetside panorama. - */ - public static getClosestPanorama(bounds: LocationRect, success: (panoramaInfo: IPanoramaInfo) => void, missingCoverage: () => void): void; - - /** Returns the branch name; release, experimental, frozen. */ - public static getVersion(): string; - - - /** Deletes the Map object and releases any associated resources. */ - public dispose(): void; - - /** - * Gets the location rectangle that defines the boundaries of the current map view. - * @returns The location rectangle that defines the boundaries of the current map view. - */ - public getBounds(): LocationRect; - - /** - * Gets the location of the center of the current map view. - * @returns The location of the center of the current map view. - */ - public getCenter(): Location; - - /** - * Gets to the specified callback an array of strings representing the attributions of the imagery currently displayed on the map. - * @param callback The callback function that needs to be called after retrieving the copyright information. - */ - public getCopyrights(callback: (copyrights: string[]) => void): void; - - /** - * Gets the session ID. This method calls the callback function with the session ID as the first parameter - * @param callback The callback function that needs to be called with the session id. - */ - public getCredentials(callback: (creds: string) => void): void; - - /** - * Gets the current culture. - * @returns The current culture. - */ - public getCulture(): string; - - /** - * Gets the height of the map control. - * @returns The height of the map control. - */ - public getHeight(): number; - - /** - * Returns the heading of the current map view. - * @returns Returns the heading of the current map view. - */ - public getHeading(): number; - - /** - * Gets the string that represents the imagery currently displayed on the map. - * @returns The string that represents the imagery currently displayed on the map. - */ - public getImageryId(): string; - - /** - * Gets a string that represents the current map type displayed on the map. - * @returns A string that represents the current map type displayed on the map. - */ - public getMapTypeId(): MapTypeId; - - /** - * Gets the current scale in meters per pixel of the center of the map. - * @returns The current scale in meters per pixel of the center of the map. - */ - public getMetersPerPixel(): number; - - /** - * Gets the map options that have been set. - * @returns the map options that have been set. - */ - public getOptions(): IMapOptions; - - /** - * Gets the x coordinate of the top left corner of the map control, relative to the page. - * @returns The x coordinate of the top left corner of the map control, relative to the page. - */ - public getPageX(): number; - - /** - * Gets the y coordinate of the top left corner of the map control, relative to the page. - * @returns The y coordinate of the top left corner of the map control, relative to the page. - */ - public getPageY(): number; - - /** - * Returns the pitch of the current streetside map view. - * @returns Returns the pitch of the current streetside map view. - */ - public getPitch(): number; - - /** - * Gets the map root node. - * @returns the map root node. - */ - public getRootElement(): HTMLElement; - - /** - * Gets the user region. - * @returns The user region. - */ - public getUserRegion(): string; - - /** - * Gets the width of the map control. - * @returns the width of the map control. - */ - public getWidth(): number; - - /** - * Gets the zoom level of the current map view. - * @returns Returns the zoom level of the current map view. - */ - public getZoom(): number; - - /** - * Gets the range of valid zoom levels for the current map view. - * @returns The range of valid zoom levels for the current map view. - */ - public getZoomRange(): IRange; - - /** - * Gets a boolean indicating whether the map is in a regular Mercator nadir mode. - * @returns A boolean indicating whether the map is in a regular Mercator nadir mode. - */ - public isMercator(): boolean; - - /** - * Gets a boolean indicating if the current map type allows the heading to change; false if the display heading is fixed. - * @returns true if the current map type allows the heading to change; false if the display heading is fixed. - */ - public isRotationEnabled(): boolean; - - /** - * Sets the current map type. - * @param mapTypeId The map imagery type of the map to set. - */ - public setMapType(mapTypeId: MapTypeId): void; - - /** - * Sets the map options. - * @param options The map options to be set. - */ - public setOptions(options: IMapOptions): void; - - /** - * Sets the view of the map. - * @param viewOptions The view options to be set. - */ - public setView(viewOptions: IViewOptions): void; - - /** - * Converts a specified Location or a Location array to a Point or Point array on the map - * relative to the specified PixelReference. If no reference is specified, PixelReference.viewport - * is taken. - * @param location The given Location or Location[] to convert. - * @param reference The PixelReference to specify the reference point. - * @returns The converted Point or Point[], or null if the conversion fails. - */ - public tryLocationToPixel(location: Location | Location[], reference?: any): Point | Point[]; - - /** - * Converts a specified Point or a Point array to a Location or Location array on the map - * relative to the specified PixelReference. If no reference is specified, PixelReference.viewport - * is taken. - * @param point The given Point or Point[] to convert. - * @param reference The PixelReference to specify the reference point. - * @returns The converted Location or Location[], or null if the conversion fails. - */ - public tryPixelToLocation(point: Point | Point[], reference?: any): Location | Location[]; - } - - /** - * This class is used to represent a pixel coordinate or offset. This is often used by pushpin anchors, and map location to pixel conversion calculations. - */ - export class Point { - /** The x coordinate */ - public x: number; - - /** The y coordinate */ - public y: number; - - /** - * @constructor - * @param x The x coordinate. - * @param y The y coordinate. - */ - constructor(x: number, y: number); - - /** - * Adds the x and y values of two points and returns a new Point. - * @param point The point to add. - * @returns A new point created by the sum of two points. - */ - public add(point: Point): Point; - - /** - * Creates a copy of the current point. - * @returns A new instance of the current point. - */ - public clone(): Point; - - /** - * Compares the x and y values of two points to see if they are equal. If a tolerance value is specified, it checks to see if the linear distance between the points is less than or equal to the tolerance value. - * @param point The point to compare to. - * @param tolerance Optional, tolerance (>= 0) to avoid false result because of floating point errors. - * @returns true if this point equals point, false otherwise - */ - public equals(point: Point, tolerance?: number): boolean; - - /** - * Subtracts the x and y values of a points and returns a new Point. - * @param point The point to subtract. - * @returns A new point created by the subtraction of two points. - */ - public subtract(point: Point): Point; - - /** - * Converts the Point to a string representation. - * @returns A string representation of the point. - */ - public toString(): string; - } - - /** - * This compression algorithm encodes/decodes an array of locations into a string. - * This algorithm is used for generating a compressed collection of locations for use - * with the Bing Maps REST Elevation Service. This algorithm is also used for decoding - * the compressed coordinates returned by the GeoData API. - * - * These algorithms come from the following documentation: - * http://msdn.microsoft.com/en-us/library/jj158958.aspx - * http://msdn.microsoft.com/en-us/library/dn306801.aspx - */ - export class PointCompression { - /** - * Decodes a collection of locations from a compressed string. - * @param value Compressed string to decode. - * @returns An array of locations that have been decoded from the compressed string. - */ - public static decode(value: string): Location[]; - - /** - * Compresses an array of locations into a string. - * @param locations Collection of coordinates to compress. - * @returns A compressed string representing an array of locations. - */ - public static encode(locations: Location[]): string; - } - - /** - * A polygon is an area defined by a closed ring of locations. A simple polygon consists of an array of Location objects that form a boundary. - * A complex polygon consists of several arrays of Locations, where the first array is the outline of the polygon, and the subsequent arrays are holes in the polygon. - * The Polygon class derives from the IPrimitive interface. - */ - export class Polygon implements IPrimitive { - /** - * Information that is linked to the polygon. - * Some modules such as the GeoJSON, and Spatial Data Service modules will also often add information to this property. - */ - public metadata: any; - - /** - * @constructor - * @param rings A Location array for basic polygon with single outer perimeter, - * or an array of Location arrays for advanced polygon (multi-polygon, polygon with holes, or combination of polygons). - * @param options Options used to customize polygon. - */ - constructor(rings: Location[] | Location[][], options?: IPolygonOptions); - - /** - * Gets the css cursor value when polygon has events on it. - * @returns CSS cursor string when polygon has events on it. - */ - public getCursor(): string; - - /** - * Gets the fill color of the inside of the polygon. Will be string or Color object depending on the the what method was used in the pushpin options. - * @returns The fill color of the inside of the polygon. - */ - public getFillColor(): string | Color; - - /** - * Returns whether the polygon is generalizable based on zoom level or not. - * @returns whether the polygon is generalizable based on zoom level or not. - */ - public getGeneralizable(): boolean; - - /** - * Gets the first ring of the polygon (for V7 compatability). - * @returns An array of Locations that is the first ring of the polygon; or an empty array if the polygon has no ring at all. - */ - public getLocations(): Location[]; - - /** - * Gets an array of location arrays, where each location array defines a ring of the polygon. - * @returns An array of location arrays, where each location array defines a ring of the polygon. - */ - public getRings(): Location[][]; - - /** - * Gets the color of the border stroke of the polygon. Will be string or Color object depending on the the what method was used in the pushpin options. - * @returns The color of the border stroke of the polygon. - */ - public getStrokeColor(): string | Color; - - /** - * Gets the stroke dash array of the polygon, in format of either array or string, whichever user provides. - * @returns The stroke dash array of the polygon. - */ - public getStrokeDashArray(): number[] | string; - - /** - * Gets the thickness of the border stroke of the polygon. - * @returns The thickness of the border stroke of the polygon as a number. - */ - public getStrokeThickness(): number; - - /** - * Gets whether the polygon is visible. - * @returns A boolean indicating whether the polygon is visible or not. - */ - public getVisible(): boolean; - - /** - * Sets locations (single ring) of the polygon. (for V7 compatability) - * @param locations A Location[] that defines the only ring of the polygon - */ - public setLocations(locations: Location[]): void; - - /** - * Sets the properties for the polygon. - * @param options The IPolygonOptions object containing the options to customize the polygon. - */ - public setOptions(options: IPolygonOptions): void; - - /** - * Sets rings of the polygon. - * @param rings A Location[][] where each Location[] defines a ring of the polygon. - */ - public setRings(rings: Location[] | Location[][]): void; - } - - /** - * Polylines allow you to draw connected lines on a map. In many spatial database systems, this is also known as a LineString. - * The Polyline class derives from the IPrimitive interface. - */ - export class Polyline implements IPrimitive { - /** - * Information that is linked to the polyline. - * Some modules such as the GeoJSON, and Spatial Data Service modules will also often add information to this property. - */ - public metadata: any; - - /** - * @constructor - * @param locations An array of locations that make up the path of the polyine. - * @param options Options used to customize polyline. - */ - constructor(locations: Location[], options?: IPolylineOptions); - - /** - * Gets the css cursor value when polyline has events on it. - * @returns CSS cursor string when polyline has events on it. - */ - public getCursor(): string; - - /** - * Returns whether the polyline is generalizable based on zoom level or not. - * @returns whether the polyline is generalizable based on zoom level or not. - */ - public getGeneralizable(): boolean; - - /** - * Gets the locations that make up the polyline. - * @returns An array that defines the path of the polyline. - */ - public getLocations(): Location[]; - - /** - * Gets the color of the border stroke of the polyline. Will be string or Color object depending on the the what method was used in the polyline options. - * @returns The stroke color of the polyline. - */ - public getStrokeColor(): string | Color; - - /** - * Gets the stroke dash array of the polyline, in format of either array or string, whichever user provides. - * @returns The stroke dash array of the polyline. - */ - public getStrokeDashArray(): number[] | string; - - /** - * Gets the thickness of the border stroke of the polyline. - * @returns The thickness of the border stroke of the polyline as a number. - */ - public getStrokeThickness(): number; - - /** - * Gets whether the polyline is visible. - * @returns A boolean indicating whether the polyline is visible or not. - */ - public getVisible(): boolean; - - /** - * Sets locations of the polyline. - * @param locations A Location[] that defines path of the polyline - */ - public setLocations(locations: Location[]): void; - - /** - * Sets the properties for the polyline. - * @param options The IPolylineOptions object containing the options to customize the polyline. - */ - public setOptions(options: IPolylineOptions): void; - } - - /** - * Pushpins, sometimes also referred to as markers or MapIcons on other mapping platforms, are one of the primary ways of marking a location on a map. - * The Pushpin class derives from the IPrimitive interface. - */ - export class Pushpin implements IPrimitive { - - /** - * Information that is linked to the pushpin. - * Some modules such as the GeoJSON, and Spatial Data Service modules will also often add information to this property. - */ - public metadata: any; - - /** - * @constructor - * @param location A Location object that specifies where to display the pushpin. - * @param options Options used when creating the Pushpin. - */ - constructor(location: Location, options?: IPushpinOptions); - - /** - * Gets the point on the Pushpin icon which is anchored to the pushpin location. - * An anchor of (0,0) is the top left corner of the icon. - * @returns The point on the Pushpin icon which is anchored to the pushpin location. - */ - public getAnchor(): Point; - - /** - * Gets whether the pushpin clicked style is enabled - * @returns Whether the pushpin clicked style is enabled. - */ - public getClickedStyleEnabled(): boolean; - - /** - * Gets the color option of the pushpin. - * @returns The color option of the pushpin. - */ - public getColor(): string | Color; - - /** - * Gets the css cursor value when pushpin has events on it. - * @returns CSS cursor string when pushpin has events on it. - */ - public getCursor(): string; - - /** - * Gets a boolean indicating if the pushpin is draggable or not. - * @returns A boolean indicating if the pushpin is draggable or not. - */ - public getDraggable(): boolean; - - /** - * Gets whether the pushpin hover style is enabled - * @returns Whether the pushpin hover style is enabled. - */ - public getHoverStyleEnabled(): boolean; - - /** - * Gets the custom Pushpin source icon string which can be a url to an image or SVG, inline SVG string, or data URI. - * @returns the custom Pushpin icon source string, which can be a url to an image or SVG, inline SVG string, or data URI. - */ - public getIcon(): string; - - /** - * Returns the location of the pushpin. - * @returns The location of the pushpin. - */ - public getLocation(): Location; - - /** - * Returns whether the clickable area of the pushpin is an ellipse. - * @returns A boolean indicating whether the clickable area of the pushpin is an ellipse. - */ - public getRoundClickableArea(): boolean; - - /** - * Gets the subtitle label of the Pushpin. - * @returns The subtitle label of the Pushpin. - */ - public getSubTitle(): string; - - /** - * Gets the text within the Pushpin icon. - * @returns The text within the Pushpin icon. - */ - public getText(): string; - - /** - * Gets the amount the text is shifted from the Pushpin icon. - * @returns the amount the text is shifted from the Pushpin icon. - */ - public getTextOffset(): Point; - - /** - * Gets the title label of the Pushpin. - * @returns the title label of the Pushpin. - */ - public getTitle(): string; - - /** - * Gets whether the pushpin is visible. - * @returns A boolean indicating whether the pushpin is visible or not. - */ - public getVisible(): boolean; - - /** - * Sets the location of the Pushpin. - * @param location The location of the Pushpin. - */ - public setLocation(location: Location): void; - - /** - * Sets the properties for the pushpin. - * @param options The IPushpinOptions object containing the options to customize the pushpin. - */ - public setOptions(options: IPushpinOptions): void; - } - - /** - * Used to represent the location of a map tile in the quadkey tile pyramid system used by the map. - * If using a tile source where the uriConstructor property is set to a callback function, that callback function will recieve - * an instance of the PyramidTileId class. - */ - export class PyramidTileId { - /** The height of the tile. */ - public pixelHeight: number; - - /** The width of the tile. */ - public pixelWidth: number; - - /** The quadkey ID of the tile. */ - public quadKey: string; - - /** The x tile coordinate. */ - public x: number; - - /** The y tile coordinate. */ - public y: number; - - /** The zoom level of the tile. */ - public zoom: number; - - /** - * @constructor - * @param x The integer x position of the tile within the tile layer at the specified zoom level. - * @param y The integer y position of the tile within the tile layer at the specified zoom level. - * @param zoom The zoom level of the tile. - * @param width The tile's width in pixels. Default value: 256 - * @param height The tile's height in pixels. Default value: 256 - */ - constructor(x: number, y: number, zoom: number, width?: number, height?: number) - - /** - * Compares two PyramidTileId objects and returns a boolean indicating if the two PyramidTileId are equal. - * @param tileId1 The first PyramidTileId to compare to the second. - * @param tileId2 The second PyramidTileId to compare to the first. - * @returns A boolean indicating if the two PyramidTileId are equal. - */ - public static areEqual(tileId1: PyramidTileId, tileId2: PyramidTileId): boolean; - - /** - * Generates a PyramidTileId from a quadkey tile id string. - * @param quadkey The quadkey tile id string to convert into a PyramidTileId object. - * @param width The tile's width in pixels. Default value: 256 - * @param height The tile's height in pixels. Default value: 256 - */ - public static fromQuadKey(quadkey: string, width?: number, height?: number): PyramidTileId; - } - - /** Provides static functions for generating random test data. */ - export class TestDataGenerator { - /** - * Generates a random hex or rgba color string. - * @param withAlpha A boolean indicating if the color should have an alpha value or not. if set to true, a rgba value will be returned with an alpha value of 0.5. - * @returns A css color string, hex or rgba. - */ - public static getColor(withAlpha?: boolean): string; - - /** - * Generates random Location objects. - * @param num The number of locations to generate. If set to one a single Location will be returned. If greater than one and array will be returned. - * @param bounds The bounding box in which all the locations should fall within. - * @returns One or more random Locations. - */ - public static getLocations(num?: number, bounds?: LocationRect): Location | Location[]; - - /** - * Generates random pushpins. - * @param num The number of pushpins to generate. If set to one a single Pushpin will be returned. If greater than one and array will be returned. - * @param bounds The bounding box in which all the pushpins should fall within. - * @param options The options to use for rendering the pushpins. Default is random. - * @returns One or more random Pushpins. - */ - public static getPushpins(num?: number, bounds?: LocationRect, options?: IPushpinOptions): Pushpin | Pushpin[]; - - /** - * Generates random polylines. - * @param num The number of polylines to generate. If set to one a single Polyline will be returned. If greater than one and array will be returned. - * @param bounds The bounding box in which all the locations of the polylines should fall within. - * @param size The number of locations each polylines should have. Default: random between 3 and 10. - * @param scaleFactor A number that scales the size of the polylines based on size of the bounding box. A value of 0.1 would generate polylines that are no larger than 10% of the width/height of the map. Default: 0.1 - * @param options The options to use for rendering the polylines. Default is random. - * @returns One or more random Polylines. - */ - public static getPolylines(num?: number, bounds?: LocationRect, size?: number, scaleFactor?: number, options?: IPolylineOptions): Polyline | Polyline[]; - - /** - * Generates random polygons. - * @param num The number of polygons to generate. If set to one a single Polygon will be returned. If greater than one and array will be returned. - * @param bounds The bounding box in which all the locations of the polygon should fall within. - * @param size The number of locations each polygon should have. Default: random between 3 and 10. - * @param scaleFactor A number that scales the size of the polygons based on the size of the bounding box. A value of 0.1 would generate polygons that are no larger than 10% of the width/height of the map. Default: 0.1 - * @param options The options to use for rendering the polygons. Default is random. - * @param addHole A boolean indicating if the generated polygon should have a hole or not. Note that this will double the number of Location objects that are in the Polygon. Default: false - * @returns One or more random polygons. - */ - public static getPolygons(num?: number, bounds?: LocationRect, size?: number, scaleFactor?: number, options?: IPolygonOptions, addHole?: boolean): Polygon | Polygon[]; - } - - /** Represents a tile layer that can be overlaid on top of the map. */ - export class TileLayer implements ILayer { - /** - * @constructor - * @param options The options to use to define the tile layer. - */ - constructor(options: ITileLayerOptions); - - /** - * Gets the opacity of the tile layer, defined as a double between 0 (not visible) and 1. - * @returns The opacity of the tile layer, defined as a double between 0 (not visible) and 1. - */ - public getOpacity(): number; - - /** - * Gets the tile source of the tile layer. - * @returns The tile source of the tile layer. - */ - public getTileSource(): TileSource; - - /** - * Gets a boolean that indicates if the tile layer is visible or not. - * @returns A boolean that indicates if the tile layer is visible or not. - */ - public getVisible(): boolean; - - /** - * Gets the zIndex of the tile layer. - * @returns The zIndex of the tile layer. - */ - public getZIndex(): number; - - /** - * Sets the opacity of the tile layer. Value must be a number between 0 and 1. - * @param opacity The opacity of the tile layer. Value must be a number between 0 and 1. - */ - public setOpacity(opacity: number): void; - - /** - * Sets options for the tile layer. - * @param options The options for the tile layer. - */ - public setOptions(options: ITileLayerOptions): void; - - /** - * Sets the visibility of the tile layer. - * @param show A boolean indicating if the tile layer should be visible or not. - */ - public setVisible(show: boolean): void; - - /** - * Sets the zIndex of the tile layer. - * @param idx The zIndex of the tile layer. - */ - public setZIndex(idx: number): void; - } - - /** Defines the data source for a tile layer. */ - export class TileSource { - /** - * @constructor - * @param options The options to use to define the tile source. - */ - constructor(options: ITileSourceOptions); - - /** - * Gets the specified bounding box of the of the tile source. - * @returns The specified bounding box of the of the tile source. - */ - public getBounds(): LocationRect; - - /** - * Gets the pixel height of each tile in the tile source. - * @returns The pixel height of each tile in the tile source. - */ - public getHeight(): number; - - /** - * Gets the maximum zoom level specified for the tile source. - * @returns The maximum zoom level specified for the tile source. - */ - public getMaxZoom(): number; - - /** - * Gets the minimum zoom level specified for the tile source. - * @returns The minimum zoom level specified for the tile source. - */ - public getMinZoom(): number; - - /** - * Gets a string that constructs tile URLs used to retrieve tiles for the tile layer. - * @returns A string that constructs tile URLs used to retrieve tiles for the tile layer. - */ - public getUriConstructor(): string | ((tile: PyramidTileId) => string); - - /** - * Gets the pixel width of each tile in the tile source. - * @returns The pixel width of each tile in the tile source. - */ - public getWidth(): number; - } -} diff --git a/types/bingmaps/tsconfig.json b/types/bingmaps/tsconfig.json deleted file mode 100644 index 421876221b..0000000000 --- a/types/bingmaps/tsconfig.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "Autosuggest.d.ts", - "Clustering.d.ts", - "Contour.d.ts", - "DataBinning.d.ts", - "Directions.d.ts", - "DrawingTools.d.ts", - "GeoJson.d.ts", - "HeatMapLayer.d.ts", - "Search.d.ts", - "SpatialDataService.d.ts", - "SpatialMath.d.ts", - "Traffic.d.ts", - "WellKnownText.d.ts", - "bingmaps-tests.ts" - ] -} \ No newline at end of file diff --git a/types/bip38/tsconfig.json b/types/bip38/tsconfig.json index 6ce875b1d1..74baba8f90 100644 --- a/types/bip38/tsconfig.json +++ b/types/bip38/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "bip38-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/bip39/tsconfig.json b/types/bip39/tsconfig.json index d44c1197ad..bb95bb90d0 100644 --- a/types/bip39/tsconfig.json +++ b/types/bip39/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "bip39-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/bitcore-lib/bitcore-lib-tests.ts b/types/bitcore-lib/bitcore-lib-tests.ts new file mode 100644 index 0000000000..fb39c85fc1 --- /dev/null +++ b/types/bitcore-lib/bitcore-lib-tests.ts @@ -0,0 +1,27 @@ +import * as bitcore from 'bitcore-lib'; + +const transaction = new bitcore.Transaction({}); + +const output: bitcore.Output = transaction.outputs[0]; + +const privateKey: bitcore.PrivateKey = new bitcore.PrivateKey('privateKey'); +const publicKey: bitcore.PublicKey = privateKey.publicKey; +const publicKeyAsString: string = publicKey.toString(); + +const signature = bitcore.crypto.ECDSA.sign(Buffer.from('sign this message', 'hex'), new bitcore.PrivateKey('privateKey')); + +bitcore.crypto.ECDSA.verify( + Buffer.from('buffer', 'hex'), + bitcore.crypto.Signature.fromString('signature'), + new bitcore.PublicKey('publicKey') +); + +const utxo: bitcore.Transaction.UnspentOutput[] = [new bitcore.Transaction.UnspentOutput({})]; + +new bitcore.Block(Buffer.from('123', 'hex')); + +const tx = new bitcore.Transaction() + .from(utxo) + .change('bitcoinAddress') + .addData(Buffer.from('')) + .sign('bitcoinAddressPrivateKey'); diff --git a/types/bitcore-lib/index.d.ts b/types/bitcore-lib/index.d.ts new file mode 100644 index 0000000000..0846b85c0d --- /dev/null +++ b/types/bitcore-lib/index.d.ts @@ -0,0 +1,130 @@ +// Type definitions for bitcore-lib 0.15 +// Project: https://github.com/bitpay/bitcore-lib +// Definitions by: Lautaro Dragan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.2 + +/// + +export namespace crypto { + class BN { } + namespace ECDSA { + function sign(message: Buffer, key: PrivateKey): Signature; + function verify(hashbuf: Buffer, sig: Signature, pubkey: PublicKey, endian?: 'little'): boolean; + } + namespace Hash { + function sha256(buffer: Buffer): Uint8Array; + } + namespace Random { + function getRandomBuffer(size: number): Buffer; + } + namespace Point {} + class Signature { + static fromDER(sig: Buffer): Signature; + static fromString(data: string): Signature; + SIGHASH_ALL: number; + toString(): string; + } +} + +export class Transaction { + inputs: Input[]; + outputs: Output[]; + readonly id: string; + readonly hash: string; + nid: string; + + constructor(serialized?: any); + + from(utxos: Transaction.UnspentOutput[]): Transaction; + to(address: Address | string, amount: number): Transaction; + change(address: Address | string): Transaction; + sign(privateKey: PrivateKey | string): Transaction; + applySignature(sig: crypto.Signature): Transaction; + addData(data: Buffer): this; + serialize(): string; +} + +export namespace Transaction { + class UnspentOutput { + static fromObject(o: object): UnspentOutput; + + readonly address: Address; + readonly txId: string; + readonly outputIndex: number; + readonly script: Script; + readonly satoshis: number; + + constructor(data: object); + + inspect(): string; + toObject(): this; + toString(): string; + } +} + +export class Block { + hash: string; + height: number; + transactions: Transaction[]; + header: { + time: number; + prevHash: string; + }; + + constructor(data: Buffer | object); +} + +export class PrivateKey { + readonly publicKey: PublicKey; + + constructor(key: string); +} + +export class PublicKey { + constructor(source: string); + + static fromPrivateKey(privateKey: PrivateKey): PublicKey; + + toBuffer(): Buffer; + toDER(): Buffer; +} + +export interface Output { + readonly script: any; +} + +export namespace Script { + const types: { + DATA_OUT: string; + }; + function buildPublicKeyHashOut(address: Address): Script; +} + +export class Script { } + +export interface Util { + readonly buffer: { + reverse(a: any): any; + }; +} + +export namespace Networks { + interface Network { + readonly name: string; + readonly alias: string; + } + + const livenet: Network; + const mainnet: Network; + const testnet: Network; + + function add(data: any): Network; + function remove(network: Network): void; + function get(args: string | number | Network, keys: string | string[]): Network; +} + +export class Address {} + +export class Input {} diff --git a/types/rollup/tsconfig.json b/types/bitcore-lib/tsconfig.json similarity index 93% rename from types/rollup/tsconfig.json rename to types/bitcore-lib/tsconfig.json index 2fad31b1b1..30334d3846 100644 --- a/types/rollup/tsconfig.json +++ b/types/bitcore-lib/tsconfig.json @@ -1,10 +1,10 @@ { "compilerOptions": { "module": "commonjs", - "target": "es6", "lib": [ "es6" ], + "target": "es6", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, @@ -19,6 +19,6 @@ }, "files": [ "index.d.ts", - "rollup-tests.ts" + "bitcore-lib-tests.ts" ] } \ No newline at end of file diff --git a/types/bitcore-lib/tslint.json b/types/bitcore-lib/tslint.json new file mode 100644 index 0000000000..dae7fb7540 --- /dev/null +++ b/types/bitcore-lib/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} \ No newline at end of file diff --git a/types/bittorrent-protocol/bittorrent-protocol-tests.ts b/types/bittorrent-protocol/bittorrent-protocol-tests.ts index c32b2af368..2faca76a5e 100644 --- a/types/bittorrent-protocol/bittorrent-protocol-tests.ts +++ b/types/bittorrent-protocol/bittorrent-protocol-tests.ts @@ -1,4 +1,4 @@ -import * as Protocol from 'bittorrent-protocol'; +import Protocol = require('bittorrent-protocol'); import * as net from 'net'; class TestExtension implements Protocol.Extension { diff --git a/types/blessed/blessed-tests.ts b/types/blessed/blessed-tests.ts index c5f857146f..aa38af8985 100644 --- a/types/blessed/blessed-tests.ts +++ b/types/blessed/blessed-tests.ts @@ -1,5 +1,6 @@ import * as blessed from "blessed"; import { readFileSync } from "fs"; +import { inspect } from "util"; let screen: blessed.Widgets.Screen = null; @@ -743,3 +744,71 @@ setTimeout(() => { table.setData(data1); screen.render(); }, 3000); + +// https://github.com/chjj/blessed/blob/master/test/program-mouse.js + +const program = blessed.program({ + dump: __dirname + '/logs/mouse.log' +}); + +// program.setMouse({ +// allMotion: true, +// //utfMouse: true +// urxvtMouse: true +// }, true); + +program.alternateBuffer(); +program.enableMouse(); +program.hideCursor(); + +program.setMouse({ sendFocus: true }, true); + +program.on('mouse', function(data) { + program.cup(data.y, data.x); + program.write(' '); + program.cup(0, 0); + program.write(inspect(data)); +}); + +program.on('resize', function(data) { + setTimeout(function() { + program.clear(); + program.cup(0, 0); + program.write(inspect({ cols: program.cols, rows: program.rows })); + }, 200); +}); + +process.on('SIGWINCH', function(data) { + setTimeout(function() { + program.cup(1, 0); + program.write(inspect({ winch: true, cols: program.cols, rows: program.rows })); + }, 200); +}); + +program.on('focus', function(data) { + program.clear(); + program.cup(0, 0); + program.write('FOCUSIN'); +}); + +program.on('blur', function(data) { + program.clear(); + program.cup(0, 0); + program.write('FOCUSOUT'); +}); + +program.key(['q', 'escape', 'C-c'], function() { + program.showCursor(); + program.disableMouse(); + program.normalBuffer(); + process.exit(0); +}); + +program.on('keypress', function(ch, data) { + if (data.name === 'mouse') return; + program.clear(); + program.cup(0, 0); + program.write(inspect(data)); +}); + +program.clear(); diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index 9098648240..7dae1709d2 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -7,13 +7,433 @@ /// import { EventEmitter } from "events"; +import { Writable, Readable } from "stream"; import * as stream from "stream"; import * as child_process from "child_process"; -export class BlessedProgram { - hideCursor: () => void; - move: any; - showCursor: any; +export interface IBlessedProgramOptions { + input?: Readable; + output?: Writable; + log?: string; + dump?: boolean; + zero?: boolean; + buffer?: boolean; + terminal?: string; + term?: string; + tput?: string; + debug?: boolean; + resizeTimeout?: boolean; +} + +export class BlessedProgram extends EventEmitter { + type: string; + options: IBlessedProgramOptions; + input: Readable; + output: Writable; + zero: boolean; + useBuffer: boolean; + x: number; + y: number; + savedX: number; + savedY: number; + cols: number; + rows: number; + scrollTop: number; + scrollBottom: number; + isOSXTerm: boolean; + isiTerm2: boolean; + isXFCE: boolean; + isTerminator: boolean; + isLXDE: boolean; + isVTE: boolean; + isRxvt: boolean; + isXterm: boolean; + tmux: boolean; + tmuxVersion: number; + + constructor(options?: IBlessedProgramOptions); + + log(): boolean; + debug(): boolean; + setupDump(): void; + setupTput(): void; + setTerminal(terminal: string): void; + has(name: string): boolean; + term(is: string): boolean; + + listen(): void; + destroy(): void; + + key(key: string|string[], listener: Function): void; + onceKey(key: string|string[], listener: Function): void; + + unKey(key: string|string[], listener: Function): void; + removeKey(key: string|string[], listener: Function): void; + + bindMouse(): void; + enableGpm(): void; + disableGpm(): void; + bindResponse(): void; + + response(name: string, text: string, callback: Function, noBypass?: boolean): boolean; + response(name: string, callback?: Function): boolean; + + write(text: string): boolean; + flush(): void; + print(text: string, attr?: boolean): boolean; + echo(text: string, attr?: boolean): boolean; + + setx(x: number): boolean; + sety(y: number): boolean; + move(x: number, y: number): boolean; + omove(x: number, y: number): void; + rsetx(x: number): boolean; + rsety(y: number): boolean; + rmove(x: number, y: number): void; + + simpleInsert(ch: string, i?: number, attr?: boolean): boolean; + repeat(ch: string, i?: number): string; + copyToClipboard(text: string): boolean; + + cursorShape(shape: string, blink?: boolean): boolean; + cursorColor(color: string): boolean; + cursorReset(): boolean; + resetCursor(): boolean; + + getTextParams(param: string, callback: Function): boolean; + getCursorColor(callback: Function): boolean; + + nul(): boolean; + + bell(): boolean; + bel(): boolean; + + vtab(): boolean; + + form(): boolean; + ff(): boolean; + + backspace(): boolean; + kbs(): boolean; + + tab(): boolean; + ht(): boolean; + + shiftOut(): boolean; + shiftIn(): boolean; + + return(): boolean; + cr(): boolean; + + feed(): boolean; + newline(): boolean; + nl(): boolean; + + index(): boolean; + ind(): boolean; + + reverseIndex(): boolean; + reverse(): boolean; + ri(): boolean; + + nextLine(): boolean; + reset(): boolean; + tabSet(): boolean; + + saveCursor(key: string): boolean; + sc(key: string): boolean; + + restoreCursor(key?: string, hide?: boolean): boolean; + rc(key?: string, hide?: boolean): boolean; + + lsaveCursor(key?: string): void; + lrestoreCursor(key?: string, hide?: boolean): void; + + lineHeight(): boolean; + + charset(val?: string, level?: number): boolean; + + enter_alt_charset_mode(): boolean; + as(): boolean; + smacs(): boolean; + + exit_alt_charset_mode(): boolean; + ae(): boolean; + rmacs(): boolean; + + setG(val: number): boolean; + + setTitle(title: string): boolean; + + resetColors(param?: string): boolean; + + dynamicColors(param?: string): boolean; + + selData(a: string, b: string): boolean; + + cursorUp(param?: number): boolean; + cuu(param?: number): boolean; + up(param?: number): boolean; + + cursorDown(param?: number): boolean; + cud(param?: number): boolean; + down(param?: number): boolean; + + cursorForward(param?: number): boolean; + cuf(param?: number): boolean; + right(param?: number): boolean; + forward(param?: number): boolean; + + cursorBackward(param?: number): boolean; + cub(param?: number): boolean; + left(param?: number): boolean; + back(param?: number): boolean; + + cursorPos(row?: number, col?: number): boolean; + cup(row?: number, col?: number): boolean; + pos(row?: number, col?: number): boolean; + + eraseInDisplay(param?: string): boolean; + ed(param?: string): boolean; + + clear(): boolean; + + eraseInLine(param?: string): boolean; + el(param?: string): boolean; + + charAttributes(param: string, val?: boolean): boolean; + charAttributes(param: string[], val?: boolean): boolean; + + setForeground(color: string, val?: boolean): boolean; + fg(color: string, val?: boolean): boolean; + + setBackground(color: string, val?: boolean): boolean; + bg(color: string, val?: boolean): boolean; + + deviceStatuses(param?: string, callback?: Function, dec?: boolean, noBypass?: boolean): boolean; + dsr(param?: string, callback?: Function, dec?: boolean, noBypass?: boolean): boolean; + + getCursor(callback: Function): boolean; + saveReportedCursor(callback: Function): void; + + restoreReportedCursor: () => boolean; + + insertChars(param?: number): boolean; + ich(param?: number): boolean; + + cursorNextLine(param?: number): boolean; + cnl(param?: number): boolean; + + cursorPrecedingLine(param?: number): boolean; + cpl(param?: number): boolean; + + cursorCharAbsolute(param?: number): boolean; + cha(param?: number): boolean; + + insertLines(param?: number): boolean; + il(param?: number): boolean; + + deleteLines(param?: number): boolean; + dl(param?: number): boolean; + + deleteChars(param?: number): boolean; + dch(param?: number): boolean; + + eraseChars(param?: number): boolean; + ech(param?: number): boolean; + + charPosAbsolute(param?: number): boolean; + hpa(param?: number): boolean; + + HPositionRelative(param?: number): boolean; + + sendDeviceAttributes(param?: number, callback?: Function): boolean; + da(param?: number, callback?: Function): boolean; + + linePosAbsolute(param?: number): boolean; + vpa(param?: number): boolean; + + VPositionRelative(param?: number): boolean; + vpr(param?: number): boolean; + + HVPosition(row?: number, col?: number): boolean; + hvp(row?: number, col?: number): boolean; + + setMode(...args: string[]): boolean; + sm(...args: string[]): boolean; + + decset(...args: string[]): boolean; + + showCursor(): boolean; + + alternateBuffer(): boolean; + smcup(): boolean; + alternate(): boolean; + + resetMode(...args: string[]): boolean; + rm(...args: string[]): boolean; + + decrst(...args: string[]): boolean; + + hideCursor(): boolean; + civis(): boolean; + vi(): boolean; + cursor_invisible(): boolean; + dectcemh(): boolean; + + normalBuffer(): boolean; + rmcup(): boolean; + + enableMouse(): void; + disableMouse(): void; + + setMouse(opt?: {}, enable?: boolean): void; + + setScrollRegion(top: number, bottom: number): boolean; + csr(top: number, bottom: number): boolean; + decstbm(top: number, bottom: number): boolean; + + saveCursorA(): boolean; + scA(): boolean; + + restoreCursorA(): boolean; + rcA(): boolean; + + cursorForwardTab(param?: number): boolean; + cht(param?: number): boolean; + + scrollUp(param?: number): boolean; + su(param?: number): boolean; + + scrollDown(param?: number): boolean; + sd(param?: number): boolean; + + initMouseTracking(...args: string[]): boolean; + + resetTitleModes(...args: string[]): boolean; + + cursorBackwardTab(param?: number): boolean; + cbt(param?: number): boolean; + + repeatPrecedingCharacter(param?: number): boolean; + rep(param?: number): boolean; + + tabClear(param?: number): boolean; + tbc(param?: number): boolean; + + mediaCopy(...args: string[]): boolean; + mc(...args: string[]): boolean; + + mc0(): boolean; + print_screen(): boolean; + ps(): boolean; + + mc5(): boolean; + prtr_on(): boolean; + po(): boolean; + + mc4(): boolean; + prtr_off(): boolean; + pf(): boolean; + + mc5p(): boolean; + prtr_non(): boolean; + p0(): boolean; + + setResources(...args: string[]): boolean; + + disableModifieres(...args: string[]): boolean; + + setPointerMode(...args: string[]): boolean; + + softReset(): boolean; + rs2(): boolean; + decstr(): boolean; + + requestAnsiMode(param?: number): boolean; + decrqm(param?: number): boolean; + + requestPrivateMode(param?: number): boolean; + decrqmp(param?: number): boolean; + + setConformanceLevel(...args: string[]): boolean; + decscl(...args: string[]): boolean; + + loadLEDs(param?: number): boolean; + decll(param?: number): boolean; + + setCursorStyle(param?: string): boolean; + decscursr(param?: string): boolean; + + setCharProtectionAttr(param?: number): boolean; + decsca(param?: number): boolean; + + restorePrivateValues(...args: string[]): boolean; + + setAttrInRectangle(...args: string[]): boolean; + deccara(...args: string[]): boolean; + + savePrivateValues(...args: string[]): boolean; + + manipulateWindow(...args: any[]): boolean; + + getWindowSize(callback?: Function): boolean; + + reverseAttrInRectangle(...args: string[]): boolean; + decrara(...args: string[]): boolean; + + setTitleModeFeature(...args: string[]): boolean; + + setWarningBellVolume(param?: number): boolean; + decswbv(param?: number): boolean; + + setMarginBellVolume(param?: number): boolean; + + copyRectangle(...args: string[]): boolean; + deccra(...args: string[]): boolean; + + enableFilterRectangle(...args: string[]): boolean; + decefr(...args: string[]): boolean; + + requestParameters(param?: number): boolean; + decreqtparm(param: number): boolean; + + selectChangeExtent(param?: number): boolean; + decsace(param?: number): boolean; + + fillRectangle(...args: string[]): boolean; + decfra(...args: string[]): boolean; + + enableLocatorReporting(...args: string[]): boolean; + decelr(...args: string[]): boolean; + + eraseRectangle(...args: string[]): boolean; + decera(...args: string[]): boolean; + + setLocatorEvents(...args: string[]): boolean; + decsle(...args: string[]): boolean; + + selectiveEraseRectangle(...args: string[]): boolean; + decsera(...args: string[]): boolean; + + requestLocatorPosition(param?: string, callback?: Function): boolean; + reqmp(param?: string, callback?: Function): boolean; + req_mouse_pos(param?: string, callback?: Function): boolean; + decrqlp(param?: string, callback?: Function): boolean; + + insertColumns(...args: string[]): boolean; + decic(...args: string[]): boolean; + + deleteColumns(...args: string[]): boolean; + decdc(...args: string[]): boolean; + + out(param: string, ...args: any[]): boolean; + + sigtstp(callback?: Function): boolean; + + pause(callback?: Function): Function; + + resume: () => void; } export namespace Widgets { @@ -516,7 +936,7 @@ export namespace Widgets { * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when * pressing F12. It will display all log and debug messages. */ - debug?(...msg: string[]): void; + debug?: boolean; /** * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful @@ -963,7 +1383,7 @@ export namespace Widgets { /** * Spawn a process in the foreground, return to blessed app after exit. */ - spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + spawn(file: string, args?: string[], options?: NodeChildProcessExecOptions): child_process.ChildProcess; /** * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. @@ -3024,6 +3444,7 @@ export function message(options?: Widgets.MessageOptions): Widgets.MessageElemen export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; export function log(options?: Widgets.LogOptions): Widgets.Log; export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; +export function program(options?: Widgets.IScreenOptions): BlessedProgram; export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; export function escape(item: any): any; diff --git a/types/blob-to-buffer/tsconfig.json b/types/blob-to-buffer/tsconfig.json index 2421ce2493..37848b0516 100644 --- a/types/blob-to-buffer/tsconfig.json +++ b/types/blob-to-buffer/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "blob-to-buffer-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/bluebird-global/index.d.ts b/types/bluebird-global/index.d.ts index c0e220ce07..6b22cb7114 100644 --- a/types/bluebird-global/index.d.ts +++ b/types/bluebird-global/index.d.ts @@ -31,6 +31,22 @@ * in the runtime. Do this by either importing bluebird.js via a ` header necessary for Browser Monitoring. + * + * This script must be manually injected into your templates, as high as possible + * in the header, but _after_ any X-UA-COMPATIBLE HTTP-EQUIV meta tags. + * Otherwise you may hurt IE! + * + * This method must be called _during_ a transaction, and must be called every + * time you want to generate the headers. + * + * Do *not* reuse the headers between users, or even between requests. + */ + getBrowserTimingHeader(): string; + + /** + * Instrument a particular callback to improve visibility into a transaction. + * + * Use this API call to improve instrumentation of a particular method, or to track work across asynchronous + * boundaries by calling createTracer() in both the target function and its parent asynchronous function. + * + * The name will be visible in transaction traces and as a new metric in the New Relic UI. + * + * The agent begins timing the segment when createTracer is called, and ends the segment when the callback + * defined by the callback argument finishes executing. + */ + createTracer any>(name: string, handle: T): T; + + /** + * Creates and starts a web transaction to record work done in the handle supplied. + * + * This transaction will run until the handle + * synchronously returns UNLESS: + * 1. The handle function returns a promise, where the end of the + * transaction will be tied to the end of the promise returned. + * 2. `getTransaction` is called in the handle, flagging the + * transaction as externally handled. In this case the transaction + * will be ended when `TransactionHandle#end` is called in the user's code. + * + * @example + * var newrelic = require('newrelic') + * newrelic.startWebTransaction('/some/url/path', function() { + * var transaction = newrelic.getTransaction() + * setTimeout(function() { + * // do some work + * transaction.end() + * }, 100) + * }) + * + * The `url` is used to name and group related transactions in APM, + * so it should be a generic name and not include any variable parameters. + */ + startWebTransaction(url: string, handle: (...args: any[]) => any): any; + + /** + * Creates and starts a background transaction to record work done in the handle supplied. + * + * This transaction will run until the handle + * synchronously returns UNLESS: + * 1. The handle function returns a promise, where the end of the + * transaction will be tied to the end of the promise returned. + * 2. `API#getTransaction` is called in the handle, flagging the + * transaction as externally handled. In this case the transaction + * will be ended when `TransactionHandle#end` is called in the user's code. + * + * @example + * var newrelic = require('newrelic') + * newrelic.startBackgroundTransaction('Red October', 'Subs', function() { + * var transaction = newrelic.getTransaction() + * setTimeout(function() { + * // do some work + * transaction.end() + * }, 100) + * }) + * + * The `url` is used to name and group related transactions in APM, + * so it should be a generic name and not include any variable parameters. + * + * The optional `group can be used for grouping background transactions in APM. + * For more information see: + * https://docs.newrelic.com/docs/apm/applications-menu/monitoring/transactions-page#txn-type-dropdown + */ + startBackgroundTransaction(name: string, handle: (...args: any[]) => any): any; + startBackgroundTransaction(name: string, group: string, handle: (...args: any[]) => any): any; + + /** + * End the current web or background custom transaction. + * + * This method requires being in the correct transaction context when called. + */ + endTransaction(): void; + + /** + * Record an event-based metric, usually associated with a particular duration. + * + * The `name` must be a string following standard metric naming rules. The `value` will + * usually be a number, but it can also be an object. + * * When `value` is a numeric value, it should represent the magnitude of a measurement + * associated with an event; for example, the duration for a particular method call. + * * When `value` is an object, it must contain count, total, min, max, and sumOfSquares + * keys, all with number values. This form is useful to aggregate metrics on your own + * and report them periodically; for example, from a setInterval. These values will + * be aggregated with any previously collected values for the same metric. The names + * of these keys match the names of the keys used by the platform API. + */ + recordMetric(name: string, value: number | Metric): void; + + /** + * Update a metric that acts as a simple counter. + * + * The count of the selected metric will be incremented by the specified amount, defaulting to 1. + */ + incrementMetric(name: string, value?: number): void; + + /** + * Record an event-based metric, usually associated with a particular duration. + * + * `eventType` must be an alphanumeric string less than 255 characters. + * The keys of `attributes` must be shorter than 255 characters. + */ + recordCustomEvent(eventType: string, attributes: { [keys: string]: boolean | number | string }): void; + + /** + * Registers an instrumentation function. + * + * The provided onRequire callback will be fired when the given module is loaded with require. + * The moduleName parameter should be the string that will be passed to require; + * for example, 'express' or 'amqplib/callback_api'. + * + * The optional onError callback is called if the onRequire parameters throws an error. + * This is useful for debugging your instrumentation. + * + * Use this method to: + * - Add instrumentation for modules not currently instrumented by New Relic. + * - Instrument your own code. + * - Replace the Node.js agent's built-in instrumentation with your own. + */ + instrument: Instrument; + + /** + * Sets an instrumentation callback for a datastore module. + * + * This method is just like `instrument`, except it provides a datastore-service-specialized shim. + */ + instrumentDatastore: Instrument; + + /** + * Sets an instrumentation callback for a web framework module. + * + * This method is just like `instrument`, except it provides a web-framework-specialized shim. + */ + instrumentWebframework: Instrument; + + /** + * Sets an instrumentation callback for a message service client module. + * + * This method is just like `instrument`, except it provides a message-service-specialized shim. + */ + instrumentMessages: Instrument; + + /** + * Gracefully shuts down the agent. + * + * If `collectPendingData` is true, the agent will send any pending data to the collector + * before shutting down. Defaults to `false`. + */ + shutdown(cb?: (error?: Error) => void): void; + shutdown(options?: { collectPendingData?: boolean, timeout?: number }, cb?: (error?: Error) => void): void; + } + + interface Instrument { + (opts: { moduleName: string, onRequire: () => void, onError?: (err: Error) => void }): void; + (moduleName: string, onRequire: () => void, onError?: (err: Error) => void): void; + } + + interface Metric { + count: number; + total: number; + min: number; + max: number; + sumOfSquares: number; + } + + interface TransactionHandle { + /** + * End the transaction. + */ + end(callback?: () => any): void; + + /** + * Mark the transaction to be ignored. + */ + ignore(): void; + } +} +declare const api: newrelic.NewRelicAPI; +export = api; diff --git a/types/newrelic/newrelic-tests.ts b/types/newrelic/newrelic-tests.ts new file mode 100644 index 0000000000..73cd53cc78 --- /dev/null +++ b/types/newrelic/newrelic-tests.ts @@ -0,0 +1,98 @@ +/// +import * as newrelic from "newrelic"; + +newrelic.setTransactionName("foo"); // $ExpectType void + +const trans = newrelic.getTransaction(); +trans.ignore(); // $ExpectType void +trans.end(); // $ExpectType void +trans.end(() => { }); // $ExpectType void + +newrelic.setDispatcher("foo"); // $ExpectType void +newrelic.setDispatcher("foo", "42"); // $ExpectType void + +newrelic.setControllerName("foo", "GET"); // $ExpectType void + +newrelic.addCustomAttribute("foo", "bar"); // $ExpectType void +newrelic.addCustomAttributes({ foo: "bar", baz: "bang" }); // $ExpectType void + +newrelic.setIgnoreTransaction(true); // $ExpectType void + +newrelic.noticeError(Error("Oh no!")); // $ExpectType void +newrelic.noticeError(Error("Oh no!"), { foo: "bar" }); // $ExpectType void + +newrelic.addNamingRule("/user/customers/all/.*", "/user/customers/all"); // $ExpectType void +newrelic.addNamingRule(/\/user\/customers\/.*/, "/user/customers/:customer"); // $ExpectType void + +newrelic.addIgnoringRule("^/items/[0-9]+$"); // $ExpectType void +newrelic.addIgnoringRule(/^[0-9]+$/); // $ExpectType void + +newrelic.getBrowserTimingHeader(); // $ExpectType string + +const wrappedFn = newrelic.createTracer("foo", (x: number) => { + return x * x; +}); +const wrappedResult: number = wrappedFn(42); + +newrelic.startWebTransaction('/some/url/path', () => { + const transaction = newrelic.getTransaction(); + Promise.all([]); + setTimeout(() => { + // do some work + transaction.end(); + }, 100); +}); + +newrelic.startBackgroundTransaction('Red October', (foo) => foo); // $ExpectType any +newrelic.startBackgroundTransaction('Red October', 'Subs', () => { + const transaction = newrelic.getTransaction(); + setTimeout(() => { + // do some work + transaction.end(); + }, 100); +}); + +newrelic.endTransaction(); // $ExpectType void + +newrelic.recordMetric("foo", 42); // $ExpectType void +newrelic.recordMetric("foo", { + count: 10, + total: 42, + min: 1, + max: 17, + sumOfSquares: 60, +}); + +newrelic.incrementMetric("foo"); // $ExpectType void +newrelic.incrementMetric("foo", 42); // $ExpectType void + +newrelic.recordCustomEvent("my_event", { + foo: true, + bar: 42, + baz: "don't panic", +}); + +newrelic.instrument("foo", () => { }); // $ExpectType void +newrelic.instrumentDatastore("foo", () => { }, (err: Error) => { }); +newrelic.instrumentWebframework({ + moduleName: "foo", + onRequire: () => { }, +}); +newrelic.instrumentMessages({ + moduleName: "foo", + onRequire: () => { }, + onError: (err) => { + const error: Error = err; + }, +}); + +newrelic.shutdown(); // $ExpectType void +newrelic.shutdown({ collectPendingData: true }); +newrelic.shutdown({ timeout: 3000 }); +newrelic.shutdown({ collectPendingData: true, timeout: 3000 }); +newrelic.shutdown({ collectPendingData: true, timeout: 3000 }, (err) => { + const error: Error | undefined = err; +}); +newrelic.shutdown((err) => { + const error: Error | undefined = err; +}); diff --git a/types/newrelic/tsconfig.json b/types/newrelic/tsconfig.json new file mode 100644 index 0000000000..479dde054f --- /dev/null +++ b/types/newrelic/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", + "newrelic-tests.ts" + ] +} \ No newline at end of file diff --git a/types/newrelic/tslint.json b/types/newrelic/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/newrelic/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts index a6b1da550e..38e20f608a 100644 --- a/types/next-redux-wrapper/index.d.ts +++ b/types/next-redux-wrapper/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kirill-konshin/next-redux-wrapper // Definitions by: Steve // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.6 /// /*~ Note that ES6 modules cannot directly export callable functions. diff --git a/types/next/index.d.ts b/types/next/index.d.ts index 70bc8ef049..036e9f58ce 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Drew Hays // Brice BERNARD // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 /// diff --git a/types/ngreact/index.d.ts b/types/ngreact/index.d.ts index cb39e45ee1..6db92506ce 100644 --- a/types/ngreact/index.d.ts +++ b/types/ngreact/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ngReact/ngReact // Definitions by: Vicky Lai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 /// /// diff --git a/types/nightmare/index.d.ts b/types/nightmare/index.d.ts index 737137f22e..061f22bd10 100644 --- a/types/nightmare/index.d.ts +++ b/types/nightmare/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/segmentio/nightmare // Definitions by: horiuchi // Sam Yang +// Bleser // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -132,6 +133,10 @@ declare class Nightmare { declare namespace Nightmare { export interface IConstructorOptions { timeout?: any; // number | string; + waitTimeout?:number //in ms + gotoTimeout?:number + pollInterval?:number + executionTimeout?:number interval?: any; // number | string; port?: number; weak?: boolean; diff --git a/types/nightmare/nightmare-tests.ts b/types/nightmare/nightmare-tests.ts index 1dfe655c94..7eb376b996 100644 --- a/types/nightmare/nightmare-tests.ts +++ b/types/nightmare/nightmare-tests.ts @@ -4,27 +4,27 @@ import Nightmare = require("nightmare"); new Nightmare() .goto('http://yahoo.com') - .type('input[title="Search"]', 'github nightmare') - .click('.searchsubmit') - .run((err: any, nightmare: Nightmare) => { - if (err) return console.log(err); - console.log('Done!'); - }); + .type('input[title="Search"]', 'github nightmare') + .click('.searchsubmit') + .run((err: any, nightmare: Nightmare) => { + if (err) return console.log(err); + console.log('Done!'); + }); new Nightmare() .goto('http://yahoo.com') - .type('input[title="Search"]', 'github nightmare') - .click('.searchsubmit') - .wait('.url.breadcrumb') - .evaluate(() => { - return (document.querySelector('.url.breadcrumb')).innerText; - }, (breadcrumb: string) => { - // expect(breadcrumb).to.equal('github.com'); - }) - .run((err: any, nightmare: Nightmare) => {}); + .type('input[title="Search"]', 'github nightmare') + .click('.searchsubmit') + .wait('.url.breadcrumb') + .evaluate(() => { + return (document.querySelector('.url.breadcrumb')).innerText; + }, (breadcrumb: string) => { + // expect(breadcrumb).to.equal('github.com'); + }) + .run((err: any, nightmare: Nightmare) => { }); -var done = (err: any) => {}; +var done = (err: any) => { }; new Nightmare() .goto('http://www.google.com/') @@ -141,7 +141,7 @@ new Nightmare() }; }, function (coordinates) { }) - .scrollTo(100,50) + .scrollTo(100, 50) .evaluate(function () { return { top: document.body.scrollTop, @@ -174,12 +174,12 @@ new Nightmare() new Nightmare() .goto('http://yahoo.com') - .screenshot('test/test.png', { x: 10, y: 5, width: 10, height: 10}) + .screenshot('test/test.png', { x: 10, y: 5, width: 10, height: 10 }) .run(done); new Nightmare() .goto('http://yahoo.com') - .screenshot({ x: 10, y: 5, width: 10, height: 10}, (err, buffer) => { + .screenshot({ x: 10, y: 5, width: 10, height: 10 }, (err, buffer) => { console.log(Buffer.isBuffer(buffer)); }) .run(done); @@ -197,7 +197,7 @@ new Nightmare() var seconds = function () { var gifs = document.querySelectorAll('img'); - var split = (gifs[gifs.length-2]).src.split('.gif')[0]; + var split = (gifs[gifs.length - 2]).src.split('.gif')[0]; var seconds = split.split('.com/c')[1]; return parseInt(seconds, 10); }; @@ -209,8 +209,8 @@ new Nightmare() var seconds = function () { var text = document.querySelectorAll('b')[0].textContent; var splits = text.split(/\s/); - var seconds = splits[splits.length-2].split(':')[2]; - return parseInt(seconds, 10)%10; + var seconds = splits[splits.length - 2].split(':')[2]; + return parseInt(seconds, 10) % 10; }; new Nightmare() .goto('http://www.whattimeisit.com/') @@ -218,8 +218,8 @@ new Nightmare() .run(done); new Nightmare({ - timeout: 1000 - }) + timeout: 1000 +}) .on('timeout', function (msg) { }) .goto('http://www.google.com/') @@ -262,15 +262,15 @@ new Nightmare() .run(done); new Nightmare() - .authentication('my','auth') + .authentication('my', 'auth') .goto('http://httpbin.org/basic-auth/my/auth') .evaluate(function () { return document.body.innerHTML; - }, function (data){ + }, function (data) { }) .run(done); -var size = { width : 400, height: 1000 }; +var size = { width: 400, height: 1000 }; new Nightmare() .viewport(size.width, size.height) .goto('http://www.wikipedia.org/') @@ -316,8 +316,8 @@ function search(term: string) { return function (nightmare: Nightmare) { nightmare .goto('http://yahoo.com') - .type('.input-query', term) - .click('.searchsubmit') + .type('.input-query', term) + .click('.searchsubmit') .wait(); }; } @@ -335,7 +335,7 @@ new Nightmare() .use(testTitle('test term')) .run(done); -new Nightmare({show: true}); +new Nightmare({ show: true }); new Nightmare() .goto('http://google.com', { bogus: 'foo' }) @@ -366,4 +366,28 @@ new Nightmare() .click('a[href="/segmentio/nightmare/archive/master.zip"]') .download('/some/other/path/master.zip'); -new Nightmare({show: true, openDevTools: {mode: 'detach'}}); +new Nightmare({ show: true, openDevTools: { mode: 'detach' } }); + + +new Nightmare({ waitTimeout: 1000 }) + .goto("https//google.com") + .wait(".really-not-real") + + +new Nightmare({ gotoTimeout: 10000 }) + .goto("https://45.56.178.93/") + + +new Nightmare({ executionTimeout: 1000 }) + .goto("https//google.com") + .evaluate(() => { + new Promise((resolve, reject) => { + setTimeout(() => { + resolve() + }, 2000) + }) + }) + + + + diff --git a/types/nock/index.d.ts b/types/nock/index.d.ts index 8c6e4f2faf..91037b8e54 100644 --- a/types/nock/index.d.ts +++ b/types/nock/index.d.ts @@ -4,6 +4,7 @@ // Horiuchi_H // afharo // Matt R. Wilson +// Garanzha Dmitriy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -34,7 +35,7 @@ declare namespace nock { export var back: NockBack; - type HttpHeaders = { [key: string]: string | { (req: any, res: any, body: string): any; }; }; + type HttpHeaders = { [key: string]: string | string[] | { (req: any, res: any, body: string): any; }; }; type InterceptFunction = ( uri: string | RegExp | { (uri: string): boolean; }, requestBody?: string | RegExp | { (body: any): boolean; } | any, diff --git a/types/nock/nock-tests.ts b/types/nock/nock-tests.ts index 180c7a9c63..44397db941 100644 --- a/types/nock/nock-tests.ts +++ b/types/nock/nock-tests.ts @@ -1,6 +1,4 @@ - - -import * as nock from 'nock'; +import nock = require('nock'); import * as fs from 'fs'; var scope: nock.Scope; @@ -368,6 +366,12 @@ var scope = nock('http://www.headdy.com') 'X-My-Headers': 'My Header value' }); +var scope = nock('http://www.headdy.com') + .get('/') + .reply(200, 'Hello World!', { + 'X-My-Headers': ['My Header value 1', 'My Header value 2'] + }); + var scope = nock('http://www.headdy.com') .get('/') .reply(200, 'Hello World!', { diff --git a/types/node-cron/index.d.ts b/types/node-cron/index.d.ts new file mode 100644 index 0000000000..75ddaefdde --- /dev/null +++ b/types/node-cron/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for node-cron 1.2 +// Project: http://merencia.com/node-cron/ +// Definitions by: morsic +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// immediateStart - default true +export function schedule(a: string, func: () => void, immediateStart?: boolean): ScheduledTask; + +export function validate(a: string): boolean; + +export interface ScheduledTask { + start: () => this; + stop: () => this; + destroy: () => void; +} diff --git a/types/node-cron/node-cron-tests.ts b/types/node-cron/node-cron-tests.ts new file mode 100644 index 0000000000..c670924d27 --- /dev/null +++ b/types/node-cron/node-cron-tests.ts @@ -0,0 +1,47 @@ +/// + +import cron = require('node-cron'); + +// tslint:disable-next-line no-console +const log = console.log; + +cron.schedule('* * * * *', () => { + log('running a task every minute'); +}); + +cron.schedule('1-5 * * * *', () => { + log('running every minute to 1 from 5'); +}); + +// tslint:disable-next-line rule +const task = cron.schedule('* * * * *', () => { + log('immediately started'); + // because of manual call start method +}, false); + +task.start(); + +const task1 = cron.schedule('* * * * *', () => { + log('will execute every minute until stopped'); +}); + +task1.start(); + +const task2 = cron.schedule('* * * * *', () => { + log('will execute every minute until stopped'); +}); + +task2.stop(); + +const task3 = cron.schedule('* * * * *', () => { + log('will execute every minute until stopped'); +}); + +task3.destroy(); + +const valid = cron.validate('59 * * * *'); +const invalid = cron.validate('60 * * * *'); + +if (valid && !invalid) { + log('validator works'); +} diff --git a/types/node-cron/tsconfig.json b/types/node-cron/tsconfig.json new file mode 100644 index 0000000000..9fb50ab907 --- /dev/null +++ b/types/node-cron/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "noUnusedLocals": true, + "strictFunctionTypes": true, + "noUnusedParameters": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-cron-tests.ts" + ] +} \ No newline at end of file diff --git a/types/node-cron/tslint.json b/types/node-cron/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/node-cron/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index a5d3f078fe..2784d95fa3 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -14,7 +14,7 @@ declare module "node-forge" { type Utf8 = string; type OID = string; - namespace pem { + namespace pem { interface EncodeOptions { maxline?: number; @@ -32,7 +32,7 @@ declare module "node-forge" { function encode(msg: ObjectPEM, options?: EncodeOptions): string; function decode(str: string): ObjectPEM[]; } - + namespace pki { type PEM = string; @@ -79,10 +79,11 @@ declare module "node-forge" { interface CertificateField extends CertificateFieldOptions { valueConstructed?: boolean; valueTagClass?: asn1.Class; - value?: any[]; + value?: any[] | string; extensions?: any[]; } + interface Certificate { version: number; serialNumber: string; @@ -107,11 +108,61 @@ declare module "node-forge" { extensions: any[]; publicKey: any; md: any; + /** + * Sets the subject of this certificate. + * + * @param attrs the array of subject attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + setSubject(attrs: CertificateField[], uniqueId?: string): void; + /** + * Sets the subject of this certificate. + * + * @param attrs the array of subject attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + setIssuer(attrs: CertificateField[], uniqueId?: string): void; + /** + * Sets the extensions of this certificate. + * + * @param exts the array of extensions to use. + */ + setExtensions(exts: any[]): void; + /** + * Gets an extension by its name or id. + * + * @param options the name to use or an object with: + * name the name to use. + * id the id to use. + * + * @return the extension or null if not found. + */ + getExtension(options: string | {name: string;} | {id: number;}): {} | undefined; + + /** + * Signs this certificate using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + sign(key: pki.Key, md: md.MessageDigest): void; + /** + * Attempts verify the signature on the passed certificate using this + * certificate's public key. + * + * @param child the certificate to verify. + * + * @return true if verified, false if not. + */ + verify(child: Certificate): boolean; + } function certificateFromAsn1(obj: asn1.Asn1, computeHash?: boolean): Certificate; function decryptRsaPrivateKey(pem: PEM, passphrase?: string): Key; + + function createCertificate(): Certificate; } namespace ssh { diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index 63ccca6c70..29b8267714 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -1,4 +1,4 @@ -import * as forge from "node-forge"; +import * as forge from 'node-forge'; let keypair = forge.pki.rsa.generateKeyPair({ bits: 512 }); let privateKeyPem = forge.pki.privateKeyToPem(keypair.privateKey); @@ -8,19 +8,23 @@ let x: string = forge.ssh.privateKeyToOpenSSH(key); let pemKey: forge.pki.PEM = publicKeyPem; let publicKeyRsa = forge.pki.publicKeyFromPem(pemKey); let privateKeyRsa = forge.pki.privateKeyFromPem(privateKeyPem); +let cert = forge.pki.createCertificate(); { let subjectPublicKeyInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [ - forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false, - forge.asn1.oidToDer(forge.pki.oids['rsaEncryption']).getBytes(), + forge.asn1.create( + forge.asn1.Class.UNIVERSAL, + forge.asn1.Type.OID, + false, + forge.asn1.oidToDer(forge.pki.oids['rsaEncryption']).getBytes() ), - forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''), + forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, '') ]), forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.BITSTRING, false, [ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [ forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false, []), - forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false, []), + forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false, []) ]) ]) ]); @@ -52,12 +56,14 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin src = new Uint8Array(2); encode = forge.util.binary.hex.encode(src); decode = forge.util.binary.hex.decode(encode); - if (encode !== '0000' || src.byteLength !== decode.byteLength) throw Error('forge.util.binary.hex.encode / decode fail'); + if (encode !== '0000' || src.byteLength !== decode.byteLength) + throw Error('forge.util.binary.hex.encode / decode fail'); src = new Uint8Array(2); encode = forge.util.binary.base64.encode(src); decode = forge.util.binary.base64.decode(encode); - if (encode !== 'AAA=' || src.byteLength !== decode.byteLength) throw Error('forge.util.binary.base64.encode / decode fail'); + if (encode !== 'AAA=' || src.byteLength !== decode.byteLength) + throw Error('forge.util.binary.base64.encode / decode fail'); src = new Uint8Array(10); encode = forge.util.binary.raw.encode(src); @@ -97,7 +103,6 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin if (hex.length !== 40) throw Error('forge.md.MessageDigest.update / digest fail'); } - { let md: forge.md.MessageDigest; let hex: string; @@ -110,26 +115,74 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin } { - let payload = { "asd": "asd" } - let cipher = forge.cipher.createCipher( - "3DES-ECB", - forge.util.createBuffer(key, "raw") - ); + let payload = { asd: 'asd' }; + let cipher = forge.cipher.createCipher('3DES-ECB', forge.util.createBuffer(key, 'raw')); cipher.start(); - cipher.update(forge.util.createBuffer(JSON.stringify(payload), "raw")); + cipher.update(forge.util.createBuffer(JSON.stringify(payload), 'raw')); cipher.finish(); let encrypted = cipher.output; let token = forge.util.encode64(encrypted.getBytes()); - let decipher = forge.cipher.createDecipher( - "3DES-ECB", - forge.util.createBuffer(key, "raw") - ); + let decipher = forge.cipher.createDecipher('3DES-ECB', forge.util.createBuffer(key, 'raw')); decipher.start(); - decipher.update(forge.util.createBuffer(forge.util.decode64(token), "raw")); + decipher.update(forge.util.createBuffer(forge.util.decode64(token), 'raw')); decipher.finish(); let decrypted = decipher.output as forge.util.ByteStringBuffer; let content = JSON.parse(forge.util.encodeUtf8(decrypted.getBytes())); if (content.asd == payload.asd) throw Error('forge.cipher.createCipher failed'); -} \ No newline at end of file +} + +{ + cert.publicKey = keypair.publicKey; + cert.serialNumber = new Date().getTime() + ''; + cert.validity.notBefore = new Date(); + cert.validity.notAfter = new Date(); + cert.validity.notAfter.setFullYear(cert.validity.notAfter.getFullYear() + 20); + const attrs = [ + { + name: 'commonName', + value: 'x22x22' + }, + { + name: 'countryName', + value: 'GitHub' + }, + { + shortName: 'ST', + value: 'GitHub' + }, + { + name: 'localityName', + value: 'GitHub' + }, + { + name: 'organizationName', + value: 'x22x22' + }, + { + shortName: 'OU', + value: 'https://github.com/x22x22' + } + ]; + cert.setSubject(attrs); + cert.setIssuer(attrs); + cert.setExtensions([ + { + name: 'basicConstraints', + critical: true, + cA: true + }, + { + name: 'keyUsage', + critical: true, + keyCertSign: true + }, + { + name: 'subjectKeyIdentifier' + } + ]); + + // self-sign certificate + cert.sign(keypair.privateKey, forge.md.sha256.create()); +} diff --git a/types/node-geocoder/node-geocoder-tests.ts b/types/node-geocoder/node-geocoder-tests.ts index 33ed4b3036..bb554d03ba 100644 --- a/types/node-geocoder/node-geocoder-tests.ts +++ b/types/node-geocoder/node-geocoder-tests.ts @@ -1,4 +1,4 @@ -import * as NodeGeocoder from 'node-geocoder'; +import NodeGeocoder = require('node-geocoder'); const geocoder = NodeGeocoder({ provider: 'google', diff --git a/types/node-horseman/tsconfig.json b/types/node-horseman/tsconfig.json index 5490648512..8ac7d67c3e 100644 --- a/types/node-horseman/tsconfig.json +++ b/types/node-horseman/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "node-horseman-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/node-pg-migrate/index.d.ts b/types/node-pg-migrate/index.d.ts deleted file mode 100644 index 07c20ab3fa..0000000000 --- a/types/node-pg-migrate/index.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -// Type definitions for node-pg-migrate 2.3 -// Project: https://github.com/theoephraim/node-pg-migrate#readme -// Definitions by: Bradley Ayers -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -export interface ColumnDefinition { - type: string; - unique?: boolean; - primaryKey?: boolean; - notNull?: boolean; - check?: string; - references?: string; - onDelete?: string; - onUpdate?: string; -} - -export interface ColumnOptions { - type?: string; - default?: string | PgLiteral | null; - notNull?: boolean; - allowNull?: boolean; -} - -export interface CreateIndexOptions { - name?: string; - unique?: boolean; - where?: string; - concurrently?: boolean; - method?: 'btree' | 'hash' | 'gist' | 'spgist' | 'gin'; -} - -export interface ColumnDefinitions { - [name: string]: ColumnDefinition; -} - -export type TableDescriptor = string | { schema: string, name: string }; - -export interface MigrationBuilder { - addExtension(extension: string | string[]): void; - createExtension(extension: string | string[]): void; - dropExtension(extension: string | string[]): void; - - createTable(tableName: TableDescriptor, columns: ColumnDefinitions, options?: { inherits?: string }): void; - dropTable(tableName: TableDescriptor): void; - renameTable(tablename: TableDescriptor, new_tablename: TableDescriptor): void; - - addColumn(tablename: TableDescriptor, new_columns: ColumnDefinitions): void; - addColumns(tablename: TableDescriptor, new_columns: ColumnDefinitions): void; - dropColumn(tablename: TableDescriptor, columns: string[] | { [name: string]: any }): void; - dropColumns(tablename: TableDescriptor, columns: string[] | { [name: string]: any }): void; - renameColumn(tablename: TableDescriptor, old_column_name: string, new_column_name: string): void; - alterColumn(tableName: TableDescriptor, columnName: string, options: ColumnOptions): void; - - addConstraint(tablename: TableDescriptor, constraint_name: string, expression: string): void; - createConstraint(tablename: TableDescriptor, constraint_name: string, expression: string): void; - dropConstraint(tablename: TableDescriptor, constraint_name: string): void; - - addType(type_name: string, values: string[] | { [name: string]: string }): void; - createType(type_name: string, values: string[] | { [name: string]: string }): void; - dropType(type_name: string): void; - - createIndex(tableName: TableDescriptor, columns: string | string[], options?: CreateIndexOptions): void; - dropIndex(tableName: TableDescriptor, columns: string | string[], options?: CreateIndexOptions): void; - addIndex(tableName: TableDescriptor, columns: string | string[], options?: CreateIndexOptions): void; - - sql(sql: string, args?: object): void; - func(sql: string): PgLiteral; - - noTransaction(): void; -} - -export default function(options: any): Promise; - -export class PgLiteral { - static create(str: string): PgLiteral; - constructor(str: string); -} diff --git a/types/node-pg-migrate/node-pg-migrate-tests.ts b/types/node-pg-migrate/node-pg-migrate-tests.ts deleted file mode 100644 index c3f1edf9b8..0000000000 --- a/types/node-pg-migrate/node-pg-migrate-tests.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { MigrationBuilder } from 'node-pg-migrate'; - -const pgm = {} as MigrationBuilder; - -// Minimal examples -pgm.addColumn('table', { - column1: { - type: 'int4', - }, -}); -pgm.addExtension('extension'); -pgm.addExtension(['extension1', 'extension2']); -pgm.createExtension('extension'); -pgm.createExtension(['extension1', 'extension2']); -pgm.dropExtension('extension'); -pgm.dropExtension(['extension1', 'extension2']); - -pgm.createTable('table', { column1: { type: 'int4' } }); -pgm.dropTable('table'); -pgm.renameTable('table', 'tablenew'); - -pgm.addColumn('table', { column1: { type: 'int4' } }); -pgm.addColumns('table', { column1: { type: 'int4' } }); -pgm.dropColumn('table', ['column1', 'column2']); -pgm.dropColumns('table', ['column1', 'column2']); -pgm.renameColumn('table', 'old_column_name', 'new_column_name'); -pgm.alterColumn('table', 'column1', {}); - -pgm.addConstraint('table', 'table_constraint', 'column1 is not null'); -pgm.createConstraint('table', 'table_constraint', 'column1 is not null'); -pgm.dropConstraint('table', 'table_constraint'); - -pgm.addType('composite_type', ['enum1', 'enum2']); -pgm.createType('composite_type', { field1: 'int', field2: 'int' }); -pgm.dropType('composite_type'); - -pgm.createIndex('table', 'column1'); -pgm.createIndex('table', ['column1', 'column2']); -pgm.dropIndex('table', 'column1'); -pgm.dropIndex('table', ['column1', 'column2']); -pgm.addIndex('table', 'column1'); -pgm.addIndex('table', ['column1', 'column2']); - -pgm.sql(`select 1;`); -pgm.sql(`select 1;`, { one: '1' }); -pgm.func('now()'); - -// Elaborate example -pgm.addColumn({ schema: 'schema', name: 'table' }, { - column1: { - type: 'int4', - unique: true, - primaryKey: true, - notNull: true, - check: '', - references: '', - onDelete: '', - onUpdate: '', - } -}); - -pgm.noTransaction(); diff --git a/types/node-pg-migrate/tslint.json b/types/node-pg-migrate/tslint.json deleted file mode 100644 index 11ffe86764..0000000000 --- a/types/node-pg-migrate/tslint.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - // TODOs - "no-object-literal-type-assertion": false, - "no-unnecessary-class": false - } -} diff --git a/types/node-powershell/node-powershell-tests.ts b/types/node-powershell/node-powershell-tests.ts index a60f9db331..186d0bd68e 100644 --- a/types/node-powershell/node-powershell-tests.ts +++ b/types/node-powershell/node-powershell-tests.ts @@ -1,4 +1,4 @@ -import * as nodePowershell from 'node-powershell'; +import nodePowershell = require('node-powershell'); var options: nodePowershell.ShellOptions = { debugMsg: true diff --git a/types/node-rsa/node-rsa-tests.ts b/types/node-rsa/node-rsa-tests.ts index e210d5b68d..0f8defacbd 100644 --- a/types/node-rsa/node-rsa-tests.ts +++ b/types/node-rsa/node-rsa-tests.ts @@ -1,4 +1,4 @@ -import * as NodeRSA from 'node-rsa'; +import NodeRSA = require('node-rsa'); const key = new NodeRSA({ b: 512 }); diff --git a/types/node-sass-middleware/node-sass-middleware-tests.ts b/types/node-sass-middleware/node-sass-middleware-tests.ts index bfc755a424..34820155ed 100644 --- a/types/node-sass-middleware/node-sass-middleware-tests.ts +++ b/types/node-sass-middleware/node-sass-middleware-tests.ts @@ -1,6 +1,5 @@ - -import * as express from "express"; -import * as sassMiddleware from "node-sass-middleware"; +import express = require("express"); +import sassMiddleware = require("node-sass-middleware"); import * as path from "path"; var app = express(); app.use(sassMiddleware({ diff --git a/types/node-sprite-generator/node-sprite-generator-tests.ts b/types/node-sprite-generator/node-sprite-generator-tests.ts index 23309cea6d..7490d84865 100644 --- a/types/node-sprite-generator/node-sprite-generator-tests.ts +++ b/types/node-sprite-generator/node-sprite-generator-tests.ts @@ -1,5 +1,5 @@ -import * as nsg from 'node-sprite-generator'; -import * as express from 'express'; +import nsg = require('node-sprite-generator'); +import express = require('express'); const app = express(); app.use(nsg.middleware({ diff --git a/types/node-vault/index.d.ts b/types/node-vault/index.d.ts index 653db37e85..835e364ae7 100644 --- a/types/node-vault/index.d.ts +++ b/types/node-vault/index.d.ts @@ -122,7 +122,5 @@ declare namespace NodeVault { } } -type GetClient = (options?: NodeVault.VaultOptions) => NodeVault.client; - -declare const getClient: GetClient; -export = getClient; +declare function NodeVault(options?: NodeVault.VaultOptions): NodeVault.client; +export = NodeVault; diff --git a/types/node-vault/node-vault-tests.ts b/types/node-vault/node-vault-tests.ts index d6d85980a1..506514cc92 100644 --- a/types/node-vault/node-vault-tests.ts +++ b/types/node-vault/node-vault-tests.ts @@ -1,7 +1,7 @@ -import * as nv from "node-vault"; +import nv = require("node-vault"); // Test code came from the sample code in README of the module. -const options = { +const options: nv.VaultOptions = { apiVersion: 'v1', // default endpoint: 'http://127.0.0.1:8200', // default token: '1234', // optional client token; can be fetched after valid initialization of the server diff --git a/types/node-waves/index.d.ts b/types/node-waves/index.d.ts deleted file mode 100644 index fd2cb4937c..0000000000 --- a/types/node-waves/index.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -// Type definitions for node-waves 0.7 -// Project: http://fian.my.id/Waves -// Definitions by: Stephen Lautier -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export type ElementTarget = string | Element | Element[]; - -export interface WavesConfig { - /** - * Determines how long the waves effect duration (in milliseconds). - * - */ - duration?: number; - - /** - * Delay amount to show waves effect on touch and hide the effect if user scrolls. - * Set to 0 to disable delay (in milliseconds). - * - */ - delay?: number; -} - -export interface RippleOptions { - /** - * Specify how long to wait between starting and stopping the ripple. - * - */ - wait?: number | null; - - /** - * Specify the position inside the element. - * - */ - position?: { - x: number; - y: number; - } | null; -} - -/** - * Initializes waves with an optional config. - */ -export function init(config?: WavesConfig): void; - -/** - * Attach ripple effect by adding `.waves-effect` to HTML element. - * Make sure you call `init` to activate the ripple. - * - * @param elements elements to target. - * @param classes classes to add. - */ -export function attach(elements: ElementTarget, classes?: string | string[]): void; - -/** - * Creates a ripple effect in HTML element programmatically. - * @param elements elements to target (must have `.waves-effect` already applied, ideally via `attach`). - * @param options specify how long to wait between starting and stopping the ripple, and it's position inside the element. - */ -export function ripple(elements: ElementTarget, options?: RippleOptions): void; - -/** - * Removes all ripples from inside an element immediately. - * - * @param elements elements to remove ripples from. - */ -export function calm(elements: ElementTarget): void; diff --git a/types/node-waves/node-waves-tests.ts b/types/node-waves/node-waves-tests.ts deleted file mode 100644 index b9eac6682e..0000000000 --- a/types/node-waves/node-waves-tests.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { init, ripple, attach, calm } from "node-waves"; - -init({ delay: 300 }); - -attach("button", "waves-light"); - -ripple(".box", { wait: null }); - -calm(".box"); diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 8f4e6cf636..b2e310cffa 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 9.3.x +// Type definitions for Node.js 9.4.x // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -18,6 +18,7 @@ // Hannes Magnusson // Alberto Schiabel // Klaus Meinhardt +// Huw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -113,17 +114,22 @@ declare function clearImmediate(immediateId: any): void; // TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. interface NodeRequireFunction { -/* tslint:disable-next-line:callable-types */ + /* tslint:disable-next-line:callable-types */ (id: string): any; } interface NodeRequire extends NodeRequireFunction { - resolve(id: string): string; + resolve: RequireResolve; cache: any; extensions: NodeExtensions; main: NodeModule | undefined; } +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + interface NodeExtensions { '.js': (m: NodeModule, filename: string) => any; '.json': (m: NodeModule, filename: string) => any; @@ -410,6 +416,7 @@ declare namespace NodeJS { setMaxListeners(n: number): this; getMaxListeners(): number; listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; emit(event: string | symbol, ...args: any[]): boolean; listenerCount(type: string | symbol): number; // Added in Node 6... @@ -520,6 +527,7 @@ declare namespace NodeJS { export interface WriteStream extends Socket { readonly writableHighWaterMark: number; + readonly writableLength: number; columns?: number; rows?: number; _write(chunk: any, encoding: string, callback: Function): void; @@ -532,6 +540,7 @@ declare namespace NodeJS { } export interface ReadStream extends Socket { readonly readableHighWaterMark: number; + readonly readableLength: number; isRaw?: boolean; setRawMode?(mode: boolean): void; _read(size: number): void; @@ -916,6 +925,7 @@ declare module "events" { setMaxListeners(n: number): this; getMaxListeners(): number; listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; emit(event: string | symbol, ...args: any[]): boolean; eventNames(): Array; listenerCount(type: string | symbol): number; @@ -1466,27 +1476,28 @@ declare module "zlib" { export function createInflateRaw(options?: ZlibOptions): InflateRaw; export function createUnzip(options?: ZlibOptions): Unzip; - export function deflate(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function deflate(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function deflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function deflateRaw(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function deflateRaw(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function gzip(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function gzip(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function gzipSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function gunzip(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function gunzip(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function gunzipSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function inflate(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function inflate(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function inflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function inflateRaw(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function inflateRaw(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function inflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function unzip(buf: Buffer | string, callback: (error: Error | null, result: Buffer) => void): void; - export function unzip(buf: Buffer | string, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; - export function unzipSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + type InputType = string | Buffer | DataView | ArrayBuffer /* | TypedArray */; + export function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + export function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + export function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + export function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + export function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + export function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + export function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + export function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + export function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; export namespace constants { // Allowed flush values. @@ -1735,33 +1746,20 @@ declare module "https" { import * as http from "http"; import { URL } from "url"; - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string, cb: (err: Error | null, ctx: tls.SecureContext) => void) => void; - secureProtocol?: string; - } + export type ServerOptions = tls.SecureContextOptions & tls.TlsOptions; - export interface RequestOptions extends http.RequestOptions { - pfx?: any; - key?: any; + export type RequestOptions = http.RequestOptions & { + rejectUnauthorized?: boolean; // Defaults to true + servername?: string; // SNI TLS Extension + pfx?: string | Buffer | Array; + key?: string | Buffer | Array; passphrase?: string; - cert?: any; - ca?: any; + cert?: string | Buffer | Array; + ca?: string | Buffer | Array; ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - servername?: string; - } + clientCertEngine?: string; + secureProtocol?: string; // SSL Method, e.g. SSLv23_method + }; export interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { rejectUnauthorized?: boolean; @@ -2106,6 +2104,7 @@ declare module "child_process" { killSignal?: string; uid?: number; gid?: number; + windowsHide?: boolean; } export interface ExecOptionsWithStringEncoding extends ExecOptions { @@ -2152,6 +2151,7 @@ declare module "child_process" { killSignal?: string; uid?: number; gid?: number; + windowsHide?: boolean; windowsVerbatimArguments?: boolean; } export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { @@ -2235,6 +2235,7 @@ declare module "child_process" { maxBuffer?: number; encoding?: string; shell?: boolean | string; + windowsHide?: boolean; windowsVerbatimArguments?: boolean; } export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { @@ -2272,6 +2273,7 @@ declare module "child_process" { killSignal?: string; maxBuffer?: number; encoding?: string; + windowsHide?: boolean; } export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { encoding: BufferEncoding; @@ -2295,6 +2297,7 @@ declare module "child_process" { killSignal?: string; maxBuffer?: number; encoding?: string; + windowsHide?: boolean; } export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { encoding: BufferEncoding; @@ -2616,9 +2619,9 @@ declare module "net" { destroy(err?: any): void; pause(): this; resume(): this; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; address(): { port: number; family: string; address: string; }; unref(): void; ref(): void; @@ -3711,7 +3714,7 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: Array) => void): void; + export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void; /** * Asynchronous readdir(3) - read a directory. @@ -3740,7 +3743,7 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise>; + export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; } /** @@ -3762,7 +3765,7 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): Array; + export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): string[] | Buffer[]; /** * Asynchronous close(2) - close a file descriptor. @@ -4834,7 +4837,7 @@ declare module "tls" { * An array of strings or a Buffer naming possible NPN protocols. * (Protocols should be ordered by their priority.) */ - NPNProtocols?: string[] | Buffer, + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, /** * An array of strings or a Buffer naming possible ALPN protocols. * (Protocols should be ordered by their priority.) When the server @@ -4842,7 +4845,7 @@ declare module "tls" { * precedence over NPN and the server does not send an NPN extension * to the client. */ - ALPNProtocols?: string[] | Buffer, + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, /** * SNICallback(servername, cb) A function that will be * called if the client supports SNI TLS extension. Two arguments @@ -4897,6 +4900,14 @@ declare module "tls" { getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; /** * Could be used to speed up handshake establishment when reconnecting to the server. * @returns ASN.1 encoded TLS session or undefined if none was negotiated. @@ -4918,7 +4929,7 @@ declare module "tls" { * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. */ - renegotiate(options: TlsOptions, callback: (err: Error | null) => void): any; + renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any; /** * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by @@ -4961,30 +4972,16 @@ declare module "tls" { prependOnceListener(event: "secureConnect", listener: () => void): this; } - export interface TlsOptions { - host?: string; - port?: number; - pfx?: string | Buffer[]; - key?: string | string[] | Buffer | any[]; - passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | string[] | Buffer | Buffer[]; - crl?: string | string[]; - ciphers?: string; - honorCipherOrder?: boolean; + export interface TlsOptions extends SecureContextOptions { + clientCertEngine?: string; + handshakeTimeout?: number; requestCert?: boolean; rejectUnauthorized?: boolean; - NPNProtocols?: string[] | Buffer; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; - ecdhCurve?: string; - dhparam?: string | Buffer; - handshakeTimeout?: number; - ALPNProtocols?: string[] | Buffer; sessionTimeout?: number; ticketKeys?: Buffer; - sessionIdContext?: string; - secureProtocol?: string; - secureOptions?: number; } export interface ConnectionOptions extends SecureContextOptions { @@ -4993,8 +4990,8 @@ declare module "tls" { path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket rejectUnauthorized?: boolean; // Defaults to true - NPNProtocols?: Array; - ALPNProtocols?: Array; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; checkServerIdentity?: typeof checkServerIdentity; servername?: string; // SNI TLS Extension session?: Buffer; @@ -5092,6 +5089,7 @@ declare module "tls" { ciphers?: string; honorCipherOrder?: boolean; ecdhCurve?: string; + clientCertEngine?: string; crl?: string | Buffer | Array; dhparam?: string | Buffer; secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options @@ -5304,7 +5302,8 @@ declare module "stream" { export class Readable extends Stream implements NodeJS.ReadableStream { readable: boolean; - readableHighWaterMark: number; + readonly readableHighWaterMark: number; + readonly readableLength: number; constructor(opts?: ReadableOptions); _read(size: number): void; read(size?: number): any; @@ -5329,7 +5328,6 @@ declare module "stream" { * 5. error */ addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: Buffer | string) => void): this; addListener(event: "end", listener: () => void): this; @@ -5392,9 +5390,10 @@ declare module "stream" { export class Writable extends Stream implements NodeJS.WritableStream { writable: boolean; readonly writableHighWaterMark: number; + readonly writableLength: number; constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; - _writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; _destroy(err: Error, callback: Function): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; @@ -5484,9 +5483,10 @@ declare module "stream" { export class Duplex extends Readable implements Writable { writable: boolean; readonly writableHighWaterMark: number; + readonly writableLength: number; constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; - _writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; _destroy(err: Error, callback: Function): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; @@ -5566,9 +5566,9 @@ declare module "util" { export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; @@ -5642,12 +5642,12 @@ declare module "tty" { import * as net from "net"; export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { + export class ReadStream extends net.Socket { isRaw: boolean; setRawMode(mode: boolean): void; isTTY: boolean; } - export interface WriteStream extends net.Socket { + export class WriteStream extends net.Socket { columns: number; rows: number; isTTY: boolean; @@ -6161,7 +6161,7 @@ declare module "http2" { } export interface ServerStreamFileResponseOptions { - statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void|boolean; + statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; getTrailers?: (trailers: OutgoingHttpHeaders) => void; offset?: number; length?: number; @@ -6173,15 +6173,12 @@ declare module "http2" { export interface Http2Stream extends stream.Duplex { readonly aborted: boolean; + close(code: number, callback?: () => void): void; + readonly closed: boolean; readonly destroyed: boolean; + readonly pending: boolean; priority(options: StreamPriorityOptions): void; readonly rstCode: number; - rstStream(code: number): void; - rstWithNoError(): void; - rstWithProtocolError(): void; - rstWithCancel(): void; - rstWithRefuse(): void; - rstWithInternalError(): void; readonly session: Http2Session; setTimeout(msecs: number, callback?: () => void): void; readonly state: StreamState; @@ -6313,8 +6310,8 @@ declare module "http2" { additionalHeaders(headers: OutgoingHttpHeaders): void; readonly headersSent: boolean; readonly pushAllowed: boolean; - pushStream(headers: OutgoingHttpHeaders, callback?: (pushStream: ServerHttp2Stream) => void): void; - pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (pushStream: ServerHttp2Stream) => void): void; + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; @@ -6339,13 +6336,6 @@ declare module "http2" { getTrailers?: (trailers: OutgoingHttpHeaders, flags: number) => void; } - export interface SessionShutdownOptions { - graceful?: boolean; - errorCode?: number; - lastStreamID?: number; - opaqueData?: Buffer | Uint8Array; - } - export interface SessionState { effectiveLocalWindowSize?: number; effectiveRecvDataLength?: number; @@ -6359,20 +6349,26 @@ declare module "http2" { } export interface Http2Session extends events.EventEmitter { - destroy(): void; + readonly alpnProtocol?: string; + close(callback?: () => void): void; + readonly closed: boolean; + destroy(error?: Error, code?: number): void; readonly destroyed: boolean; + readonly encrypted?: boolean; + goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView /*| TypedArray*/): void; readonly localSettings: Settings; + readonly originSet?: string[]; readonly pendingSettingsAck: boolean; + ref(): void; readonly remoteSettings: Settings; rstStream(stream: Http2Stream, code?: number): void; setTimeout(msecs: number, callback?: () => void): void; - shutdown(callback?: () => void): void; - shutdown(options: SessionShutdownOptions, callback?: () => void): void; readonly socket: net.Socket | tls.TLSSocket; readonly state: SessionState; priority(stream: Http2Stream, options: StreamPriorityOptions): void; settings(settings: Settings): void; readonly type: number; + unref(): void; addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; @@ -6381,7 +6377,6 @@ declare module "http2" { addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; addListener(event: "localSettings", listener: (settings: Settings) => void): this; addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - addListener(event: "socketError", listener: (err: Error) => void): this; addListener(event: "timeout", listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; @@ -6391,7 +6386,6 @@ declare module "http2" { emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; emit(event: "localSettings", settings: Settings): boolean; emit(event: "remoteSettings", settings: Settings): boolean; - emit(event: "socketError", err: Error): boolean; emit(event: "timeout"): boolean; on(event: string, listener: (...args: any[]) => void): this; @@ -6401,7 +6395,6 @@ declare module "http2" { on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; on(event: "localSettings", listener: (settings: Settings) => void): this; on(event: "remoteSettings", listener: (settings: Settings) => void): this; - on(event: "socketError", listener: (err: Error) => void): this; on(event: "timeout", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; @@ -6411,7 +6404,6 @@ declare module "http2" { once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; once(event: "localSettings", listener: (settings: Settings) => void): this; once(event: "remoteSettings", listener: (settings: Settings) => void): this; - once(event: "socketError", listener: (err: Error) => void): this; once(event: "timeout", listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; @@ -6421,7 +6413,6 @@ declare module "http2" { prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; prependListener(event: "localSettings", listener: (settings: Settings) => void): this; prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependListener(event: "socketError", listener: (err: Error) => void): this; prependListener(event: "timeout", listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; @@ -6431,7 +6422,6 @@ declare module "http2" { prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "socketError", listener: (err: Error) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; } @@ -6439,31 +6429,42 @@ declare module "http2" { request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; on(event: string, listener: (...args: any[]) => void): this; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; once(event: string, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; readonly server: Http2Server | Http2SecureServer; addListener(event: string, listener: (...args: any[]) => void): this; @@ -6519,93 +6520,93 @@ declare module "http2" { export interface Http2Server extends net.Server { addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "socketError", listener: (err: Error) => void): this; addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; addListener(event: "timeout", listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; emit(event: "sessionError", err: Error): boolean; - emit(event: "socketError", err: Error): boolean; emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; emit(event: "timeout"): boolean; on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "socketError", listener: (err: Error) => void): this; on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; on(event: "timeout", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "socketError", listener: (err: Error) => void): this; once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; once(event: "timeout", listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "socketError", listener: (err: Error) => void): this; prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependListener(event: "timeout", listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "socketError", listener: (err: Error) => void): this; prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; } export interface Http2SecureServer extends tls.Server { addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "socketError", listener: (err: Error) => void): this; addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; addListener(event: "timeout", listener: () => void): this; addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; emit(event: "sessionError", err: Error): boolean; - emit(event: "socketError", err: Error): boolean; emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; emit(event: "timeout"): boolean; emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "socketError", listener: (err: Error) => void): this; on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; on(event: "timeout", listener: () => void): this; on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "socketError", listener: (err: Error) => void): this; once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; once(event: "timeout", listener: () => void): this; once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "socketError", listener: (err: Error) => void): this; prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependListener(event: "timeout", listener: () => void): this; prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "socketError", listener: (err: Error) => void): this; prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index dccde2db47..1eb6539b09 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -1,4 +1,4 @@ -import * as assert from "assert"; +import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; import events2 = require("events"); @@ -235,6 +235,25 @@ namespace fs_tests { }); } + { + let listS: string[]; + listS = fs.readdirSync('path'); + listS = fs.readdirSync('path', { encoding: 'utf8' }); + listS = fs.readdirSync('path', { encoding: null }); + listS = fs.readdirSync('path', { encoding: undefined }); + listS = fs.readdirSync('path', 'utf8'); + listS = fs.readdirSync('path', null); + listS = fs.readdirSync('path', undefined); + + let listB: Buffer[]; + listB = fs.readdirSync('path', { encoding: 'buffer' }); + listB = fs.readdirSync("path", 'buffer'); + + let enc = 'buffer'; + fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[] + fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[] + } + { fs.mkdtemp('/tmp/foo-', (err, folder) => { console.log(folder); @@ -2030,14 +2049,17 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); + childProcess.exec("echo test", {windowsHide: true}); childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); } { childProcess.execFile("npm", () => {}); + childProcess.execFile("npm", { windowsHide: true }, () => {}); childProcess.execFile("npm", ["-v"], () => {}); - childProcess.execFile("npm", ["-v"], { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); - childProcess.execFile("npm", ["-v"], { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); + childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); + childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); childProcess.execFile("npm", { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); } @@ -3373,16 +3395,22 @@ namespace http2_tests { http2Session.on('localSettings', (settings: http2.Settings) => {}); http2Session.on('remoteSettings', (settings: http2.Settings) => {}); http2Session.on('stream', (stream: http2.Http2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); - http2Session.on('socketError', (err: Error) => {}); http2Session.on('timeout', () => {}); http2Session.destroy(); + let alpnProtocol: string = http2Session.alpnProtocol; let destroyed: boolean = http2Session.destroyed; + let encrypted: boolean = http2Session.encrypted; + let originSet: string[] = http2Session.originSet; let pendingSettingsAck: boolean = http2Session.pendingSettingsAck; let settings: http2.Settings = http2Session.localSettings; + let closed: boolean = http2Session.closed; settings = http2Session.remoteSettings; + http2Session.ref(); + http2Session.unref(); + let headers: http2.OutgoingHttpHeaders; let options: http2.ClientSessionRequestOptions = { endStream: true, @@ -3400,16 +3428,7 @@ namespace http2_tests { http2Session.rstStream(stream, 0); http2Session.setTimeout(100, () => {}); - - let shutdownOptions: http2.SessionShutdownOptions = { - graceful: true, - errorCode: 0, - lastStreamID: 0, - opaqueData: Buffer.from([]) - }; - shutdownOptions.opaqueData = Uint8Array.from([]); - http2Session.shutdown(shutdownOptions); - http2Session.shutdown(shutdownOptions, () => {}); + http2Session.close(() => {}); let socket: net.Socket | tls.TLSSocket = http2Session.socket; let state: http2.SessionState = http2Session.state; @@ -3448,7 +3467,9 @@ namespace http2_tests { http2Stream.on('trailers', (trailers: http2.IncomingHttpHeaders, flags: number) => {}); let aborted: boolean = http2Stream.aborted; + let closed: boolean = http2Stream.closed; let destroyed: boolean = http2Stream.destroyed; + let pending: boolean = http2Stream.pending; http2Stream.priority({ exclusive: true, @@ -3457,14 +3478,6 @@ namespace http2_tests { silent: true }); - let rstCode: number = http2Stream.rstCode; - http2Stream.rstStream(rstCode); - http2Stream.rstWithNoError(); - http2Stream.rstWithProtocolError(); - http2Stream.rstWithCancel(); - http2Stream.rstWithRefuse(); - http2Stream.rstWithInternalError(); - let sesh: http2.Http2Session = http2Stream.session; http2Stream.setTimeout(100, () => {}); @@ -3492,7 +3505,7 @@ namespace http2_tests { serverHttp2Stream.additionalHeaders(headers); let headerSent: boolean = serverHttp2Stream.headersSent; let pushAllowed: boolean = serverHttp2Stream.pushAllowed; - serverHttp2Stream.pushStream(headers, (pushStream: http2.ServerHttp2Stream) => {}); + serverHttp2Stream.pushStream(headers, (err: Error | null, pushStream: http2.ServerHttp2Stream, headers: http2.OutgoingHttpHeaders) => {}); let options: http2.ServerStreamResponseOptions = { endStream: true, @@ -3533,7 +3546,7 @@ namespace http2_tests { let s2: tls.Server = http2SecureServer; [http2Server, http2SecureServer].forEach((server) => { server.on('sessionError', (err: Error) => {}); - server.on('socketError', (err: Error) => {}); + server.on('checkContinue', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); server.on('stream', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); server.on('request', (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => {}); server.on('timeout', () => {}); @@ -3658,6 +3671,15 @@ namespace http2_tests { secureClientSessionOptions.ca = ''; let onConnectHandler = (session: http2.Http2Session, socket: net.Socket) => {}; + let serverHttp2Session: http2.ServerHttp2Session; + + serverHttp2Session.altsvc('', ''); + serverHttp2Session.altsvc('', 0); + serverHttp2Session.altsvc('', new url.URL('')); + serverHttp2Session.altsvc('', { origin: '' }); + serverHttp2Session.altsvc('', { origin: 0 }); + serverHttp2Session.altsvc('', { origin: new url.URL('') }); + let clientHttp2Session: http2.ClientHttp2Session; clientHttp2Session = http2.connect(''); @@ -3666,6 +3688,7 @@ namespace http2_tests { clientHttp2Session = http2.connect('', clientSessionOptions, onConnectHandler); clientHttp2Session = http2.connect('', secureClientSessionOptions); clientHttp2Session = http2.connect('', secureClientSessionOptions, onConnectHandler); + clientHttp2Session.on('altsvc', (alt: string, origin: string, number: number) => {}); settings = http2.getDefaultSettings(); settings = http2.getPackedSettings(settings); diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index 814bbe793e..800a909c49 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -1902,11 +1902,11 @@ declare module "tty" { import * as net from "net"; export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { + export class ReadStream extends net.Socket { isRaw: boolean; setRawMode(mode: boolean): void; } - export interface WriteStream extends net.Socket { + export class WriteStream extends net.Socket { columns: number; rows: number; } diff --git a/types/node/v0/node-tests.ts b/types/node/v0/node-tests.ts index 8e2443b360..d8e0a40699 100644 --- a/types/node/v0/node-tests.ts +++ b/types/node/v0/node-tests.ts @@ -1,5 +1,4 @@ - -import * as assert from "assert"; +import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; import * as zlib from "zlib"; diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index b2db9f80ee..09cbd8bb43 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1549,9 +1549,9 @@ declare module "net" { destroy(): void; pause(): void; resume(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; address(): { port: number; family: string; address: string; }; unref(): void; ref(): void; @@ -2477,12 +2477,12 @@ declare module "tty" { import * as net from "net"; export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { + export class ReadStream extends net.Socket { isRaw: boolean; setRawMode(mode: boolean): void; isTTY: boolean; } - export interface WriteStream extends net.Socket { + export class WriteStream extends net.Socket { columns: number; rows: number; isTTY: boolean; diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index 2bb28ce779..e60b578ccf 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -1,4 +1,4 @@ -import * as assert from "assert"; +import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; import * as zlib from "zlib"; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 5cbe7ab3dc..152507c3a8 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -5,6 +5,7 @@ // Wilco Bakker // Thomas Bouldin // Sebastian Silbermann +// Alorel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -2093,9 +2094,9 @@ declare module "net" { setEncoding(encoding?: string): void; write(data: any, encoding?: string, callback?: Function): void; destroy(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; address(): { port: number; family: string; address: string; }; unref(): void; ref(): void; @@ -2595,8 +2596,51 @@ declare module "fs" { * @returns Returns the created folder path. */ export function mkdtempSync(prefix: string): string; - export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string | Buffer): string[]; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: string | Buffer, options: { encoding: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: string | Buffer, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: string | Buffer, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. + */ + export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: string | Buffer, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: string | Buffer, options: { encoding: "buffer" } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: string | Buffer, options?: { encoding?: string | null } | string | null): string[] | Buffer[]; export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function closeSync(fd: number): void; export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; @@ -3171,6 +3215,14 @@ declare module "tls" { fingerprint: string; serialNumber: string; }; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; /** * Could be used to speed up handshake establishment when reconnecting to the server. * @returns ASN.1 encoded TLS session or undefined if none was negotiated. @@ -3605,7 +3657,6 @@ declare module "stream" { * 5. error **/ addListener(event: string, listener: Function): this; - addListener(event: string, listener: Function): this; addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: Buffer | string) => void): this; addListener(event: "end", listener: () => void): this; @@ -3854,12 +3905,12 @@ declare module "tty" { import * as net from "net"; export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { + export class ReadStream extends net.Socket { isRaw: boolean; setRawMode(mode: boolean): void; isTTY: boolean; } - export interface WriteStream extends net.Socket { + export class WriteStream extends net.Socket { columns: number; rows: number; isTTY: boolean; diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 34a62bf88d..cd363c708c 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -1,4 +1,4 @@ -import * as assert from "assert"; +import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; import events2 = require("events"); @@ -218,6 +218,25 @@ namespace fs_tests { fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); } + { + fs.readdir('foo', (err: any, files: string[]) => {}) + fs.readdir('foo', 'utf8', (err: any, files: string[]) => {}); + fs.readdir('foo', {encoding: 'utf8'}, (err: any, files: string[]) => {}); + fs.readdir('foo', 'buffer', (err: any, files: Buffer[]) => {}); + fs.readdir('foo', {encoding: 'buffer'}, (err: any, files: Buffer[]) => {}); + + let fsStringOut: string[] = fs.readdirSync('utf8'); + fsStringOut = fs.readdirSync('foo', 'utf8'); + fsStringOut = fs.readdirSync('foo', {encoding: 'utf8'}); + + let fsBufferOut: Buffer[] = fs.readdirSync('utf8', 'buffer'); + fsBufferOut = fs.readdirSync('foo', {encoding: 'buffer'}); + + let enc = 'buffer'; + fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[] + fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[] + } + { var errno: number; fs.readFile('testfile', (err, data) => { diff --git a/types/node/v6/tslint.json b/types/node/v6/tslint.json index 518f58df03..82d575f726 100644 --- a/types/node/v6/tslint.json +++ b/types/node/v6/tslint.json @@ -14,6 +14,7 @@ "jsdoc-format": false, "max-line-length": false, "no-any-union": false, + "no-const-enum": false, "no-consecutive-blank-lines": false, "no-duplicate-imports": false, "no-duplicate-variable": false, diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 038c4a6f58..bdcb47d2e1 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -2219,9 +2219,9 @@ declare module "net" { destroy(err?: any): void; pause(): this; resume(): this; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; address(): { port: number; family: string; address: string; }; unref(): void; ref(): void; @@ -3313,6 +3313,14 @@ declare module "tls" { getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; /** * Could be used to speed up handshake establishment when reconnecting to the server. * @returns ASN.1 encoded TLS session or undefined if none was negotiated. @@ -3754,7 +3762,6 @@ declare module "stream" { * 5. error **/ addListener(event: string, listener: Function): this; - addListener(event: string, listener: Function): this; addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: Buffer | string) => void): this; addListener(event: "end", listener: () => void): this; @@ -4003,12 +4010,12 @@ declare module "tty" { import * as net from "net"; export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { + export class ReadStream extends net.Socket { isRaw: boolean; setRawMode(mode: boolean): void; isTTY: boolean; } - export interface WriteStream extends net.Socket { + export class WriteStream extends net.Socket { columns: number; rows: number; isTTY: boolean; diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index a2f25db8ec..0240dcc120 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -1,4 +1,4 @@ -import * as assert from "assert"; +import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; import events2 = require("events"); diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 3fbd9f9253..f28c0959a4 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 8.5.x +// Type definitions for Node.js 8.9.x // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -17,13 +17,9 @@ // Sebastian Silbermann // Hannes Magnusson // Alberto Schiabel +// Huw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/************************************************ -* * -* Node.js v8.5.x API * -* * -************************************************/ +// TypeScript Version: 2.1 /** inspector module types */ /// @@ -117,17 +113,22 @@ declare function clearImmediate(immediateId: any): void; // TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. interface NodeRequireFunction { -/* tslint:disable-next-line:callable-types */ + /* tslint:disable-next-line:callable-types */ (id: string): any; } interface NodeRequire extends NodeRequireFunction { - resolve(id: string): string; + resolve: RequireResolve; cache: any; extensions: NodeExtensions; main: NodeModule | undefined; } +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + interface NodeExtensions { '.js': (m: NodeModule, filename: string) => any; '.json': (m: NodeModule, filename: string) => any; @@ -145,6 +146,7 @@ interface NodeModule { loaded: boolean; parent: NodeModule | null; children: NodeModule[]; + paths: string[]; } declare var module: NodeModule; @@ -1176,13 +1178,7 @@ declare module "cluster" { stdio?: any[]; uid?: number; gid?: number; - } - - export interface ClusterSetupMasterSettings { - exec?: string; // default: process.argv[1] - args?: string[]; // default: process.argv.slice(2) - silent?: boolean; // default: false - stdio?: any[]; + inspectPort?: number | (() => number); } export interface Address { @@ -1269,7 +1265,7 @@ declare module "cluster" { isWorker: boolean; // TODO: cluster.schedulingPolicy settings: ClusterSettings; - setupMaster(settings?: ClusterSetupMasterSettings): void; + setupMaster(settings?: ClusterSettings): void; worker?: Worker; workers?: { [index: string]: Worker | undefined @@ -1346,7 +1342,7 @@ declare module "cluster" { export var isWorker: boolean; // TODO: cluster.schedulingPolicy export var settings: ClusterSettings; - export function setupMaster(settings?: ClusterSetupMasterSettings): void; + export function setupMaster(settings?: ClusterSettings): void; export var worker: Worker; export var workers: { [index: string]: Worker | undefined @@ -1729,7 +1725,7 @@ declare module "os" { export function arch(): string; export function platform(): NodeJS.Platform; export function tmpdir(): string; - export var EOL: string; + export const EOL: string; export function endianness(): "BE" | "LE"; } @@ -1739,32 +1735,20 @@ declare module "https" { import * as http from "http"; import { URL } from "url"; - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string, cb: (err: Error | null, ctx: tls.SecureContext) => void) => void; - } + export type ServerOptions = tls.SecureContextOptions & tls.TlsOptions; - export interface RequestOptions extends http.RequestOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - servername?: string; - } + // see https://nodejs.org/docs/latest-v8.x/api/https.html#https_https_request_options_callback + type extendedRequestKeys = "pfx" | + "key" | + "passphrase" | + "cert" | + "ca" | + "ciphers" | + "rejectUnauthorized" | + "secureProtocol" | + "servername"; + + export type RequestOptions = http.RequestOptions & Pick; export interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { rejectUnauthorized?: boolean; @@ -2109,6 +2093,7 @@ declare module "child_process" { killSignal?: string; uid?: number; gid?: number; + windowsHide?: boolean; } export interface ExecOptionsWithStringEncoding extends ExecOptions { @@ -2155,6 +2140,7 @@ declare module "child_process" { killSignal?: string; uid?: number; gid?: number; + windowsHide?: boolean; windowsVerbatimArguments?: boolean; } export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { @@ -2238,6 +2224,7 @@ declare module "child_process" { maxBuffer?: number; encoding?: string; shell?: boolean | string; + windowsHide?: boolean; windowsVerbatimArguments?: boolean; } export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { @@ -2275,6 +2262,7 @@ declare module "child_process" { killSignal?: string; maxBuffer?: number; encoding?: string; + windowsHide?: boolean; } export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { encoding: BufferEncoding; @@ -2298,6 +2286,7 @@ declare module "child_process" { killSignal?: string; maxBuffer?: number; encoding?: string; + windowsHide?: boolean; } export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { encoding: BufferEncoding; @@ -2342,7 +2331,19 @@ declare module "url" { query?: string | null | ParsedUrlQuery; } - export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; + export interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + + export interface UrlWithStringQuery extends Url { + query: string | null; + } + + export function parse(urlStr: string): UrlWithStringQuery; + export function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + export function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + export function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + export function format(URL: URL, options?: URLFormatOptions): string; export function format(urlObject: UrlObject | string): string; export function resolve(from: string, to: string): string; @@ -2607,9 +2608,9 @@ declare module "net" { destroy(err?: any): void; pause(): this; resume(): this; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; address(): { port: number; family: string; address: string; }; unref(): void; ref(): void; @@ -3691,7 +3692,7 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: Array) => void): void; + export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void; /** * Asynchronous readdir(3) - read a directory. @@ -3720,7 +3721,7 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise>; + export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; } /** @@ -3742,7 +3743,7 @@ declare module "fs" { * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): Array; + export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): string[] | Buffer[]; /** * Asynchronous close(2) - close a file descriptor. @@ -4573,7 +4574,6 @@ declare module "path" { */ name: string; } - export interface FormatInputPathObject { /** * The root of the path such as '/' or 'c:\' @@ -4620,7 +4620,7 @@ declare module "path" { * * @param pathSegments string paths to join. Non-string arguments are ignored. */ - export function resolve(...pathSegments: any[]): string; + export function resolve(...pathSegments: string[]): string; /** * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. * @@ -4686,7 +4686,7 @@ declare module "path" { export var sep: string; export var delimiter: string; export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; + export function format(pP: FormatInputPathObject): string; } export module win32 { @@ -4701,7 +4701,7 @@ declare module "path" { export var sep: string; export var delimiter: string; export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; + export function format(pP: FormatInputPathObject): string; } } @@ -4815,7 +4815,7 @@ declare module "tls" { * An array of strings or a Buffer naming possible NPN protocols. * (Protocols should be ordered by their priority.) */ - NPNProtocols?: string[] | Buffer, + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, /** * An array of strings or a Buffer naming possible ALPN protocols. * (Protocols should be ordered by their priority.) When the server @@ -4823,7 +4823,7 @@ declare module "tls" { * precedence over NPN and the server does not send an NPN extension * to the client. */ - ALPNProtocols?: string[] | Buffer, + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, /** * SNICallback(servername, cb) A function that will be * called if the client supports SNI TLS extension. Two arguments @@ -4878,6 +4878,14 @@ declare module "tls" { getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; /** * Could be used to speed up handshake establishment when reconnecting to the server. * @returns ASN.1 encoded TLS session or undefined if none was negotiated. @@ -4899,7 +4907,7 @@ declare module "tls" { * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. */ - renegotiate(options: TlsOptions, callback: (err: Error | null) => void): any; + renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any; /** * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by @@ -4942,30 +4950,15 @@ declare module "tls" { prependOnceListener(event: "secureConnect", listener: () => void): this; } - export interface TlsOptions { - host?: string; - port?: number; - pfx?: string | Buffer[]; - key?: string | string[] | Buffer | any[]; - passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | string[] | Buffer | Buffer[]; - crl?: string | string[]; - ciphers?: string; - honorCipherOrder?: boolean; + export interface TlsOptions extends SecureContextOptions { + handshakeTimeout?: number; requestCert?: boolean; rejectUnauthorized?: boolean; - NPNProtocols?: string[] | Buffer; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; - ecdhCurve?: string; - dhparam?: string | Buffer; - handshakeTimeout?: number; - ALPNProtocols?: string[] | Buffer; sessionTimeout?: number; ticketKeys?: Buffer; - sessionIdContext?: string; - secureProtocol?: string; - secureOptions?: number; } export interface ConnectionOptions extends SecureContextOptions { @@ -4974,8 +4967,8 @@ declare module "tls" { path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket rejectUnauthorized?: boolean; // Defaults to true - NPNProtocols?: Array; - ALPNProtocols?: Array; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; checkServerIdentity?: typeof checkServerIdentity; servername?: string; // SNI TLS Extension session?: Buffer; @@ -5309,7 +5302,6 @@ declare module "stream" { * 5. error */ addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: Buffer | string) => void): this; addListener(event: "end", listener: () => void): this; @@ -5373,7 +5365,7 @@ declare module "stream" { writable: boolean; constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; - _writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; _destroy(err: Error, callback: Function): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; @@ -5464,7 +5456,7 @@ declare module "stream" { writable: boolean; constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; - _writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; _destroy(err: Error, callback: Function): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; @@ -5544,9 +5536,9 @@ declare module "util" { export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; @@ -5620,12 +5612,12 @@ declare module "tty" { import * as net from "net"; export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { + export class ReadStream extends net.Socket { isRaw: boolean; setRawMode(mode: boolean): void; isTTY: boolean; } - export interface WriteStream extends net.Socket { + export class WriteStream extends net.Socket { columns: number; rows: number; isTTY: boolean; @@ -6141,7 +6133,7 @@ declare module "http2" { } export interface ServerStreamFileResponseOptions { - statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void|boolean; + statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; getTrailers?: (trailers: OutgoingHttpHeaders) => void; offset?: number; length?: number; @@ -6920,195 +6912,195 @@ declare module "http2" { } declare module "perf_hooks" { - export interface PerformanceEntry { - /** - * The total number of milliseconds elapsed for this entry. - * This value will not be meaningful for all Performance Entry types. - */ - readonly duration: number; + export interface PerformanceEntry { + /** + * The total number of milliseconds elapsed for this entry. + * This value will not be meaningful for all Performance Entry types. + */ + readonly duration: number; - /** - * The name of the performance entry. - */ - readonly name: string; + /** + * The name of the performance entry. + */ + readonly name: string; - /** - * The high resolution millisecond timestamp marking the starting time of the Performance Entry. - */ - readonly startTime: number; + /** + * The high resolution millisecond timestamp marking the starting time of the Performance Entry. + */ + readonly startTime: number; - /** - * The type of the performance entry. - * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. - */ - readonly entryType: string; + /** + * The type of the performance entry. + * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. + */ + readonly entryType: string; - /** - * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies - * the type of garbage collection operation that occurred. - * The value may be one of perf_hooks.constants. - */ - readonly kind?: number; - } - - export interface PerformanceNodeTiming extends PerformanceEntry { - /** - * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. - */ - readonly bootstrapComplete: number; - - /** - * The high resolution millisecond timestamp at which cluster processing ended. - */ - readonly clusterSetupEnd: number; - - /** - * The high resolution millisecond timestamp at which cluster processing started. - */ - readonly clusterSetupStart: number; - - /** - * The high resolution millisecond timestamp at which the Node.js event loop exited. - */ - readonly loopExit: number; - - /** - * The high resolution millisecond timestamp at which the Node.js event loop started. - */ - readonly loopStart: number; - - /** - * The high resolution millisecond timestamp at which main module load ended. - */ - readonly moduleLoadEnd: number; - - /** - * The high resolution millisecond timestamp at which main module load started. - */ - readonly moduleLoadStart: number; - - /** - * The high resolution millisecond timestamp at which the Node.js process was initialized. - */ - readonly nodeStart: number; - - /** - * The high resolution millisecond timestamp at which preload module load ended. - */ - readonly preloadModuleLoadEnd: number; - - /** - * The high resolution millisecond timestamp at which preload module load started. - */ - readonly preloadModuleLoadStart: number; - - /** - * The high resolution millisecond timestamp at which third_party_main processing ended. - */ - readonly thirdPartyMainEnd: number; - - /** - * The high resolution millisecond timestamp at which third_party_main processing started. - */ - readonly thirdPartyMainStart: number; - - /** - * The high resolution millisecond timestamp at which the V8 platform was initialized. - */ - readonly v8Start: number; + /** + * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies + * the type of garbage collection operation that occurred. + * The value may be one of perf_hooks.constants. + */ + readonly kind?: number; } - export interface Performance { - /** - * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. - * If name is provided, removes entries with name. - * @param name - */ - clearFunctions(name?: string): void; + export interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + */ + readonly bootstrapComplete: number; - /** - * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. - * If name is provided, removes only the named mark. - * @param name - */ - clearMarks(name?: string): void; + /** + * The high resolution millisecond timestamp at which cluster processing ended. + */ + readonly clusterSetupEnd: number; - /** - * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. - * If name is provided, removes only objects whose performanceEntry.name matches name. - */ - clearMeasures(name?: string): void; + /** + * The high resolution millisecond timestamp at which cluster processing started. + */ + readonly clusterSetupStart: number; - /** - * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. - * @return list of all PerformanceEntry objects - */ - getEntries(): PerformanceEntry[]; + /** + * The high resolution millisecond timestamp at which the Node.js event loop exited. + */ + readonly loopExit: number; - /** - * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. - * @param name - * @param type - * @return list of all PerformanceEntry objects - */ - getEntriesByName(name: string, type?: string): PerformanceEntry[]; + /** + * The high resolution millisecond timestamp at which the Node.js event loop started. + */ + readonly loopStart: number; - /** - * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.entryType is equal to type. - * @param type - * @return list of all PerformanceEntry objects - */ - getEntriesByType(type: string): PerformanceEntry[]; + /** + * The high resolution millisecond timestamp at which main module load ended. + */ + readonly moduleLoadEnd: number; - /** - * Creates a new PerformanceMark entry in the Performance Timeline. - * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', - * and whose performanceEntry.duration is always 0. - * Performance marks are used to mark specific significant moments in the Performance Timeline. - * @param name - */ - mark(name?: string): void; + /** + * The high resolution millisecond timestamp at which main module load started. + */ + readonly moduleLoadStart: number; - /** - * Creates a new PerformanceMeasure entry in the Performance Timeline. - * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', - * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. - * - * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify - * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, - * then startMark is set to timeOrigin by default. - * - * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp - * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. - * @param name - * @param startMark - * @param endMark - */ - measure(name: string, startMark: string, endMark: string): void; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + */ + readonly nodeStart: number; - /** - * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. - */ - readonly nodeTiming: PerformanceNodeTiming; + /** + * The high resolution millisecond timestamp at which preload module load ended. + */ + readonly preloadModuleLoadEnd: number; - /** - * @return the current high resolution millisecond timestamp - */ - now(): number; + /** + * The high resolution millisecond timestamp at which preload module load started. + */ + readonly preloadModuleLoadStart: number; - /** - * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. - */ - readonly timeOrigin: number; + /** + * The high resolution millisecond timestamp at which third_party_main processing ended. + */ + readonly thirdPartyMainEnd: number; - /** - * Wraps a function within a new function that measures the running time of the wrapped function. - * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. - * @param fn - */ - timerify any>(fn: T): T; + /** + * The high resolution millisecond timestamp at which third_party_main processing started. + */ + readonly thirdPartyMainStart: number; + + /** + * The high resolution millisecond timestamp at which the V8 platform was initialized. + */ + readonly v8Start: number; + } + + export interface Performance { + /** + * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. + * If name is provided, removes entries with name. + * @param name + */ + clearFunctions(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only objects whose performanceEntry.name matches name. + */ + clearMeasures(name?: string): void; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + * @return list of all PerformanceEntry objects + */ + getEntries(): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + * @param name + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByType(type: string): PerformanceEntry[]; + + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string): void; + + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark: string, endMark: string): void; + + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T): T; } export interface PerformanceObserverEntryList { @@ -7156,5 +7148,5 @@ declare module "perf_hooks" { export const NODE_PERFORMANCE_GC_WEAKCB: number; } - const performance: Performance; + const performance: Performance; } diff --git a/types/node/v8/node-tests.ts b/types/node/v8/node-tests.ts index 6bb7f28495..74d4c5c222 100644 --- a/types/node/v8/node-tests.ts +++ b/types/node/v8/node-tests.ts @@ -1,4 +1,4 @@ -import * as assert from "assert"; +import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; import events2 = require("events"); @@ -235,6 +235,25 @@ namespace fs_tests { }); } + { + let listS: string[]; + listS = fs.readdirSync('path'); + listS = fs.readdirSync('path', { encoding: 'utf8' }); + listS = fs.readdirSync('path', { encoding: null }); + listS = fs.readdirSync('path', { encoding: undefined }); + listS = fs.readdirSync('path', 'utf8'); + listS = fs.readdirSync('path', null); + listS = fs.readdirSync('path', undefined); + + let listB: Buffer[]; + listB = fs.readdirSync('path', { encoding: 'buffer' }); + listB = fs.readdirSync("path", 'buffer'); + + let enc = 'buffer'; + fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[] + fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[] + } + { fs.mkdtemp('/tmp/foo-', (err, folder) => { console.log(folder); @@ -571,9 +590,22 @@ namespace url_tests { } { - var helloUrl = url.parse('http://example.com/?hello=world', true); - if (typeof helloUrl.query !== 'string') { - assert.equal(helloUrl.query['hello'], 'world'); + const helloUrl = url.parse('http://example.com/?hello=world', true); + let helloQuery = helloUrl.query['hello']; + assert.equal(helloUrl.query['hello'], 'world'); + + let strUrl = url.parse('http://example.com/?hello=world'); + let queryStr: string = strUrl.query; + + strUrl = url.parse('http://example.com/?hello=world', false); + queryStr = strUrl.query; + + function getBoolean(): boolean { return false; } + const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); + if (typeof(urlUrl.query) === 'string') { + queryStr = urlUrl.query; + } else if (urlUrl.query) { + helloQuery = urlUrl.query['hello']; } } @@ -1746,6 +1778,46 @@ namespace path_tests { }); // returns // '/home/user/dir/file.txt' + + path.format({ + dir: "/home/user/dir", + base: "file.txt" + }); + // returns + // '/home/user/dir/file.txt' + + path.posix.format({ + root: "/", + dir: "/home/user/dir", + base: "file.txt", + ext: ".txt", + name: "file" + }); + // returns + // '/home/user/dir/file.txt' + + path.posix.format({ + dir: "/home/user/dir", + base: "file.txt" + }); + // returns + // '/home/user/dir/file.txt' + + path.win32.format({ + root: "C:\\", + dir: "C:\\home\\user\\dir", + ext: ".txt", + name: "file" + }); + // returns + // 'C:\home\user\dir\file.txt' + + path.win32.format({ + dir: "C:\\home\\user\\dir", + base: "file.txt" + }); + // returns + // 'C:\home\user\dir\file.txt' } //////////////////////////////////////////////////// @@ -3860,6 +3932,8 @@ namespace module_tests { const m1: Module = new Module("moduleId"); const m2: Module = new Module.Module("moduleId"); + let paths: string[] = module.paths; + paths = m1.paths; } //////////////////////////////////////////////////// diff --git a/types/node/v8/tsconfig.json b/types/node/v8/tsconfig.json index 3f4614bef4..8deb391829 100644 --- a/types/node/v8/tsconfig.json +++ b/types/node/v8/tsconfig.json @@ -26,4 +26,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} +} \ No newline at end of file diff --git a/types/nodegit/tsconfig.json b/types/nodegit/tsconfig.json index e097a77133..5d80518149 100644 --- a/types/nodegit/tsconfig.json +++ b/types/nodegit/tsconfig.json @@ -119,4 +119,4 @@ "tree-update.d.ts", "tree.d.ts" ] -} +} \ No newline at end of file diff --git a/types/nodegit/tslint.json b/types/nodegit/tslint.json index 0ec275bd05..4ce3d76bf7 100644 --- a/types/nodegit/tslint.json +++ b/types/nodegit/tslint.json @@ -3,6 +3,7 @@ "rules": { // TODOs "ban-types": false, + "no-const-enum": false, "no-unnecessary-class": false } } diff --git a/types/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts b/types/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts index 393091816d..271dc6cf41 100644 --- a/types/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts +++ b/types/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts @@ -1,6 +1,6 @@ import * as AWS from "aws-sdk"; import * as nodemailer from "nodemailer"; -import * as sesTransport from 'nodemailer-ses-transport'; +import sesTransport = require('nodemailer-ses-transport'); const opts: sesTransport.SesOptions = { SES: new AWS.SES(), diff --git a/types/nodemailer/index.d.ts b/types/nodemailer/index.d.ts index bee4649e94..0b46c67789 100644 --- a/types/nodemailer/index.d.ts +++ b/types/nodemailer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Nodemailer 4.3 +// Type definitions for Nodemailer 4.6 // Project: https://github.com/nodemailer/nodemailer // Definitions by: Rogier Schouten // Piotr Roszatycki diff --git a/types/nodemailer/lib/fetch/index.d.ts b/types/nodemailer/lib/fetch/index.d.ts index 8fc814c517..765debb179 100644 --- a/types/nodemailer/lib/fetch/index.d.ts +++ b/types/nodemailer/lib/fetch/index.d.ts @@ -4,12 +4,18 @@ type ms = number; import _Cookies = require('./cookies'); +import * as http from 'http'; import { Writable } from 'stream'; import * as tls from 'tls'; declare namespace fetch { type Cookies = _Cookies; + interface WritableResponse extends Writable { + statusCode: number; + headers: http.IncomingHttpHeaders; + } + interface Options { fetchRes?: Writable; cookies?: Cookies; @@ -27,6 +33,6 @@ declare namespace fetch { } } -declare function fetch(url: string, options?: fetch.Options): Writable; +declare function fetch(url: string, options?: fetch.Options): fetch.WritableResponse; export = fetch; diff --git a/types/nodemailer/lib/mailer/index.d.ts b/types/nodemailer/lib/mailer/index.d.ts index f08c2d085d..f9d36d7efb 100644 --- a/types/nodemailer/lib/mailer/index.d.ts +++ b/types/nodemailer/lib/mailer/index.d.ts @@ -3,7 +3,7 @@ import { EventEmitter } from 'events'; import { Socket } from 'net'; import { Readable } from 'stream'; -import { URL } from 'url'; +import { Url } from 'url'; import { SentMessageInfo, Transport, TransportOptions } from '../..'; import * as shared from '../shared'; @@ -34,7 +34,7 @@ declare namespace Mail { /** String, Buffer or a Stream contents for the attachmentent */ content?: string | Buffer | Readable; /** path to a file or an URL (data uris are allowed as well) if you want to stream the file instead of including it (better for larger attachments) */ - path?: string | URL; + path?: string | Url; } interface Attachment extends AttachmentLike { @@ -46,7 +46,7 @@ declare namespace Mail { encoding?: string; /** optional content type for the attachment, if not set will be derived from the filename property */ contentType?: string; - /** optional transfer encoding for the attachment, if not set it will be derived from the contentType property. Example values: quoted-printable, base64 */ + /** optional transfer encoding for the attachment, if not set it will be derived from the contentType property. Example values: quoted-printable, base64. If it is unset then base64 encoding is used for the attachment. If it is set to false then previous default applies (base64 for most, 7bit for text). */ contentTransferEncoding?: string; /** optional content disposition type for the attachment, defaults to ‘attachment’ */ contentDisposition?: string; @@ -135,6 +135,8 @@ declare namespace Mail { disableFileAccess?: boolean; /** is an object with DKIM options */ dkim?: DKIM.Options; + /** method to normalize header keys for custom caseing */ + normalizeHeaderKey?(key: string): string; } type PluginFunction = (mail: MailMessage, callback: (err?: Error | null) => void) => void; @@ -175,11 +177,11 @@ declare class Mail extends EventEmitter { setupProxy(proxyUrl: string): void; set(key: 'oauth2_provision_cb', value: (user: string, renew: boolean, callback: (err: Error | null, accessToken?: string, expires?: number) => void) => void): Map; - set(key: 'proxy_handler_http' | 'proxy_handler_https' | 'proxy_handler_socks' | 'proxy_handler_socks5' | 'proxy_handler_socks4' | 'proxy_handler_socks4a', value: (proxy: URL, options: TransportOptions, callback: (err: Error | null, socketOptions?: { connection: Socket }) => void) => void): Map; + set(key: 'proxy_handler_http' | 'proxy_handler_https' | 'proxy_handler_socks' | 'proxy_handler_socks5' | 'proxy_handler_socks4' | 'proxy_handler_socks4a', value: (proxy: Url, options: TransportOptions, callback: (err: Error | null, socketOptions?: { connection: Socket }) => void) => void): Map; set(key: string, value: any): Map; get(key: 'oauth2_provision_cb'): (user: string, renew: boolean, callback: (err: Error | null, accessToken: string, expires: number) => void) => void; - get(key: 'proxy_handler_http' | 'proxy_handler_https' | 'proxy_handler_socks' | 'proxy_handler_socks5' | 'proxy_handler_socks4' | 'proxy_handler_socks4a'): (proxy: URL, options: TransportOptions, callback: (err: Error | null, socketOptions: { connection: Socket }) => void) => void; + get(key: 'proxy_handler_http' | 'proxy_handler_https' | 'proxy_handler_socks' | 'proxy_handler_socks5' | 'proxy_handler_socks4' | 'proxy_handler_socks4a'): (proxy: Url, options: TransportOptions, callback: (err: Error | null, socketOptions: { connection: Socket }) => void) => void; get(key: string): any; addListener(event: 'error', listener: (err: Error) => void): this; diff --git a/types/nodemailer/lib/mime-node.d.ts b/types/nodemailer/lib/mime-node.d.ts index 98eda91874..047770ce57 100644 --- a/types/nodemailer/lib/mime-node.d.ts +++ b/types/nodemailer/lib/mime-node.d.ts @@ -34,7 +34,9 @@ declare namespace MimeNode { /** If true, do not exclude Bcc from the generated headers */ keepBcc?: boolean; /** either 'Q' (the default) or 'B' */ - textEncoding: 'B' | 'Q'; + textEncoding?: 'B' | 'Q'; + /** method to normalize header keys for custom caseing */ + normalizeHeaderKey?(key: string): string; } } @@ -44,10 +46,10 @@ declare namespace MimeNode { * the options, assumes this is the root. */ declare class MimeNode { - constructor(contentType: string, options: MimeNode.Options); + constructor(contentType: string, options?: MimeNode.Options); /** Creates and appends a child node.Arguments provided are passed to MimeNode constructor */ - createChild(contentType: string, options: MimeNode.Options): MimeNode; + createChild(contentType: string, options?: MimeNode.Options): MimeNode; /** Appends an existing node to the mime tree. Removes the node from an existing tree if needed */ appendChild(childNode: MimeNode): MimeNode; @@ -63,7 +65,7 @@ declare class MimeNode { * You can set multiple values as well by using [{key:'', value:''}] or * {key: 'value'} as the first argument. */ - setHeader(key: string, value: string): this; + setHeader(key: string, value: string | string[]): this; setHeader(headers: { [key: string]: string } | Array<{ key: string, value: string }>): this; /** diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index 9761cb73e4..0caa84b0e0 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -10,6 +10,7 @@ import MailComposer = require('nodemailer/lib/mail-composer'); import MailMessage = require('nodemailer/lib/mailer/mail-message'); import mimeFuncs = require('nodemailer/lib/mime-funcs'); import mimeTypes = require('nodemailer/lib/mime-funcs/mime-types'); +import MimeNode = require('nodemailer/lib/mime-node'); import qp = require('nodemailer/lib/qp'); import SendmailTransport = require('nodemailer/lib/sendmail-transport'); import SESTransport = require('nodemailer/lib/ses-transport'); @@ -790,7 +791,8 @@ function stream_buffer_unix_newlines_test() { const transporter = nodemailer.createTransport({ streamTransport: true, newline: 'unix', - buffer: true + buffer: true, + normalizeHeaderKey: (key) => key.toUpperCase() }); transporter.sendMail({ from: 'sender@example.com', @@ -1090,7 +1092,11 @@ function base64_test() { // fetch function fetch_test() { - fetch('http://localhost/'); + const stream = fetch('http://localhost/'); + + const statusCode: number = stream.statusCode; + const headers = stream.headers; + const contentType: string | undefined = headers['content-type']; fetch('http://localhost:/', { allowErrorResponse: true, @@ -1201,6 +1207,50 @@ function mime_funcs_test() { mimeFuncs.foldLines('Testin command line', 76); } +// mime-node + +function mime_node_test() { + const mb = new MimeNode('text/plain', { + normalizeHeaderKey: (key) => key.toUpperCase() + }); + + const child = mb.createChild('multipart/mixed'); + mb.appendChild(child); + child.replace(child); + + mb.setHeader('key', 'value'); + const value: string = mb.getHeader('key'); + + mb.addHeader({ + key: 'value4', + key2: 'value5' + }); + + mb.setHeader([ + { + key: 'key', + value: 'value2' + }, + { + key: 'key2', + value: 'value3' + } + ]); + + mb.setHeader('key', ['value1', 'value2', 'value3']); + + mb.setContent('abc'); + + mb.build((err, msg) => { + const msgAsString: string = msg.toString(); + }); + + mb.processFunc((input) => { + const isReadable: boolean = input.readable; + return input; + }); +} + // mime-types function mime_types_test() { diff --git a/types/normalize-package-data/tsconfig.json b/types/normalize-package-data/tsconfig.json index 0e79738d04..3105673d24 100644 --- a/types/normalize-package-data/tsconfig.json +++ b/types/normalize-package-data/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "normalize-package-data-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/notyf/tsconfig.json b/types/notyf/tsconfig.json index 9cf78d162a..18fb007211 100644 --- a/types/notyf/tsconfig.json +++ b/types/notyf/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "notyf-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/nouislider/index.d.ts b/types/nouislider/index.d.ts index 0e070e89c7..76b62371fe 100644 --- a/types/nouislider/index.d.ts +++ b/types/nouislider/index.d.ts @@ -179,7 +179,7 @@ declare namespace noUiSlider { * To get the current slider value. For one-handle sliders, calling .get() will return the value. * For two-handle sliders, an array[value, value] will be returned. */ - get(): number | number[]; + get(): string | string[]; /** * noUiSlider will keep your values within the slider range, which saves you a bunch of validation. * If you have configured the slider to use one handle, you can change the current value by passing diff --git a/types/nouislider/tslint.json b/types/nouislider/tslint.json index a41bf5d19a..b6afb8acee 100644 --- a/types/nouislider/tslint.json +++ b/types/nouislider/tslint.json @@ -21,6 +21,7 @@ "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, + "no-const-enum": false, "no-construct": false, "no-declare-current-package": false, "no-duplicate-imports": false, diff --git a/types/nouislider/v8/tslint.json b/types/nouislider/v8/tslint.json index a41bf5d19a..b6afb8acee 100644 --- a/types/nouislider/v8/tslint.json +++ b/types/nouislider/v8/tslint.json @@ -21,6 +21,7 @@ "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, + "no-const-enum": false, "no-construct": false, "no-declare-current-package": false, "no-duplicate-imports": false, diff --git a/types/novnc-core/tslint.json b/types/novnc-core/tslint.json index 3db14f85ea..3224b40b8b 100644 --- a/types/novnc-core/tslint.json +++ b/types/novnc-core/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-const-enum": false + } +} diff --git a/types/npm-package-arg/npm-package-arg-tests.ts b/types/npm-package-arg/npm-package-arg-tests.ts index ed95eb5243..d7f08c6c10 100644 --- a/types/npm-package-arg/npm-package-arg-tests.ts +++ b/types/npm-package-arg/npm-package-arg-tests.ts @@ -1,4 +1,4 @@ -import * as npa from "npm-package-arg"; +import npa = require("npm-package-arg"); const result1 = npa("npm-package-arg@5.1"); const result2 = npa("npm-package-arg@5.1", ".."); diff --git a/types/npm-packlist/index.d.ts b/types/npm-packlist/index.d.ts new file mode 100644 index 0000000000..934d2f8967 --- /dev/null +++ b/types/npm-packlist/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for npm-packlist 1.1 +// Project: https://github.com/npm/npm-packlist +// Definitions by: Klaus Meinhardt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +declare function packlist(options?: packlist.Options): Promise; +declare function packlist(options: packlist.Options | undefined, callback: (result: string[]) => T): Promise; +declare namespace packlist { + interface Options { + /** Directory to walk recusively. Defaults to `process.cwd()`. */ + path?: string; + } + function sync(options?: Options): string[]; +} +export = packlist; diff --git a/types/npm-packlist/npm-packlist-tests.ts b/types/npm-packlist/npm-packlist-tests.ts new file mode 100644 index 0000000000..162a7d86f5 --- /dev/null +++ b/types/npm-packlist/npm-packlist-tests.ts @@ -0,0 +1,14 @@ +import packlist = require('npm-packlist'); + +let result: string[] = packlist.sync(); +result = packlist.sync({}); +result = packlist.sync({path: 'foo'}); + +(async () => { + result = await packlist(); + result = await packlist({}); + result = await packlist({path: 'foo'}); + + packlist(undefined, (r) => result = r); + packlist({path: 'foo'}, (r) => result = r); +})(); diff --git a/types/npm-packlist/tsconfig.json b/types/npm-packlist/tsconfig.json new file mode 100644 index 0000000000..2c60fe863a --- /dev/null +++ b/types/npm-packlist/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "npm-packlist-tests.ts" + ] +} \ No newline at end of file diff --git a/types/npm-packlist/tslint.json b/types/npm-packlist/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/npm-packlist/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ns-api/ns-api-tests.ts b/types/ns-api/ns-api-tests.ts index 5063a97e48..ab8c7e343d 100644 --- a/types/ns-api/ns-api-tests.ts +++ b/types/ns-api/ns-api-tests.ts @@ -1,4 +1,4 @@ -import * as NsApi from "ns-api"; +import NsApi = require("ns-api"); declare var console: { log(msg: any): string }; diff --git a/types/nsqjs/tsconfig.json b/types/nsqjs/tsconfig.json index 6681afbdb9..2e65f5637c 100644 --- a/types/nsqjs/tsconfig.json +++ b/types/nsqjs/tsconfig.json @@ -14,11 +14,10 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true, - "strictFunctionTypes": true + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "nsqjs-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/nunjucks/tsconfig.json b/types/nunjucks/tsconfig.json index 5824ce2f1f..4324f01fa8 100644 --- a/types/nunjucks/tsconfig.json +++ b/types/nunjucks/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "nunjucks-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/nw.js/index.d.ts b/types/nw.js/index.d.ts index b4e941b0a7..93307f9e87 100644 --- a/types/nw.js/index.d.ts +++ b/types/nw.js/index.d.ts @@ -372,7 +372,7 @@ declare module NWJS_Helpers { * The paper size spec * example: 'mediaSize':{'name': 'CUSTOM', 'width_microns': 279400, 'height_microns': 215900, 'custom_display_name':'Letter', 'is_default': true} */ - mediaSize: JSON; + mediaSize: any; /** * Whether to print CSS backgrounds @@ -1072,9 +1072,9 @@ declare module NWJS_Helpers { * Enumerate the printers in the system. * * @param callback {function(dev_win?)} callback with the native window of the DevTools window. - * - (optional) printers {JSON[]} An array of JSON objects for the printer information. + * - (optional) printers {any[]} An array of json objects for the printer information. */ - getPrinters( callback: ( printers?: JSON[] ) => void ): void; + getPrinters( callback: ( printers?: any[] ) => void ): void; /** * Query the status of devtools window. @@ -1084,9 +1084,9 @@ declare module NWJS_Helpers { /** * Print the web contents in the window without the need for user’s interaction. * - * @param options {Object} Specify whether to close the window forcely and bypass close event. + * @param options {any | PrintOption} Specify whether to close the window forcely and bypass close event. */ - print( options: JSON | PrintOption ): void; + print( options: any | PrintOption ): void; /** * Set window's maximum size. @@ -1381,9 +1381,9 @@ declare namespace nw { dataPath: string; /** - * Get the JSON object of the manifest file. + * Get the json object of the manifest file. */ - manifest: JSON; + manifest: any; /** * Clear the HTTP cache in memory and the one on disk. This method call is synchronized. diff --git a/types/o.js/o.js-tests.ts b/types/o.js/o.js-tests.ts index 26cc187723..be3e5c824a 100644 --- a/types/o.js/o.js-tests.ts +++ b/types/o.js/o.js-tests.ts @@ -1,4 +1,4 @@ -import * as o from 'o.js'; +import o = require('o.js'); import * as Q from "q"; interface Product { diff --git a/types/oauth2-server/index.d.ts b/types/oauth2-server/index.d.ts index a423f48a58..06b6fbadb0 100644 --- a/types/oauth2-server/index.d.ts +++ b/types/oauth2-server/index.d.ts @@ -5,7 +5,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -import { Request, RequestHandler } from "express"; +import Express = require("express"); /** * Represents an OAuth2 server instance. diff --git a/types/oauth2-server/oauth2-server-tests.ts b/types/oauth2-server/oauth2-server-tests.ts index be8fa83705..faf9976873 100644 --- a/types/oauth2-server/oauth2-server-tests.ts +++ b/types/oauth2-server/oauth2-server-tests.ts @@ -1,5 +1,5 @@ -import * as express from "express"; -import * as OAuth2Server from "oauth2-server"; +import express = require("express"); +import OAuth2Server = require("oauth2-server"); const oauth2Model: OAuth2Server.AuthorizationCodeModel = { getClient: async (clientId: string, clientSecret: string): Promise => { diff --git a/types/object-assign/object-assign-tests.ts b/types/object-assign/object-assign-tests.ts index e7c58cf5fb..dc8db6ba07 100644 --- a/types/object-assign/object-assign-tests.ts +++ b/types/object-assign/object-assign-tests.ts @@ -1,4 +1,4 @@ -import * as objectAssign from 'object-assign'; +import objectAssign = require('object-assign'); interface Target { hellow: string; @@ -9,7 +9,7 @@ interface Source1 { } interface Result extends Target, Source1 { - + } interface Source2 { @@ -17,7 +17,7 @@ interface Source2 { } interface Result2 extends Result, Source2 { - + } interface Source3 { @@ -25,7 +25,7 @@ interface Source3 { } interface Result3 extends Result2, Source3 { - + } interface Source4 { @@ -33,7 +33,7 @@ interface Source4 { } interface Result4 extends Result3, Source4 { - + } interface Source5 { @@ -41,7 +41,7 @@ interface Source5 { } interface Result5 extends Result4, Source5 { - + } function assign1(): Result { diff --git a/types/object-hash/index.d.ts b/types/object-hash/index.d.ts index c6b16df950..4da49c262c 100644 --- a/types/object-hash/index.d.ts +++ b/types/object-hash/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for object-hash v1.1.8 +// Type definitions for object-hash v1.2.0 // Project: https://github.com/puleos/object-hash // Definitions by: Michael Zabka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -18,6 +18,7 @@ declare namespace ObjectHash { respectFunctionNames?: boolean; unorderedArrays?: boolean; unorderedSets?: boolean; + excludeKeys?: (key: string) => boolean; } interface HashTableItem { diff --git a/types/object-inspect/tsconfig.json b/types/object-inspect/tsconfig.json index 1f167ba039..295f490d24 100644 --- a/types/object-inspect/tsconfig.json +++ b/types/object-inspect/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "object-inspect-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/object-merge/index.d.ts b/types/object-merge/index.d.ts new file mode 100644 index 0000000000..bd9f0ce8ee --- /dev/null +++ b/types/object-merge/index.d.ts @@ -0,0 +1,164 @@ +// Type definitions for object-merge 2.5 +// Project: https://github.com/matthewkastor/object-merge +// Definitions by: OpenByteDev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.2 + +interface ObjectMergeOptions { + depth: number|boolean; + throwOnCircularRef: boolean; +} + +interface ObjectMerge { + /** + * Merges JavaScript objects recursively without altering the objects merged. + * @author Matthew Kastor + * @param [opts] An options object created by + * objectMerge.createOptions. Options must be specified as the first argument + * and must be an object created with createOptions or else the object will + * not be recognized as an options object and will be merged instead. + * @param shadows [[shadows]...] One or more objects to merge. Each + * argument given will be treated as an object to merge. Each object + * overwrites the previous objects descendant properties if the property name + * matches. If objects properties are objects they will be merged recursively + * as well. + * @returns Returns a single merged object composed from clones of the + * input objects. + * @example + * var objectMerge = require('object-merge'); + * var x = { + * a : 'a', + * b : 'b', + * c : { + * d : 'd', + * e : 'e', + * f : { + * g : 'g' + * } + * } + * }; + * var y = { + * a : '`a', + * b : '`b', + * c : { + * d : '`d' + * } + * }; + * var z = { + * a : { + * b : '``b' + * }, + * fun : function foo () { + * return 'foo'; + * }, + * aps : Array.prototype.slice + * }; + * var out = objectMerge(x, y, z); + * // out.a will be { + * // b : '``b' + * // } + * // out.b will be '`b' + * // out.c will be { + * // d : '`d', + * // e : 'e', + * // f : { + * // g : 'g' + * // } + * // } + * // out.fun will be a clone of z.fun + * // out.aps will be equal to z.aps + */ + (opts: ObjectMergeOptions, ...shadows: object[]): object; + /** + * Merges JavaScript objects recursively without altering the objects merged. + * @author Matthew Kastor + * @param shadows [[shadows]...] One or more objects to merge. Each + * argument given will be treated as an object to merge. Each object + * overwrites the previous objects descendant properties if the property name + * matches. If objects properties are objects they will be merged recursively + * as well. + * @returns Returns a single merged object composed from clones of the + * input objects. + * @example + * var objectMerge = require('object-merge'); + * var x = { + * a : 'a', + * b : 'b', + * c : { + * d : 'd', + * e : 'e', + * f : { + * g : 'g' + * } + * } + * }; + * var y = { + * a : '`a', + * b : '`b', + * c : { + * d : '`d' + * } + * }; + * var z = { + * a : { + * b : '``b' + * }, + * fun : function foo () { + * return 'foo'; + * }, + * aps : Array.prototype.slice + * }; + * var out = objectMerge(x, y, z); + * // out.a will be { + * // b : '``b' + * // } + * // out.b will be '`b' + * // out.c will be { + * // d : '`d', + * // e : 'e', + * // f : { + * // g : 'g' + * // } + * // } + * // out.fun will be a clone of z.fun + * // out.aps will be equal to z.aps + */ + (...shadows: object[]): object; + /** + * Creates a new options object suitable for use with objectMerge. + * @param [opts] An object specifying the options. + * @param [opts.depth = false] Specifies the depth to traverse objects + * during merging. If this is set to false then there will be no depth limit. + * @param [opts.throwOnCircularRef = true] Set to false to suppress + * errors on circular references. + * @returns Returns an instance of ObjectMergeOptions + * to be used with objectMerge. + * @example + * var opts = objectMerge.createOptions({ + * depth : 2, + * throwOnCircularRef : false + * }); + * var obj1 = { + * a1 : { + * a2 : { + * a3 : {} + * } + * } + * }; + * var obj2 = { + * a1 : { + * a2 : { + * a3 : 'will not be in output' + * }, + * a22 : {} + * } + * }; + * objectMerge(opts, obj1, obj2); + */ + createOptions: (options: object) => ObjectMergeOptions; +} + +declare const objectMerge: ObjectMerge; + +export = objectMerge; diff --git a/types/object-merge/object-merge-tests.ts b/types/object-merge/object-merge-tests.ts new file mode 100644 index 0000000000..edaf9885ba --- /dev/null +++ b/types/object-merge/object-merge-tests.ts @@ -0,0 +1,47 @@ +import objectMerge = require('object-merge'); + +const x = { + a : 'a', + b : 'b', + c : { + d : 'd', + e : 'e', + f : { + g : 'g' + } + } +}; +const y = { + a : '`a', + b : '`b', + c : { + d : '`d' + } +}; +const z = { + a : { + b : '``b' + }, + fun : function foo() { + return 'foo'; + }, + aps : Array.prototype.slice +}; +const out = objectMerge(x, y, z); + +const a = { + a1 : { + a2 : { + a3 : {} + } + } +}; +const b = { + b1 : { + b2 : { + b3 : {} + } + } +}; +const opts = objectMerge.createOptions({depth : 2}); +const res = objectMerge(opts, a, b); diff --git a/types/object-merge/tsconfig.json b/types/object-merge/tsconfig.json new file mode 100644 index 0000000000..c098631639 --- /dev/null +++ b/types/object-merge/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", + "object-merge-tests.ts" + ] +} \ No newline at end of file diff --git a/types/object-merge/tslint.json b/types/object-merge/tslint.json new file mode 100644 index 0000000000..4e88071852 --- /dev/null +++ b/types/object-merge/tslint.json @@ -0,0 +1 @@ +{"extends": "dtslint/dt.json"} diff --git a/types/object-refs/object-refs-tests.ts b/types/object-refs/object-refs-tests.ts index 9b602aea0d..ba71756c3c 100644 --- a/types/object-refs/object-refs-tests.ts +++ b/types/object-refs/object-refs-tests.ts @@ -1,4 +1,4 @@ -import * as Refs from 'object-refs'; +import Refs = require('object-refs'); let refs = new Refs({ name: 'wheels', collection: true, enumerable: true }, { name: 'car' }); diff --git a/types/odata/index.d.ts b/types/odata/index.d.ts index 349d48763b..e56ac4296c 100644 --- a/types/odata/index.d.ts +++ b/types/odata/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for odata v0.3.4 +// Type definitions for odata v0.3 // Project: https://github.com/janhommes/odata // Definitions by: Jan Hommes , Jean-Christophe Chalte // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,14 +26,16 @@ declare module 'odata' { } interface OHandler { - inlinecount : number - data : T + inlinecount: number; // if inlinecount is set, here the counting is gold + data: T; // holds the data after an callback + param: {}; // this object holds all parameter for a route config(options ?: Options) : OHandler progress(callback : () => any) : OHandler - get(callback ?: (data : T) => void) : Q.Promise> - save(callback ?: (data : T) => void) : Q.Promise> + get(callback ?: (data : T) => void, errorCallback?: (status: number) => void) : Q.Promise> + save(callback ?: (data : T) => void, errorCallback?: (status: number) => void) : Q.Promise> + query: () => string; post(params : any) : OHandler patch(params : any) : OHandler @@ -78,11 +80,14 @@ declare module 'odata' { deleteRef(resource : string, id : string | number) : OHandler } - interface OFn extends OHandler { - (options ?: string | Options) : OHandler + interface OHandlerStatic { + (): OHandlerStatic; + (options?: string | Options): OHandler<{}>; + config: (config: Options) => OHandlerStatic; + isEndpoint: () => boolean; } - var o : OFn<{}>; + var o : OHandlerStatic; export = o } \ No newline at end of file diff --git a/types/odata/odata-tests.ts b/types/odata/odata-tests.ts index 522dc3d529..743c5cd906 100644 --- a/types/odata/odata-tests.ts +++ b/types/odata/odata-tests.ts @@ -1,4 +1,4 @@ -import * as o from 'odata'; +import o = require('odata'); import * as Q from "q"; interface Product { @@ -20,6 +20,8 @@ interface Category { o('http://services.odata.org/V4/OData/OData.svc/Products') .get(function(data) { console.log(data); //returns an array of Product data + }, function(status) { + console.error(status); // error with status }); @@ -70,7 +72,8 @@ o('http://services.odata.org/V4/OData/OData.svc/Products(2)') .get() .then(function(oHandler) { console.log(oHandler.data); - }).fail(function(ex) { + }) + .fail(function(ex) { console.log(ex); }); @@ -114,10 +117,12 @@ o('http://services.odata.org/V4/OData/OData.svc/Products') .get() .then(function(oHandler) { oHandler.data.Name="NewName"; - return(o.save()); - }).then(function(oHandler) { + return(oHandler.save()); + }) + .then(function(oHandler) { console.log(oHandler.data.Name); //NewName - }).fail(function(ex) { + }) + .fail(function(ex) { console.log("error"); }); @@ -132,7 +137,12 @@ o('Products').get(function(data) { //same result like the first example on this page }); - +const oEequest = o('http://services.odata.org/V4/OData/OData.svc/Products') + .find(2); +const queryString = oEequest.query(); +if (queryString !== 'http://services.odata.org/V4/OData/OData.svc/Products(2)') { + throw new Error('assert error'); +} //basic config o().config({ diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index e24b6c4a2c..159293057e 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Office.js // Project: http://dev.office.com -// Definitions by: OfficeDev , Lance Austin +// Definitions by: OfficeDev , Lance Austin , Michael Zlatkovsky , Kim Brandl , Ricky Kirkham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* @@ -134,17 +134,14 @@ declare namespace Office { export interface Error { /** * Gets the numeric code of the error. - * @since 1.0 */ code: number; /** * Gets the name of the error. - * @since 1.0 */ message: string; /** * Gets a detailed description of the error. - * @since 1.0 */ name: string; } @@ -244,7 +241,7 @@ declare namespace Office { bodyBackgroundColor: string; bodyForegroundColor: string; controlBackgroundColor: string; - controlForgroundColor: string; + controlForegroundColor: string; } /** * Dialog object returned as part of the displayDialogAsync callback. The object exposes methods for registering event handlers and closing the dialog @@ -2610,7 +2607,22 @@ declare namespace OfficeExtension { /** Synchronizes the state between JavaScript proxy objects and the Office document, by executing instructions queued on the request context and retrieving properties of loaded Office objects for use in your code.�This method returns a promise, which is resolved when the synchronization is complete. */ sync(passThroughValue?: T): IPromise; } + + export interface EmbeddedOptions { + sessionKey?: string, + container?: HTMLElement, + id?: string; + timeoutInMilliseconds?: number; + height?: string; + width?: string; + } + + class EmbeddedSession { + constructor(url: string, options?: EmbeddedOptions); + public init(): IPromise; + } } + declare namespace OfficeExtension { /** Contains the result for methods that return primitive types. The object's value property is retrieved from the document after "context.sync()" is invoked. */ class ClientResult { @@ -22314,3 +22326,2256 @@ declare namespace OneNote { //////////////////////////////////////////////////////////////// /////////////////////// End OneNote APIs /////////////////////// //////////////////////////////////////////////////////////////// + + + +//////////////////////////////////////////////////////////////// +/////////////////////// Begin Visio APIs /////////////////////// +//////////////////////////////////////////////////////////////// + + + +declare namespace Visio { + /** + * + * Provides information about the shape that raised the ShapeMouseEnter event. + * + * [Api set: 1.1] + */ + interface ShapeMouseEnterEventArgs { + /** + * + * Gets the name of the page which has the shape object that raised the ShapeMouseEnter event. + * + * [Api set: 1.1] + */ + pageName: string; + /** + * + * Gets the shape object that raised the ShapeMouseEnter event. + * + * [Api set: 1.1] + */ + shapeName: string; + } + /** + * + * Provides information about the shape that raised the ShapeMouseLeave event. + * + * [Api set: 1.1] + */ + interface ShapeMouseLeaveEventArgs { + /** + * + * Gets the name of the page which has the shape object that raised the ShapeMouseLeave event. + * + * [Api set: 1.1] + */ + pageName: string; + /** + * + * Gets the shape object that raised the ShapeMouseLeave event. + * + * [Api set: 1.1] + */ + shapeName: string; + } + /** + * + * Provides information about the page that raised the PageLoadComplete event. + * + * [Api set: 1.1] + */ + interface PageLoadCompleteEventArgs { + /** + * + * Gets the name of the page that raised the PageLoad event. + * + * [Api set: 1.1] + */ + pageName: string; + /** + * + * Gets the success/failure of the PageLoadComplete event. + * + * [Api set: 1.1] + */ + success: boolean; + } + /** + * + * Provides information about the document that raised the DataRefreshComplete event. + * + * [Api set: 1.1] + */ + interface DataRefreshCompleteEventArgs { + /** + * + * Gets the document object that raised the DataRefreshComplete event. + * + * [Api set: 1.1] + */ + document: Visio.Document; + /** + * + * Gets the success/failure of the DataRefreshComplete event. + * + * [Api set: 1.1] + */ + success: boolean; + } + /** + * + * Provides information about the shape collection that raised the SelectionChanged event. + * + * [Api set: 1.1] + */ + interface SelectionChangedEventArgs { + /** + * + * Gets the name of the page which has the ShapeCollection object that raised the SelectionChanged event. + * + * [Api set: 1.1] + */ + pageName: string; + /** + * + * Gets the ShapeCollection object that raised the SelectionChanged event. + * + * [Api set: 1.1] + */ + shapeNames: Array; + } + /** + * + * Provides information about the drawing that raised the DiagramLoadComplete event. + * + * [Api set: 1.1] + */ + interface DocumentLoadCompleteEventArgs { + /** + * + * Gets the success/failure of the DocumentLoadComplete event. + * + * [Api set: 1.1] + */ + success: boolean; + } + /** + * + * Represents the Application. + * + * [Api set: 1.1] + */ + class Application extends OfficeExtension.ClientObject { + /** + * + * Show/Hide the application borders. + * + * [Api set: 1.1] + */ + showBorders: boolean; + /** + * + * Show or Hide the standard toolbars. + * + * [Api set: 1.1] + */ + showToolbars: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ApplicationUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Application): void; + /** + * + * Show or Hide a particular toolbar. + * + * [Api set: 1.1] + */ + showToolbar(id: string, show: boolean): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.ApplicationLoadOptions): Visio.Application; + load(option?: string | string[]): Visio.Application; + load(option?: { + select?: string; + expand?: string; + }): Visio.Application; + toJSON(): Visio.Interfaces.ApplicationData; + } + /** + * + * Represents the Document class. + * + * [Api set: 1.1] + */ + class Document extends OfficeExtension.ClientObject { + /** + * + * Represents a Visio application instance that contains this document. Read-only. + * + * [Api set: 1.1] + */ + readonly application: Visio.Application; + /** + * + * Represents a collection of pages associated with the document. Read-only. + * + * [Api set: 1.1] + */ + readonly pages: Visio.PageCollection; + /** + * + * Returns the DocumentView object. + * + * [Api set: 1.1] + */ + readonly view: Visio.DocumentView; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.DocumentUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Document): void; + /** + * + * Returns the Active Page of the document. + * + * [Api set: 1.1] + */ + getActivePage(): Visio.Page; + /** + * + * Set the Active Page of the document. + * + * [Api set: 1.1] + * + * @param PageName Name of the page + */ + setActivePage(PageName: string): void; + /** + * + * Triggers the refresh of the data in the Diagram, for all pages. + * + * [Api set: 1.1] + */ + startDataRefresh(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.DocumentLoadOptions): Visio.Document; + load(option?: string | string[]): Visio.Document; + load(option?: { + select?: string; + expand?: string; + }): Visio.Document; + /** + * + * Occurs when the data is refreshed in the diagram. + * + * [Api set: 1.1] + */ + readonly onDataRefreshComplete: OfficeExtension.EventHandlers; + /** + * + * Occurs when the Document is loaded, refreshed, or changed. + * + * [Api set: 1.1] + */ + readonly onDocumentLoadComplete: OfficeExtension.EventHandlers; + /** + * + * Occurs when the page is finished loading. + * + * [Api set: 1.1] + */ + readonly onPageLoadComplete: OfficeExtension.EventHandlers; + /** + * + * Occurs when the current selection of shapes changes. + * + * [Api set: 1.1] + */ + readonly onSelectionChanged: OfficeExtension.EventHandlers; + /** + * + * Occurs when the user moves the mouse pointer into the bounding box of a shape. + * + * [Api set: 1.1] + */ + readonly onShapeMouseEnter: OfficeExtension.EventHandlers; + /** + * + * Occurs when the user moves the mouse out of the bounding box of a shape. + * + * [Api set: 1.1] + */ + readonly onShapeMouseLeave: OfficeExtension.EventHandlers; + toJSON(): Visio.Interfaces.DocumentData; + } + /** + * + * Represents the DocumentView class. + * + * [Api set: 1.1] + */ + class DocumentView extends OfficeExtension.ClientObject { + /** + * + * Disable Hyperlinks. + * + * [Api set: 1.1] + */ + disableHyperlinks: boolean; + /** + * + * Disable Pan. + * + * [Api set: 1.1] + */ + disablePan: boolean; + /** + * + * Disable Zoom. + * + * [Api set: 1.1] + */ + disableZoom: boolean; + /** + * + * Disable Hyperlinks. + * + * [Api set: 1.1] + */ + hideDiagramBoundary: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.DocumentViewUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: DocumentView): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.DocumentViewLoadOptions): Visio.DocumentView; + load(option?: string | string[]): Visio.DocumentView; + load(option?: { + select?: string; + expand?: string; + }): Visio.DocumentView; + toJSON(): Visio.Interfaces.DocumentViewData; + } + /** + * + * Represents the Page class. + * + * [Api set: 1.1] + */ + class Page extends OfficeExtension.ClientObject { + /** + * + * All shapes in the page. Read-only. + * + * [Api set: 1.1] + */ + readonly allShapes: Visio.ShapeCollection; + /** + * + * Returns the Comments Collection + * + * [Api set: 1.1] + */ + readonly comments: Visio.CommentCollection; + /** + * + * Shapes at root level, in the page. Read-only. + * + * [Api set: 1.1] + */ + readonly shapes: Visio.ShapeCollection; + /** + * + * Returns the view of the page. Read-only. + * + * [Api set: 1.1] + */ + readonly view: Visio.PageView; + /** + * + * Returns the height of the page. Read-only. + * + * [Api set: 1.1] + */ + readonly height: number; + /** + * + * Index of the Page. + * + * [Api set: 1.1] + */ + readonly index: number; + /** + * + * Whether the page is a background page or not. Read-only. + * + * [Api set: 1.1] + */ + readonly isBackground: boolean; + /** + * + * Page name. Read-only. + * + * [Api set: 1.1] + */ + readonly name: string; + /** + * + * Returns the width of the page. Read-only. + * + * [Api set: 1.1] + */ + readonly width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.PageUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Page): void; + /** + * + * Set the page as Active Page of the document. + * + * [Api set: 1.1] + */ + activate(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.PageLoadOptions): Visio.Page; + load(option?: string | string[]): Visio.Page; + load(option?: { + select?: string; + expand?: string; + }): Visio.Page; + toJSON(): Visio.Interfaces.PageData; + } + /** + * + * Represents the PageView class. + * + * [Api set: 1.1] + */ + class PageView extends OfficeExtension.ClientObject { + /** + * + * Get/Set Page's Zoom level. The value can be between 10 and 400 and denotes the percentage of zoom. + * + * [Api set: 1.1] + */ + zoom: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.PageViewUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: PageView): void; + /** + * + * Pans the Visio drawing to place the specified shape in the center of the view. + * + * [Api set: 1.1] + * + * @param ShapeId ShapeId to be seen in the center. + */ + centerViewportOnShape(ShapeId: number): void; + /** + * + * Fit Page to current window. + * + * [Api set: 1.1] + */ + fitToWindow(): void; + /** + * + * Returns the position object that specifies the position of the page in the view. + * + * [Api set: 1.1] + */ + getPosition(): OfficeExtension.ClientResult; + /** + * + * Represents the Selection in the page. + * + * [Api set: 1.1] + */ + getSelection(): Visio.Selection; + /** + * + * To check if the shape is in view of the page or not. + * + * [Api set: 1.1] + * + * @param Shape Shape to be checked. + */ + isShapeInViewport(Shape: Visio.Shape): OfficeExtension.ClientResult; + /** + * + * Sets the position of the page in the view. + * + * [Api set: 1.1] + * + * @param Position Position object that specifies the new position of the page in the view. + */ + setPosition(Position: Visio.Position): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.PageViewLoadOptions): Visio.PageView; + load(option?: string | string[]): Visio.PageView; + load(option?: { + select?: string; + expand?: string; + }): Visio.PageView; + toJSON(): Visio.Interfaces.PageViewData; + } + /** + * + * Represents a collection of Page objects that are part of the document. + * + * [Api set: 1.1] + */ + class PageCollection extends OfficeExtension.ClientObject { + /** Gets the loaded child items in this collection. */ + readonly items: Array; + /** + * + * Gets the number of pages in the collection. + * + * [Api set: 1.1] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Gets a page using its key (name or Id). + * + * [Api set: 1.1] + * + * @param key Key is the name or Id of the page to be retrieved. + */ + getItem(key: number | string): Visio.Page; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.PageCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.PageCollection; + load(option?: string | string[]): Visio.PageCollection; + load(option?: OfficeExtension.LoadOption): Visio.PageCollection; + toJSON(): Visio.Interfaces.PageCollectionData; + } + /** + * + * Represents the Shape Collection. + * + * [Api set: 1.1] + */ + class ShapeCollection extends OfficeExtension.ClientObject { + /** Gets the loaded child items in this collection. */ + readonly items: Array; + /** + * + * Gets the number of Shapes in the collection. + * + * [Api set: 1.1] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Gets a Shape using its key (name or Index). + * + * [Api set: 1.1] + * + * @param key Key is the Name or Index of the shape to be retrieved. + */ + getItem(key: number | string): Visio.Shape; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.ShapeCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.ShapeCollection; + load(option?: string | string[]): Visio.ShapeCollection; + load(option?: OfficeExtension.LoadOption): Visio.ShapeCollection; + toJSON(): Visio.Interfaces.ShapeCollectionData; + } + /** + * + * Represents the Shape class. + * + * [Api set: 1.1] + */ + class Shape extends OfficeExtension.ClientObject { + /** + * + * Returns the Comments Collection + * + * [Api set: 1.1] + */ + readonly comments: Visio.CommentCollection; + /** + * + * Returns the Hyperlinks collection for a Shape object. Read-only. + * + * [Api set: 1.1] + */ + readonly hyperlinks: Visio.HyperlinkCollection; + /** + * + * Returns the Shape's Data Section. Read-only. + * + * [Api set: 1.1] + */ + readonly shapeDataItems: Visio.ShapeDataItemCollection; + /** + * + * Gets SubShape Collection. + * + * [Api set: 1.1] + */ + readonly subShapes: Visio.ShapeCollection; + /** + * + * Returns the view of the shape. Read-only. + * + * [Api set: 1.1] + */ + readonly view: Visio.ShapeView; + /** + * + * Shape's Identifier. + * + * [Api set: 1.1] + */ + readonly id: number; + /** + * + * Shape's name. + * + * [Api set: 1.1] + */ + readonly name: string; + /** + * + * Returns true, if shape is selected. User can set true to select the shape explicitly. + * + * [Api set: 1.1] + */ + select: boolean; + /** + * + * Shape's Text. + * + * [Api set: 1.1] + */ + readonly text: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ShapeUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Shape): void; + /** + * + * Returns the BoundingBox object that specifies bounding box of the shape. + * + * [Api set: 1.1] + */ + getBounds(): OfficeExtension.ClientResult; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.ShapeLoadOptions): Visio.Shape; + load(option?: string | string[]): Visio.Shape; + load(option?: { + select?: string; + expand?: string; + }): Visio.Shape; + toJSON(): Visio.Interfaces.ShapeData; + } + /** + * + * Represents the ShapeView class. + * + * [Api set: 1.1] + */ + class ShapeView extends OfficeExtension.ClientObject { + /** + * + * Represents the highlight around the shape. + * + * [Api set: 1.1] + */ + highlight: Visio.Highlight; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ShapeViewUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ShapeView): void; + /** + * + * Adds an overlay on top of the shape. + * + * [Api set: 1.1] + * + * @param OverlayType An Overlay Type -Text, Image. + * @param Content Content of Overlay. + * @param OverlayHorizontalAlignment Horizontal Alignment of Overlay - Left, Center, Right + * @param OverlayVerticalAlignment Vertical Alignment of Overlay - Top, Middle, Bottom + * @param Width Overlay Width. + * @param Height Overlay Height. + */ + addOverlay(OverlayType: string, Content: string, OverlayHorizontalAlignment: string, OverlayVerticalAlignment: string, Width: number, Height: number): OfficeExtension.ClientResult; + /** + * + * Removes particular overlay or all overlays on the Shape. + * + * [Api set: 1.1] + * + * @param OverlayId An Overlay Id. Removes the specific overlay id from the shape. + */ + removeOverlay(OverlayId: number): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.ShapeViewLoadOptions): Visio.ShapeView; + load(option?: string | string[]): Visio.ShapeView; + load(option?: { + select?: string; + expand?: string; + }): Visio.ShapeView; + toJSON(): Visio.Interfaces.ShapeViewData; + } + /** + * + * Represents the Position of the object in the view. + * + * [Api set: 1.1] + */ + interface Position { + /** + * + * An integer that specifies the x-coordinate of the object, which is the signed value of the distance in pixels from the viewport's center to the left boundary of the page. + * + * [Api set: 1.1] + */ + x: number; + /** + * + * An integer that specifies the y-coordinate of the object, which is the signed value of the distance in pixels from the viewport's center to the top boundary of the page. + * + * [Api set: 1.1] + */ + y: number; + } + /** + * + * Represents the BoundingBox of the shape. + * + * [Api set: 1.1] + */ + interface BoundingBox { + /** + * + * The distance between the top and bottom edges of the bounding box of the shape, excluding any data graphics associated with the shape. + * + * [Api set: 1.1] + */ + height: number; + /** + * + * The distance between the left and right edges of the bounding box of the shape, excluding any data graphics associated with the shape. + * + * [Api set: 1.1] + */ + width: number; + /** + * + * An integer that specifies the x-coordinate of the bounding box. + * + * [Api set: 1.1] + */ + x: number; + /** + * + * An integer that specifies the y-coordinate of the bounding box. + * + * [Api set: 1.1] + */ + y: number; + } + /** + * + * Represents the highlight data added to the shape. + * + * [Api set: 1.1] + */ + interface Highlight { + /** + * + * A string that specifies the color of the highlight. It must have the form "#RRGGBB", where each letter represents a hexadecimal digit between 0 and F, and where RR is the red value between 0 and 0xFF (255), GG the green value between 0 and 0xFF (255), and BB is the blue value between 0 and 0xFF (255). + * + * [Api set: 1.1] + */ + color: string; + /** + * + * A positive integer that specifies the width of the highlight's stroke in pixels. + * + * [Api set: 1.1] + */ + width: number; + } + /** + * + * Represents the ShapeDataItemCollection for a given Shape. + * + * [Api set: 1.1] + */ + class ShapeDataItemCollection extends OfficeExtension.ClientObject { + /** Gets the loaded child items in this collection. */ + readonly items: Array; + /** + * + * Gets the number of Shape Data Items. + * + * [Api set: 1.1] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Gets the ShapeDataItem using its name. + * + * [Api set: 1.1] + * + * @param key Key is the name of the ShapeDataItem to be retrieved. + */ + getItem(key: string): Visio.ShapeDataItem; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.ShapeDataItemCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.ShapeDataItemCollection; + load(option?: string | string[]): Visio.ShapeDataItemCollection; + load(option?: OfficeExtension.LoadOption): Visio.ShapeDataItemCollection; + toJSON(): Visio.Interfaces.ShapeDataItemCollectionData; + } + /** + * + * Represents the ShapeDataItem. + * + * [Api set: 1.1] + */ + class ShapeDataItem extends OfficeExtension.ClientObject { + /** + * + * A string that specifies the format of the shape data item. + * + * [Api set: 1.1] + */ + readonly format: string; + /** + * + * A string that specifies the formatted value of the shape data item. + * + * [Api set: 1.1] + */ + readonly formattedValue: string; + /** + * + * A string that specifies the label of the shape data item. + * + * [Api set: 1.1] + */ + readonly label: string; + /** + * + * A string that specifies the value of the shape data item. + * + * [Api set: 1.1] + */ + readonly value: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.ShapeDataItemLoadOptions): Visio.ShapeDataItem; + load(option?: string | string[]): Visio.ShapeDataItem; + load(option?: { + select?: string; + expand?: string; + }): Visio.ShapeDataItem; + toJSON(): Visio.Interfaces.ShapeDataItemData; + } + /** + * + * Represents the Hyperlink Collection. + * + * [Api set: 1.1] + */ + class HyperlinkCollection extends OfficeExtension.ClientObject { + /** Gets the loaded child items in this collection. */ + readonly items: Array; + /** + * + * Gets the number of hyperlinks. + * + * [Api set: 1.1] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Gets a Hyperlink using its key (name or Id). + * + * [Api set: 1.1] + * + * @param Key Key is the name or index of the Hyperlink to be retrieved. + */ + getItem(Key: number | string): Visio.Hyperlink; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.HyperlinkCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.HyperlinkCollection; + load(option?: string | string[]): Visio.HyperlinkCollection; + load(option?: OfficeExtension.LoadOption): Visio.HyperlinkCollection; + toJSON(): Visio.Interfaces.HyperlinkCollectionData; + } + /** + * + * Represents the Hyperlink. + * + * [Api set: 1.1] + */ + class Hyperlink extends OfficeExtension.ClientObject { + /** + * + * Gets the address of the Hyperlink object. + * + * [Api set: 1.1] + */ + readonly address: string; + /** + * + * Gets the description of a hyperlink. + * + * [Api set: 1.1] + */ + readonly description: string; + /** + * + * Gets the extra info of a hyperlink. + * + * [Api set: 1.1] + */ + readonly extraInfo: string; + /** + * + * Gets the sub-address of the Hyperlink object. + * + * [Api set: 1.1] + */ + readonly subAddress: string; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.HyperlinkLoadOptions): Visio.Hyperlink; + load(option?: string | string[]): Visio.Hyperlink; + load(option?: { + select?: string; + expand?: string; + }): Visio.Hyperlink; + toJSON(): Visio.Interfaces.HyperlinkData; + } + /** + * + * Represents the CommentCollection for a given Shape. + * + * [Api set: 1.1] + */ + class CommentCollection extends OfficeExtension.ClientObject { + /** Gets the loaded child items in this collection. */ + readonly items: Array; + /** + * + * Gets the number of Shape Data Items. + * + * [Api set: 1.1] + */ + getCount(): OfficeExtension.ClientResult; + /** + * + * Gets the Comment using its name. + * + * [Api set: 1.1] + * + * @param key Key is the name of the Comment to be retrieved. + */ + getItem(key: string): Visio.Comment; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.CommentCollectionLoadOptions & Visio.Interfaces.CollectionLoadOptions): Visio.CommentCollection; + load(option?: string | string[]): Visio.CommentCollection; + load(option?: OfficeExtension.LoadOption): Visio.CommentCollection; + toJSON(): Visio.Interfaces.CommentCollectionData; + } + /** + * + * Represents the Comment. + * + * [Api set: 1.1] + */ + class Comment extends OfficeExtension.ClientObject { + /** + * + * A string that specifies the label of the shape data item. + * + * [Api set: 1.1] + */ + author: string; + /** + * + * A string that specifies the format of the shape data item. + * + * [Api set: 1.1] + */ + date: string; + /** + * + * A string that specifies the value of the shape data item. + * + * [Api set: 1.1] + */ + text: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.CommentUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Comment): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: Visio.Interfaces.CommentLoadOptions): Visio.Comment; + load(option?: string | string[]): Visio.Comment; + load(option?: { + select?: string; + expand?: string; + }): Visio.Comment; + toJSON(): Visio.Interfaces.CommentData; + } + /** + * + * Represents the Selection in the page. + * + * [Api set: 1.1] + */ + class Selection extends OfficeExtension.ClientObject { + /** + * + * Gets the Shapes of the Selection + * + * [Api set: 1.1] + */ + readonly shapes: Visio.ShapeCollection; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[]): Visio.Selection; + load(option?: { + select?: string; + expand?: string; + }): Visio.Selection; + toJSON(): Visio.Interfaces.SelectionData; + } + /** + * + * Represents the Horizontal Alignment of the Overlay relative to the shape. + * + * [Api set: 1.1] + */ + namespace OverlayHorizontalAlignment { + /** + * + * left + * + */ + var left: string; + /** + * + * center + * + */ + var center: string; + /** + * + * right + * + */ + var right: string; + } + /** + * + * Represents the Vertical Alignment of the Overlay relative to the shape. + * + * [Api set: 1.1] + */ + namespace OverlayVerticalAlignment { + /** + * + * top + * + */ + var top: string; + /** + * + * middle + * + */ + var middle: string; + /** + * + * bottom + * + */ + var bottom: string; + } + /** + * + * Represents the type of the overlay. + * + * [Api set: 1.1] + */ + namespace OverlayType { + /** + * + * text + * + */ + var text: string; + /** + * + * image + * + */ + var image: string; + } + /** + * + * Toolbar IDs of the app + * + * [Api set: 1.1] + */ + namespace ToolBarType { + /** + * + * CommandBar + * + */ + var commandBar: string; + /** + * + * PageNavigationBar + * + */ + var pageNavigationBar: string; + /** + * + * StatusBar + * + */ + var statusBar: string; + } + namespace ErrorCodes { + var accessDenied: string; + var generalException: string; + var invalidArgument: string; + var itemNotFound: string; + var notImplemented: string; + var unsupportedOperation: string; + } + module Interfaces { + interface CollectionLoadOptions { + $top?: number; + $skip?: number; + } + /** An interface for updating data on the Application object, for use in "application.set({ ... })". */ + interface ApplicationUpdateData { + /** + * + * Show/Hide the application borders. + * + * [Api set: 1.1] + */ + showBorders?: boolean; + /** + * + * Show or Hide the standard toolbars. + * + * [Api set: 1.1] + */ + showToolbars?: boolean; + } + /** An interface for updating data on the Document object, for use in "document.set({ ... })". */ + interface DocumentUpdateData { + /** + * + * Represents a Visio application instance that contains this document. + * + * [Api set: 1.1] + */ + application?: Visio.Interfaces.ApplicationUpdateData; + /** + * + * Returns the DocumentView object. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.DocumentViewUpdateData; + } + /** An interface for updating data on the DocumentView object, for use in "documentView.set({ ... })". */ + interface DocumentViewUpdateData { + /** + * + * Disable Hyperlinks. + * + * [Api set: 1.1] + */ + disableHyperlinks?: boolean; + /** + * + * Disable Pan. + * + * [Api set: 1.1] + */ + disablePan?: boolean; + /** + * + * Disable Zoom. + * + * [Api set: 1.1] + */ + disableZoom?: boolean; + /** + * + * Disable Hyperlinks. + * + * [Api set: 1.1] + */ + hideDiagramBoundary?: boolean; + } + /** An interface for updating data on the Page object, for use in "page.set({ ... })". */ + interface PageUpdateData { + /** + * + * Returns the view of the page. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.PageViewUpdateData; + } + /** An interface for updating data on the PageView object, for use in "pageView.set({ ... })". */ + interface PageViewUpdateData { + /** + * + * Get/Set Page's Zoom level. The value can be between 10 and 400 and denotes the percentage of zoom. + * + * [Api set: 1.1] + */ + zoom?: number; + } + /** An interface for updating data on the PageCollection object, for use in "pageCollection.set({ ... })". */ + interface PageCollectionUpdateData { + items?: Visio.Interfaces.PageData[]; + } + /** An interface for updating data on the ShapeCollection object, for use in "shapeCollection.set({ ... })". */ + interface ShapeCollectionUpdateData { + items?: Visio.Interfaces.ShapeData[]; + } + /** An interface for updating data on the Shape object, for use in "shape.set({ ... })". */ + interface ShapeUpdateData { + /** + * + * Returns the view of the shape. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.ShapeViewUpdateData; + /** + * + * Returns true, if shape is selected. User can set true to select the shape explicitly. + * + * [Api set: 1.1] + */ + select?: boolean; + } + /** An interface for updating data on the ShapeView object, for use in "shapeView.set({ ... })". */ + interface ShapeViewUpdateData { + /** + * + * Represents the highlight around the shape. + * + * [Api set: 1.1] + */ + highlight?: Visio.Highlight; + } + /** An interface for updating data on the ShapeDataItemCollection object, for use in "shapeDataItemCollection.set({ ... })". */ + interface ShapeDataItemCollectionUpdateData { + items?: Visio.Interfaces.ShapeDataItemData[]; + } + /** An interface for updating data on the HyperlinkCollection object, for use in "hyperlinkCollection.set({ ... })". */ + interface HyperlinkCollectionUpdateData { + items?: Visio.Interfaces.HyperlinkData[]; + } + /** An interface for updating data on the CommentCollection object, for use in "commentCollection.set({ ... })". */ + interface CommentCollectionUpdateData { + items?: Visio.Interfaces.CommentData[]; + } + /** An interface for updating data on the Comment object, for use in "comment.set({ ... })". */ + interface CommentUpdateData { + /** + * + * A string that specifies the label of the shape data item. + * + * [Api set: 1.1] + */ + author?: string; + /** + * + * A string that specifies the format of the shape data item. + * + * [Api set: 1.1] + */ + date?: string; + /** + * + * A string that specifies the value of the shape data item. + * + * [Api set: 1.1] + */ + text?: string; + } + /** An interface describing the data returned by calling "application.toJSON()". */ + interface ApplicationData { + /** + * + * Show/Hide the application borders. + * + * [Api set: 1.1] + */ + showBorders?: boolean; + /** + * + * Show or Hide the standard toolbars. + * + * [Api set: 1.1] + */ + showToolbars?: boolean; + } + /** An interface describing the data returned by calling "document.toJSON()". */ + interface DocumentData { + /** + * + * Represents a Visio application instance that contains this document. Read-only. + * + * [Api set: 1.1] + */ + application?: Visio.Interfaces.ApplicationData; + /** + * + * Represents a collection of pages associated with the document. Read-only. + * + * [Api set: 1.1] + */ + pages?: Visio.Interfaces.PageData[]; + /** + * + * Returns the DocumentView object. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.DocumentViewData; + } + /** An interface describing the data returned by calling "documentView.toJSON()". */ + interface DocumentViewData { + /** + * + * Disable Hyperlinks. + * + * [Api set: 1.1] + */ + disableHyperlinks?: boolean; + /** + * + * Disable Pan. + * + * [Api set: 1.1] + */ + disablePan?: boolean; + /** + * + * Disable Zoom. + * + * [Api set: 1.1] + */ + disableZoom?: boolean; + /** + * + * Disable Hyperlinks. + * + * [Api set: 1.1] + */ + hideDiagramBoundary?: boolean; + } + /** An interface describing the data returned by calling "page.toJSON()". */ + interface PageData { + /** + * + * All shapes in the page. Read-only. + * + * [Api set: 1.1] + */ + allShapes?: Visio.Interfaces.ShapeData[]; + /** + * + * Returns the Comments Collection + * + * [Api set: 1.1] + */ + comments?: Visio.Interfaces.CommentData[]; + /** + * + * Shapes at root level, in the page. Read-only. + * + * [Api set: 1.1] + */ + shapes?: Visio.Interfaces.ShapeData[]; + /** + * + * Returns the view of the page. Read-only. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.PageViewData; + /** + * + * Returns the height of the page. Read-only. + * + * [Api set: 1.1] + */ + height?: number; + /** + * + * Index of the Page. + * + * [Api set: 1.1] + */ + index?: number; + /** + * + * Whether the page is a background page or not. Read-only. + * + * [Api set: 1.1] + */ + isBackground?: boolean; + /** + * + * Page name. Read-only. + * + * [Api set: 1.1] + */ + name?: string; + /** + * + * Returns the width of the page. Read-only. + * + * [Api set: 1.1] + */ + width?: number; + } + /** An interface describing the data returned by calling "pageView.toJSON()". */ + interface PageViewData { + /** + * + * Get/Set Page's Zoom level. The value can be between 10 and 400 and denotes the percentage of zoom. + * + * [Api set: 1.1] + */ + zoom?: number; + } + /** An interface describing the data returned by calling "pageCollection.toJSON()". */ + interface PageCollectionData { + items?: Visio.Interfaces.PageData[]; + } + /** An interface describing the data returned by calling "shapeCollection.toJSON()". */ + interface ShapeCollectionData { + items?: Visio.Interfaces.ShapeData[]; + } + /** An interface describing the data returned by calling "shape.toJSON()". */ + interface ShapeData { + /** + * + * Returns the Comments Collection + * + * [Api set: 1.1] + */ + comments?: Visio.Interfaces.CommentData[]; + /** + * + * Returns the Hyperlinks collection for a Shape object. Read-only. + * + * [Api set: 1.1] + */ + hyperlinks?: Visio.Interfaces.HyperlinkData[]; + /** + * + * Returns the Shape's Data Section. Read-only. + * + * [Api set: 1.1] + */ + shapeDataItems?: Visio.Interfaces.ShapeDataItemData[]; + /** + * + * Gets SubShape Collection. + * + * [Api set: 1.1] + */ + subShapes?: Visio.Interfaces.ShapeData[]; + /** + * + * Returns the view of the shape. Read-only. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.ShapeViewData; + /** + * + * Shape's Identifier. + * + * [Api set: 1.1] + */ + id?: number; + /** + * + * Shape's name. + * + * [Api set: 1.1] + */ + name?: string; + /** + * + * Returns true, if shape is selected. User can set true to select the shape explicitly. + * + * [Api set: 1.1] + */ + select?: boolean; + /** + * + * Shape's Text. + * + * [Api set: 1.1] + */ + text?: string; + } + /** An interface describing the data returned by calling "shapeView.toJSON()". */ + interface ShapeViewData { + /** + * + * Represents the highlight around the shape. + * + * [Api set: 1.1] + */ + highlight?: Visio.Highlight; + } + /** An interface describing the data returned by calling "shapeDataItemCollection.toJSON()". */ + interface ShapeDataItemCollectionData { + items?: Visio.Interfaces.ShapeDataItemData[]; + } + /** An interface describing the data returned by calling "shapeDataItem.toJSON()". */ + interface ShapeDataItemData { + /** + * + * A string that specifies the format of the shape data item. + * + * [Api set: 1.1] + */ + format?: string; + /** + * + * A string that specifies the formatted value of the shape data item. + * + * [Api set: 1.1] + */ + formattedValue?: string; + /** + * + * A string that specifies the label of the shape data item. + * + * [Api set: 1.1] + */ + label?: string; + /** + * + * A string that specifies the value of the shape data item. + * + * [Api set: 1.1] + */ + value?: string; + } + /** An interface describing the data returned by calling "hyperlinkCollection.toJSON()". */ + interface HyperlinkCollectionData { + items?: Visio.Interfaces.HyperlinkData[]; + } + /** An interface describing the data returned by calling "hyperlink.toJSON()". */ + interface HyperlinkData { + /** + * + * Gets the address of the Hyperlink object. + * + * [Api set: 1.1] + */ + address?: string; + /** + * + * Gets the description of a hyperlink. + * + * [Api set: 1.1] + */ + description?: string; + /** + * + * Gets the extra info of a hyperlink. + * + * [Api set: 1.1] + */ + extraInfo?: string; + /** + * + * Gets the sub-address of the Hyperlink object. + * + * [Api set: 1.1] + */ + subAddress?: string; + } + /** An interface describing the data returned by calling "commentCollection.toJSON()". */ + interface CommentCollectionData { + items?: Visio.Interfaces.CommentData[]; + } + /** An interface describing the data returned by calling "comment.toJSON()". */ + interface CommentData { + /** + * + * A string that specifies the label of the shape data item. + * + * [Api set: 1.1] + */ + author?: string; + /** + * + * A string that specifies the format of the shape data item. + * + * [Api set: 1.1] + */ + date?: string; + /** + * + * A string that specifies the value of the shape data item. + * + * [Api set: 1.1] + */ + text?: string; + } + /** An interface describing the data returned by calling "selection.toJSON()". */ + interface SelectionData { + /** + * + * Gets the Shapes of the Selection + * + * [Api set: 1.1] + */ + shapes?: Visio.Interfaces.ShapeData[]; + } + /** + * + * Represents the Application. + * + * [Api set: 1.1] + */ + interface ApplicationLoadOptions { + $all?: boolean; + /** + * + * Show/Hide the application borders. + * + * [Api set: 1.1] + */ + showBorders?: boolean; + /** + * + * Show or Hide the standard toolbars. + * + * [Api set: 1.1] + */ + showToolbars?: boolean; + } + /** + * + * Represents the Document class. + * + * [Api set: 1.1] + */ + interface DocumentLoadOptions { + $all?: boolean; + /** + * + * Represents a Visio application instance that contains this document. + * + * [Api set: 1.1] + */ + application?: Visio.Interfaces.ApplicationLoadOptions; + /** + * + * Returns the DocumentView object. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.DocumentViewLoadOptions; + } + /** + * + * Represents the DocumentView class. + * + * [Api set: 1.1] + */ + interface DocumentViewLoadOptions { + $all?: boolean; + /** + * + * Disable Hyperlinks. + * + * [Api set: 1.1] + */ + disableHyperlinks?: boolean; + /** + * + * Disable Pan. + * + * [Api set: 1.1] + */ + disablePan?: boolean; + /** + * + * Disable Zoom. + * + * [Api set: 1.1] + */ + disableZoom?: boolean; + /** + * + * Disable Hyperlinks. + * + * [Api set: 1.1] + */ + hideDiagramBoundary?: boolean; + } + /** + * + * Represents the Page class. + * + * [Api set: 1.1] + */ + interface PageLoadOptions { + $all?: boolean; + /** + * + * Returns the view of the page. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.PageViewLoadOptions; + /** + * + * Returns the height of the page. Read-only. + * + * [Api set: 1.1] + */ + height?: boolean; + /** + * + * Index of the Page. + * + * [Api set: 1.1] + */ + index?: boolean; + /** + * + * Whether the page is a background page or not. Read-only. + * + * [Api set: 1.1] + */ + isBackground?: boolean; + /** + * + * Page name. Read-only. + * + * [Api set: 1.1] + */ + name?: boolean; + /** + * + * Returns the width of the page. Read-only. + * + * [Api set: 1.1] + */ + width?: boolean; + } + /** + * + * Represents the PageView class. + * + * [Api set: 1.1] + */ + interface PageViewLoadOptions { + $all?: boolean; + /** + * + * Get/Set Page's Zoom level. The value can be between 10 and 400 and denotes the percentage of zoom. + * + * [Api set: 1.1] + */ + zoom?: boolean; + } + /** + * + * Represents a collection of Page objects that are part of the document. + * + * [Api set: 1.1] + */ + interface PageCollectionLoadOptions { + $all?: boolean; + /** + * + * For EACH ITEM in the collection: Returns the view of the page. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.PageViewLoadOptions; + /** + * + * For EACH ITEM in the collection: Returns the height of the page. Read-only. + * + * [Api set: 1.1] + */ + height?: boolean; + /** + * + * For EACH ITEM in the collection: Index of the Page. + * + * [Api set: 1.1] + */ + index?: boolean; + /** + * + * For EACH ITEM in the collection: Whether the page is a background page or not. Read-only. + * + * [Api set: 1.1] + */ + isBackground?: boolean; + /** + * + * For EACH ITEM in the collection: Page name. Read-only. + * + * [Api set: 1.1] + */ + name?: boolean; + /** + * + * For EACH ITEM in the collection: Returns the width of the page. Read-only. + * + * [Api set: 1.1] + */ + width?: boolean; + } + /** + * + * Represents the Shape Collection. + * + * [Api set: 1.1] + */ + interface ShapeCollectionLoadOptions { + $all?: boolean; + /** + * + * For EACH ITEM in the collection: Returns the view of the shape. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.ShapeViewLoadOptions; + /** + * + * For EACH ITEM in the collection: Shape's Identifier. + * + * [Api set: 1.1] + */ + id?: boolean; + /** + * + * For EACH ITEM in the collection: Shape's name. + * + * [Api set: 1.1] + */ + name?: boolean; + /** + * + * For EACH ITEM in the collection: Returns true, if shape is selected. User can set true to select the shape explicitly. + * + * [Api set: 1.1] + */ + select?: boolean; + /** + * + * For EACH ITEM in the collection: Shape's Text. + * + * [Api set: 1.1] + */ + text?: boolean; + } + /** + * + * Represents the Shape class. + * + * [Api set: 1.1] + */ + interface ShapeLoadOptions { + $all?: boolean; + /** + * + * Returns the view of the shape. + * + * [Api set: 1.1] + */ + view?: Visio.Interfaces.ShapeViewLoadOptions; + /** + * + * Shape's Identifier. + * + * [Api set: 1.1] + */ + id?: boolean; + /** + * + * Shape's name. + * + * [Api set: 1.1] + */ + name?: boolean; + /** + * + * Returns true, if shape is selected. User can set true to select the shape explicitly. + * + * [Api set: 1.1] + */ + select?: boolean; + /** + * + * Shape's Text. + * + * [Api set: 1.1] + */ + text?: boolean; + } + /** + * + * Represents the ShapeView class. + * + * [Api set: 1.1] + */ + interface ShapeViewLoadOptions { + $all?: boolean; + /** + * + * Represents the highlight around the shape. + * + * [Api set: 1.1] + */ + highlight?: boolean; + } + /** + * + * Represents the ShapeDataItemCollection for a given Shape. + * + * [Api set: 1.1] + */ + interface ShapeDataItemCollectionLoadOptions { + $all?: boolean; + /** + * + * For EACH ITEM in the collection: A string that specifies the format of the shape data item. + * + * [Api set: 1.1] + */ + format?: boolean; + /** + * + * For EACH ITEM in the collection: A string that specifies the formatted value of the shape data item. + * + * [Api set: 1.1] + */ + formattedValue?: boolean; + /** + * + * For EACH ITEM in the collection: A string that specifies the label of the shape data item. + * + * [Api set: 1.1] + */ + label?: boolean; + /** + * + * For EACH ITEM in the collection: A string that specifies the value of the shape data item. + * + * [Api set: 1.1] + */ + value?: boolean; + } + /** + * + * Represents the ShapeDataItem. + * + * [Api set: 1.1] + */ + interface ShapeDataItemLoadOptions { + $all?: boolean; + /** + * + * A string that specifies the format of the shape data item. + * + * [Api set: 1.1] + */ + format?: boolean; + /** + * + * A string that specifies the formatted value of the shape data item. + * + * [Api set: 1.1] + */ + formattedValue?: boolean; + /** + * + * A string that specifies the label of the shape data item. + * + * [Api set: 1.1] + */ + label?: boolean; + /** + * + * A string that specifies the value of the shape data item. + * + * [Api set: 1.1] + */ + value?: boolean; + } + /** + * + * Represents the Hyperlink Collection. + * + * [Api set: 1.1] + */ + interface HyperlinkCollectionLoadOptions { + $all?: boolean; + /** + * + * For EACH ITEM in the collection: Gets the address of the Hyperlink object. + * + * [Api set: 1.1] + */ + address?: boolean; + /** + * + * For EACH ITEM in the collection: Gets the description of a hyperlink. + * + * [Api set: 1.1] + */ + description?: boolean; + /** + * + * For EACH ITEM in the collection: Gets the extra info of a hyperlink. + * + * [Api set: 1.1] + */ + extraInfo?: boolean; + /** + * + * For EACH ITEM in the collection: Gets the sub-address of the Hyperlink object. + * + * [Api set: 1.1] + */ + subAddress?: boolean; + } + /** + * + * Represents the Hyperlink. + * + * [Api set: 1.1] + */ + interface HyperlinkLoadOptions { + $all?: boolean; + /** + * + * Gets the address of the Hyperlink object. + * + * [Api set: 1.1] + */ + address?: boolean; + /** + * + * Gets the description of a hyperlink. + * + * [Api set: 1.1] + */ + description?: boolean; + /** + * + * Gets the extra info of a hyperlink. + * + * [Api set: 1.1] + */ + extraInfo?: boolean; + /** + * + * Gets the sub-address of the Hyperlink object. + * + * [Api set: 1.1] + */ + subAddress?: boolean; + } + /** + * + * Represents the CommentCollection for a given Shape. + * + * [Api set: 1.1] + */ + interface CommentCollectionLoadOptions { + $all?: boolean; + /** + * + * For EACH ITEM in the collection: A string that specifies the label of the shape data item. + * + * [Api set: 1.1] + */ + author?: boolean; + /** + * + * For EACH ITEM in the collection: A string that specifies the format of the shape data item. + * + * [Api set: 1.1] + */ + date?: boolean; + /** + * + * For EACH ITEM in the collection: A string that specifies the value of the shape data item. + * + * [Api set: 1.1] + */ + text?: boolean; + } + /** + * + * Represents the Comment. + * + * [Api set: 1.1] + */ + interface CommentLoadOptions { + $all?: boolean; + /** + * + * A string that specifies the label of the shape data item. + * + * [Api set: 1.1] + */ + author?: boolean; + /** + * + * A string that specifies the format of the shape data item. + * + * [Api set: 1.1] + */ + date?: boolean; + /** + * + * A string that specifies the value of the shape data item. + * + * [Api set: 1.1] + */ + text?: boolean; + } + } +} +declare module Visio { + /** + * The RequestContext object facilitates requests to the Visio application. Since the Office add-in and the Visio application run in two different processes, the request context is required to get access to the Visio object model from the add-in. + */ + class RequestContext extends OfficeExtension.ClientRequestContext { + constructor(url?: string | OfficeExtension.EmbeddedSession); + readonly document: Document; + } + /** + * Executes a batch script that performs actions on the Visio object model, using a new request context. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param batch - A function that takes in an Visio.RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Visio application. Since the Office add-in and the Visio application run in two different processes, the request context is required to get access to the Visio object model from the add-in. + */ + function run(batch: (context: Visio.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Visio object model, using the request context of a previously-created API object. + * @param object - A previously-created API object. The batch will use the same request context as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". + * @param batch - A function that takes in an Visio.RequestContext and returns a promise (typically, just the result of "context.sync()"). When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + */ + function run(object: OfficeExtension.ClientObject | OfficeExtension.EmbeddedSession, batch: (context: Visio.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Visio object model, using the RequestContext of a previously-created object. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param contextObject - A previously-created Visio.RequestContext. This context will get re-used by the batch function (instead of having a new context created). This means that the batch will be able to pick up changes made to existing API objects, if those objects were derived from this same context. + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Visio application. Since the Office add-in and the Visio application run in two different processes, the RequestContext is required to get access to the Visio object model from the add-in. + */ + function run(contextObject: OfficeExtension.ClientRequestContext, batch: (context: Visio.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Visio object model, using the request context of previously-created API objects. + * @param objects - An array of previously-created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared request context, which means that any changes applied to these objects will be picked up by "context.sync()". + * @param batch - A function that takes in a Visio.RequestContext and returns a promise (typically, just the result of "context.sync()"). When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + */ + function run(objects: OfficeExtension.ClientObject[], batch: (context: Visio.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; +} + + + +//////////////////////////////////////////////////////////////// +//////////////////////// End Visio APIs //////////////////////// +//////////////////////////////////////////////////////////////// diff --git a/types/ol/assertionerror/index.d.ts b/types/ol/assertionerror/index.d.ts new file mode 100644 index 0000000000..3585cd64da --- /dev/null +++ b/types/ol/assertionerror/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.AssertionError; diff --git a/types/ol/attribution/index.d.ts b/types/ol/attribution/index.d.ts new file mode 100644 index 0000000000..71eb87ff73 --- /dev/null +++ b/types/ol/attribution/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Attribution; diff --git a/types/ol/collection/index.d.ts b/types/ol/collection/index.d.ts new file mode 100644 index 0000000000..5943115188 --- /dev/null +++ b/types/ol/collection/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Collection; diff --git a/types/ol/color/index.d.ts b/types/ol/color/index.d.ts new file mode 100644 index 0000000000..92407b2fa4 --- /dev/null +++ b/types/ol/color/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.color; diff --git a/types/ol/colorlike/index.d.ts b/types/ol/colorlike/index.d.ts new file mode 100644 index 0000000000..5cf7ed88a8 --- /dev/null +++ b/types/ol/colorlike/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.colorlike; diff --git a/types/ol/control/attribution.d.ts b/types/ol/control/attribution.d.ts new file mode 100644 index 0000000000..9157d3ea5e --- /dev/null +++ b/types/ol/control/attribution.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.Attribution; diff --git a/types/ol/control/control.d.ts b/types/ol/control/control.d.ts new file mode 100644 index 0000000000..221bc895aa --- /dev/null +++ b/types/ol/control/control.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.Control; diff --git a/types/ol/control/fullscreen.d.ts b/types/ol/control/fullscreen.d.ts new file mode 100644 index 0000000000..5f0112dd06 --- /dev/null +++ b/types/ol/control/fullscreen.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.FullScreen; diff --git a/types/ol/control/index.d.ts b/types/ol/control/index.d.ts new file mode 100644 index 0000000000..551c3303d8 --- /dev/null +++ b/types/ol/control/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control; diff --git a/types/ol/control/mouseposition.d.ts b/types/ol/control/mouseposition.d.ts new file mode 100644 index 0000000000..f8d89d4dff --- /dev/null +++ b/types/ol/control/mouseposition.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.MousePosition; diff --git a/types/ol/control/overviewmap.d.ts b/types/ol/control/overviewmap.d.ts new file mode 100644 index 0000000000..60dd9b8900 --- /dev/null +++ b/types/ol/control/overviewmap.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.OverviewMap; diff --git a/types/ol/control/rotate.d.ts b/types/ol/control/rotate.d.ts new file mode 100644 index 0000000000..136db4ddeb --- /dev/null +++ b/types/ol/control/rotate.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.Rotate; diff --git a/types/ol/control/scaleline.d.ts b/types/ol/control/scaleline.d.ts new file mode 100644 index 0000000000..bbcad827f3 --- /dev/null +++ b/types/ol/control/scaleline.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.ScaleLine; diff --git a/types/ol/control/zoom.d.ts b/types/ol/control/zoom.d.ts new file mode 100644 index 0000000000..550d98c300 --- /dev/null +++ b/types/ol/control/zoom.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.Zoom; diff --git a/types/ol/control/zoomslider.d.ts b/types/ol/control/zoomslider.d.ts new file mode 100644 index 0000000000..4f5845939c --- /dev/null +++ b/types/ol/control/zoomslider.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.ZoomSlider; diff --git a/types/ol/control/zoomtoextent.d.ts b/types/ol/control/zoomtoextent.d.ts new file mode 100644 index 0000000000..d536325932 --- /dev/null +++ b/types/ol/control/zoomtoextent.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.control.ZoomToExtent; diff --git a/types/ol/coordinate/index.d.ts b/types/ol/coordinate/index.d.ts new file mode 100644 index 0000000000..9d95bc2f5b --- /dev/null +++ b/types/ol/coordinate/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.coordinate; diff --git a/types/ol/deviceorientation/index.d.ts b/types/ol/deviceorientation/index.d.ts new file mode 100644 index 0000000000..53ce703660 --- /dev/null +++ b/types/ol/deviceorientation/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.DeviceOrientation; diff --git a/types/ol/disposable/index.d.ts b/types/ol/disposable/index.d.ts new file mode 100644 index 0000000000..dd3aca2bff --- /dev/null +++ b/types/ol/disposable/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Disposable; diff --git a/types/ol/easing/index.d.ts b/types/ol/easing/index.d.ts new file mode 100644 index 0000000000..28e1552f42 --- /dev/null +++ b/types/ol/easing/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.easing; diff --git a/types/ol/events/condition.d.ts b/types/ol/events/condition.d.ts new file mode 100644 index 0000000000..bb43999775 --- /dev/null +++ b/types/ol/events/condition.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.events.condition; diff --git a/types/ol/events/event.d.ts b/types/ol/events/event.d.ts new file mode 100644 index 0000000000..5aefb9f530 --- /dev/null +++ b/types/ol/events/event.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.events.Event; diff --git a/types/ol/events/eventtarget.d.ts b/types/ol/events/eventtarget.d.ts new file mode 100644 index 0000000000..898b74ee65 --- /dev/null +++ b/types/ol/events/eventtarget.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.events.EventTarget; diff --git a/types/ol/events/index.d.ts b/types/ol/events/index.d.ts new file mode 100644 index 0000000000..defc980e5a --- /dev/null +++ b/types/ol/events/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.events; diff --git a/types/ol/extent/index.d.ts b/types/ol/extent/index.d.ts new file mode 100644 index 0000000000..a4c284b29e --- /dev/null +++ b/types/ol/extent/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.extent; diff --git a/types/ol/feature/index.d.ts b/types/ol/feature/index.d.ts new file mode 100644 index 0000000000..ba86ca0ad0 --- /dev/null +++ b/types/ol/feature/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Feature; diff --git a/types/ol/featureloader/index.d.ts b/types/ol/featureloader/index.d.ts new file mode 100644 index 0000000000..3d3d4a1105 --- /dev/null +++ b/types/ol/featureloader/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.featureloader; diff --git a/types/ol/format/esrijson.d.ts b/types/ol/format/esrijson.d.ts new file mode 100644 index 0000000000..5145422ade --- /dev/null +++ b/types/ol/format/esrijson.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.EsriJSON; diff --git a/types/ol/format/feature.d.ts b/types/ol/format/feature.d.ts new file mode 100644 index 0000000000..dc53e6709a --- /dev/null +++ b/types/ol/format/feature.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.Feature; diff --git a/types/ol/format/filter.d.ts b/types/ol/format/filter.d.ts new file mode 100644 index 0000000000..1fb2086477 --- /dev/null +++ b/types/ol/format/filter.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.filter; diff --git a/types/ol/format/geojson.d.ts b/types/ol/format/geojson.d.ts new file mode 100644 index 0000000000..d954287590 --- /dev/null +++ b/types/ol/format/geojson.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.GeoJSON; diff --git a/types/ol/format/gml2.d.ts b/types/ol/format/gml2.d.ts new file mode 100644 index 0000000000..95cdee80b7 --- /dev/null +++ b/types/ol/format/gml2.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.GML2; diff --git a/types/ol/format/gml3.d.ts b/types/ol/format/gml3.d.ts new file mode 100644 index 0000000000..416fc64c24 --- /dev/null +++ b/types/ol/format/gml3.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.GML3; diff --git a/types/ol/format/gmlbase.d.ts b/types/ol/format/gmlbase.d.ts new file mode 100644 index 0000000000..5d495bc5c0 --- /dev/null +++ b/types/ol/format/gmlbase.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.GMLBase; diff --git a/types/ol/format/gpx.d.ts b/types/ol/format/gpx.d.ts new file mode 100644 index 0000000000..3094e44275 --- /dev/null +++ b/types/ol/format/gpx.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.GPX; diff --git a/types/ol/format/igc.d.ts b/types/ol/format/igc.d.ts new file mode 100644 index 0000000000..d358419696 --- /dev/null +++ b/types/ol/format/igc.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.IGC; diff --git a/types/ol/format/jsonfeature.d.ts b/types/ol/format/jsonfeature.d.ts new file mode 100644 index 0000000000..cf76949b70 --- /dev/null +++ b/types/ol/format/jsonfeature.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.JSONFeature; diff --git a/types/ol/format/kml.d.ts b/types/ol/format/kml.d.ts new file mode 100644 index 0000000000..6f45f45005 --- /dev/null +++ b/types/ol/format/kml.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.KML; diff --git a/types/ol/format/mvt.d.ts b/types/ol/format/mvt.d.ts new file mode 100644 index 0000000000..857aaea5e7 --- /dev/null +++ b/types/ol/format/mvt.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.MVT; diff --git a/types/ol/format/osmxml.d.ts b/types/ol/format/osmxml.d.ts new file mode 100644 index 0000000000..67029aa020 --- /dev/null +++ b/types/ol/format/osmxml.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.OSMXML; diff --git a/types/ol/format/polyline.d.ts b/types/ol/format/polyline.d.ts new file mode 100644 index 0000000000..6c60d844c3 --- /dev/null +++ b/types/ol/format/polyline.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.Polyline; diff --git a/types/ol/format/textfeature.d.ts b/types/ol/format/textfeature.d.ts new file mode 100644 index 0000000000..13c50b8f80 --- /dev/null +++ b/types/ol/format/textfeature.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.TextFeature; diff --git a/types/ol/format/topojson.d.ts b/types/ol/format/topojson.d.ts new file mode 100644 index 0000000000..af1258d5a2 --- /dev/null +++ b/types/ol/format/topojson.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.TopoJSON; diff --git a/types/ol/format/wfs.d.ts b/types/ol/format/wfs.d.ts new file mode 100644 index 0000000000..b2ee31971a --- /dev/null +++ b/types/ol/format/wfs.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.WFS; diff --git a/types/ol/format/wkt.d.ts b/types/ol/format/wkt.d.ts new file mode 100644 index 0000000000..68bfbee10f --- /dev/null +++ b/types/ol/format/wkt.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.WKT; diff --git a/types/ol/format/wmscapabilities.d.ts b/types/ol/format/wmscapabilities.d.ts new file mode 100644 index 0000000000..c727c689c6 --- /dev/null +++ b/types/ol/format/wmscapabilities.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.WMSCapabilities; diff --git a/types/ol/format/wmsgetfeatureinfo.d.ts b/types/ol/format/wmsgetfeatureinfo.d.ts new file mode 100644 index 0000000000..6aaffa7b5e --- /dev/null +++ b/types/ol/format/wmsgetfeatureinfo.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.WMSGetFeatureInfo; diff --git a/types/ol/format/wmtscapabilities.d.ts b/types/ol/format/wmtscapabilities.d.ts new file mode 100644 index 0000000000..c17cdf8f2d --- /dev/null +++ b/types/ol/format/wmtscapabilities.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.WMTSCapabilities; diff --git a/types/ol/format/xml.d.ts b/types/ol/format/xml.d.ts new file mode 100644 index 0000000000..4032d4758e --- /dev/null +++ b/types/ol/format/xml.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.XML; diff --git a/types/ol/format/xmlfeature.d.ts b/types/ol/format/xmlfeature.d.ts new file mode 100644 index 0000000000..28b544565b --- /dev/null +++ b/types/ol/format/xmlfeature.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.format.XMLFeature; diff --git a/types/ol/geolocation/index.d.ts b/types/ol/geolocation/index.d.ts new file mode 100644 index 0000000000..a08c095e0c --- /dev/null +++ b/types/ol/geolocation/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Geolocation; diff --git a/types/ol/geom/circle.d.ts b/types/ol/geom/circle.d.ts new file mode 100644 index 0000000000..48abeeed8e --- /dev/null +++ b/types/ol/geom/circle.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.Circle; diff --git a/types/ol/geom/geometry.d.ts b/types/ol/geom/geometry.d.ts new file mode 100644 index 0000000000..59f0ba50d9 --- /dev/null +++ b/types/ol/geom/geometry.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.Geometry; diff --git a/types/ol/geom/geometrycollection.d.ts b/types/ol/geom/geometrycollection.d.ts new file mode 100644 index 0000000000..d8aaddefbf --- /dev/null +++ b/types/ol/geom/geometrycollection.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.GeometryCollection; diff --git a/types/ol/geom/linearring.d.ts b/types/ol/geom/linearring.d.ts new file mode 100644 index 0000000000..4341aa8780 --- /dev/null +++ b/types/ol/geom/linearring.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.LinearRing; diff --git a/types/ol/geom/linestring.d.ts b/types/ol/geom/linestring.d.ts new file mode 100644 index 0000000000..8f58f85ff4 --- /dev/null +++ b/types/ol/geom/linestring.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.LineString; diff --git a/types/ol/geom/multilinestring.d.ts b/types/ol/geom/multilinestring.d.ts new file mode 100644 index 0000000000..b9c3de266e --- /dev/null +++ b/types/ol/geom/multilinestring.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.MultiLineString; diff --git a/types/ol/geom/multipoint.d.ts b/types/ol/geom/multipoint.d.ts new file mode 100644 index 0000000000..1846edddb5 --- /dev/null +++ b/types/ol/geom/multipoint.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.MultiPoint; diff --git a/types/ol/geom/multipolygon.d.ts b/types/ol/geom/multipolygon.d.ts new file mode 100644 index 0000000000..9a058fac0f --- /dev/null +++ b/types/ol/geom/multipolygon.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.MultiPolygon; diff --git a/types/ol/geom/point.d.ts b/types/ol/geom/point.d.ts new file mode 100644 index 0000000000..0c8bf8e7d8 --- /dev/null +++ b/types/ol/geom/point.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.Point; diff --git a/types/ol/geom/polygon.d.ts b/types/ol/geom/polygon.d.ts new file mode 100644 index 0000000000..67351267ed --- /dev/null +++ b/types/ol/geom/polygon.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.Polygon; diff --git a/types/ol/geom/simplegeometry.d.ts b/types/ol/geom/simplegeometry.d.ts new file mode 100644 index 0000000000..20695d2bb1 --- /dev/null +++ b/types/ol/geom/simplegeometry.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.geom.SimpleGeometry; diff --git a/types/ol/graticule/index.d.ts b/types/ol/graticule/index.d.ts new file mode 100644 index 0000000000..97bd1e8e2d --- /dev/null +++ b/types/ol/graticule/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Graticule; diff --git a/types/ol/image/index.d.ts b/types/ol/image/index.d.ts new file mode 100644 index 0000000000..5a4c9a304b --- /dev/null +++ b/types/ol/image/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Image; diff --git a/types/ol/imagebase/index.d.ts b/types/ol/imagebase/index.d.ts new file mode 100644 index 0000000000..91e7971e27 --- /dev/null +++ b/types/ol/imagebase/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.ImageBase; diff --git a/types/ol/imagetile/index.d.ts b/types/ol/imagetile/index.d.ts new file mode 100644 index 0000000000..57b9b1c9fa --- /dev/null +++ b/types/ol/imagetile/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.ImageTile; diff --git a/types/ol/index.d.ts b/types/ol/index.d.ts new file mode 100644 index 0000000000..947423f2aa --- /dev/null +++ b/types/ol/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for ol 4.6 +// Project: https://github.com/openlayers/openlayers/tree/master/package#readme +// Definitions by: Yair Tawil +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import * as ol from 'openlayers'; + +export default ol; diff --git a/types/ol/interaction/doubleclickzoom.d.ts b/types/ol/interaction/doubleclickzoom.d.ts new file mode 100644 index 0000000000..3982ba3b7f --- /dev/null +++ b/types/ol/interaction/doubleclickzoom.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.DoubleClickZoom; diff --git a/types/ol/interaction/draganddrop.d.ts b/types/ol/interaction/draganddrop.d.ts new file mode 100644 index 0000000000..bbfbbeb727 --- /dev/null +++ b/types/ol/interaction/draganddrop.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.DragAndDrop; diff --git a/types/ol/interaction/dragbox.d.ts b/types/ol/interaction/dragbox.d.ts new file mode 100644 index 0000000000..dbb06b7a18 --- /dev/null +++ b/types/ol/interaction/dragbox.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.DragBox; diff --git a/types/ol/interaction/dragpan.d.ts b/types/ol/interaction/dragpan.d.ts new file mode 100644 index 0000000000..e9c14d7b5d --- /dev/null +++ b/types/ol/interaction/dragpan.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.DragPan; diff --git a/types/ol/interaction/dragrotate.d.ts b/types/ol/interaction/dragrotate.d.ts new file mode 100644 index 0000000000..31ebec3772 --- /dev/null +++ b/types/ol/interaction/dragrotate.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.DragRotate; diff --git a/types/ol/interaction/dragrotateandzoom.d.ts b/types/ol/interaction/dragrotateandzoom.d.ts new file mode 100644 index 0000000000..6b8a2979e1 --- /dev/null +++ b/types/ol/interaction/dragrotateandzoom.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.DragRotateAndZoom; diff --git a/types/ol/interaction/dragzoom.d.ts b/types/ol/interaction/dragzoom.d.ts new file mode 100644 index 0000000000..c0e0413b21 --- /dev/null +++ b/types/ol/interaction/dragzoom.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.DragZoom; diff --git a/types/ol/interaction/draw.d.ts b/types/ol/interaction/draw.d.ts new file mode 100644 index 0000000000..d7e1318f69 --- /dev/null +++ b/types/ol/interaction/draw.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.Draw; diff --git a/types/ol/interaction/index.d.ts b/types/ol/interaction/index.d.ts new file mode 100644 index 0000000000..6ef5898695 --- /dev/null +++ b/types/ol/interaction/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction; diff --git a/types/ol/interaction/interaction.d.ts b/types/ol/interaction/interaction.d.ts new file mode 100644 index 0000000000..9eb1c46525 --- /dev/null +++ b/types/ol/interaction/interaction.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.Interaction; diff --git a/types/ol/interaction/keyboardpan.d.ts b/types/ol/interaction/keyboardpan.d.ts new file mode 100644 index 0000000000..5c32c8dfa3 --- /dev/null +++ b/types/ol/interaction/keyboardpan.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.KeyboardPan; diff --git a/types/ol/interaction/keyboardzoom.d.ts b/types/ol/interaction/keyboardzoom.d.ts new file mode 100644 index 0000000000..e52bf705eb --- /dev/null +++ b/types/ol/interaction/keyboardzoom.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.KeyboardZoom; diff --git a/types/ol/interaction/modify.d.ts b/types/ol/interaction/modify.d.ts new file mode 100644 index 0000000000..8079ab0ba5 --- /dev/null +++ b/types/ol/interaction/modify.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.Modify; diff --git a/types/ol/interaction/mousewheelzoom.d.ts b/types/ol/interaction/mousewheelzoom.d.ts new file mode 100644 index 0000000000..d8a5223153 --- /dev/null +++ b/types/ol/interaction/mousewheelzoom.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.MouseWheelZoom; diff --git a/types/ol/interaction/pinchrotate.d.ts b/types/ol/interaction/pinchrotate.d.ts new file mode 100644 index 0000000000..b10400ce30 --- /dev/null +++ b/types/ol/interaction/pinchrotate.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.PinchRotate; diff --git a/types/ol/interaction/pinchzoom.d.ts b/types/ol/interaction/pinchzoom.d.ts new file mode 100644 index 0000000000..0d666096c2 --- /dev/null +++ b/types/ol/interaction/pinchzoom.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.PinchZoom; diff --git a/types/ol/interaction/pointer.d.ts b/types/ol/interaction/pointer.d.ts new file mode 100644 index 0000000000..22936f602a --- /dev/null +++ b/types/ol/interaction/pointer.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.Pointer; diff --git a/types/ol/interaction/select.d.ts b/types/ol/interaction/select.d.ts new file mode 100644 index 0000000000..fe8c16b4b9 --- /dev/null +++ b/types/ol/interaction/select.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.Select; diff --git a/types/ol/interaction/snap.d.ts b/types/ol/interaction/snap.d.ts new file mode 100644 index 0000000000..90a7fee1bb --- /dev/null +++ b/types/ol/interaction/snap.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.Snap; diff --git a/types/ol/interaction/translate.d.ts b/types/ol/interaction/translate.d.ts new file mode 100644 index 0000000000..b035bae021 --- /dev/null +++ b/types/ol/interaction/translate.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.interaction.Translate; diff --git a/types/ol/kinetic/index.d.ts b/types/ol/kinetic/index.d.ts new file mode 100644 index 0000000000..ba283fca68 --- /dev/null +++ b/types/ol/kinetic/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Kinetic; diff --git a/types/ol/layer/base.d.ts b/types/ol/layer/base.d.ts new file mode 100644 index 0000000000..25c11c8edd --- /dev/null +++ b/types/ol/layer/base.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.layer.Base; diff --git a/types/ol/layer/group.d.ts b/types/ol/layer/group.d.ts new file mode 100644 index 0000000000..b3669bc387 --- /dev/null +++ b/types/ol/layer/group.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.layer.Group; diff --git a/types/ol/layer/heatmap.d.ts b/types/ol/layer/heatmap.d.ts new file mode 100644 index 0000000000..4b4f112642 --- /dev/null +++ b/types/ol/layer/heatmap.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.layer.Heatmap; diff --git a/types/ol/layer/image.d.ts b/types/ol/layer/image.d.ts new file mode 100644 index 0000000000..34a862498e --- /dev/null +++ b/types/ol/layer/image.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.layer.Image; diff --git a/types/ol/layer/layer.d.ts b/types/ol/layer/layer.d.ts new file mode 100644 index 0000000000..38c31c927f --- /dev/null +++ b/types/ol/layer/layer.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.layer.Layer; diff --git a/types/ol/layer/tile.d.ts b/types/ol/layer/tile.d.ts new file mode 100644 index 0000000000..bbd95be84d --- /dev/null +++ b/types/ol/layer/tile.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.layer.Tile; diff --git a/types/ol/layer/vector.d.ts b/types/ol/layer/vector.d.ts new file mode 100644 index 0000000000..f26e2a3bf5 --- /dev/null +++ b/types/ol/layer/vector.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.layer.Vector; diff --git a/types/ol/layer/vectortile.d.ts b/types/ol/layer/vectortile.d.ts new file mode 100644 index 0000000000..27ac70d8c3 --- /dev/null +++ b/types/ol/layer/vectortile.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.layer.VectorTile; diff --git a/types/ol/loadingstrategy/index.d.ts b/types/ol/loadingstrategy/index.d.ts new file mode 100644 index 0000000000..9b3d8bff3b --- /dev/null +++ b/types/ol/loadingstrategy/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.loadingstrategy; diff --git a/types/ol/map/index.d.ts b/types/ol/map/index.d.ts new file mode 100644 index 0000000000..58f635d45a --- /dev/null +++ b/types/ol/map/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Map; diff --git a/types/ol/mapbrowserevent/index.d.ts b/types/ol/mapbrowserevent/index.d.ts new file mode 100644 index 0000000000..048fc22481 --- /dev/null +++ b/types/ol/mapbrowserevent/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.MapBrowserEvent; diff --git a/types/ol/mapbrowserpointerevent/index.d.ts b/types/ol/mapbrowserpointerevent/index.d.ts new file mode 100644 index 0000000000..616325e218 --- /dev/null +++ b/types/ol/mapbrowserpointerevent/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.MapBrowserPointerEvent; diff --git a/types/ol/mapevent/index.d.ts b/types/ol/mapevent/index.d.ts new file mode 100644 index 0000000000..6e7487ec29 --- /dev/null +++ b/types/ol/mapevent/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.MapEvent; diff --git a/types/ol/object/index.d.ts b/types/ol/object/index.d.ts new file mode 100644 index 0000000000..e4580cd0ce --- /dev/null +++ b/types/ol/object/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Object; diff --git a/types/ol/observable/index.d.ts b/types/ol/observable/index.d.ts new file mode 100644 index 0000000000..09489e7382 --- /dev/null +++ b/types/ol/observable/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Observable; diff --git a/types/ol/ol-tests.ts b/types/ol/ol-tests.ts new file mode 100644 index 0000000000..13a36df6f3 --- /dev/null +++ b/types/ol/ol-tests.ts @@ -0,0 +1,323 @@ +import ControlAttribution from 'ol/control/attribution'; + +import ControlControl from 'ol/control/control'; + +import ControlFullScreen from 'ol/control/fullscreen'; + +import ControlMousePosition from 'ol/control/mouseposition'; + +import ControlOverviewMap from 'ol/control/overviewmap'; + +import ControlRotate from 'ol/control/rotate'; + +import ControlScaleLine from 'ol/control/scaleline'; + +import ControlZoom from 'ol/control/zoom'; + +import ControlZoomSlider from 'ol/control/zoomslider'; + +import ControlZoomToExtent from 'ol/control/zoomtoextent'; + +import Eventscondition from 'ol/events/condition'; + +import EventsEvent from 'ol/events/event'; + +import EventsEventTarget from 'ol/events/eventtarget'; + +import FormatEsriJSON from 'ol/format/esrijson'; + +import FormatFeature from 'ol/format/feature'; + +import Formatfilter from 'ol/format/filter'; + +import FormatGeoJSON from 'ol/format/geojson'; + +import FormatGML2 from 'ol/format/gml2'; + +import FormatGML3 from 'ol/format/gml3'; + +import FormatGMLBase from 'ol/format/gmlbase'; + +import FormatGPX from 'ol/format/gpx'; + +import FormatIGC from 'ol/format/igc'; + +import FormatJSONFeature from 'ol/format/jsonfeature'; + +import FormatKML from 'ol/format/kml'; + +import FormatMVT from 'ol/format/mvt'; + +import FormatOSMXML from 'ol/format/osmxml'; + +import FormatPolyline from 'ol/format/polyline'; + +import FormatTextFeature from 'ol/format/textfeature'; + +import FormatTopoJSON from 'ol/format/topojson'; + +import FormatWFS from 'ol/format/wfs'; + +import FormatWKT from 'ol/format/wkt'; + +import FormatWMSCapabilities from 'ol/format/wmscapabilities'; + +import FormatWMSGetFeatureInfo from 'ol/format/wmsgetfeatureinfo'; + +import FormatWMTSCapabilities from 'ol/format/wmtscapabilities'; + +import FormatXML from 'ol/format/xml'; + +import FormatXMLFeature from 'ol/format/xmlfeature'; + +import GeomCircle from 'ol/geom/circle'; + +import GeomGeometry from 'ol/geom/geometry'; + +import GeomGeometryCollection from 'ol/geom/geometrycollection'; + +import GeomLinearRing from 'ol/geom/linearring'; + +import GeomLineString from 'ol/geom/linestring'; + +import GeomMultiLineString from 'ol/geom/multilinestring'; + +import GeomMultiPoint from 'ol/geom/multipoint'; + +import GeomMultiPolygon from 'ol/geom/multipolygon'; + +import GeomPoint from 'ol/geom/point'; + +import GeomPolygon from 'ol/geom/polygon'; + +import GeomSimpleGeometry from 'ol/geom/simplegeometry'; + +import InteractionDoubleClickZoom from 'ol/interaction/doubleclickzoom'; + +import InteractionDragAndDrop from 'ol/interaction/draganddrop'; + +import InteractionDragBox from 'ol/interaction/dragbox'; + +import InteractionDragPan from 'ol/interaction/dragpan'; + +import InteractionDragRotate from 'ol/interaction/dragrotate'; + +import InteractionDragRotateAndZoom from 'ol/interaction/dragrotateandzoom'; + +import InteractionDragZoom from 'ol/interaction/dragzoom'; + +import InteractionDraw from 'ol/interaction/draw'; + +import InteractionInteraction from 'ol/interaction/interaction'; + +import InteractionKeyboardPan from 'ol/interaction/keyboardpan'; + +import InteractionKeyboardZoom from 'ol/interaction/keyboardzoom'; + +import InteractionModify from 'ol/interaction/modify'; + +import InteractionMouseWheelZoom from 'ol/interaction/mousewheelzoom'; + +import InteractionPinchRotate from 'ol/interaction/pinchrotate'; + +import InteractionPinchZoom from 'ol/interaction/pinchzoom'; + +import InteractionPointer from 'ol/interaction/pointer'; + +import InteractionSelect from 'ol/interaction/select'; + +import InteractionSnap from 'ol/interaction/snap'; + +import InteractionTranslate from 'ol/interaction/translate'; + +import LayerBase from 'ol/layer/base'; + +import LayerGroup from 'ol/layer/group'; + +import LayerHeatmap from 'ol/layer/heatmap'; + +import LayerImage from 'ol/layer/image'; + +import LayerLayer from 'ol/layer/layer'; + +import LayerTile from 'ol/layer/tile'; + +import LayerVector from 'ol/layer/vector'; + +import LayerVectorTile from 'ol/layer/vectortile'; + +import PointerPointerEvent from 'ol/pointer/pointerevent'; + +import ProjProjection from 'ol/proj/projection'; + +import Rendercanvas from 'ol/render/canvas'; + +import RenderEvent from 'ol/render/event'; + +import RenderFeature from 'ol/render/feature'; + +import RenderVectorContext from 'ol/render/vectorcontext'; + +import SourceBingMaps from 'ol/source/bingmaps'; + +import SourceCartoDB from 'ol/source/cartodb'; + +import SourceCluster from 'ol/source/cluster'; + +import SourceImage from 'ol/source/image'; + +import SourceImageArcGISRest from 'ol/source/imagearcgisrest'; + +import SourceImageCanvas from 'ol/source/imagecanvas'; + +import SourceImageMapGuide from 'ol/source/imagemapguide'; + +import SourceImageStatic from 'ol/source/imagestatic'; + +import SourceImageVector from 'ol/source/imagevector'; + +import SourceImageWMS from 'ol/source/imagewms'; + +import SourceOSM from 'ol/source/osm'; + +import SourceRaster from 'ol/source/raster'; + +import SourceSource from 'ol/source/source'; + +import SourceStamen from 'ol/source/stamen'; + +import SourceTile from 'ol/source/tile'; + +import SourceTileArcGISRest from 'ol/source/tilearcgisrest'; + +import SourceTileDebug from 'ol/source/tiledebug'; + +import SourceTileImage from 'ol/source/tileimage'; + +import SourceTileJSON from 'ol/source/tilejson'; + +import SourceTileUTFGrid from 'ol/source/tileutfgrid'; + +import SourceTileWMS from 'ol/source/tilewms'; + +import SourceUrlTile from 'ol/source/urltile'; + +import SourceVector from 'ol/source/vector'; + +import SourceVectorTile from 'ol/source/vectortile'; + +import SourceWMTS from 'ol/source/wmts'; + +import SourceXYZ from 'ol/source/xyz'; + +import SourceZoomify from 'ol/source/zoomify'; + +import StyleAtlasManager from 'ol/style/atlasmanager'; + +import StyleCircle from 'ol/style/circle'; + +import StyleFill from 'ol/style/fill'; + +import StyleIcon from 'ol/style/icon'; + +import StyleImage from 'ol/style/image'; + +import StyleRegularShape from 'ol/style/regularshape'; + +import StyleStroke from 'ol/style/stroke'; + +import StyleStyle from 'ol/style/style'; + +import StyleText from 'ol/style/text'; + +import TilegridTileGrid from 'ol/tilegrid/tilegrid'; + +import TilegridWMTS from 'ol/tilegrid/wmts'; + +import AssertionError from 'ol/assertionerror'; + +import Attribution from 'ol/attribution'; + +import Collection from 'ol/collection'; + +import Color from 'ol/color'; + +import Colorlike from 'ol/colorlike'; + +import Control from 'ol/control'; + +import DeviceOrientation from 'ol/deviceorientation'; + +import Disposable from 'ol/disposable'; + +import Easing from 'ol/easing'; + +import Events from 'ol/events'; + +import Extent from 'ol/extent'; + +import Feature from 'ol/feature'; + +import FeatureLoader from 'ol/featureloader'; + +import Geolocation from 'ol/geolocation'; + +import Graticule from 'ol/graticule'; + +import Image from 'ol/image'; + +import ImageBase from 'ol/imagebase'; + +import ImageTile from 'ol/imagetile'; + +import Interaction from 'ol/interaction'; + +import Kinetic from 'ol/kinetic'; + +import Loadingstrategy from 'ol/loadingstrategy'; + +import Map from 'ol/map'; + +import MapBrowserEvent from 'ol/mapbrowserevent'; + +import MapBrowserPointerEvent from 'ol/mapbrowserpointerevent'; + +import MapEvent from 'ol/mapevent'; + +import Object from 'ol/object'; + +import Observable from 'ol/observable'; + +import Overlay from 'ol/overlay'; + +import Sphere from 'ol/sphere'; + +import Tile from 'ol/tile'; + +import Tilegrid from 'ol/tilegrid'; + +import VectorTile from 'ol/vectortile'; + +import View from 'ol/view'; + +// Map +const map: ol.Map = new Map( {}); +const mapView: View = {}; +const layerBase: LayerBase = {}; +const control: ControlControl = {}; +const interaction: InteractionInteraction = {}; +map.setView(mapView); +map.addLayer(layerBase); +map.addControl(control); +map.addInteraction(interaction); + +// View +let view: View; +const coordinate: ol.Coordinate = {}; +const size: ol.Size = {}; +const position: ol.Pixel = {}; +view = map.getView(); +view.getProjection(); +view.animate( {}); +view.calculateExtent( 'size'); +view.centerOn(coordinate, size, position); diff --git a/types/ol/overlay/index.d.ts b/types/ol/overlay/index.d.ts new file mode 100644 index 0000000000..d350f1c828 --- /dev/null +++ b/types/ol/overlay/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Overlay; diff --git a/types/ol/pointer/pointerevent.d.ts b/types/ol/pointer/pointerevent.d.ts new file mode 100644 index 0000000000..62e84e6207 --- /dev/null +++ b/types/ol/pointer/pointerevent.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.pointer.PointerEvent; diff --git a/types/ol/proj/projection.d.ts b/types/ol/proj/projection.d.ts new file mode 100644 index 0000000000..26050bb377 --- /dev/null +++ b/types/ol/proj/projection.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.proj.Projection; diff --git a/types/ol/render/canvas.d.ts b/types/ol/render/canvas.d.ts new file mode 100644 index 0000000000..9e6d06eca6 --- /dev/null +++ b/types/ol/render/canvas.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.render.canvas; diff --git a/types/ol/render/event.d.ts b/types/ol/render/event.d.ts new file mode 100644 index 0000000000..981b821b5e --- /dev/null +++ b/types/ol/render/event.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.render.Event; diff --git a/types/ol/render/feature.d.ts b/types/ol/render/feature.d.ts new file mode 100644 index 0000000000..95e4831fba --- /dev/null +++ b/types/ol/render/feature.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.render.Feature; diff --git a/types/ol/render/vectorcontext.d.ts b/types/ol/render/vectorcontext.d.ts new file mode 100644 index 0000000000..b3e287c91b --- /dev/null +++ b/types/ol/render/vectorcontext.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.render.VectorContext; diff --git a/types/ol/source/bingmaps.d.ts b/types/ol/source/bingmaps.d.ts new file mode 100644 index 0000000000..963623bc7e --- /dev/null +++ b/types/ol/source/bingmaps.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.BingMaps; diff --git a/types/ol/source/cartodb.d.ts b/types/ol/source/cartodb.d.ts new file mode 100644 index 0000000000..28b44ebc4c --- /dev/null +++ b/types/ol/source/cartodb.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.CartoDB; diff --git a/types/ol/source/cluster.d.ts b/types/ol/source/cluster.d.ts new file mode 100644 index 0000000000..0a793ed0b2 --- /dev/null +++ b/types/ol/source/cluster.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.Cluster; diff --git a/types/ol/source/image.d.ts b/types/ol/source/image.d.ts new file mode 100644 index 0000000000..82071b1636 --- /dev/null +++ b/types/ol/source/image.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.Image; diff --git a/types/ol/source/imagearcgisrest.d.ts b/types/ol/source/imagearcgisrest.d.ts new file mode 100644 index 0000000000..ae296156cd --- /dev/null +++ b/types/ol/source/imagearcgisrest.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.ImageArcGISRest; diff --git a/types/ol/source/imagecanvas.d.ts b/types/ol/source/imagecanvas.d.ts new file mode 100644 index 0000000000..cbfee5d9d5 --- /dev/null +++ b/types/ol/source/imagecanvas.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.ImageCanvas; diff --git a/types/ol/source/imagemapguide.d.ts b/types/ol/source/imagemapguide.d.ts new file mode 100644 index 0000000000..42877b1052 --- /dev/null +++ b/types/ol/source/imagemapguide.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.ImageMapGuide; diff --git a/types/ol/source/imagestatic.d.ts b/types/ol/source/imagestatic.d.ts new file mode 100644 index 0000000000..02a6d37e50 --- /dev/null +++ b/types/ol/source/imagestatic.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.ImageStatic; diff --git a/types/ol/source/imagevector.d.ts b/types/ol/source/imagevector.d.ts new file mode 100644 index 0000000000..2f1ae17a2d --- /dev/null +++ b/types/ol/source/imagevector.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.ImageVector; diff --git a/types/ol/source/imagewms.d.ts b/types/ol/source/imagewms.d.ts new file mode 100644 index 0000000000..0aeb5fb39c --- /dev/null +++ b/types/ol/source/imagewms.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.ImageWMS; diff --git a/types/ol/source/osm.d.ts b/types/ol/source/osm.d.ts new file mode 100644 index 0000000000..68b03db843 --- /dev/null +++ b/types/ol/source/osm.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.OSM; diff --git a/types/ol/source/raster.d.ts b/types/ol/source/raster.d.ts new file mode 100644 index 0000000000..de39ec8fce --- /dev/null +++ b/types/ol/source/raster.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.Raster; diff --git a/types/ol/source/source.d.ts b/types/ol/source/source.d.ts new file mode 100644 index 0000000000..379f73e579 --- /dev/null +++ b/types/ol/source/source.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.Source; diff --git a/types/ol/source/stamen.d.ts b/types/ol/source/stamen.d.ts new file mode 100644 index 0000000000..51d6d42006 --- /dev/null +++ b/types/ol/source/stamen.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.Stamen; diff --git a/types/ol/source/tile.d.ts b/types/ol/source/tile.d.ts new file mode 100644 index 0000000000..7c7cb3d874 --- /dev/null +++ b/types/ol/source/tile.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.Tile; diff --git a/types/ol/source/tilearcgisrest.d.ts b/types/ol/source/tilearcgisrest.d.ts new file mode 100644 index 0000000000..45f7f529ff --- /dev/null +++ b/types/ol/source/tilearcgisrest.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.TileArcGISRest; diff --git a/types/ol/source/tiledebug.d.ts b/types/ol/source/tiledebug.d.ts new file mode 100644 index 0000000000..f09371a620 --- /dev/null +++ b/types/ol/source/tiledebug.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.TileDebug; diff --git a/types/ol/source/tileimage.d.ts b/types/ol/source/tileimage.d.ts new file mode 100644 index 0000000000..bd3bf922b4 --- /dev/null +++ b/types/ol/source/tileimage.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.TileImage; diff --git a/types/ol/source/tilejson.d.ts b/types/ol/source/tilejson.d.ts new file mode 100644 index 0000000000..c9d52d2903 --- /dev/null +++ b/types/ol/source/tilejson.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.TileJSON; diff --git a/types/ol/source/tileutfgrid.d.ts b/types/ol/source/tileutfgrid.d.ts new file mode 100644 index 0000000000..17ae2022a2 --- /dev/null +++ b/types/ol/source/tileutfgrid.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.TileUTFGrid; diff --git a/types/ol/source/tilewms.d.ts b/types/ol/source/tilewms.d.ts new file mode 100644 index 0000000000..7ae163f2c5 --- /dev/null +++ b/types/ol/source/tilewms.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.TileWMS; diff --git a/types/ol/source/urltile.d.ts b/types/ol/source/urltile.d.ts new file mode 100644 index 0000000000..606583cac4 --- /dev/null +++ b/types/ol/source/urltile.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.UrlTile; diff --git a/types/ol/source/vector.d.ts b/types/ol/source/vector.d.ts new file mode 100644 index 0000000000..ee2d968d28 --- /dev/null +++ b/types/ol/source/vector.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.Vector; diff --git a/types/ol/source/vectortile.d.ts b/types/ol/source/vectortile.d.ts new file mode 100644 index 0000000000..1aa59678d3 --- /dev/null +++ b/types/ol/source/vectortile.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.VectorTile; diff --git a/types/ol/source/wmts.d.ts b/types/ol/source/wmts.d.ts new file mode 100644 index 0000000000..afdc2c352b --- /dev/null +++ b/types/ol/source/wmts.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.WMTS; diff --git a/types/ol/source/xyz.d.ts b/types/ol/source/xyz.d.ts new file mode 100644 index 0000000000..d29b5f9e06 --- /dev/null +++ b/types/ol/source/xyz.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.XYZ; diff --git a/types/ol/source/zoomify.d.ts b/types/ol/source/zoomify.d.ts new file mode 100644 index 0000000000..a48e675012 --- /dev/null +++ b/types/ol/source/zoomify.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.source.Zoomify; diff --git a/types/ol/sphere/index.d.ts b/types/ol/sphere/index.d.ts new file mode 100644 index 0000000000..a3481e4339 --- /dev/null +++ b/types/ol/sphere/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Sphere; diff --git a/types/ol/style/atlasmanager.d.ts b/types/ol/style/atlasmanager.d.ts new file mode 100644 index 0000000000..0be77a6621 --- /dev/null +++ b/types/ol/style/atlasmanager.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.style.AtlasManager; diff --git a/types/ol/style/circle.d.ts b/types/ol/style/circle.d.ts new file mode 100644 index 0000000000..ff593230b5 --- /dev/null +++ b/types/ol/style/circle.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.style.Circle; diff --git a/types/ol/style/fill.d.ts b/types/ol/style/fill.d.ts new file mode 100644 index 0000000000..ef6b246ad5 --- /dev/null +++ b/types/ol/style/fill.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.style.Fill; diff --git a/types/ol/style/icon.d.ts b/types/ol/style/icon.d.ts new file mode 100644 index 0000000000..4100f3fbf8 --- /dev/null +++ b/types/ol/style/icon.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.style.Icon; diff --git a/types/ol/style/image.d.ts b/types/ol/style/image.d.ts new file mode 100644 index 0000000000..bdfb4319e3 --- /dev/null +++ b/types/ol/style/image.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.style.Image; diff --git a/types/ol/style/regularshape.d.ts b/types/ol/style/regularshape.d.ts new file mode 100644 index 0000000000..fb4a227d1d --- /dev/null +++ b/types/ol/style/regularshape.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.style.RegularShape; diff --git a/types/ol/style/stroke.d.ts b/types/ol/style/stroke.d.ts new file mode 100644 index 0000000000..af7a49d6b5 --- /dev/null +++ b/types/ol/style/stroke.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.style.Stroke; diff --git a/types/ol/style/style.d.ts b/types/ol/style/style.d.ts new file mode 100644 index 0000000000..839583e313 --- /dev/null +++ b/types/ol/style/style.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.style.Style; diff --git a/types/ol/style/text.d.ts b/types/ol/style/text.d.ts new file mode 100644 index 0000000000..33d1b50962 --- /dev/null +++ b/types/ol/style/text.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.style.Text; diff --git a/types/ol/tile/index.d.ts b/types/ol/tile/index.d.ts new file mode 100644 index 0000000000..61e802d921 --- /dev/null +++ b/types/ol/tile/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.Tile; diff --git a/types/ol/tilegrid/index.d.ts b/types/ol/tilegrid/index.d.ts new file mode 100644 index 0000000000..467e92480f --- /dev/null +++ b/types/ol/tilegrid/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.tilegrid; diff --git a/types/ol/tilegrid/tilegrid.d.ts b/types/ol/tilegrid/tilegrid.d.ts new file mode 100644 index 0000000000..b6edeba4aa --- /dev/null +++ b/types/ol/tilegrid/tilegrid.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.tilegrid.TileGrid; diff --git a/types/ol/tilegrid/wmts.d.ts b/types/ol/tilegrid/wmts.d.ts new file mode 100644 index 0000000000..3f1f33e647 --- /dev/null +++ b/types/ol/tilegrid/wmts.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.tilegrid.WMTS; diff --git a/types/ol/tsconfig.json b/types/ol/tsconfig.json new file mode 100644 index 0000000000..6402adb0f7 --- /dev/null +++ b/types/ol/tsconfig.json @@ -0,0 +1,176 @@ +{ + "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", + "ol-tests.ts", + "control/attribution.d.ts", + "control/control.d.ts", + "control/fullscreen.d.ts", + "control/mouseposition.d.ts", + "control/overviewmap.d.ts", + "control/rotate.d.ts", + "control/scaleline.d.ts", + "control/zoom.d.ts", + "control/zoomslider.d.ts", + "control/zoomtoextent.d.ts", + "events/condition.d.ts", + "events/event.d.ts", + "events/eventtarget.d.ts", + "format/esrijson.d.ts", + "format/feature.d.ts", + "format/filter.d.ts", + "format/geojson.d.ts", + "format/gml2.d.ts", + "format/gml3.d.ts", + "format/gmlbase.d.ts", + "format/gpx.d.ts", + "format/igc.d.ts", + "format/jsonfeature.d.ts", + "format/kml.d.ts", + "format/mvt.d.ts", + "format/osmxml.d.ts", + "format/polyline.d.ts", + "format/textfeature.d.ts", + "format/topojson.d.ts", + "format/wfs.d.ts", + "format/wkt.d.ts", + "format/wmscapabilities.d.ts", + "format/wmsgetfeatureinfo.d.ts", + "format/wmtscapabilities.d.ts", + "format/xml.d.ts", + "format/xmlfeature.d.ts", + "geom/circle.d.ts", + "geom/geometry.d.ts", + "geom/geometrycollection.d.ts", + "geom/linearring.d.ts", + "geom/linestring.d.ts", + "geom/multilinestring.d.ts", + "geom/multipoint.d.ts", + "geom/multipolygon.d.ts", + "geom/point.d.ts", + "geom/polygon.d.ts", + "geom/simplegeometry.d.ts", + "interaction/doubleclickzoom.d.ts", + "interaction/draganddrop.d.ts", + "interaction/dragbox.d.ts", + "interaction/dragpan.d.ts", + "interaction/dragrotate.d.ts", + "interaction/dragrotateandzoom.d.ts", + "interaction/dragzoom.d.ts", + "interaction/draw.d.ts", + "interaction/interaction.d.ts", + "interaction/keyboardpan.d.ts", + "interaction/keyboardzoom.d.ts", + "interaction/modify.d.ts", + "interaction/mousewheelzoom.d.ts", + "interaction/pinchrotate.d.ts", + "interaction/pinchzoom.d.ts", + "interaction/pointer.d.ts", + "interaction/select.d.ts", + "interaction/snap.d.ts", + "interaction/translate.d.ts", + "layer/base.d.ts", + "layer/group.d.ts", + "layer/heatmap.d.ts", + "layer/image.d.ts", + "layer/layer.d.ts", + "layer/tile.d.ts", + "layer/vector.d.ts", + "layer/vectortile.d.ts", + "pointer/pointerevent.d.ts", + "proj/projection.d.ts", + "render/canvas.d.ts", + "render/event.d.ts", + "render/feature.d.ts", + "render/vectorcontext.d.ts", + "source/bingmaps.d.ts", + "source/cartodb.d.ts", + "source/cluster.d.ts", + "source/image.d.ts", + "source/imagearcgisrest.d.ts", + "source/imagecanvas.d.ts", + "source/imagemapguide.d.ts", + "source/imagestatic.d.ts", + "source/imagevector.d.ts", + "source/imagewms.d.ts", + "source/osm.d.ts", + "source/raster.d.ts", + "source/source.d.ts", + "source/stamen.d.ts", + "source/tile.d.ts", + "source/tilearcgisrest.d.ts", + "source/tiledebug.d.ts", + "source/tileimage.d.ts", + "source/tilejson.d.ts", + "source/tileutfgrid.d.ts", + "source/tilewms.d.ts", + "source/urltile.d.ts", + "source/vector.d.ts", + "source/vectortile.d.ts", + "source/wmts.d.ts", + "source/xyz.d.ts", + "source/zoomify.d.ts", + "style/atlasmanager.d.ts", + "style/circle.d.ts", + "style/fill.d.ts", + "style/icon.d.ts", + "style/image.d.ts", + "style/regularshape.d.ts", + "style/stroke.d.ts", + "style/style.d.ts", + "style/text.d.ts", + "tilegrid/tilegrid.d.ts", + "tilegrid/wmts.d.ts", + "assertionerror/index.d.ts", + "attribution/index.d.ts", + "collection/index.d.ts", + "color/index.d.ts", + "colorlike/index.d.ts", + "control/index.d.ts", + "coordinate/index.d.ts", + "deviceorientation/index.d.ts", + "disposable/index.d.ts", + "easing/index.d.ts", + "events/index.d.ts", + "extent/index.d.ts", + "feature/index.d.ts", + "featureloader/index.d.ts", + "geolocation/index.d.ts", + "graticule/index.d.ts", + "image/index.d.ts", + "imagebase/index.d.ts", + "imagetile/index.d.ts", + "interaction/index.d.ts", + "kinetic/index.d.ts", + "loadingstrategy/index.d.ts", + "map/index.d.ts", + "mapbrowserevent/index.d.ts", + "mapbrowserpointerevent/index.d.ts", + "mapevent/index.d.ts", + "object/index.d.ts", + "observable/index.d.ts", + "overlay/index.d.ts", + "sphere/index.d.ts", + "tile/index.d.ts", + "tilegrid/index.d.ts", + "vectortile/index.d.ts", + "view/index.d.ts" + ] +} \ No newline at end of file diff --git a/types/ol/tslint.json b/types/ol/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ol/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ol/vectortile/index.d.ts b/types/ol/vectortile/index.d.ts new file mode 100644 index 0000000000..21b2ed9297 --- /dev/null +++ b/types/ol/vectortile/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.VectorTile; diff --git a/types/ol/view/index.d.ts b/types/ol/view/index.d.ts new file mode 100644 index 0000000000..6df86cd89d --- /dev/null +++ b/types/ol/view/index.d.ts @@ -0,0 +1,3 @@ +import * as ol from 'openlayers'; + +export default ol.View; diff --git a/types/onesignal-cordova-plugin/tsconfig.json b/types/onesignal-cordova-plugin/tsconfig.json index bcee47426f..a256428f0e 100644 --- a/types/onesignal-cordova-plugin/tsconfig.json +++ b/types/onesignal-cordova-plugin/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "onesignal-cordova-plugin-tests.ts" ] -} +} \ No newline at end of file diff --git a/types/onesignal-cordova-plugin/tslint.json b/types/onesignal-cordova-plugin/tslint.json index 3db14f85ea..3224b40b8b 100644 --- a/types/onesignal-cordova-plugin/tslint.json +++ b/types/onesignal-cordova-plugin/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-const-enum": false + } +} diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index c2e7ab1530..3c87320827 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for OpenLayers v4.3.4 +// Type definitions for OpenLayers 4.6 // Project: http://openlayers.org/ // Definitions by: Olivier Sechet // Bin Wang @@ -6,33 +6,26 @@ // Alexandre Melard // Chad Johnston // Dan Manastireanu +// Yair Tawil +// Pierre Marchand // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Definitions partially generated using tsd-jsdoc (https://github.com/englercj/tsd-jsdoc) -declare type GlobalObject = Object; +interface GlobalObject { [key: string]: any; } -/** - * @namespace ol - */ -declare module ol { +declare namespace ol { /** - * Error object thrown when an assertion failed. This is an ECMA-262 Error, - * extended with a `code` property. - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} - * @constructor - * @extends {Error} - * @implements {oli.AssertionError} - * @param {number} code Error code. - */ + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @param code Error code. + */ class AssertionError extends Error { /** * Error object thrown when an assertion failed. This is an ECMA-262 Error, * extended with a `code` property. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} - * @constructor - * @extends {Error} - * @implements {oli.AssertionError} - * @param {number} code Error code. + * @param code Error code. */ constructor(code: number); @@ -41,11 +34,9 @@ declare module ol { * {@link http://openlayers.org/en/latest/errors.html} (replace `latest` with * the version found in the OpenLayers script's header comment if a version * other than the latest is used). - * @type {number} * @api */ code: number; - } /** @@ -64,8 +55,7 @@ declare module ol { * ], * .. * - * @constructor - * @param {olx.AttributionOptions} options Attribution options. + * @param options Attribution options. * @struct * @api stable */ @@ -86,8 +76,7 @@ declare module ol { * ], * .. * - * @constructor - * @param {olx.AttributionOptions} options Attribution options. + * @param options Attribution options. * @struct * @api stable */ @@ -95,11 +84,10 @@ declare module ol { /** * Get the attribution markup. - * @return {string} The attribution HTML. + * @return The attribution HTML. * @api stable */ getHTML(): string; - } /** @@ -110,10 +98,8 @@ declare module ol { * Collection; they trigger events on the appropriate object, not on the * Collection as a whole. * - * @constructor - * @extends {ol.Object} * @fires ol.Collection.Event - * @param {!Array.=} opt_array Array. + * @param opt_array Array. * @template T * @api stable */ @@ -126,10 +112,8 @@ declare module ol { * Collection; they trigger events on the appropriate object, not on the * Collection as a whole. * - * @constructor - * @extends {ol.Object} * @fires ol.Collection.Event - * @param {!Array.=} opt_array Array. + * @param opt_array Array. * @template T * @api stable */ @@ -144,18 +128,18 @@ declare module ol { /** * Add elements to the collection. This pushes each item in the provided array * to the end of the collection. - * @param {!Array.} arr Array. - * @return {ol.Collection.} This collection. + * @param arr Array. + * @return This collection. * @api stable */ extend(arr: T[]): ol.Collection; /** * Iterate over each element, calling the provided callback. - * @param {function(this: S, T, number, Array.): *} f The function to call + * @param f The function to call * for every element. This function takes 3 arguments (the element, the * index and the array). The return value is ignored. - * @param {S=} opt_this The object to use as `this` in `f`. + * @param opt_this The object to use as `this` in `f`. * @template S * @api stable */ @@ -166,22 +150,22 @@ declare module ol { * is mutated, no events will be dispatched by the collection, and the * collection's "length" property won't be in sync with the actual length * of the array. - * @return {!Array.} Array. + * @return Array. * @api stable */ getArray(): T[]; /** * Get the element at the provided index. - * @param {number} index Index. - * @return {T} Element. + * @param index Index. + * @return Element. * @api stable */ item(index: number): T; /** * Get the length of this collection. - * @return {number} The length of the array. + * @return The length of the array. * @observable * @api stable */ @@ -189,8 +173,8 @@ declare module ol { /** * Insert an element at the provided index. - * @param {number} index Index. - * @param {T} elem Element. + * @param index Index. + * @param elem Element. * @api stable */ insertAt(index: number, elem: T): void; @@ -198,23 +182,23 @@ declare module ol { /** * Remove the last element of the collection and return it. * Return `undefined` if the collection is empty. - * @return {T|undefined} Element. + * @return Element. * @api stable */ pop(): (T); /** * Insert the provided element at the end of the collection. - * @param {T} elem Element. - * @return {number} Length. + * @param elem Element. + * @return Length. * @api stable */ push(elem: T): number; /** * Remove the first occurrence of an element from the collection. - * @param {T} elem Element. - * @return {T|undefined} The removed element or undefined if none found. + * @param elem Element. + * @return The removed element or undefined if none found. * @api stable */ remove(elem: T): (T); @@ -222,58 +206,48 @@ declare module ol { /** * Remove the element at the provided index and return it. * Return `undefined` if the collection does not contain this index. - * @param {number} index Index. - * @return {T|undefined} Value. + * @param index Index. + * @return Value. * @api stable */ removeAt(index: number): (T); /** * Set the element at the provided index. - * @param {number} index Index. - * @param {T} elem Element. + * @param index Index. + * @param elem Element. * @api stable */ setAt(index: number, elem: T): void; - } - module Collection { - + namespace Collection { type EventType = string; /** - * @classdesc - * Events emitted by {@link ol.Collection} instances are instances of this - * type. - * - * @constructor - * @extends {ol.events.Event} - * @implements {oli.Collection.Event} - * @param {ol.Collection.EventType} type Type. - * @param {*=} opt_element Element. - */ + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @param type Type. + * @param opt_element Element. + */ class Event extends ol.events.Event { /** * @classdesc * Events emitted by {@link ol.Collection} instances are instances of this * type. * - * @constructor - * @extends {ol.events.Event} - * @implements {oli.Collection.Event} - * @param {ol.Collection.EventType} type Type. - * @param {*=} opt_element Element. + * @param type Type. + * @param opt_element Element. */ constructor(type: ol.Collection.EventType, opt_element?: any); /** * The element that is added to or removed from the collection. - * @type {*} * @api stable */ element: any; - } } @@ -283,47 +257,40 @@ declare module ol { * Color names, like 'red', 'blue' or 'green', may also be used with the * Canvas renderer. * - * @namespace ol.color */ - module color { + namespace color { /** * Return the color as an array. This function maintains a cache of calculated * arrays which means the result should not be modified. - * @param {ol.Color|string} color Color. - * @return {ol.Color} Color. + * @param color Color. + * @return Color. * @api */ function asArray(color: (ol.Color | string)): ol.Color; /** * Return the color as an rgba string. - * @param {ol.Color|string} color Color. - * @return {string} Rgba string. + * @param color Color. + * @return Rgba string. * @api */ function asString(color: (ol.Color | string)): string; - } /** * An {@link ol.ColorLike} can be a color, gradient or pattern accepted by * [CanvasRenderingContext2D.fillStyle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle). - * @namespace ol.colorlike */ - module colorlike { + namespace colorlike { /** - * @param {ol.Color|ol.ColorLike} color Color. - * @return {ol.ColorLike} The color as an ol.ColorLike + * @param color Color. + * @return The color as an ol.ColorLike * @api */ function asColorLike(color: (ol.Color | ol.ColorLike)): ol.ColorLike; - } - /** - * @namespace ol.control - */ - module control { + namespace control { /** * @classdesc * Control to show all the attributions associated with the layer sources @@ -331,9 +298,7 @@ declare module ol { * By default it will show in the bottom right portion of the map, but this can * be changed by using a css selector for `.ol-attribution`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @param opt_options Attribution options. * @api stable */ class Attribution extends ol.control.Control { @@ -344,31 +309,28 @@ declare module ol { * By default it will show in the bottom right portion of the map, but this can * be changed by using a css selector for `.ol-attribution`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @param opt_options Attribution options. * @api stable */ constructor(opt_options?: olx.control.AttributionOptions); /** * Update the attribution element. - * @param {ol.MapEvent} mapEvent Map event. - * @this {ol.control.Attribution} + * @param mapEvent Map event. * @api */ static render(mapEvent: ol.MapEvent): void; /** * Return `true` if the attribution is collapsible, `false` otherwise. - * @return {boolean} True if the widget is collapsible. + * @return True if the widget is collapsible. * @api stable */ getCollapsible(): boolean; /** * Set whether the attribution should be collapsible. - * @param {boolean} collapsible True if the widget is collapsible. + * @param collapsible True if the widget is collapsible. * @api stable */ setCollapsible(collapsible: boolean): void; @@ -377,7 +339,7 @@ declare module ol { * Collapse or expand the attribution according to the passed parameter. Will * not do anything if the attribution isn't collapsible or if the current * collapsed state is already the one requested. - * @param {boolean} collapsed True if the widget is collapsed. + * @param collapsed True if the widget is collapsed. * @api stable */ setCollapsed(collapsed: boolean): void; @@ -385,11 +347,10 @@ declare module ol { /** * Return `true` when the attribution is currently collapsed or `false` * otherwise. - * @return {boolean} True if the widget is collapsed. + * @return True if the widget is collapsed. * @api stable */ getCollapsed(): boolean; - } /** @@ -415,10 +376,7 @@ declare module ol { * You can also extend this base for your own control class. See * examples/custom-controls for an example of how to do this. * - * @constructor - * @extends {ol.Object} - * @implements {oli.control.Control} - * @param {olx.control.ControlOptions} options Control options. + * @param options Control options. * @api stable */ class Control extends ol.Object { @@ -445,17 +403,14 @@ declare module ol { * You can also extend this base for your own control class. See * examples/custom-controls for an example of how to do this. * - * @constructor - * @extends {ol.Object} - * @implements {oli.control.Control} - * @param {olx.control.ControlOptions} options Control options. + * @param options Control options. * @api stable */ constructor(options: olx.control.ControlOptions); /** * Get the map associated with this control. - * @return {ol.Map} Map. + * @return Map. * @api stable */ getMap(): ol.Map; @@ -464,7 +419,7 @@ declare module ol { * Remove the control from its current map and attach it to the new map. * Subclasses may set up event handlers to get notified about changes to * the map here. - * @param {ol.Map} map Map. + * @param map Map. * @api stable */ setMap(map: ol.Map): void; @@ -475,11 +430,10 @@ declare module ol { * after `setMap` is called on the control). If no `target` is set in the * options passed to the control constructor and if `setTarget` is not called * then the control is added to the map's overlay container. - * @param {Element|string} target Target. + * @param target Target. * @api */ setTarget(target: (Element | string)): void; - } /** @@ -494,9 +448,7 @@ declare module ol { * toggle the map in full screen mode. * * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.FullScreenOptions=} opt_options Options. + * @param opt_options Options. * @api stable */ class FullScreen extends ol.control.Control { @@ -512,13 +464,10 @@ declare module ol { * toggle the map in full screen mode. * * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.FullScreenOptions=} opt_options Options. + * @param opt_options Options. * @api stable */ constructor(opt_options?: olx.control.FullScreenOptions); - } /** @@ -529,8 +478,8 @@ declare module ol { * * {@link ol.control.Rotate} * * {@link ol.control.Attribution} * - * @param {olx.control.DefaultsOptions=} opt_options Defaults options. - * @return {ol.Collection.} Controls. + * @param opt_options Defaults options. + * @return Controls. * @api stable */ function defaults(opt_options?: olx.control.DefaultsOptions): ol.Collection; @@ -542,9 +491,7 @@ declare module ol { * By default the control is shown in the top right corner of the map, but this * can be changed by using the css selector `.ol-mouse-position`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * @param opt_options Mouse position * options. * @api stable */ @@ -556,9 +503,7 @@ declare module ol { * By default the control is shown in the top right corner of the map, but this * can be changed by using the css selector `.ol-mouse-position`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * @param opt_options Mouse position * options. * @api stable */ @@ -566,8 +511,7 @@ declare module ol { /** * Update the mouseposition element. - * @param {ol.MapEvent} mapEvent Map event. - * @this {ol.control.MousePosition} + * @param mapEvent Map event. * @api */ static render(mapEvent: ol.MapEvent): void; @@ -575,7 +519,7 @@ declare module ol { /** * Return the coordinate format type used to render the current position or * undefined. - * @return {ol.CoordinateFormatType|undefined} The format to render the current + * @return The format to render the current * position in. * @observable * @api stable @@ -584,7 +528,7 @@ declare module ol { /** * Return the projection that is used to report the mouse position. - * @return {ol.proj.Projection|undefined} The projection to report mouse + * @return The projection to report mouse * position in. * @observable * @api stable @@ -593,7 +537,7 @@ declare module ol { /** * Set the coordinate format type used to render the current position. - * @param {ol.CoordinateFormatType} format The format to render the current + * @param format The format to render the current * position in. * @observable * @api stable @@ -602,52 +546,46 @@ declare module ol { /** * Set the projection that is used to report the mouse position. - * @param {ol.proj.Projection} projection The projection to report mouse + * @param projection The projection to report mouse * position in. * @observable * @api stable */ setProjection(projection: ol.proj.Projection): void; - } /** * Create a new control with a map acting as an overview map for an other * defined map. - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @param opt_options OverviewMap options. * @api */ class OverviewMap extends ol.control.Control { /** * Create a new control with a map acting as an overview map for an other * defined map. - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @param opt_options OverviewMap options. * @api */ constructor(opt_options?: olx.control.OverviewMapOptions); /** * Update the overview map element. - * @param {ol.MapEvent} mapEvent Map event. - * @this {ol.control.OverviewMap} + * @param mapEvent Map event. * @api */ static render(mapEvent: ol.MapEvent): void; /** * Return `true` if the overview map is collapsible, `false` otherwise. - * @return {boolean} True if the widget is collapsible. + * @return True if the widget is collapsible. * @api stable */ getCollapsible(): boolean; /** * Set whether the overview map should be collapsible. - * @param {boolean} collapsible True if the widget is collapsible. + * @param collapsible True if the widget is collapsible. * @api stable */ setCollapsible(collapsible: boolean): void; @@ -656,25 +594,24 @@ declare module ol { * Collapse or expand the overview map according to the passed parameter. Will * not do anything if the overview map isn't collapsible or if the current * collapsed state is already the one requested. - * @param {boolean} collapsed True if the widget is collapsed. + * @param collapsed True if the widget is collapsed. * @api stable */ setCollapsed(collapsed: boolean): void; /** * Determine if the overview map is collapsed. - * @return {boolean} The overview map is collapsed. + * @return The overview map is collapsed. * @api stable */ getCollapsed(): boolean; /** * Return the overview map. - * @return {ol.Map} Overview map. + * @return Overview map. * @api */ getOverviewMap(): ol.Map; - } /** @@ -683,9 +620,7 @@ declare module ol { * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css * selector is added to the button when the rotation is 0. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @param opt_options Rotate options. * @api stable */ class Rotate extends ol.control.Control { @@ -695,21 +630,17 @@ declare module ol { * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css * selector is added to the button when the rotation is 0. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @param opt_options Rotate options. * @api stable */ constructor(opt_options?: olx.control.RotateOptions); /** * Update the rotate control element. - * @param {ol.MapEvent} mapEvent Map event. - * @this {ol.control.Rotate} + * @param mapEvent Map event. * @api */ static render(mapEvent: ol.MapEvent): void; - } /** @@ -722,9 +653,7 @@ declare module ol { * By default the scale line will show in the bottom left portion of the map, * but this can be changed by using the css selector `.ol-scale-line`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @param opt_options Scale line options. * @api stable */ class ScaleLine extends ol.control.Control { @@ -738,16 +667,14 @@ declare module ol { * By default the scale line will show in the bottom left portion of the map, * but this can be changed by using the css selector `.ol-scale-line`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @param opt_options Scale line options. * @api stable */ constructor(opt_options?: olx.control.ScaleLineOptions); /** * Return the units to use in the scale line. - * @return {ol.control.ScaleLine.Units|undefined} The units to use in the scale + * @return The units to use in the scale * line. * @observable * @api stable @@ -756,33 +683,30 @@ declare module ol { /** * Update the scale line element. - * @param {ol.MapEvent} mapEvent Map event. - * @this {ol.control.ScaleLine} + * @param mapEvent Map event. * @api */ static render(mapEvent: ol.MapEvent): void; /** * Set the units to use in the scale line. - * @param {ol.control.ScaleLine.Units} units The units to use in the scale line. + * @param units The units to use in the scale line. * @observable * @api stable */ setUnits(units: ol.control.ScaleLine.Units): void; } - module ScaleLine { + namespace ScaleLine { /** - * @enum {string} * @api */ type Property = string; /** - * Units for the scale line. Supported values are `'degrees'`, `'imperial'`, - * `'nautical'`, `'metric'`, `'us'`. - * @enum {string} - */ + * Units for the scale line. Supported values are `'degrees'`, `'imperial'`, + * `'nautical'`, `'metric'`, `'us'`. + */ type Units = "degrees" | "imperial" | "nautical" | "metric" | "us"; } @@ -792,9 +716,7 @@ declare module ol { * This control is one of the default controls of a map. To style this control * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @param opt_options Zoom options. * @api stable */ class Zoom extends ol.control.Control { @@ -804,13 +726,10 @@ declare module ol { * This control is one of the default controls of a map. To style this control * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @param opt_options Zoom options. * @api stable */ constructor(opt_options?: olx.control.ZoomOptions); - } /** @@ -821,9 +740,7 @@ declare module ol { * * map.addControl(new ol.control.ZoomSlider()); * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @param opt_options Zoom slider options. * @api stable */ class ZoomSlider extends ol.control.Control { @@ -835,21 +752,17 @@ declare module ol { * * map.addControl(new ol.control.ZoomSlider()); * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @param opt_options Zoom slider options. * @api stable */ constructor(opt_options?: olx.control.ZoomSliderOptions); /** * Update the zoomslider element. - * @param {ol.MapEvent} mapEvent Map event. - * @this {ol.control.ZoomSlider} + * @param mapEvent Map event. * @api */ static render(mapEvent: ol.MapEvent): void; - } /** @@ -857,9 +770,7 @@ declare module ol { * A button control which, when pressed, changes the map view to a specific * extent. To style this control use the css selector `.ol-zoom-extent`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @param opt_options Options. * @api stable */ class ZoomToExtent extends ol.control.Control { @@ -868,21 +779,14 @@ declare module ol { * A button control which, when pressed, changes the map view to a specific * extent. To style this control use the css selector `.ol-zoom-extent`. * - * @constructor - * @extends {ol.control.Control} - * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @param opt_options Options. * @api stable */ constructor(opt_options?: olx.control.ZoomToExtentOptions); - } - } - /** - * @namespace ol.coordinate - */ - module coordinate { + namespace coordinate { /** * Add `delta` to `coordinate`. `coordinate` is modified in place and returned * by the function. @@ -893,9 +797,9 @@ declare module ol { * ol.coordinate.add(coord, [-2, 4]); * // coord is now [5.85, 51.983333] * - * @param {ol.Coordinate} coordinate Coordinate. - * @param {ol.Coordinate} delta Delta. - * @return {ol.Coordinate} The input coordinate adjusted by the given delta. + * @param coordinate Coordinate. + * @param delta Delta. + * @return The input coordinate adjusted by the given delta. * @api stable */ function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; @@ -918,9 +822,9 @@ declare module ol { * var out = stringifyFunc(coord); * // out is now '7.85, 47.98' * - * @param {number=} opt_fractionDigits The number of digits to include + * @param opt_fractionDigits The number of digits to include * after the decimal point. Default is `0`. - * @return {ol.CoordinateFormatType} Coordinate format. + * @return Coordinate format. * @api stable */ function createStringXY(opt_fractionDigits?: number): ol.CoordinateFormatType; @@ -944,12 +848,12 @@ declare module ol { * var out = ol.coordinate.format(coord, template, 2); * // out is now 'Coordinate is (7.85|47.98).' * - * @param {ol.Coordinate|undefined} coordinate Coordinate. - * @param {string} template A template string with `{x}` and `{y}` placeholders + * @param coordinate Coordinate. + * @param template A template string with `{x}` and `{y}` placeholders * that will be replaced by first and second coordinate values. - * @param {number=} opt_fractionDigits The number of digits to include + * @param opt_fractionDigits The number of digits to include * after the decimal point. Default is `0`. - * @return {string} Formatted coordinate. + * @return Formatted coordinate. * @api stable */ function format(coordinate: (ol.Coordinate), template: string, opt_fractionDigits?: number): string; @@ -965,9 +869,9 @@ declare module ol { * ol.coordinate.rotate(coord, rotateRadians); * // coord is now [-47.983333, 7.85] * - * @param {ol.Coordinate} coordinate Coordinate. - * @param {number} angle Angle in radian. - * @return {ol.Coordinate} Coordinate. + * @param coordinate Coordinate. + * @param angle Angle in radian. + * @return Coordinate. * @api stable */ function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; @@ -988,10 +892,10 @@ declare module ol { * var out = ol.coordinate.toStringHDMS(coord, 1); * // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E' * - * @param {ol.Coordinate|undefined} coordinate Coordinate. - * @param {number=} opt_fractionDigits The number of digits to include + * @param coordinate Coordinate. + * @param opt_fractionDigits The number of digits to include * after the decimal point. Default is `0`. - * @return {string} Hemisphere, degrees, minutes and seconds. + * @return Hemisphere, degrees, minutes and seconds. * @api stable */ function toStringHDMS(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; @@ -1011,14 +915,13 @@ declare module ol { * var out = ol.coordinate.toStringXY(coord, 1); * // out is now '7.8, 48.0' * - * @param {ol.Coordinate|undefined} coordinate Coordinate. - * @param {number=} opt_fractionDigits The number of digits to include + * @param coordinate Coordinate. + * @param opt_fractionDigits The number of digits to include * after the decimal point. Default is `0`. - * @return {string} XY. + * @return XY. * @api stable */ function toStringXY(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; - } /** @@ -1071,9 +974,7 @@ declare module ol { * * @see {@link http://www.w3.org/TR/orientation-event/} * - * @constructor - * @extends {ol.Object} - * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @param opt_options Options. * @api */ class DeviceOrientation extends ol.Object { @@ -1127,16 +1028,14 @@ declare module ol { * * @see {@link http://www.w3.org/TR/orientation-event/} * - * @constructor - * @extends {ol.Object} - * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @param opt_options Options. * @api */ constructor(opt_options?: olx.DeviceOrientationOptions); /** * Rotation around the device z-axis (in radians). - * @return {number|undefined} The euler angle in radians of the device from the + * @return The euler angle in radians of the device from the * standard Z axis. * @observable * @api @@ -1145,7 +1044,7 @@ declare module ol { /** * Rotation around the device x-axis (in radians). - * @return {number|undefined} The euler angle in radians of the device from the + * @return The euler angle in radians of the device from the * planar X axis. * @observable * @api @@ -1154,7 +1053,7 @@ declare module ol { /** * Rotation around the device y-axis (in radians). - * @return {number|undefined} The euler angle in radians of the device from the + * @return The euler angle in radians of the device from the * planar Y axis. * @observable * @api @@ -1163,7 +1062,7 @@ declare module ol { /** * The heading of the device relative to north (in radians). - * @return {number|undefined} The heading of the device relative to north, in + * @return The heading of the device relative to north, in * radians, normalizing for different browser behavior. * @observable * @api @@ -1172,7 +1071,7 @@ declare module ol { /** * Determine if orientation is being tracked. - * @return {boolean} Changes in device orientation are being tracked. + * @return Changes in device orientation are being tracked. * @observable * @api */ @@ -1180,61 +1079,56 @@ declare module ol { /** * Enable or disable tracking of device orientation events. - * @param {boolean} tracking The status of tracking changes to alpha, beta and + * @param tracking The status of tracking changes to alpha, beta and * gamma. If true, changes are tracked and reported immediately. * @observable * @api */ setTracking(tracking: boolean): void; - } /** * Objects that need to clean up after themselves. - * @constructor */ class Disposable { /** * Objects that need to clean up after themselves. - * @constructor */ constructor(); - } /** * Easing functions for {@link ol.animation}. - * @namespace ol.easing */ - module easing { + namespace easing { /** * Start slow and speed up. - * @param {number} t Input between 0 and 1. - * @return {number} Output between 0 and 1. + * @param t Input between 0 and 1. + * @return Output between 0 and 1. * @api */ function easeIn(t: number): number; /** * Start fast and slow down. - * @param {number} t Input between 0 and 1. - * @return {number} Output between 0 and 1. + * @param t Input between 0 and 1. + * @return Output between 0 and 1. * @api */ function easeOut(t: number): number; /** * Start slow, speed up, and then slow down again. - * @param {number} t Input between 0 and 1. - * @return {number} Output between 0 and 1. + * @param t Input between 0 and 1. + * @return Output between 0 and 1. * @api */ function inAndOut(t: number): number; /** * Maintain a constant speed over time. - * @param {number} t Input between 0 and 1. - * @return {number} Output between 0 and 1. + * @param t Input between 0 and 1. + * @return Output between 0 and 1. * @api */ function linear(t: number): number; @@ -1243,12 +1137,11 @@ declare module ol { * Start slow, speed up, and at the very end slow down again. This has the * same general behavior as {@link ol.easing.inAndOut}, but the final slowdown * is delayed. - * @param {number} t Input between 0 and 1. - * @return {number} Output between 0 and 1. + * @param t Input between 0 and 1. + * @return Output between 0 and 1. * @api */ function upAndDown(t: number): number; - } /** @@ -1263,19 +1156,15 @@ declare module ol { * Some classes have their own event type, which return additional * properties; see the specific event class page for details. * - * @namespace ol.events */ - module events { - /** - * @namespace ol.events.condition - */ - module condition { + namespace events { + namespace condition { /** * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when * additionally the shift-key is pressed). * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True if only the alt key is pressed. + * @param mapBrowserEvent Map browser event. + * @return True if only the alt key is pressed. * @api stable */ function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1284,8 +1173,8 @@ declare module ol { * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise * (e.g. when additionally the platform-modifier-key is pressed). * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True if only the alt and shift keys are pressed. + * @param mapBrowserEvent Map browser event. + * @return True if only the alt and shift keys are pressed. * @api stable */ function altShiftKeysOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1293,9 +1182,8 @@ declare module ol { /** * Return always true. * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True. - * @function + * @param mapBrowserEvent Map browser event. + * @return True. * @api stable */ function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1303,8 +1191,8 @@ declare module ol { /** * Return `true` if the event is a `click` event, `false` otherwise. * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True if the event is a map `click` event. + * @param mapBrowserEvent Map browser event. + * @return True if the event is a map `click` event. * @api stable */ function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1312,9 +1200,8 @@ declare module ol { /** * Return always false. * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} False. - * @function + * @param mapBrowserEvent Map browser event. + * @return False. * @api stable */ function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1323,8 +1210,8 @@ declare module ol { * Return `true` if the browser event is a `pointermove` event, `false` * otherwise. * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True if the browser event is a `pointermove` event. + * @param mapBrowserEvent Map browser event. + * @return True if the browser event is a `pointermove` event. * @api */ function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1332,8 +1219,8 @@ declare module ol { /** * Return `true` if the event is a map `singleclick` event, `false` otherwise. * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True if the event is a map `singleclick` event. + * @param mapBrowserEvent Map browser event. + * @return True if the event is a map `singleclick` event. * @api stable */ function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1341,8 +1228,8 @@ declare module ol { /** * Return `true` if the event is a map `dblclick` event, `false` otherwise. * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True if the event is a map `dblclick` event. + * @param mapBrowserEvent Map browser event. + * @return True if the event is a map `dblclick` event. * @api stable */ function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1351,8 +1238,8 @@ declare module ol { * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is * pressed. * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True only if there no modifier keys are pressed. + * @param mapBrowserEvent Map browser event. + * @return True only if there no modifier keys are pressed. * @api stable */ function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1362,8 +1249,8 @@ declare module ol { * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally * the shift-key is pressed). * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True if only the platform modifier key is pressed. + * @param mapBrowserEvent Map browser event. + * @return True if only the platform modifier key is pressed. * @api stable */ function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1372,8 +1259,8 @@ declare module ol { * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when * additionally the alt-key is pressed). * - * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. - * @return {boolean} True if only the shift key is pressed. + * @param mapBrowserEvent Map browser event. + * @return True if only the shift key is pressed. * @api stable */ function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; @@ -1382,8 +1269,8 @@ declare module ol { * Return `true` if the target element is not editable, i.e. not a ``-, * `